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