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