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