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