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