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