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