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