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