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