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