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