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