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