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