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