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