]> git.ipfire.org Git - thirdparty/cups.git/blame - scheduler/main.c
Fix "ippfind _SomeName" (Issue #4833)
[thirdparty/cups.git] / scheduler / main.c
CommitLineData
ef416fc2 1/*
581dae2d 2 * Main loop for the CUPS scheduler.
ef416fc2 3 *
b393bc25 4 * Copyright 2007-2017 by Apple Inc.
581dae2d 5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
ef416fc2 6 *
581dae2d
MS
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * "LICENSE" which should have been included with this file. If this
11 * file is missing or damaged, see the license at "http://www.cups.org/".
ef416fc2 12 */
13
14/*
15 * Include necessary headers...
16 */
17
18#define _MAIN_C_
19#include "cupsd.h"
20#include <sys/resource.h>
a1797929
MS
21#ifdef HAVE_ASL_H
22# include <asl.h>
23#elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
24# define SD_JOURNAL_SUPPRESS_LOCATION
25# include <systemd/sd-journal.h>
26#endif /* HAVE_ASL_H */
ef416fc2 27#include <syslog.h>
28#include <grp.h>
29
a4d04587 30#ifdef HAVE_LAUNCH_H
31# include <launch.h>
a4d04587 32#endif /* HAVE_LAUNCH_H */
33
1720786e 34#ifdef HAVE_SYSTEMD
5950e7bd 35# include <systemd/sd-daemon.h>
1720786e
MS
36#endif /* HAVE_SYSTEMD */
37
441de8b2
BN
38#ifdef HAVE_ONDEMAND
39# define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
40 /* Name of the KeepAlive file */
03bc3ef4 41#endif /* HAVE_ONDEMAND */
441de8b2 42
ef416fc2 43#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
44# include <malloc.h>
45#endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
3dd9c340 46
fa73b229 47#ifdef HAVE_NOTIFY_H
48# include <notify.h>
49#endif /* HAVE_NOTIFY_H */
ef416fc2 50
e7f455a5
MS
51#ifdef HAVE_DBUS
52# include <dbus/dbus.h>
53#endif /* HAVE_DBUS */
54
3dd9c340
MS
55#ifdef HAVE_SYS_PARAM_H
56# include <sys/param.h>
57#endif /* HAVE_SYS_PARAM_H */
58
ef416fc2 59
60/*
61 * Local functions...
62 */
63
411affcf 64static void parent_handler(int sig);
65static void process_children(void);
66static void sigchld_handler(int sig);
67static void sighup_handler(int sig);
68static void sigterm_handler(int sig);
69static long select_timeout(int fds);
1720786e 70static void service_checkin(void);
03bc3ef4 71static void service_checkout(int shutdown);
85dda01c 72static void usage(int status) __attribute__((noreturn));
ef416fc2 73
74
75/*
76 * Local globals...
77 */
78
411affcf 79static int parent_signal = 0;
80 /* Set to signal number from child */
81static int holdcount = 0; /* Number of times "hold" was called */
ef416fc2 82#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
411affcf 83static sigset_t holdmask; /* Old POSIX signal mask */
ef416fc2 84#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
411affcf 85static int dead_children = 0;
86 /* Dead children? */
87static int stop_scheduler = 0;
88 /* Should the scheduler stop? */
e1bb4a6e
MS
89static time_t local_timeout = 0;
90 /* Next local printer timeout */
411affcf 91
ef416fc2 92
93/*
94 * 'main()' - Main entry for the CUPS scheduler.
95 */
96
97int /* O - Exit status */
bd7854cb 98main(int argc, /* I - Number of command-line args */
ef416fc2 99 char *argv[]) /* I - Command-line arguments */
100{
101 int i; /* Looping var */
102 char *opt; /* Option character */
108f7505
MS
103 int close_all = 1, /* Close all file descriptors? */
104 disconnect = 1, /* Disconnect from controlling terminal? */
105 fg = 0, /* Run in foreground? */
2dd94018 106 run_as_child = 0,
108f7505 107 /* Running as child process? */
2dd94018
MS
108 print_profile = 0;
109 /* Print the sandbox profile to stdout? */
bd7854cb 110 int fds; /* Number of ready descriptors */
ef416fc2 111 cupsd_client_t *con; /* Current client */
112 cupsd_job_t *job; /* Current job */
113 cupsd_listener_t *lis; /* Current listener */
114 time_t current_time, /* Current time */
a4d04587 115 activity, /* Client activity timer */
ef416fc2 116 senddoc_time, /* Send-Document time */
411affcf 117 expire_time, /* Subscription expire time */
50fe7201 118 report_time, /* Malloc/client/job report time */
5a662dc0 119 event_time; /* Last event notification time */
f7deaa1a 120 long timeout; /* Timeout for cupsdDoSelect() */
ef416fc2 121 struct rlimit limit; /* Runtime limit */
122#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
123 struct sigaction action; /* Actions for POSIX signals */
124#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
a41f09e2 125#ifdef __APPLE__
1deb86fd 126 int use_sysman = 1; /* Use system management functions? */
a4924f6c
MS
127#else
128 time_t netif_time = 0; /* Time since last network update */
a41f09e2 129#endif /* __APPLE__ */
c187d9ab 130#if defined(HAVE_ONDEMAND)
1720786e 131 int service_idle_exit;
a4d04587 132 /* Idle exit on select timeout? */
c187d9ab 133#endif /* HAVE_ONDEMAND */
ef416fc2 134
135
db1f069b
MS
136#ifdef HAVE_GETEUID
137 /*
138 * Check for setuid invocation, which we do not support!
139 */
140
141 if (getuid() != geteuid())
142 {
1deb86fd 143 fputs("cupsd: Cannot run as a setuid program.\n", stderr);
db1f069b
MS
144 return (1);
145 }
146#endif /* HAVE_GETEUID */
147
ef416fc2 148 /*
149 * Check for command-line arguments...
150 */
151
4400e98d 152 fg = 0;
ef416fc2 153
09a101d6 154#ifdef HAVE_LAUNCHD
155 if (getenv("CUPSD_LAUNCHD"))
156 {
108f7505
MS
157 OnDemand = 1;
158 fg = 1;
159 close_all = 0;
160 disconnect = 0;
09a101d6 161 }
162#endif /* HAVE_LAUNCHD */
163
ef416fc2 164 for (i = 1; i < argc; i ++)
165 if (argv[i][0] == '-')
166 for (opt = argv[i] + 1; *opt != '\0'; opt ++)
167 switch (*opt)
168 {
a41f09e2
MS
169 case 'C' : /* Run as child with config file */
170 run_as_child = 1;
108f7505
MS
171 fg = 1;
172 close_all = 0;
a41f09e2 173
ef416fc2 174 case 'c' : /* Configuration file */
175 i ++;
176 if (i >= argc)
a4d04587 177 {
178 _cupsLangPuts(stderr, _("cupsd: Expected config filename "
0837b7e8 179 "after \"-c\" option."));
a4d04587 180 usage(1);
181 }
ef416fc2 182
183 if (argv[i][0] == '/')
184 {
185 /*
186 * Absolute directory...
187 */
188
189 cupsdSetString(&ConfigurationFile, argv[i]);
190 }
191 else
192 {
193 /*
194 * Relative directory...
195 */
196
09ec0018 197 char *current; /* Current directory */
ef416fc2 198
09ec0018 199 /*
200 * Allocate a buffer for the current working directory to
201 * reduce run-time stack usage; this approximates the
202 * behavior of some implementations of getcwd() when they
203 * are passed a NULL pointer.
204 */
205
91c84a35
MS
206 if ((current = malloc(1024)) == NULL)
207 {
208 _cupsLangPuts(stderr,
0837b7e8 209 _("cupsd: Unable to get current directory."));
91c84a35
MS
210 return (1);
211 }
212
213 if (!getcwd(current, 1024))
214 {
215 _cupsLangPuts(stderr,
0837b7e8 216 _("cupsd: Unable to get current directory."));
91c84a35
MS
217 free(current);
218 return (1);
219 }
09ec0018 220
ef416fc2 221 cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
09ec0018 222 free(current);
ef416fc2 223 }
224 break;
225
226 case 'f' : /* Run in foreground... */
108f7505
MS
227 fg = 1;
228 disconnect = 0;
229 close_all = 0;
ef416fc2 230 break;
231
bd7854cb 232 case 'F' : /* Run in foreground, but disconnect from terminal... */
108f7505
MS
233 fg = 1;
234 close_all = 0;
ef416fc2 235 break;
236
a4d04587 237 case 'h' : /* Show usage/help */
238 usage(0);
239 break;
240
441de8b2 241 case 'l' : /* Started by launchd/systemd/upstart... */
03bc3ef4 242#ifdef HAVE_ONDEMAND
108f7505
MS
243 OnDemand = 1;
244 fg = 1;
245 close_all = 0;
246 disconnect = 0;
a4d04587 247#else
1720786e 248 _cupsLangPuts(stderr, _("cupsd: On-demand support not compiled "
0837b7e8 249 "in, running in normal mode."));
108f7505
MS
250 fg = 0;
251 disconnect = 1;
252 close_all = 1;
c187d9ab 253#endif /* HAVE_ONDEMAND */
a4d04587 254 break;
255
a74454a7 256 case 'p' : /* Stop immediately for profiling */
5a662dc0
MS
257 fputs("cupsd: -p (startup profiling) is for internal testing "
258 "use only!\n", stderr);
a74454a7 259 stop_scheduler = 1;
260 fg = 1;
108f7505
MS
261 disconnect = 0;
262 close_all = 0;
a74454a7 263 break;
264
1340db2d 265 case 'P' : /* Disable security profiles */
8fe0183a
MS
266 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr);
267 UseSandboxing = 0;
1340db2d
MS
268 break;
269
c41769ff
MS
270 case 's' : /* Set cups-files.conf location */
271 i ++;
272 if (i >= argc)
273 {
274 _cupsLangPuts(stderr, _("cupsd: Expected cups-files.conf "
275 "filename after \"-s\" option."));
276 usage(1);
277 }
278
279 if (argv[i][0] != '/')
280 {
281 /*
282 * Relative filename not allowed...
283 */
284
285 _cupsLangPuts(stderr, _("cupsd: Relative cups-files.conf "
286 "filename not allowed."));
287 usage(1);
288 }
289
290 cupsdSetString(&CupsFilesFile, argv[i]);
291 break;
292
68b10830
MS
293#ifdef __APPLE__
294 case 'S' : /* Disable system management functions */
5a662dc0
MS
295 fputs("cupsd: -S (disable system management) for internal "
296 "testing use only!\n", stderr);
68b10830
MS
297 use_sysman = 0;
298 break;
299#endif /* __APPLE__ */
300
2e4ff8af
MS
301 case 't' : /* Test the cupsd.conf file... */
302 TestConfigFile = 1;
303 fg = 1;
108f7505
MS
304 disconnect = 0;
305 close_all = 0;
2e4ff8af
MS
306 break;
307
2dd94018
MS
308 case 'T' : /* Print security profile */
309 print_profile = 1;
310 fg = 1;
311 disconnect = 0;
312 close_all = 0;
313 break;
314
ef416fc2 315 default : /* Unknown option */
a4d04587 316 _cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
0837b7e8 317 "aborting."), *opt);
a4d04587 318 usage(1);
ef416fc2 319 break;
320 }
321 else
322 {
0837b7e8 323 _cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting."),
a4d04587 324 argv[i]);
325 usage(1);
ef416fc2 326 }
327
328 if (!ConfigurationFile)
329 cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
330
cb7f98ee
MS
331 if (!CupsFilesFile)
332 {
333 char *filename, /* Copy of cupsd.conf filename */
334 *slash; /* Final slash in cupsd.conf filename */
335 size_t len; /* Size of buffer */
336
337 len = strlen(ConfigurationFile) + 15;
338 if ((filename = malloc(len)) == NULL)
339 {
340 _cupsLangPrintf(stderr,
341 _("cupsd: Unable to get path to "
342 "cups-files.conf file."));
343 return (1);
344 }
345
346 strlcpy(filename, ConfigurationFile, len);
347 if ((slash = strrchr(filename, '/')) == NULL)
348 {
349 _cupsLangPrintf(stderr,
350 _("cupsd: Unable to get path to "
351 "cups-files.conf file."));
352 return (1);
353 }
354
7e86f2f6 355 strlcpy(slash, "/cups-files.conf", len - (size_t)(slash - filename));
cb7f98ee
MS
356 cupsdSetString(&CupsFilesFile, filename);
357 free(filename);
358 }
359
108f7505
MS
360 if (disconnect)
361 {
362 /*
363 * Make sure we aren't tying up any filesystems...
364 */
365
366 chdir("/");
367
368 /*
369 * Disconnect from the controlling terminal...
370 */
371
372 setsid();
373 }
374
375 if (close_all)
376 {
377 /*
378 * Close all open files...
379 */
380
381 getrlimit(RLIMIT_NOFILE, &limit);
382
383 for (i = 0; i < (int)limit.rlim_cur && i < 1024; i ++)
384 close(i);
385
386 /*
387 * Redirect stdin/out/err to /dev/null...
388 */
389
390 if ((i = open("/dev/null", O_RDONLY)) != 0)
391 {
392 dup2(i, 0);
393 close(i);
394 }
395
396 if ((i = open("/dev/null", O_WRONLY)) != 1)
397 {
398 dup2(i, 1);
399 close(i);
400 }
401
402 if ((i = open("/dev/null", O_WRONLY)) != 2)
403 {
404 dup2(i, 2);
405 close(i);
406 }
407 }
a1797929
MS
408 else
409 LogStderr = cupsFileStderr();
108f7505 410
ef416fc2 411 /*
108f7505 412 * Run in the background as needed...
ef416fc2 413 */
414
415 if (!fg)
416 {
417 /*
418 * Setup signal handlers for the parent...
419 */
420
421#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
422 sigset(SIGUSR1, parent_handler);
423 sigset(SIGCHLD, parent_handler);
424
425 sigset(SIGHUP, SIG_IGN);
426#elif defined(HAVE_SIGACTION)
427 memset(&action, 0, sizeof(action));
428 sigemptyset(&action.sa_mask);
429 sigaddset(&action.sa_mask, SIGUSR1);
430 action.sa_handler = parent_handler;
431 sigaction(SIGUSR1, &action, NULL);
432 sigaction(SIGCHLD, &action, NULL);
433
434 sigemptyset(&action.sa_mask);
435 action.sa_handler = SIG_IGN;
436 sigaction(SIGHUP, &action, NULL);
437#else
438 signal(SIGUSR1, parent_handler);
439 signal(SIGCLD, parent_handler);
440
441 signal(SIGHUP, SIG_IGN);
442#endif /* HAVE_SIGSET */
443
444 if (fork() > 0)
445 {
446 /*
447 * OK, wait for the child to startup and send us SIGUSR1 or to crash
448 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
449 * might be sent by the init script to restart the scheduler...
450 */
451
452 for (; parent_signal == 0;)
453 sleep(1);
454
455 if (parent_signal == SIGUSR1)
456 return (0);
457
458 if (wait(&i) < 0)
459 {
460 perror("cupsd");
461 return (1);
462 }
463 else if (WIFEXITED(i))
464 {
4d301e69 465 fprintf(stderr, "cupsd: Child exited with status %d\n",
bd7854cb 466 WEXITSTATUS(i));
ef416fc2 467 return (2);
468 }
469 else
470 {
4d301e69 471 fprintf(stderr, "cupsd: Child exited on signal %d\n", WTERMSIG(i));
ef416fc2 472 return (3);
473 }
474 }
a41f09e2 475
3dd9c340 476#if defined(__OpenBSD__) && OpenBSD < 201211
68b10830
MS
477 /*
478 * Call _thread_sys_closefrom() so the child process doesn't reset the
479 * parent's file descriptors to be blocking. This is a workaround for a
3dd9c340 480 * limitation of userland libpthread on older versions of OpenBSD.
68b10830 481 */
ef55b745 482
68b10830 483 _thread_sys_closefrom(0);
3dd9c340 484#endif /* __OpenBSD__ && OpenBSD < 201211 */
68b10830 485
a41f09e2 486 /*
108f7505
MS
487 * Since many system libraries create fork-unsafe data on execution of a
488 * program, we need to re-execute the background cupsd with the "-C" and "-s"
489 * options to avoid problems. Unfortunately, we also have to assume that
490 * argv[0] contains the name of the cupsd executable - there is no portable
491 * way to get the real pathname...
a41f09e2
MS
492 */
493
108f7505 494 execlp(argv[0], argv[0], "-C", ConfigurationFile, "-s", CupsFilesFile, (char *)0);
a41f09e2 495 exit(errno);
ef416fc2 496 }
497
e4e37194
MS
498 /*
499 * Let the system know we are busy while we bring up cupsd...
500 */
501
502 cupsdSetBusyState(1);
503
ef416fc2 504 /*
505 * Set the timezone info...
506 */
507
508 tzset();
509
510#ifdef LC_TIME
511 setlocale(LC_TIME, "");
512#endif /* LC_TIME */
513
0cf0c416
MS
514#ifdef HAVE_DBUS_THREADS_INIT
515 /*
516 * Enable threading support for D-BUS...
517 */
518
e7f455a5 519 dbus_threads_init_default();
0cf0c416
MS
520#endif /* HAVE_DBUS_THREADS_INIT */
521
ef416fc2 522 /*
523 * Set the maximum number of files...
524 */
525
526 getrlimit(RLIMIT_NOFILE, &limit);
527
f7deaa1a 528#if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
f7faf1f5 529 if (limit.rlim_max > FD_SETSIZE)
530 MaxFDs = FD_SETSIZE;
ef416fc2 531 else
f7deaa1a 532#endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
533#ifdef RLIM_INFINITY
534 if (limit.rlim_max == RLIM_INFINITY)
535 MaxFDs = 16384;
536 else
537#endif /* RLIM_INFINITY */
ef416fc2 538 MaxFDs = limit.rlim_max;
539
7e86f2f6 540 limit.rlim_cur = (rlim_t)MaxFDs;
ef416fc2 541
542 setrlimit(RLIMIT_NOFILE, &limit);
543
f7deaa1a 544 cupsdStartSelect();
ef416fc2 545
546 /*
547 * Read configuration...
548 */
549
550 if (!cupsdReadConfiguration())
ef416fc2 551 return (1);
2e4ff8af
MS
552 else if (TestConfigFile)
553 {
cb7f98ee
MS
554 printf("\"%s\" is OK.\n", CupsFilesFile);
555 printf("\"%s\" is OK.\n", ConfigurationFile);
2e4ff8af
MS
556 return (0);
557 }
2dd94018
MS
558 else if (print_profile)
559 {
560 cups_file_t *fp; /* File pointer */
561 const char *profile = cupsdCreateProfile(42, 0);
562 /* Profile */
563 char line[1024]; /* Line from file */
564
565
566 if ((fp = cupsFileOpen(profile, "r")) == NULL)
567 {
568 printf("Unable to open profile file \"%s\": %s\n", profile ? profile : "(null)", strerror(errno));
569 return (1);
570 }
571
572 while (cupsFileGets(fp, line, sizeof(line)))
573 puts(line);
574
575 cupsFileClose(fp);
576
577 return (0);
578 }
ef416fc2 579
ba55dc12
MS
580 /*
581 * Clean out old temp files and printer cache data.
582 */
cc0d019f 583
ba55dc12 584 if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)))
321d8d57 585 cupsdCleanFiles(TempDir, NULL);
cc0d019f 586
321d8d57 587 cupsdCleanFiles(CacheDir, "*.ipp");
cc0d019f 588
03bc3ef4
MS
589 /*
590 * If we were started on demand by launchd or systemd get the listen sockets
591 * file descriptors...
592 */
a4d04587 593
03bc3ef4
MS
594 service_checkin();
595 service_checkout(0);
a4d04587 596
597 /*
598 * Startup the server...
599 */
600
6d2f911b
MS
601 httpInitialize();
602
a4d04587 603 cupsdStartServer();
604
ef416fc2 605 /*
606 * Catch hangup and child signals and ignore broken pipes...
607 */
608
609#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
e1d6a774 610 sigset(SIGCHLD, sigchld_handler);
4744bd90 611 sigset(SIGHUP, sighup_handler);
ef416fc2 612 sigset(SIGPIPE, SIG_IGN);
613 sigset(SIGTERM, sigterm_handler);
614#elif defined(HAVE_SIGACTION)
615 memset(&action, 0, sizeof(action));
616
e1d6a774 617 sigemptyset(&action.sa_mask);
618 sigaddset(&action.sa_mask, SIGTERM);
619 sigaddset(&action.sa_mask, SIGCHLD);
620 action.sa_handler = sigchld_handler;
621 sigaction(SIGCHLD, &action, NULL);
622
ef416fc2 623 sigemptyset(&action.sa_mask);
624 sigaddset(&action.sa_mask, SIGHUP);
4744bd90 625 action.sa_handler = sighup_handler;
ef416fc2 626 sigaction(SIGHUP, &action, NULL);
627
628 sigemptyset(&action.sa_mask);
629 action.sa_handler = SIG_IGN;
630 sigaction(SIGPIPE, &action, NULL);
631
632 sigemptyset(&action.sa_mask);
633 sigaddset(&action.sa_mask, SIGTERM);
634 sigaddset(&action.sa_mask, SIGCHLD);
635 action.sa_handler = sigterm_handler;
636 sigaction(SIGTERM, &action, NULL);
637#else
e1d6a774 638 signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */
4744bd90 639 signal(SIGHUP, sighup_handler);
ef416fc2 640 signal(SIGPIPE, SIG_IGN);
641 signal(SIGTERM, sigterm_handler);
642#endif /* HAVE_SIGSET */
643
ef416fc2 644 /*
645 * Initialize authentication certificates...
646 */
647
648 cupsdInitCerts();
649
650 /*
651 * If we are running in the background, signal the parent process that
652 * we are up and running...
653 */
654
a41f09e2 655 if (!fg || run_as_child)
ef416fc2 656 {
657 /*
658 * Send a signal to the parent process, but only if the parent is
659 * not PID 1 (init). This avoids accidentally shutting down the
660 * system on OpenBSD if you CTRL-C the server before it is up...
661 */
662
663 i = getppid(); /* Save parent PID to avoid race condition */
664
665 if (i != 1)
666 kill(i, SIGUSR1);
667 }
668
e1d6a774 669#ifdef __APPLE__
09ec0018 670 /*
671 * Start power management framework...
672 */
673
1340db2d
MS
674 if (use_sysman)
675 cupsdStartSystemMonitor();
e1d6a774 676#endif /* __APPLE__ */
ef416fc2 677
49d87452
MS
678 /*
679 * Send server-started event...
680 */
681
03bc3ef4 682#ifdef HAVE_ONDEMAND
1720786e
MS
683 if (OnDemand)
684 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL, "Scheduler started on demand.");
49d87452 685 else
c187d9ab 686#endif /* HAVE_ONDEMAND */
49d87452 687 if (fg)
1720786e 688 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL, "Scheduler started in foreground.");
49d87452 689 else
1720786e 690 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL, "Scheduler started in background.");
49d87452 691
e4e37194
MS
692 cupsdSetBusyState(0);
693
ef416fc2 694 /*
695 * Start any pending print jobs...
696 */
697
698 cupsdCheckJobs();
699
700 /*
701 * Loop forever...
702 */
703
50fe7201 704 current_time = time(NULL);
50fe7201
MS
705 event_time = current_time;
706 expire_time = current_time;
123cfe02 707 local_timeout = 0;
ef416fc2 708 fds = 1;
5bd77a73 709 report_time = 0;
50fe7201 710 senddoc_time = current_time;
ef416fc2 711
712 while (!stop_scheduler)
713 {
ef416fc2 714 /*
715 * Check if there are dead children to handle...
716 */
717
718 if (dead_children)
719 process_children();
720
721 /*
722 * Check if we need to load the server configuration file...
723 */
724
725 if (NeedReload)
726 {
727 /*
728 * Close any idle clients...
729 */
730
bd7854cb 731 if (cupsArrayCount(Clients) > 0)
ef416fc2 732 {
bd7854cb 733 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
734 con;
735 con = (cupsd_client_t *)cupsArrayNext(Clients))
996acce8 736 if (httpGetState(con->http) == HTTP_WAITING)
ef416fc2 737 cupsdCloseClient(con);
ef416fc2 738 else
996acce8 739 con->http->keep_alive = HTTP_KEEPALIVE_OFF;
ef416fc2 740
741 cupsdPauseListening();
742 }
743
ef416fc2 744 /*
745 * Restart if all clients are closed and all jobs finished, or
746 * if the reload timeout has elapsed...
747 */
748
bd7854cb 749 if ((cupsArrayCount(Clients) == 0 &&
238c3832 750 (cupsArrayCount(PrintingJobs) == 0 || NeedReload != RELOAD_ALL)) ||
ef416fc2 751 (time(NULL) - ReloadTime) >= ReloadTimeout)
752 {
a4d04587 753 /*
754 * Shutdown the server...
755 */
756
1166bf58 757#ifdef HAVE_ONDEMAND
83d8789d
MS
758 if (OnDemand)
759 break;
1166bf58 760#endif /* HAVE_ONDEMAND */
83d8789d 761
7cf5915e
MS
762 DoingShutdown = 1;
763
a4d04587 764 cupsdStopServer();
765
766 /*
767 * Read configuration...
768 */
769
ef416fc2 770 if (!cupsdReadConfiguration())
771 {
250bb8a9 772#ifdef HAVE_SYSTEMD_SD_JOURNAL_H
a1797929
MS
773 sd_journal_print(LOG_ERR, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile);
774#else
775 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting.", ConfigurationFile);
250bb8a9 776#endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
a1797929 777
ef416fc2 778 break;
779 }
a4d04587 780
a4d04587 781 /*
782 * Startup the server...
783 */
784
7cf5915e
MS
785 DoingShutdown = 0;
786
a4d04587 787 cupsdStartServer();
49d87452
MS
788
789 /*
790 * Send a server-restarted event...
791 */
792
793 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED, NULL, NULL,
794 "Scheduler restarted.");
ef416fc2 795 }
796 }
797
798 /*
f7deaa1a 799 * Check for available input or ready output. If cupsdDoSelect()
800 * returns 0 or -1, something bad happened and we should exit
801 * immediately.
ef416fc2 802 *
803 * Note that we at least have one listening socket open at all
804 * times.
805 */
806
50fe7201
MS
807 if ((timeout = select_timeout(fds)) > 1 && LastEvent)
808 timeout = 1;
ef416fc2 809
1166bf58 810#ifdef HAVE_ONDEMAND
a4d04587 811 /*
812 * If no other work is scheduled and we're being controlled by
411affcf 813 * launchd then timeout after 'LaunchdTimeout' seconds of
a4d04587 814 * inactivity...
815 */
816
1720786e 817 if (timeout == 86400 && OnDemand && IdleExitTimeout &&
bc44d920 818 !cupsArrayCount(ActiveJobs) &&
0627e869
MS
819# ifdef HAVE_SYSTEMD
820 !WebInterface &&
821# endif /* HAVE_SYSTEMD */
a2326b5b 822 (!Browsing || !BrowseLocalProtocols || !cupsArrayCount(Printers)))
a4d04587 823 {
1720786e
MS
824 timeout = IdleExitTimeout;
825 service_idle_exit = 1;
a4d04587 826 }
827 else
1720786e 828 service_idle_exit = 0;
c187d9ab 829#endif /* HAVE_ONDEMAND */
a4d04587 830
f7deaa1a 831 if ((fds = cupsdDoSelect(timeout)) < 0)
ef416fc2 832 {
ef416fc2 833 /*
834 * Got an error from select!
835 */
836
37e7e6e0 837#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
f7deaa1a 838 cupsd_printer_t *p; /* Current printer */
37e7e6e0 839#endif /* HAVE_DNSSD || HAVE_AVAHI */
f7deaa1a 840
f7deaa1a 841 if (errno == EINTR) /* Just interrupted by a signal */
ef416fc2 842 continue;
843
844 /*
845 * Log all sorts of debug info to help track down the problem.
846 */
847
f7deaa1a 848 cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
ef416fc2 849 strerror(errno));
850
bd7854cb 851 for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
852 con;
853 i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 854 cupsdLogMessage(CUPSD_LOG_EMERG,
855 "Clients[%d] = %d, file = %d, state = %d",
996acce8 856 i, con->number, con->file, httpGetState(con->http));
ef416fc2 857
bd7854cb 858 for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
859 lis;
860 i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
ef416fc2 861 cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
862
923edb68 863 cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);
864
09ec0018 865#ifdef __APPLE__
866 cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
867 SysEventPipes[0]);
868#endif /* __APPLE__ */
869
ef416fc2 870 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
871 job;
872 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
873 cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
874 job->id,
875 job->status_buffer ? job->status_buffer->fd : -1,
876 job->print_pipes[0], job->print_pipes[1],
877 job->back_pipes[0], job->back_pipes[1]);
f7deaa1a 878
37e7e6e0 879#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
f7deaa1a 880 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
881 p;
882 p = (cupsd_printer_t *)cupsArrayNext(Printers))
7a14d768
MS
883 cupsdLogMessage(CUPSD_LOG_EMERG, "printer[%s] reg_name=\"%s\"", p->name,
884 p->reg_name ? p->reg_name : "(null)");
37e7e6e0 885#endif /* HAVE_DNSSD || HAVE_AVAHI */
f7deaa1a 886
ef416fc2 887 break;
888 }
889
890 current_time = time(NULL);
891
3dfe78b3
MS
892 /*
893 * Write dirty config/state files...
894 */
895
b393bc25 896 if (DirtyCleanTime && current_time >= DirtyCleanTime && cupsArrayCount(Clients) == 0)
3dfe78b3 897 cupsdCleanDirty();
3dfe78b3 898
e6013cfa
MS
899#ifdef __APPLE__
900 /*
901 * If we are going to sleep and still have pending jobs, stop them after
902 * a period of time...
903 */
904
905 if (SleepJobs > 0 && current_time >= SleepJobs &&
906 cupsArrayCount(PrintingJobs) > 0)
907 {
908 SleepJobs = 0;
e60ec91f 909 cupsdStopAllJobs(CUPSD_JOB_DEFAULT, 5);
e6013cfa
MS
910 }
911#endif /* __APPLE__ */
912
a4924f6c
MS
913#ifndef __APPLE__
914 /*
915 * Update the network interfaces once a minute...
916 */
917
918 if ((current_time - netif_time) >= 60)
919 {
920 netif_time = current_time;
921 NetIFUpdate = 1;
922 }
923#endif /* !__APPLE__ */
924
1166bf58 925#ifdef HAVE_ONDEMAND
a4d04587 926 /*
1166bf58
MS
927 * If no other work was scheduled and we're being controlled by launchd,
928 * systemd, or upstart then timeout after 'LaunchdTimeout' seconds of
929 * inactivity...
a4d04587 930 */
931
1720786e 932 if (!fds && service_idle_exit)
a4d04587 933 {
934 cupsdLogMessage(CUPSD_LOG_INFO,
935 "Printer sharing is off and there are no jobs pending, "
936 "will restart on demand.");
937 stop_scheduler = 1;
938 break;
939 }
c187d9ab 940#endif /* HAVE_ONDEMAND */
a4d04587 941
76cd9e37
MS
942 /*
943 * Resume listening for new connections as needed...
944 */
945
946 if (ListeningPaused && ListeningPaused <= current_time &&
947 cupsArrayCount(Clients) < MaxClients)
948 cupsdResumeListening();
949
ef416fc2 950 /*
bd7854cb 951 * Expire subscriptions and unload completed jobs as needed...
ef416fc2 952 */
953
bd7854cb 954 if (current_time > expire_time)
ef416fc2 955 {
bd7854cb 956 if (cupsArrayCount(Subscriptions) > 0)
957 cupsdExpireSubscriptions(NULL, NULL);
958
959 cupsdUnloadCompletedJobs();
ef416fc2 960
961 expire_time = current_time;
962 }
963
e1bb4a6e
MS
964 /*
965 * Delete stale local printers...
966 */
967
968 if (current_time >= local_timeout)
123cfe02 969 {
e1bb4a6e 970 cupsdDeleteTemporaryPrinters(0);
123cfe02
MS
971 local_timeout = 0;
972 }
e1bb4a6e 973
07ed0e9a 974#ifndef HAVE_AUTHORIZATION_H
ef416fc2 975 /*
f7deaa1a 976 * Update the root certificate once every 5 minutes if we have client
977 * connections...
ef416fc2 978 */
979
f7deaa1a 980 if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
981 !RunUser && cupsArrayCount(Clients))
982 {
983 /*
984 * Update the root certificate...
985 */
986
987 cupsdDeleteCert(0);
0fa6c7fa 988 cupsdAddCert(0, "root", cupsdDefaultAuthType());
f7deaa1a 989 }
07ed0e9a 990#endif /* !HAVE_AUTHORIZATION_H */
ef416fc2 991
992 /*
993 * Check for new data on the client sockets...
994 */
995
bd7854cb 996 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
997 con;
998 con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 999 {
1000 /*
f7deaa1a 1001 * Process pending data in the input buffer...
ef416fc2 1002 */
1003
1720786e 1004 if (httpGetReady(con->http))
ef416fc2 1005 {
f7deaa1a 1006 cupsdReadClient(con);
1007 continue;
ef416fc2 1008 }
1009
1010 /*
1011 * Check the activity and close old clients...
1012 */
1013
1014 activity = current_time - Timeout;
1720786e 1015 if (httpGetActivity(con->http) < activity && !con->pipe_pid)
ef416fc2 1016 {
1720786e 1017 cupsdLogMessage(CUPSD_LOG_DEBUG, "Closing client %d after %d seconds of inactivity.", con->number, Timeout);
ef416fc2 1018
1019 cupsdCloseClient(con);
ef416fc2 1020 continue;
1021 }
1022 }
1023
1024 /*
1025 * Update any pending multi-file documents...
1026 */
1027
1028 if ((current_time - senddoc_time) >= 10)
1029 {
1030 cupsdCheckJobs();
1031 senddoc_time = current_time;
1032 }
1033
82cc1f9a
MS
1034 /*
1035 * Clean job history...
1036 */
1037
1038 if (JobHistoryUpdate && current_time >= JobHistoryUpdate)
1039 cupsdCleanJobs();
1040
ef416fc2 1041 /*
5bd77a73 1042 * Log statistics at most once a minute when in debug mode...
ef416fc2 1043 */
1044
5bd77a73 1045 if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
ef416fc2 1046 {
5bd77a73
MS
1047 size_t string_count, /* String count */
1048 alloc_bytes, /* Allocated string bytes */
1049 total_bytes; /* Total string bytes */
4400e98d 1050#ifdef HAVE_MALLINFO
5bd77a73 1051 struct mallinfo mem; /* Malloc information */
ef416fc2 1052
1053
1054 mem = mallinfo();
5bd77a73
MS
1055 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
1056 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
1057 mem.usmblks + mem.uordblks);
1058 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
ef416fc2 1059 mem.fsmblks + mem.fordblks);
4400e98d 1060#endif /* HAVE_MALLINFO */
1061
5bd77a73
MS
1062 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
1063 cupsArrayCount(Clients));
1064 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
1065 cupsArrayCount(Jobs));
1066 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
1067 cupsArrayCount(ActiveJobs));
1068 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
1069 cupsArrayCount(Printers));
5bd77a73 1070
757d2cad 1071 string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
5bd77a73
MS
1072 cupsdLogMessage(CUPSD_LOG_DEBUG,
1073 "Report: stringpool-string-count=" CUPS_LLFMT,
1074 CUPS_LLCAST string_count);
1075 cupsdLogMessage(CUPSD_LOG_DEBUG,
1076 "Report: stringpool-alloc-bytes=" CUPS_LLFMT,
1077 CUPS_LLCAST alloc_bytes);
1078 cupsdLogMessage(CUPSD_LOG_DEBUG,
1079 "Report: stringpool-total-bytes=" CUPS_LLFMT,
4400e98d 1080 CUPS_LLCAST total_bytes);
1081
5bd77a73 1082 report_time = current_time;
ef416fc2 1083 }
ef416fc2 1084
fa73b229 1085 /*
1086 * Handle OS-specific event notification for any events that have
1087 * accumulated. Don't send these more than once a second...
1088 */
1089
50fe7201 1090 if (LastEvent && (current_time - event_time) >= 1)
fa73b229 1091 {
1092#ifdef HAVE_NOTIFY_POST
a41f09e2
MS
1093 if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
1094 CUPSD_EVENT_PRINTER_DELETED |
1095 CUPSD_EVENT_PRINTER_MODIFIED))
fa73b229 1096 {
e00b005a 1097 cupsdLogMessage(CUPSD_LOG_DEBUG2,
fa73b229 1098 "notify_post(\"com.apple.printerListChange\")");
1099 notify_post("com.apple.printerListChange");
1100 }
1101
1102 if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
1103 {
e00b005a 1104 cupsdLogMessage(CUPSD_LOG_DEBUG2,
fa73b229 1105 "notify_post(\"com.apple.printerHistoryChange\")");
1106 notify_post("com.apple.printerHistoryChange");
1107 }
1108
1109 if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
1110 CUPSD_EVENT_JOB_CONFIG_CHANGED |
1111 CUPSD_EVENT_JOB_PROGRESS))
1112 {
e00b005a 1113 cupsdLogMessage(CUPSD_LOG_DEBUG2,
fa73b229 1114 "notify_post(\"com.apple.jobChange\")");
1115 notify_post("com.apple.jobChange");
1116 }
1117#endif /* HAVE_NOTIFY_POST */
1118
1119 /*
e53920b9 1120 * Reset the accumulated events...
fa73b229 1121 */
1122
50fe7201
MS
1123 LastEvent = CUPSD_EVENT_NONE;
1124 event_time = current_time;
fa73b229 1125 }
ef416fc2 1126 }
1127
1128 /*
1129 * Log a message based on what happened...
1130 */
1131
1132 if (stop_scheduler)
49d87452 1133 {
ef416fc2 1134 cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
49d87452
MS
1135 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1136 "Scheduler shutting down normally.");
1137 }
ef416fc2 1138 else
49d87452 1139 {
ef416fc2 1140 cupsdLogMessage(CUPSD_LOG_ERROR,
1141 "Scheduler shutting down due to program error.");
49d87452
MS
1142 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1143 "Scheduler shutting down due to program error.");
1144 }
ef416fc2 1145
1146 /*
7ff4fea9 1147 * Close all network clients...
ef416fc2 1148 */
1149
7cf5915e
MS
1150 DoingShutdown = 1;
1151
ef416fc2 1152 cupsdStopServer();
1153
7ff4fea9 1154 /*
03bc3ef4 1155 * Update the KeepAlive/PID file as needed...
7ff4fea9
MS
1156 */
1157
03bc3ef4 1158 service_checkout(1);
7ff4fea9
MS
1159
1160 /*
1161 * Stop all jobs...
1162 */
1163
bd7854cb 1164 cupsdFreeAllJobs();
ef416fc2 1165
b4974142
MS
1166 /*
1167 * Delete all temporary printers...
1168 */
1169
1170 cupsdDeleteTemporaryPrinters(1);
1171
e1d6a774 1172#ifdef __APPLE__
7ff4fea9
MS
1173 /*
1174 * Stop monitoring system event monitoring...
1175 */
1176
1340db2d
MS
1177 if (use_sysman)
1178 cupsdStopSystemMonitor();
e1d6a774 1179#endif /* __APPLE__ */
09ec0018 1180
f7deaa1a 1181 cupsdStopSelect();
ef416fc2 1182
1183 return (!stop_scheduler);
1184}
1185
1186
10d09e33
MS
1187/*
1188 * 'cupsdAddString()' - Copy and add a string to an array.
1189 */
1190
1191int /* O - 1 on success, 0 on failure */
1192cupsdAddString(cups_array_t **a, /* IO - String array */
1193 const char *s) /* I - String to copy and add */
1194{
1195 if (!*a)
1196 *a = cupsArrayNew3((cups_array_func_t)strcmp, NULL,
1197 (cups_ahash_func_t)NULL, 0,
5e6c3df7
MS
1198 (cups_acopy_func_t)strdup,
1199 (cups_afree_func_t)free);
10d09e33
MS
1200
1201 return (cupsArrayAdd(*a, (char *)s));
1202}
1203
1204
d7871c8c
MS
1205/*
1206 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1207 */
1208
1209void
1210cupsdCheckProcess(void)
1211{
1212 /*
1213 * Flag that we have dead children...
1214 */
1215
1216 dead_children = 1;
1217}
1218
1219
10d09e33
MS
1220/*
1221 * 'cupsdClearString()' - Clear a string.
1222 */
1223
1224void
1225cupsdClearString(char **s) /* O - String value */
1226{
1227 if (s && *s)
1228 {
5e6c3df7 1229 free(*s);
10d09e33
MS
1230 *s = NULL;
1231 }
1232}
1233
1234
10d09e33
MS
1235/*
1236 * 'cupsdFreeStrings()' - Free an array of strings.
1237 */
1238
1239void
1240cupsdFreeStrings(cups_array_t **a) /* IO - String array */
1241{
1242 if (*a)
1243 {
1244 cupsArrayDelete(*a);
1245 *a = NULL;
1246 }
1247}
1248
1249
1250/*
1251 * 'cupsdHoldSignals()' - Hold child and termination signals.
1252 */
1253
1254void
1255cupsdHoldSignals(void)
1256{
1257#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1258 sigset_t newmask; /* New POSIX signal mask */
1259#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1260
1261
1262 holdcount ++;
1263 if (holdcount > 1)
1264 return;
1265
1266#ifdef HAVE_SIGSET
1267 sighold(SIGTERM);
1268 sighold(SIGCHLD);
1269#elif defined(HAVE_SIGACTION)
1270 sigemptyset(&newmask);
1271 sigaddset(&newmask, SIGTERM);
1272 sigaddset(&newmask, SIGCHLD);
1273 sigprocmask(SIG_BLOCK, &newmask, &holdmask);
1274#endif /* HAVE_SIGSET */
1275}
1276
1277
ef416fc2 1278/*
1279 * 'cupsdReleaseSignals()' - Release signals for delivery.
1280 */
1281
1282void
1283cupsdReleaseSignals(void)
1284{
1285 holdcount --;
1286 if (holdcount > 0)
1287 return;
1288
1289#ifdef HAVE_SIGSET
1290 sigrelse(SIGTERM);
1291 sigrelse(SIGCHLD);
1292#elif defined(HAVE_SIGACTION)
1293 sigprocmask(SIG_SETMASK, &holdmask, NULL);
1294#endif /* HAVE_SIGSET */
1295}
1296
1297
1298/*
1299 * 'cupsdSetString()' - Set a string value.
1300 */
1301
1302void
1303cupsdSetString(char **s, /* O - New string */
1304 const char *v) /* I - String value */
1305{
1306 if (!s || *s == v)
1307 return;
1308
1309 if (*s)
5e6c3df7 1310 free(*s);
ef416fc2 1311
1312 if (v)
5e6c3df7 1313 *s = strdup(v);
ef416fc2 1314 else
1315 *s = NULL;
1316}
1317
1318
1319/*
1320 * 'cupsdSetStringf()' - Set a formatted string value.
1321 */
1322
1323void
1324cupsdSetStringf(char **s, /* O - New string */
1325 const char *f, /* I - Printf-style format string */
1326 ...) /* I - Additional args as needed */
1327{
94436c5a 1328 char v[65536 + 64]; /* Formatting string value */
ef416fc2 1329 va_list ap; /* Argument pointer */
1330 char *olds; /* Old string */
1331
1332
1333 if (!s)
1334 return;
1335
1336 olds = *s;
1337
1338 if (f)
1339 {
1340 va_start(ap, f);
1341 vsnprintf(v, sizeof(v), f, ap);
1342 va_end(ap);
1343
5e6c3df7 1344 *s = strdup(v);
ef416fc2 1345 }
1346 else
1347 *s = NULL;
1348
1349 if (olds)
5e6c3df7 1350 free(olds);
ef416fc2 1351}
1352
1353
1354/*
1355 * 'parent_handler()' - Catch USR1/CHLD signals...
1356 */
1357
1358static void
1359parent_handler(int sig) /* I - Signal */
1360{
1361 /*
1362 * Store the signal we got from the OS and return...
1363 */
1364
1365 parent_signal = sig;
1366}
1367
1368
1369/*
1370 * 'process_children()' - Process all dead children...
1371 */
1372
1373static void
1374process_children(void)
1375{
1376 int status; /* Exit status of child */
b9faaae1
MS
1377 int pid, /* Process ID of child */
1378 job_id; /* Job ID of child */
ef416fc2 1379 cupsd_job_t *job; /* Current job */
1380 int i; /* Looping var */
e00b005a 1381 char name[1024]; /* Process name */
dcb445bc 1382 const char *type; /* Type of program */
ef416fc2 1383
1384
1385 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1386
1387 /*
1388 * Reset the dead_children flag...
1389 */
1390
1391 dead_children = 0;
1392
1393 /*
1394 * Collect the exit status of some children...
1395 */
1396
1397#ifdef HAVE_WAITPID
1398 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1399#elif defined(HAVE_WAIT3)
1400 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1401#else
1402 if ((pid = wait(&status)) > 0)
1403#endif /* HAVE_WAITPID */
1404 {
ef416fc2 1405 /*
745129be 1406 * Collect the name of the process that finished...
ef416fc2 1407 */
1408
b9faaae1 1409 cupsdFinishProcess(pid, name, sizeof(name), &job_id);
e00b005a 1410
ef416fc2 1411 /*
1412 * Delete certificates for CGI processes...
1413 */
1414
1415 if (pid)
1416 cupsdDeleteCert(pid);
1417
1418 /*
b9faaae1 1419 * Handle completed job filters...
ef416fc2 1420 */
1421
dcb445bc
MS
1422 if (job_id > 0)
1423 job = cupsdFindJob(job_id);
1424 else
1425 job = NULL;
1426
1427 if (job)
b9faaae1
MS
1428 {
1429 for (i = 0; job->filters[i]; i ++)
1430 if (job->filters[i] == pid)
1431 break;
1432
1433 if (job->filters[i] || job->backend == pid)
ef416fc2 1434 {
b9faaae1
MS
1435 /*
1436 * OK, this process has gone away; what's left?
1437 */
1438
1439 if (job->filters[i])
dcb445bc 1440 {
b9faaae1 1441 job->filters[i] = -pid;
dcb445bc
MS
1442 type = "Filter";
1443 }
b9faaae1 1444 else
dcb445bc 1445 {
b9faaae1 1446 job->backend = -pid;
dcb445bc
MS
1447 type = "Backend";
1448 }
ef416fc2 1449
b9faaae1 1450 if (status && status != SIGTERM && status != SIGKILL &&
f3c17241 1451 status != SIGPIPE)
ef416fc2 1452 {
1453 /*
b9faaae1
MS
1454 * An error occurred; save the exit status so we know to stop
1455 * the printer or cancel the job when all of the filters finish...
1456 *
1457 * A negative status indicates that the backend failed and the
1458 * printer needs to be stopped.
f3c17241
MS
1459 *
1460 * In order to preserve the most serious status, we always log
1461 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1462 * and SIGBUS) and prefer to log the backend exit status over a
1463 * filter's.
ef416fc2 1464 */
1465
f3c17241
MS
1466 int old_status = abs(job->status);
1467
1468 if (WIFSIGNALED(status) || /* This process crashed, or */
1469 !job->status || /* No process had a status, or */
1470 (!job->filters[i] && WIFEXITED(old_status)))
1471 { /* Backend and filter didn't crash */
1472 if (job->filters[i])
1473 job->status = status; /* Filter failed */
1474 else
1475 job->status = -status; /* Backend failed */
1476 }
ef416fc2 1477
f11a948a 1478 if (job->state_value == IPP_JOB_PROCESSING &&
dcb445bc
MS
1479 job->status_level > CUPSD_LOG_ERROR &&
1480 (job->filters[i] || !WIFEXITED(status)))
ef416fc2 1481 {
f11a948a
MS
1482 char message[1024]; /* New printer-state-message */
1483
1484
b9faaae1 1485 job->status_level = CUPSD_LOG_ERROR;
ef416fc2 1486
dcb445bc 1487 snprintf(message, sizeof(message), "%s failed", type);
f11a948a 1488
e07d4801
MS
1489 if (job->printer)
1490 {
f11a948a
MS
1491 strlcpy(job->printer->state_message, message,
1492 sizeof(job->printer->state_message));
e07d4801
MS
1493 }
1494
1495 if (!job->attrs)
1496 cupsdLoadJob(job);
e00b005a 1497
e07d4801 1498 if (!job->printer_message && job->attrs)
e00b005a 1499 {
b9faaae1
MS
1500 if ((job->printer_message =
1501 ippFindAttribute(job->attrs, "job-printer-state-message",
1502 IPP_TAG_TEXT)) == NULL)
1503 job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB,
1504 IPP_TAG_TEXT,
1505 "job-printer-state-message",
5a662dc0 1506 NULL, NULL);
e00b005a 1507 }
b9faaae1 1508
e07d4801 1509 if (job->printer_message)
5e6c3df7 1510 ippSetString(job->attrs, &job->printer_message, 0, message);
ef416fc2 1511 }
b9faaae1 1512 }
ef416fc2 1513
b9faaae1
MS
1514 /*
1515 * If this is not the last file in a job, see if all of the
1516 * filters are done, and if so move to the next file.
1517 */
ef416fc2 1518
5a4c3fcf
MS
1519 if (job->state_value >= IPP_JOB_CANCELED)
1520 {
1521 /*
1522 * Remove the job from the active list if there are no processes still
1523 * running for it...
1524 */
1525
1526 for (i = 0; job->filters[i] < 0; i++);
1527
1528 if (!job->filters[i] && job->backend <= 0)
1529 cupsArrayRemove(ActiveJobs, job);
1530 }
1531 else if (job->current_file < job->num_files && job->printer)
b9faaae1
MS
1532 {
1533 for (i = 0; job->filters[i] < 0; i ++);
ef416fc2 1534
82f97232
MS
1535 if (!job->filters[i] &&
1536 (!job->printer->pc || !job->printer->pc->single_file ||
1537 job->backend <= 0))
b9faaae1
MS
1538 {
1539 /*
1540 * Process the next file...
1541 */
ef416fc2 1542
b9faaae1 1543 cupsdContinueJob(job);
ef416fc2 1544 }
ef416fc2 1545 }
1546 }
b9faaae1 1547 }
3dfe78b3
MS
1548
1549 /*
745129be
MS
1550 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1551 * since they come when we kill/end a process...
3dfe78b3
MS
1552 */
1553
745129be
MS
1554 if (status == SIGTERM || status == SIGKILL)
1555 {
dcb445bc
MS
1556 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1557 "PID %d (%s) was terminated normally with signal %d.", pid,
1558 name, status);
745129be 1559 }
5a6b583a
MS
1560 else if (status == SIGPIPE)
1561 {
dcb445bc
MS
1562 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1563 "PID %d (%s) did not catch or ignore signal %d.", pid, name,
1564 status);
5a6b583a 1565 }
745129be 1566 else if (status)
3dfe78b3
MS
1567 {
1568 if (WIFEXITED(status))
88f9aafc
MS
1569 {
1570 int code = WEXITSTATUS(status); /* Exit code */
1571
1572 if (code > 100)
dcb445bc
MS
1573 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1574 "PID %d (%s) stopped with status %d (%s)", pid, name,
1575 code, strerror(code - 100));
88f9aafc 1576 else
dcb445bc
MS
1577 cupsdLogJob(job, CUPSD_LOG_DEBUG,
1578 "PID %d (%s) stopped with status %d.", pid, name, code);
88f9aafc 1579 }
3dfe78b3 1580 else
dcb445bc
MS
1581 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PID %d (%s) crashed on signal %d.",
1582 pid, name, WTERMSIG(status));
3dfe78b3
MS
1583
1584 if (LogLevel < CUPSD_LOG_DEBUG)
dcb445bc
MS
1585 cupsdLogJob(job, CUPSD_LOG_INFO,
1586 "Hint: Try setting the LogLevel to \"debug\" to find out "
1587 "more.");
3dfe78b3
MS
1588 }
1589 else
dcb445bc
MS
1590 cupsdLogJob(job, CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
1591 pid, name);
ef416fc2 1592 }
dfd5680b
MS
1593
1594 /*
1595 * If wait*() is interrupted by a signal, tell main() to call us again...
1596 */
1597
1598 if (pid < 0 && errno == EINTR)
1599 dead_children = 1;
ef416fc2 1600}
1601
1602
ef416fc2 1603/*
1604 * 'select_timeout()' - Calculate the select timeout value.
1605 *
1606 */
1607
1608static long /* O - Number of seconds */
bd7854cb 1609select_timeout(int fds) /* I - Number of descriptors returned */
ef416fc2 1610{
ef416fc2 1611 long timeout; /* Timeout for select */
1612 time_t now; /* Current time */
1613 cupsd_client_t *con; /* Client information */
ef416fc2 1614 cupsd_job_t *job; /* Job information */
e1bb4a6e 1615 cupsd_printer_t *printer; /* Printer information */
ef416fc2 1616 const char *why; /* Debugging aid */
1617
1618
82cc1f9a
MS
1619 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout: JobHistoryUpdate=%ld",
1620 (long)JobHistoryUpdate);
1621
ef416fc2 1622 /*
1623 * Check to see if any of the clients have pending data to be
1624 * processed; if so, the timeout should be 0...
1625 */
1626
bd7854cb 1627 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1628 con;
1629 con = (cupsd_client_t *)cupsArrayNext(Clients))
1720786e 1630 if (httpGetReady(con->http))
ef416fc2 1631 return (0);
1632
1633 /*
f7deaa1a 1634 * If select has been active in the last second (fds > 0) or we have
ef416fc2 1635 * many resources in use then don't bother trying to optimize the
1636 * timeout, just make it 1 second.
1637 */
1638
f7deaa1a 1639 if (fds > 0 || cupsArrayCount(Clients) > 50)
ef416fc2 1640 return (1);
1641
1642 /*
1643 * Otherwise, check all of the possible events that we need to wake for...
1644 */
1645
1646 now = time(NULL);
1647 timeout = now + 86400; /* 86400 == 1 day */
1648 why = "do nothing";
1649
e6013cfa
MS
1650#ifdef __APPLE__
1651 /*
b4974142 1652 * When going to sleep, wake up to abort jobs that don't complete in time.
e6013cfa
MS
1653 */
1654
1655 if (SleepJobs > 0 && SleepJobs < timeout)
1656 {
1657 timeout = SleepJobs;
b4974142 1658 why = "abort jobs before sleeping";
e6013cfa
MS
1659 }
1660#endif /* __APPLE__ */
1661
76cd9e37
MS
1662 /*
1663 * Check whether we are accepting new connections...
1664 */
1665
1666 if (ListeningPaused > 0 && cupsArrayCount(Clients) < MaxClients &&
1667 ListeningPaused < timeout)
1668 {
1669 if (ListeningPaused <= now)
1670 timeout = now;
1671 else
1672 timeout = ListeningPaused;
1673
1674 why = "resume listening";
1675 }
1676
ef416fc2 1677 /*
1678 * Check the activity and close old clients...
1679 */
1680
bd7854cb 1681 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1682 con;
1683 con = (cupsd_client_t *)cupsArrayNext(Clients))
1720786e 1684 if ((httpGetActivity(con->http) + Timeout) < timeout)
ef416fc2 1685 {
1720786e 1686 timeout = httpGetActivity(con->http) + Timeout;
ef416fc2 1687 why = "timeout a client connection";
1688 }
1689
3dfe78b3 1690 /*
bf3816c7 1691 * Write out changes to configuration and state files...
3dfe78b3
MS
1692 */
1693
1694 if (DirtyCleanTime && timeout > DirtyCleanTime)
1695 {
1696 timeout = DirtyCleanTime;
1697 why = "write dirty config/state files";
1698 }
1699
ef416fc2 1700 /*
82cc1f9a 1701 * Check for any job activity...
ef416fc2 1702 */
1703
82cc1f9a
MS
1704 if (JobHistoryUpdate && timeout > JobHistoryUpdate)
1705 {
1706 timeout = JobHistoryUpdate;
1707 why = "update job history";
1708 }
1709
238c3832
MS
1710 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1711 job;
1712 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
ef416fc2 1713 {
82cc1f9a
MS
1714 if (job->cancel_time && job->cancel_time < timeout)
1715 {
1716 timeout = job->cancel_time;
1717 why = "cancel stuck jobs";
1718 }
1719
238c3832
MS
1720 if (job->kill_time && job->kill_time < timeout)
1721 {
1722 timeout = job->kill_time;
1723 why = "kill unresponsive jobs";
1724 }
82cc1f9a
MS
1725
1726 if (job->state_value == IPP_JOB_HELD && job->hold_until < timeout)
238c3832
MS
1727 {
1728 timeout = job->hold_until;
1729 why = "release held jobs";
1730 }
82cc1f9a
MS
1731
1732 if (job->state_value == IPP_JOB_PENDING && timeout > (now + 10))
238c3832
MS
1733 {
1734 timeout = now + 10;
1735 why = "start pending jobs";
1736 break;
1737 }
ef416fc2 1738 }
1739
e1bb4a6e
MS
1740 /*
1741 * Check for temporary printers that need to be deleted...
1742 */
1743
1744 for (printer = (cupsd_printer_t *)cupsArrayFirst(Printers); printer; printer = (cupsd_printer_t *)cupsArrayNext(Printers))
1745 {
123cfe02 1746 if (printer->temporary && !printer->job && (!local_timeout || local_timeout > (printer->state_time + 60)))
e1bb4a6e
MS
1747 local_timeout = printer->state_time + 60;
1748 }
1749
123cfe02 1750 if (timeout > local_timeout && local_timeout)
e1bb4a6e
MS
1751 {
1752 timeout = local_timeout;
1753 why = "delete stale local printers";
1754 }
1755
ef416fc2 1756 /*
dcb445bc
MS
1757 * Adjust from absolute to relative time. We add 1 second to the timeout since
1758 * events occur after the timeout expires, and limit the timeout to 86400
1759 * seconds (1 day) to avoid select() timeout limits present on some operating
ef416fc2 1760 * systems...
1761 */
1762
1763 timeout = timeout - now + 1;
1764
1765 if (timeout < 1)
1766 timeout = 1;
1767 else if (timeout > 86400)
1768 timeout = 86400;
1769
1770 /*
1771 * Log and return the timeout value...
1772 */
1773
f7deaa1a 1774 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
1775 fds, timeout, why);
ef416fc2 1776
1777 return (timeout);
1778}
1779
1780
e6013cfa
MS
1781/*
1782 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1783 */
1784
1785static void
1786sigchld_handler(int sig) /* I - Signal number */
1787{
1788 (void)sig;
1789
1790 /*
1791 * Flag that we have dead children...
1792 */
1793
1794 dead_children = 1;
1795
1796 /*
1797 * Reset the signal handler as needed...
1798 */
1799
1800#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1801 signal(SIGCLD, sigchld_handler);
1802#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1803}
1804
1805
1806/*
1807 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1808 */
1809
1810static void
1811sighup_handler(int sig) /* I - Signal number */
1812{
1813 (void)sig;
1814
1815 NeedReload = RELOAD_ALL;
1816 ReloadTime = time(NULL);
1817
1818#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1819 signal(SIGHUP, sighup_handler);
1820#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1821}
1822
1823
1824/*
1825 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1826 */
1827
1828static void
1829sigterm_handler(int sig) /* I - Signal number */
1830{
1831 (void)sig; /* remove compiler warnings... */
1832
1833 /*
1834 * Flag that we should stop and return...
1835 */
1836
1837 stop_scheduler = 1;
1838}
1839
1840
1166bf58 1841#ifdef HAVE_ONDEMAND
26c14fa6 1842/*
1166bf58 1843 * 'service_add_listener()' - Bind an open fd as a Listener.
26c14fa6
BN
1844 */
1845
1846static void
1166bf58
MS
1847service_add_listener(int fd, /* I - Socket file descriptor */
1848 int idx) /* I - Listener number, for logging */
26c14fa6
BN
1849{
1850 cupsd_listener_t *lis; /* Listeners array */
1851 http_addr_t addr; /* Address variable */
1852 socklen_t addrlen; /* Length of address */
1853 char s[256]; /* String addresss */
1854
1166bf58 1855
26c14fa6
BN
1856 addrlen = sizeof(addr);
1857
1858 if (getsockname(fd, (struct sockaddr *)&addr, &addrlen))
1859 {
1166bf58 1860 cupsdLogMessage(CUPSD_LOG_ERROR, "service_add_listener: Unable to get local address for listener #%d: %s", idx + 1, strerror(errno));
26c14fa6
BN
1861 return;
1862 }
1863
1166bf58 1864 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_add_listener: Listener #%d at fd %d, \"%s\".", idx + 1, fd, httpAddrString(&addr, s, sizeof(s)));
26c14fa6 1865
1166bf58
MS
1866 /*
1867 * Try to match the on-demand socket address to one of the listeners...
1868 */
26c14fa6
BN
1869
1870 for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
1871 lis;
1872 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
1873 if (httpAddrEqual(&lis->address, &addr))
1874 break;
1875
1876 /*
1877 * Add a new listener If there's no match...
1878 */
1879
1880 if (lis)
1881 {
1166bf58 1882 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_add_listener: Matched existing listener #%d to %s.", idx + 1, httpAddrString(&(lis->address), s, sizeof(s)));
26c14fa6
BN
1883 }
1884 else
1885 {
1166bf58 1886 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_add_listener: Adding new listener #%d for %s.", idx + 1, httpAddrString(&addr, s, sizeof(s)));
26c14fa6
BN
1887
1888 if ((lis = calloc(1, sizeof(cupsd_listener_t))) == NULL)
1889 {
1166bf58 1890 cupsdLogMessage(CUPSD_LOG_ERROR, "service_add_listener: Unable to allocate listener: %s.", strerror(errno));
26c14fa6
BN
1891 exit(EXIT_FAILURE);
1892 return;
1893 }
1894
1895 cupsArrayAdd(Listeners, lis);
1896
1897 memcpy(&lis->address, &addr, sizeof(lis->address));
1898 }
1899
1900 lis->fd = fd;
1901 lis->on_demand = 1;
1902
1903# ifdef HAVE_SSL
1904 if (httpAddrPort(&(lis->address)) == 443)
1905 lis->encryption = HTTP_ENCRYPT_ALWAYS;
1906# endif /* HAVE_SSL */
1907}
03bc3ef4 1908#endif /* HAVE_ONDEMAND */
26c14fa6 1909
1166bf58 1910
1720786e
MS
1911/*
1912 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1913 */
1914
1915static void
1916service_checkin(void)
1917{
1720786e
MS
1918 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_checkin: pid=%d", (int)getpid());
1919
03bc3ef4
MS
1920#ifdef HAVE_LAUNCHD
1921 if (OnDemand)
1720786e 1922 {
03bc3ef4
MS
1923 int error; /* Check-in error, if any */
1924 size_t i, /* Looping var */
1925 count; /* Number of listeners */
1926 int *ld_sockets; /* Listener sockets */
1720786e 1927
03bc3ef4
MS
1928 /*
1929 * Check-in with launchd...
1930 */
117466cd 1931
03bc3ef4
MS
1932 if ((error = launch_activate_socket("Listeners", &ld_sockets, &count)) != 0)
1933 {
1934 cupsdLogMessage(CUPSD_LOG_ERROR, "service_checkin: Unable to get listener sockets: %s", strerror(error));
1935 exit(EXIT_FAILURE);
1936 return; /* anti-compiler-warning */
1937 }
1720786e 1938
03bc3ef4
MS
1939 /*
1940 * Try to match the launchd sockets to the cupsd listeners...
1941 */
1720786e 1942
03bc3ef4 1943 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_checkin: %d listeners.", (int)count);
1720786e 1944
03bc3ef4
MS
1945 for (i = 0; i < count; i ++)
1946 service_add_listener(ld_sockets[i], (int)i);
1720786e 1947
03bc3ef4 1948 free(ld_sockets);
1720786e
MS
1949 }
1950
03bc3ef4
MS
1951#elif defined(HAVE_SYSTEMD)
1952 if (OnDemand)
1953 {
1954 int i, /* Looping var */
1955 count; /* Number of listeners */
1720786e 1956
03bc3ef4
MS
1957 /*
1958 * Check-in with systemd...
1959 */
1720786e 1960
03bc3ef4
MS
1961 if ((count = sd_listen_fds(0)) < 0)
1962 {
1963 cupsdLogMessage(CUPSD_LOG_ERROR, "service_checkin: Unable to get listener sockets: %s", strerror(-count));
1964 exit(EXIT_FAILURE);
1965 return; /* anti-compiler-warning */
1966 }
1166bf58 1967
03bc3ef4
MS
1968 /*
1969 * Try to match the systemd sockets to the cupsd listeners...
1970 */
1720786e 1971
03bc3ef4 1972 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_checkin: %d listeners.", count);
1166bf58 1973
03bc3ef4
MS
1974 for (i = 0; i < count; i ++)
1975 service_add_listener(SD_LISTEN_FDS_START + i, i);
441de8b2 1976 }
1720786e 1977
03bc3ef4
MS
1978#elif defined(HAVE_UPSTART)
1979 if (OnDemand)
441de8b2 1980 {
03bc3ef4
MS
1981 const char *e; /* Environment var */
1982 int fd; /* File descriptor */
1720786e 1983
1720786e 1984
03bc3ef4
MS
1985 if (!(e = getenv("UPSTART_EVENTS")))
1986 {
1987 cupsdLogMessage(CUPSD_LOG_ERROR, "service_checkin: We did not get started via Upstart.");
1988 exit(EXIT_FAILURE);
1989 return;
1990 }
1720786e 1991
03bc3ef4
MS
1992 if (strcasecmp(e, "socket"))
1993 {
1994 cupsdLogMessage(CUPSD_LOG_ERROR, "service_checkin: We did not get triggered via an Upstart socket event.");
1995 exit(EXIT_FAILURE);
1996 return;
1997 }
1720786e 1998
03bc3ef4
MS
1999 if ((e = getenv("UPSTART_FDS")) == NULL)
2000 {
2001 cupsdLogMessage(CUPSD_LOG_ERROR, "service_checkin: Unable to get listener sockets from UPSTART_FDS.");
2002 exit(EXIT_FAILURE);
2003 return;
2004 }
1166bf58 2005
03bc3ef4 2006 cupsdLogMessage(CUPSD_LOG_DEBUG, "service_checkin: UPSTART_FDS=%s", e);
1720786e 2007
03bc3ef4
MS
2008 fd = (int)strtol(e, NULL, 10);
2009 if (fd < 0)
2010 {
2011 cupsdLogMessage(CUPSD_LOG_ERROR, "service_checkin: Could not parse UPSTART_FDS: %s", strerror(errno));
2012 exit(EXIT_FAILURE);
2013 return;
2014 }
2015
2016 /*
2017 * Upstart only supportst a single on-demand socket file descriptor...
2018 */
2019
2020 service_add_listener(fd, 0);
2021 }
2022#endif /* HAVE_LAUNCHD */
1720786e
MS
2023}
2024
2025
2026/*
03bc3ef4 2027 * 'service_checkout()' - Update the KeepAlive/PID file as needed.
1720786e
MS
2028 */
2029
2030static void
03bc3ef4 2031service_checkout(int shutdown) /* I - Shutting down? */
1720786e 2032{
e9b2d701
MS
2033 cups_file_t *fp; /* File */
2034 char pidfile[1024]; /* PID/KeepAlive file */
03bc3ef4
MS
2035
2036
2037 /*
2038 * When running on-demand, use the KeepAlive file, otherwise write a PID file
2039 * to StateDir...
2040 */
1720786e 2041
03bc3ef4
MS
2042#ifdef HAVE_ONDEMAND
2043 if (OnDemand)
e9b2d701 2044 {
03bc3ef4 2045 strlcpy(pidfile, CUPS_KEEPALIVE, sizeof(pidfile));
e9b2d701
MS
2046
2047 if (cupsArrayCount(ActiveJobs) || /* Active jobs */
2048 WebInterface || /* Web interface enabled */
2049 NeedReload || /* Doing a reload */
2050 (Browsing && BrowseLocalProtocols && cupsArrayCount(Printers)))
2051 /* Printers being shared */
2052 {
2053 /*
2054 * Create or remove the "keep-alive" file based on whether there are active
2055 * jobs or shared printers to advertise...
2056 */
2057
2058 shutdown = 0;
2059 }
2060 }
03bc3ef4
MS
2061 else
2062#endif /* HAVE_ONDEMAND */
2063 snprintf(pidfile, sizeof(pidfile), "%s/cupsd.pid", StateDir);
1720786e 2064
e9b2d701
MS
2065 if (shutdown)
2066 {
2067 cupsdLogMessage(CUPSD_LOG_DEBUG, "Removing KeepAlive/PID file \"%s\".", pidfile);
1720786e 2068
e9b2d701
MS
2069 unlink(pidfile);
2070 }
2071 else
1720786e 2072 {
03bc3ef4 2073 cupsdLogMessage(CUPSD_LOG_DEBUG, "Creating KeepAlive/PID file \"%s\".", pidfile);
1720786e 2074
03bc3ef4
MS
2075 if ((fp = cupsFileOpen(pidfile, "w")) != NULL)
2076 {
2077 /*
2078 * Save the PID in the file...
2079 */
2080
2081 cupsFilePrintf(fp, "%d\n", (int)getpid());
2082 cupsFileClose(fp);
2083 }
2084 else
2085 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to create KeepAlive/PID file \"%s\": %s", pidfile, strerror(errno));
1720786e 2086 }
1720786e 2087}
1720786e
MS
2088
2089
ef416fc2 2090/*
2091 * 'usage()' - Show scheduler usage.
2092 */
2093
2094static void
a4d04587 2095usage(int status) /* O - Exit status */
ef416fc2 2096{
0837b7e8
MS
2097 FILE *fp = status ? stderr : stdout; /* Output file */
2098
2099
2100 _cupsLangPuts(fp, _("Usage: cupsd [options]"));
2101 _cupsLangPuts(fp, _("Options:"));
f3c17241 2102 _cupsLangPuts(fp, _(" -c cupsd.conf Set cupsd.conf file to use."));
84315f46 2103 _cupsLangPuts(fp, _(" -f Run in the foreground."));
3b433010 2104 _cupsLangPuts(fp, _(" -F Run in the foreground but detach from console."));
84315f46 2105 _cupsLangPuts(fp, _(" -h Show this usage message."));
1166bf58 2106#ifdef HAVE_ONDEMAND
1720786e 2107 _cupsLangPuts(fp, _(" -l Run cupsd on demand."));
1166bf58 2108#endif /* HAVE_ONDEMAND */
3b433010
MS
2109 _cupsLangPuts(fp, _(" -s cups-files.conf Set cups-files.conf file to use."));
2110 _cupsLangPuts(fp, _(" -t Test the configuration file."));
0837b7e8 2111
a4d04587 2112 exit(status);
ef416fc2 2113}