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