]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/main.c
Merge changes from CUPS 1.6svn-r10112.
[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 &&
770 !cupsArrayCount(ActiveJobs) &&
771 (!Browsing || !BrowseLocalProtocols || !cupsArrayCount(Printers)))
772 {
773 timeout = LaunchdTimeout;
774 launchd_idle_exit = 1;
775 }
776 else
777 launchd_idle_exit = 0;
778 #endif /* HAVE_LAUNCHD */
779
780 if ((fds = cupsdDoSelect(timeout)) < 0)
781 {
782 /*
783 * Got an error from select!
784 */
785
786 #ifdef HAVE_DNSSD
787 cupsd_printer_t *p; /* Current printer */
788 #endif /* HAVE_DNSSD */
789
790
791 if (errno == EINTR) /* Just interrupted by a signal */
792 continue;
793
794 /*
795 * Log all sorts of debug info to help track down the problem.
796 */
797
798 cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
799 strerror(errno));
800
801 for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
802 con;
803 i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
804 cupsdLogMessage(CUPSD_LOG_EMERG,
805 "Clients[%d] = %d, file = %d, state = %d",
806 i, con->http.fd, con->file, con->http.state);
807
808 for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
809 lis;
810 i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
811 cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
812
813 cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);
814
815 #ifdef __APPLE__
816 cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
817 SysEventPipes[0]);
818 #endif /* __APPLE__ */
819
820 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
821 job;
822 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
823 cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
824 job->id,
825 job->status_buffer ? job->status_buffer->fd : -1,
826 job->print_pipes[0], job->print_pipes[1],
827 job->back_pipes[0], job->back_pipes[1]);
828
829 #ifdef HAVE_DNSSD
830 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
831 p;
832 p = (cupsd_printer_t *)cupsArrayNext(Printers))
833 cupsdLogMessage(CUPSD_LOG_EMERG, "printer[%s] reg_name=\"%s\"", p->name,
834 p->reg_name ? p->reg_name : "(null)");
835 #endif /* HAVE_DNSSD */
836
837 break;
838 }
839
840 current_time = time(NULL);
841
842 /*
843 * Write dirty config/state files...
844 */
845
846 if (DirtyCleanTime && current_time >= DirtyCleanTime)
847 cupsdCleanDirty();
848
849 #ifdef __APPLE__
850 /*
851 * If we are going to sleep and still have pending jobs, stop them after
852 * a period of time...
853 */
854
855 if (SleepJobs > 0 && current_time >= SleepJobs &&
856 cupsArrayCount(PrintingJobs) > 0)
857 {
858 SleepJobs = 0;
859 cupsdStopAllJobs(CUPSD_JOB_DEFAULT, 5);
860 }
861 #endif /* __APPLE__ */
862
863 #ifndef __APPLE__
864 /*
865 * Update the network interfaces once a minute...
866 */
867
868 if ((current_time - netif_time) >= 60)
869 {
870 netif_time = current_time;
871 NetIFUpdate = 1;
872 }
873 #endif /* !__APPLE__ */
874
875 #if HAVE_LAUNCHD
876 /*
877 * If no other work was scheduled and we're being controlled by launchd
878 * then timeout after 'LaunchdTimeout' seconds of inactivity...
879 */
880
881 if (!fds && launchd_idle_exit)
882 {
883 cupsdLogMessage(CUPSD_LOG_INFO,
884 "Printer sharing is off and there are no jobs pending, "
885 "will restart on demand.");
886 stop_scheduler = 1;
887 break;
888 }
889 #endif /* HAVE_LAUNCHD */
890
891 /*
892 * Resume listening for new connections as needed...
893 */
894
895 if (ListeningPaused && ListeningPaused <= current_time &&
896 cupsArrayCount(Clients) < MaxClients)
897 cupsdResumeListening();
898
899 /*
900 * Expire subscriptions and unload completed jobs as needed...
901 */
902
903 if (current_time > expire_time)
904 {
905 if (cupsArrayCount(Subscriptions) > 0)
906 cupsdExpireSubscriptions(NULL, NULL);
907
908 cupsdUnloadCompletedJobs();
909
910 expire_time = current_time;
911 }
912
913 #ifndef HAVE_AUTHORIZATION_H
914 /*
915 * Update the root certificate once every 5 minutes if we have client
916 * connections...
917 */
918
919 if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
920 !RunUser && cupsArrayCount(Clients))
921 {
922 /*
923 * Update the root certificate...
924 */
925
926 cupsdDeleteCert(0);
927 cupsdAddCert(0, "root", NULL);
928 }
929 #endif /* !HAVE_AUTHORIZATION_H */
930
931 /*
932 * Check for new data on the client sockets...
933 */
934
935 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
936 con;
937 con = (cupsd_client_t *)cupsArrayNext(Clients))
938 {
939 /*
940 * Process pending data in the input buffer...
941 */
942
943 if (con->http.used)
944 {
945 cupsdReadClient(con);
946 continue;
947 }
948
949 /*
950 * Check the activity and close old clients...
951 */
952
953 activity = current_time - Timeout;
954 if (con->http.activity < activity && !con->pipe_pid)
955 {
956 cupsdLogMessage(CUPSD_LOG_DEBUG,
957 "Closing client %d after %d seconds of inactivity...",
958 con->http.fd, Timeout);
959
960 cupsdCloseClient(con);
961 continue;
962 }
963 }
964
965 /*
966 * Update any pending multi-file documents...
967 */
968
969 if ((current_time - senddoc_time) >= 10)
970 {
971 cupsdCheckJobs();
972 cupsdCleanJobs();
973 senddoc_time = current_time;
974 }
975
976 /*
977 * Log statistics at most once a minute when in debug mode...
978 */
979
980 if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
981 {
982 size_t string_count, /* String count */
983 alloc_bytes, /* Allocated string bytes */
984 total_bytes; /* Total string bytes */
985 #ifdef HAVE_MALLINFO
986 struct mallinfo mem; /* Malloc information */
987
988
989 mem = mallinfo();
990 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
991 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
992 mem.usmblks + mem.uordblks);
993 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
994 mem.fsmblks + mem.fordblks);
995 #endif /* HAVE_MALLINFO */
996
997 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
998 cupsArrayCount(Clients));
999 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
1000 cupsArrayCount(Jobs));
1001 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
1002 cupsArrayCount(ActiveJobs));
1003 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
1004 cupsArrayCount(Printers));
1005
1006 string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
1007 cupsdLogMessage(CUPSD_LOG_DEBUG,
1008 "Report: stringpool-string-count=" CUPS_LLFMT,
1009 CUPS_LLCAST string_count);
1010 cupsdLogMessage(CUPSD_LOG_DEBUG,
1011 "Report: stringpool-alloc-bytes=" CUPS_LLFMT,
1012 CUPS_LLCAST alloc_bytes);
1013 cupsdLogMessage(CUPSD_LOG_DEBUG,
1014 "Report: stringpool-total-bytes=" CUPS_LLFMT,
1015 CUPS_LLCAST total_bytes);
1016
1017 report_time = current_time;
1018 }
1019
1020 /*
1021 * Handle OS-specific event notification for any events that have
1022 * accumulated. Don't send these more than once a second...
1023 */
1024
1025 if (LastEvent && (current_time - event_time) >= 1)
1026 {
1027 #ifdef HAVE_NOTIFY_POST
1028 if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
1029 CUPSD_EVENT_PRINTER_DELETED |
1030 CUPSD_EVENT_PRINTER_MODIFIED))
1031 {
1032 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1033 "notify_post(\"com.apple.printerListChange\")");
1034 notify_post("com.apple.printerListChange");
1035 }
1036
1037 if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
1038 {
1039 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1040 "notify_post(\"com.apple.printerHistoryChange\")");
1041 notify_post("com.apple.printerHistoryChange");
1042 }
1043
1044 if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
1045 CUPSD_EVENT_JOB_CONFIG_CHANGED |
1046 CUPSD_EVENT_JOB_PROGRESS))
1047 {
1048 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1049 "notify_post(\"com.apple.jobChange\")");
1050 notify_post("com.apple.jobChange");
1051 }
1052 #endif /* HAVE_NOTIFY_POST */
1053
1054 /*
1055 * Reset the accumulated events...
1056 */
1057
1058 LastEvent = CUPSD_EVENT_NONE;
1059 event_time = current_time;
1060 }
1061 }
1062
1063 /*
1064 * Log a message based on what happened...
1065 */
1066
1067 if (stop_scheduler)
1068 {
1069 cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
1070 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1071 "Scheduler shutting down normally.");
1072 }
1073 else
1074 {
1075 cupsdLogMessage(CUPSD_LOG_ERROR,
1076 "Scheduler shutting down due to program error.");
1077 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1078 "Scheduler shutting down due to program error.");
1079 }
1080
1081 /*
1082 * Close all network clients...
1083 */
1084
1085 DoingShutdown = 1;
1086
1087 cupsdStopServer();
1088
1089 #ifdef HAVE_LAUNCHD
1090 /*
1091 * Update the launchd KeepAlive file as needed...
1092 */
1093
1094 if (Launchd)
1095 launchd_checkout();
1096 #endif /* HAVE_LAUNCHD */
1097
1098 /*
1099 * Stop all jobs...
1100 */
1101
1102 cupsdFreeAllJobs();
1103
1104 #ifdef __APPLE__
1105 /*
1106 * Stop monitoring system event monitoring...
1107 */
1108
1109 if (use_sysman)
1110 cupsdStopSystemMonitor();
1111 #endif /* __APPLE__ */
1112
1113 #ifdef HAVE_GSSAPI
1114 /*
1115 * Free the scheduler's Kerberos context...
1116 */
1117
1118 # ifdef __APPLE__
1119 /*
1120 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1121 * to use it...
1122 */
1123
1124 if (krb5_init_context != NULL)
1125 # endif /* __APPLE__ */
1126 if (KerberosContext)
1127 krb5_free_context(KerberosContext);
1128 #endif /* HAVE_GSSAPI */
1129
1130 #ifdef __sgi
1131 /*
1132 * Remove the fake IRIX lpsched lock file, but only if the existing
1133 * file is not a FIFO which indicates that the real IRIX lpsched is
1134 * running...
1135 */
1136
1137 if (!stat("/var/spool/lp/FIFO", &statbuf))
1138 if (!S_ISFIFO(statbuf.st_mode))
1139 unlink("/var/spool/lp/SCHEDLOCK");
1140 #endif /* __sgi */
1141
1142 cupsdStopSelect();
1143
1144 return (!stop_scheduler);
1145 }
1146
1147
1148 /*
1149 * 'cupsdAddString()' - Copy and add a string to an array.
1150 */
1151
1152 int /* O - 1 on success, 0 on failure */
1153 cupsdAddString(cups_array_t **a, /* IO - String array */
1154 const char *s) /* I - String to copy and add */
1155 {
1156 if (!*a)
1157 *a = cupsArrayNew3((cups_array_func_t)strcmp, NULL,
1158 (cups_ahash_func_t)NULL, 0,
1159 (cups_acopy_func_t)_cupsStrAlloc,
1160 (cups_afree_func_t)_cupsStrFree);
1161
1162 return (cupsArrayAdd(*a, (char *)s));
1163 }
1164
1165
1166 /*
1167 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1168 */
1169
1170 void
1171 cupsdCheckProcess(void)
1172 {
1173 /*
1174 * Flag that we have dead children...
1175 */
1176
1177 dead_children = 1;
1178 }
1179
1180
1181 /*
1182 * 'cupsdClearString()' - Clear a string.
1183 */
1184
1185 void
1186 cupsdClearString(char **s) /* O - String value */
1187 {
1188 if (s && *s)
1189 {
1190 _cupsStrFree(*s);
1191 *s = NULL;
1192 }
1193 }
1194
1195
1196 /*
1197 * 'cupsdFreeStrings()' - Free an array of strings.
1198 */
1199
1200 void
1201 cupsdFreeStrings(cups_array_t **a) /* IO - String array */
1202 {
1203 if (*a)
1204 {
1205 cupsArrayDelete(*a);
1206 *a = NULL;
1207 }
1208 }
1209
1210
1211 /*
1212 * 'cupsdHoldSignals()' - Hold child and termination signals.
1213 */
1214
1215 void
1216 cupsdHoldSignals(void)
1217 {
1218 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1219 sigset_t newmask; /* New POSIX signal mask */
1220 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1221
1222
1223 holdcount ++;
1224 if (holdcount > 1)
1225 return;
1226
1227 #ifdef HAVE_SIGSET
1228 sighold(SIGTERM);
1229 sighold(SIGCHLD);
1230 #elif defined(HAVE_SIGACTION)
1231 sigemptyset(&newmask);
1232 sigaddset(&newmask, SIGTERM);
1233 sigaddset(&newmask, SIGCHLD);
1234 sigprocmask(SIG_BLOCK, &newmask, &holdmask);
1235 #endif /* HAVE_SIGSET */
1236 }
1237
1238
1239 /*
1240 * 'cupsdReleaseSignals()' - Release signals for delivery.
1241 */
1242
1243 void
1244 cupsdReleaseSignals(void)
1245 {
1246 holdcount --;
1247 if (holdcount > 0)
1248 return;
1249
1250 #ifdef HAVE_SIGSET
1251 sigrelse(SIGTERM);
1252 sigrelse(SIGCHLD);
1253 #elif defined(HAVE_SIGACTION)
1254 sigprocmask(SIG_SETMASK, &holdmask, NULL);
1255 #endif /* HAVE_SIGSET */
1256 }
1257
1258
1259 /*
1260 * 'cupsdSetString()' - Set a string value.
1261 */
1262
1263 void
1264 cupsdSetString(char **s, /* O - New string */
1265 const char *v) /* I - String value */
1266 {
1267 if (!s || *s == v)
1268 return;
1269
1270 if (*s)
1271 _cupsStrFree(*s);
1272
1273 if (v)
1274 *s = _cupsStrAlloc(v);
1275 else
1276 *s = NULL;
1277 }
1278
1279
1280 /*
1281 * 'cupsdSetStringf()' - Set a formatted string value.
1282 */
1283
1284 void
1285 cupsdSetStringf(char **s, /* O - New string */
1286 const char *f, /* I - Printf-style format string */
1287 ...) /* I - Additional args as needed */
1288 {
1289 char v[4096]; /* Formatting string value */
1290 va_list ap; /* Argument pointer */
1291 char *olds; /* Old string */
1292
1293
1294 if (!s)
1295 return;
1296
1297 olds = *s;
1298
1299 if (f)
1300 {
1301 va_start(ap, f);
1302 vsnprintf(v, sizeof(v), f, ap);
1303 va_end(ap);
1304
1305 *s = _cupsStrAlloc(v);
1306 }
1307 else
1308 *s = NULL;
1309
1310 if (olds)
1311 _cupsStrFree(olds);
1312 }
1313
1314
1315 #ifdef HAVE_LAUNCHD
1316 /*
1317 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1318 */
1319
1320 static void
1321 launchd_checkin(void)
1322 {
1323 size_t i, /* Looping var */
1324 count; /* Number of listeners */
1325 launch_data_t ld_msg, /* Launch data message */
1326 ld_resp, /* Launch data response */
1327 ld_array, /* Launch data array */
1328 ld_sockets, /* Launch data sockets dictionary */
1329 tmp; /* Launch data */
1330 cupsd_listener_t *lis; /* Listeners array */
1331 http_addr_t addr; /* Address variable */
1332 socklen_t addrlen; /* Length of address */
1333 int fd; /* File descriptor */
1334 char s[256]; /* String addresss */
1335
1336
1337 cupsdLogMessage(CUPSD_LOG_DEBUG, "launchd_checkin: pid=%d", (int)getpid());
1338
1339 /*
1340 * Check-in with launchd...
1341 */
1342
1343 ld_msg = launch_data_new_string(LAUNCH_KEY_CHECKIN);
1344 if ((ld_resp = launch_msg(ld_msg)) == NULL)
1345 {
1346 cupsdLogMessage(CUPSD_LOG_ERROR,
1347 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1348 "\") IPC failure");
1349 exit(EXIT_FAILURE);
1350 return; /* anti-compiler-warning */
1351 }
1352
1353 if (launch_data_get_type(ld_resp) == LAUNCH_DATA_ERRNO)
1354 {
1355 errno = launch_data_get_errno(ld_resp);
1356 cupsdLogMessage(CUPSD_LOG_ERROR, "launchd_checkin: Check-in failed: %s",
1357 strerror(errno));
1358 exit(EXIT_FAILURE);
1359 return; /* anti-compiler-warning */
1360 }
1361
1362 /*
1363 * Get the sockets dictionary...
1364 */
1365
1366 if ((ld_sockets = launch_data_dict_lookup(ld_resp, LAUNCH_JOBKEY_SOCKETS))
1367 == NULL)
1368 {
1369 cupsdLogMessage(CUPSD_LOG_ERROR,
1370 "launchd_checkin: No sockets found to answer requests on!");
1371 exit(EXIT_FAILURE);
1372 return; /* anti-compiler-warning */
1373 }
1374
1375 /*
1376 * Get the array of listener sockets...
1377 */
1378
1379 if ((ld_array = launch_data_dict_lookup(ld_sockets, "Listeners")) == 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 * Add listening fd(s) to the Listener array...
1389 */
1390
1391 if (launch_data_get_type(ld_array) == LAUNCH_DATA_ARRAY)
1392 {
1393 count = launch_data_array_get_count(ld_array);
1394
1395 for (i = 0; i < count; i ++)
1396 {
1397 /*
1398 * Get the launchd file descriptor and address...
1399 */
1400
1401 if ((tmp = launch_data_array_get_index(ld_array, i)) != NULL)
1402 {
1403 fd = launch_data_get_fd(tmp);
1404 addrlen = sizeof(addr);
1405
1406 if (getsockname(fd, (struct sockaddr *)&addr, &addrlen))
1407 {
1408 cupsdLogMessage(CUPSD_LOG_ERROR,
1409 "launchd_checkin: Unable to get local address - %s",
1410 strerror(errno));
1411 continue;
1412 }
1413
1414 /*
1415 * Try to match the launchd socket address to one of the listeners...
1416 */
1417
1418 for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
1419 lis;
1420 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
1421 if (httpAddrEqual(&lis->address, &addr))
1422 break;
1423
1424 /*
1425 * Add a new listener If there's no match...
1426 */
1427
1428 if (lis)
1429 {
1430 cupsdLogMessage(CUPSD_LOG_DEBUG,
1431 "launchd_checkin: Matched existing listener %s with fd %d...",
1432 httpAddrString(&(lis->address), s, sizeof(s)), fd);
1433 }
1434 else
1435 {
1436 cupsdLogMessage(CUPSD_LOG_DEBUG,
1437 "launchd_checkin: Adding new listener %s with fd %d...",
1438 httpAddrString(&addr, s, sizeof(s)), fd);
1439
1440 if ((lis = calloc(1, sizeof(cupsd_listener_t))) == NULL)
1441 {
1442 cupsdLogMessage(CUPSD_LOG_ERROR,
1443 "launchd_checkin: Unable to allocate listener - "
1444 "%s.", strerror(errno));
1445 exit(EXIT_FAILURE);
1446 }
1447
1448 cupsArrayAdd(Listeners, lis);
1449
1450 memcpy(&lis->address, &addr, sizeof(lis->address));
1451 }
1452
1453 lis->fd = fd;
1454
1455 # ifdef HAVE_SSL
1456 if (_httpAddrPort(&(lis->address)) == 443)
1457 lis->encryption = HTTP_ENCRYPT_ALWAYS;
1458 # endif /* HAVE_SSL */
1459 }
1460 }
1461 }
1462
1463 launch_data_free(ld_msg);
1464 launch_data_free(ld_resp);
1465 }
1466
1467
1468 /*
1469 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1470 */
1471
1472 static void
1473 launchd_checkout(void)
1474 {
1475 int fd; /* File descriptor */
1476
1477
1478 /*
1479 * Create or remove the launchd KeepAlive file based on whether
1480 * there are active jobs, polling, browsing for remote printers or
1481 * shared printers to advertise...
1482 */
1483
1484 if (cupsArrayCount(ActiveJobs) ||
1485 (Browsing && BrowseLocalProtocols && cupsArrayCount(Printers)))
1486 {
1487 cupsdLogMessage(CUPSD_LOG_DEBUG,
1488 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1489 "\"...");
1490
1491 if ((fd = open(CUPS_KEEPALIVE, O_RDONLY | O_CREAT | O_EXCL, S_IRUSR)) >= 0)
1492 close(fd);
1493 }
1494 else
1495 {
1496 cupsdLogMessage(CUPSD_LOG_DEBUG,
1497 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1498 "\"...");
1499
1500 unlink(CUPS_KEEPALIVE);
1501 }
1502 }
1503 #endif /* HAVE_LAUNCHD */
1504
1505
1506 /*
1507 * 'parent_handler()' - Catch USR1/CHLD signals...
1508 */
1509
1510 static void
1511 parent_handler(int sig) /* I - Signal */
1512 {
1513 /*
1514 * Store the signal we got from the OS and return...
1515 */
1516
1517 parent_signal = sig;
1518 }
1519
1520
1521 /*
1522 * 'process_children()' - Process all dead children...
1523 */
1524
1525 static void
1526 process_children(void)
1527 {
1528 int status; /* Exit status of child */
1529 int pid, /* Process ID of child */
1530 job_id; /* Job ID of child */
1531 cupsd_job_t *job; /* Current job */
1532 int i; /* Looping var */
1533 char name[1024]; /* Process name */
1534
1535
1536 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1537
1538 /*
1539 * Reset the dead_children flag...
1540 */
1541
1542 dead_children = 0;
1543
1544 /*
1545 * Collect the exit status of some children...
1546 */
1547
1548 #ifdef HAVE_WAITPID
1549 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1550 #elif defined(HAVE_WAIT3)
1551 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1552 #else
1553 if ((pid = wait(&status)) > 0)
1554 #endif /* HAVE_WAITPID */
1555 {
1556 /*
1557 * Collect the name of the process that finished...
1558 */
1559
1560 cupsdFinishProcess(pid, name, sizeof(name), &job_id);
1561
1562 /*
1563 * Delete certificates for CGI processes...
1564 */
1565
1566 if (pid)
1567 cupsdDeleteCert(pid);
1568
1569 /*
1570 * Handle completed job filters...
1571 */
1572
1573 if (job_id > 0 && (job = cupsdFindJob(job_id)) != NULL)
1574 {
1575 for (i = 0; job->filters[i]; i ++)
1576 if (job->filters[i] == pid)
1577 break;
1578
1579 if (job->filters[i] || job->backend == pid)
1580 {
1581 /*
1582 * OK, this process has gone away; what's left?
1583 */
1584
1585 if (job->filters[i])
1586 job->filters[i] = -pid;
1587 else
1588 job->backend = -pid;
1589
1590 if (status && status != SIGTERM && status != SIGKILL &&
1591 status != SIGPIPE && job->status >= 0)
1592 {
1593 /*
1594 * An error occurred; save the exit status so we know to stop
1595 * the printer or cancel the job when all of the filters finish...
1596 *
1597 * A negative status indicates that the backend failed and the
1598 * printer needs to be stopped.
1599 */
1600
1601 if (job->filters[i])
1602 job->status = status; /* Filter failed */
1603 else
1604 job->status = -status; /* Backend failed */
1605
1606 if (job->state_value == IPP_JOB_PROCESSING &&
1607 job->status_level > CUPSD_LOG_ERROR)
1608 {
1609 char message[1024]; /* New printer-state-message */
1610
1611
1612 job->status_level = CUPSD_LOG_ERROR;
1613
1614 snprintf(message, sizeof(message), "%s failed", name);
1615
1616 if (job->printer)
1617 {
1618 strlcpy(job->printer->state_message, message,
1619 sizeof(job->printer->state_message));
1620 }
1621
1622 if (!job->attrs)
1623 cupsdLoadJob(job);
1624
1625 if (!job->printer_message && job->attrs)
1626 {
1627 if ((job->printer_message =
1628 ippFindAttribute(job->attrs, "job-printer-state-message",
1629 IPP_TAG_TEXT)) == NULL)
1630 job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB,
1631 IPP_TAG_TEXT,
1632 "job-printer-state-message",
1633 NULL, NULL);
1634 }
1635
1636 if (job->printer_message)
1637 cupsdSetString(&(job->printer_message->values[0].string.text),
1638 message);
1639 }
1640 }
1641
1642 /*
1643 * If this is not the last file in a job, see if all of the
1644 * filters are done, and if so move to the next file.
1645 */
1646
1647 if (job->current_file < job->num_files && job->printer)
1648 {
1649 for (i = 0; job->filters[i] < 0; i ++);
1650
1651 if (!job->filters[i] &&
1652 (!job->printer->pc || !job->printer->pc->single_file ||
1653 job->backend <= 0))
1654 {
1655 /*
1656 * Process the next file...
1657 */
1658
1659 cupsdContinueJob(job);
1660 }
1661 }
1662 else if (job->state_value >= IPP_JOB_CANCELED)
1663 {
1664 /*
1665 * Remove the job from the active list if there are no processes still
1666 * running for it...
1667 */
1668
1669 for (i = 0; job->filters[i] < 0; i++);
1670
1671 if (!job->filters[i] && job->backend <= 0)
1672 cupsArrayRemove(ActiveJobs, job);
1673 }
1674 }
1675 }
1676
1677 /*
1678 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1679 * since they come when we kill/end a process...
1680 */
1681
1682 if (status == SIGTERM || status == SIGKILL)
1683 {
1684 cupsdLogMessage(CUPSD_LOG_DEBUG,
1685 "PID %d (%s) was terminated normally with signal %d.",
1686 pid, name, status);
1687 }
1688 else if (status == SIGPIPE)
1689 {
1690 cupsdLogMessage(CUPSD_LOG_DEBUG,
1691 "PID %d (%s) did not catch or ignore signal %d.",
1692 pid, name, status);
1693 }
1694 else if (status)
1695 {
1696 if (WIFEXITED(status))
1697 {
1698 int code = WEXITSTATUS(status); /* Exit code */
1699
1700 if (code > 100)
1701 cupsdLogMessage(CUPSD_LOG_DEBUG,
1702 "PID %d (%s) stopped with status %d (%s)", pid, name,
1703 code, strerror(code - 100));
1704 else
1705 cupsdLogMessage(CUPSD_LOG_DEBUG,
1706 "PID %d (%s) stopped with status %d.", pid, name,
1707 code);
1708 }
1709 else
1710 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) crashed on signal %d.",
1711 pid, name, WTERMSIG(status));
1712
1713 if (LogLevel < CUPSD_LOG_DEBUG)
1714 cupsdLogMessage(CUPSD_LOG_INFO,
1715 "Hint: Try setting the LogLevel to \"debug\" to find "
1716 "out more.");
1717 }
1718 else
1719 cupsdLogMessage(CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
1720 pid, name);
1721 }
1722
1723 /*
1724 * If wait*() is interrupted by a signal, tell main() to call us again...
1725 */
1726
1727 if (pid < 0 && errno == EINTR)
1728 dead_children = 1;
1729 }
1730
1731
1732 /*
1733 * 'select_timeout()' - Calculate the select timeout value.
1734 *
1735 */
1736
1737 static long /* O - Number of seconds */
1738 select_timeout(int fds) /* I - Number of descriptors returned */
1739 {
1740 long timeout; /* Timeout for select */
1741 time_t now; /* Current time */
1742 cupsd_client_t *con; /* Client information */
1743 cupsd_job_t *job; /* Job information */
1744 cupsd_subscription_t *sub; /* Subscription information */
1745 const char *why; /* Debugging aid */
1746
1747
1748 /*
1749 * Check to see if any of the clients have pending data to be
1750 * processed; if so, the timeout should be 0...
1751 */
1752
1753 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1754 con;
1755 con = (cupsd_client_t *)cupsArrayNext(Clients))
1756 if (con->http.used > 0)
1757 return (0);
1758
1759 /*
1760 * If select has been active in the last second (fds > 0) or we have
1761 * many resources in use then don't bother trying to optimize the
1762 * timeout, just make it 1 second.
1763 */
1764
1765 if (fds > 0 || cupsArrayCount(Clients) > 50)
1766 return (1);
1767
1768 /*
1769 * Otherwise, check all of the possible events that we need to wake for...
1770 */
1771
1772 now = time(NULL);
1773 timeout = now + 86400; /* 86400 == 1 day */
1774 why = "do nothing";
1775
1776 #ifdef __APPLE__
1777 /*
1778 * When going to sleep, wake up to cancel jobs that don't complete in time.
1779 */
1780
1781 if (SleepJobs > 0 && SleepJobs < timeout)
1782 {
1783 timeout = SleepJobs;
1784 why = "cancel jobs before sleeping";
1785 }
1786 #endif /* __APPLE__ */
1787
1788 /*
1789 * Check whether we are accepting new connections...
1790 */
1791
1792 if (ListeningPaused > 0 && cupsArrayCount(Clients) < MaxClients &&
1793 ListeningPaused < timeout)
1794 {
1795 if (ListeningPaused <= now)
1796 timeout = now;
1797 else
1798 timeout = ListeningPaused;
1799
1800 why = "resume listening";
1801 }
1802
1803 /*
1804 * Check the activity and close old clients...
1805 */
1806
1807 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1808 con;
1809 con = (cupsd_client_t *)cupsArrayNext(Clients))
1810 if ((con->http.activity + Timeout) < timeout)
1811 {
1812 timeout = con->http.activity + Timeout;
1813 why = "timeout a client connection";
1814 }
1815
1816 /*
1817 * Write out changes to configuration and state files...
1818 */
1819
1820 if (DirtyCleanTime && timeout > DirtyCleanTime)
1821 {
1822 timeout = DirtyCleanTime;
1823 why = "write dirty config/state files";
1824 }
1825
1826 /*
1827 * Check for any active jobs...
1828 */
1829
1830 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1831 job;
1832 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1833 {
1834 if (job->kill_time && job->kill_time < timeout)
1835 {
1836 timeout = job->kill_time;
1837 why = "kill unresponsive jobs";
1838 }
1839
1840 if (job->state_value == IPP_JOB_HELD && job->hold_until < timeout)
1841 {
1842 timeout = job->hold_until;
1843 why = "release held jobs";
1844 }
1845 else if (job->state_value == IPP_JOB_PENDING && timeout > (now + 10))
1846 {
1847 timeout = now + 10;
1848 why = "start pending jobs";
1849 break;
1850 }
1851 }
1852
1853 #ifdef HAVE_MALLINFO
1854 /*
1855 * Log memory usage every minute...
1856 */
1857
1858 if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
1859 {
1860 timeout = mallinfo_time + 60;
1861 why = "display memory usage";
1862 }
1863 #endif /* HAVE_MALLINFO */
1864
1865 /*
1866 * Expire subscriptions as needed...
1867 */
1868
1869 for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
1870 sub;
1871 sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
1872 if (!sub->job && sub->expire && sub->expire < timeout)
1873 {
1874 timeout = sub->expire;
1875 why = "expire subscription";
1876 }
1877
1878 /*
1879 * Adjust from absolute to relative time. If p->browse_time above
1880 * was 0 then we can end up with a negative value here, so check.
1881 * We add 1 second to the timeout since events occur after the
1882 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1883 * to avoid select() timeout limits present on some operating
1884 * systems...
1885 */
1886
1887 timeout = timeout - now + 1;
1888
1889 if (timeout < 1)
1890 timeout = 1;
1891 else if (timeout > 86400)
1892 timeout = 86400;
1893
1894 /*
1895 * Log and return the timeout value...
1896 */
1897
1898 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
1899 fds, timeout, why);
1900
1901 return (timeout);
1902 }
1903
1904
1905 /*
1906 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1907 */
1908
1909 static void
1910 sigchld_handler(int sig) /* I - Signal number */
1911 {
1912 (void)sig;
1913
1914 /*
1915 * Flag that we have dead children...
1916 */
1917
1918 dead_children = 1;
1919
1920 /*
1921 * Reset the signal handler as needed...
1922 */
1923
1924 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1925 signal(SIGCLD, sigchld_handler);
1926 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1927 }
1928
1929
1930 /*
1931 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1932 */
1933
1934 static void
1935 sighup_handler(int sig) /* I - Signal number */
1936 {
1937 (void)sig;
1938
1939 NeedReload = RELOAD_ALL;
1940 ReloadTime = time(NULL);
1941
1942 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1943 signal(SIGHUP, sighup_handler);
1944 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1945 }
1946
1947
1948 /*
1949 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1950 */
1951
1952 static void
1953 sigterm_handler(int sig) /* I - Signal number */
1954 {
1955 (void)sig; /* remove compiler warnings... */
1956
1957 /*
1958 * Flag that we should stop and return...
1959 */
1960
1961 stop_scheduler = 1;
1962 }
1963
1964
1965 /*
1966 * 'usage()' - Show scheduler usage.
1967 */
1968
1969 static void
1970 usage(int status) /* O - Exit status */
1971 {
1972 FILE *fp = status ? stderr : stdout; /* Output file */
1973
1974
1975 _cupsLangPuts(fp, _("Usage: cupsd [options]"));
1976 _cupsLangPuts(fp, _("Options:"));
1977 _cupsLangPuts(fp, _(" -c config-file Load alternate configuration "
1978 "file."));
1979 _cupsLangPuts(fp, _(" -f Run in the foreground."));
1980 _cupsLangPuts(fp, _(" -F Run in the foreground but "
1981 "detach from console."));
1982 _cupsLangPuts(fp, _(" -h Show this usage message."));
1983 _cupsLangPuts(fp, _(" -l Run cupsd from launchd(8)."));
1984 _cupsLangPuts(fp, _(" -t Test the configuration "
1985 "file."));
1986
1987 exit(status);
1988 }
1989
1990
1991 /*
1992 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".
1993 */