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