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