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