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