]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/main.c
Merge changes from CUPS 1.5svn-r8916.
[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 cupsdCleanJobs();
1040 senddoc_time = current_time;
1041 }
1042
1043 /*
1044 * Log statistics at most once a minute when in debug mode...
1045 */
1046
1047 if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
1048 {
1049 size_t string_count, /* String count */
1050 alloc_bytes, /* Allocated string bytes */
1051 total_bytes; /* Total string bytes */
1052 #ifdef HAVE_MALLINFO
1053 struct mallinfo mem; /* Malloc information */
1054
1055
1056 mem = mallinfo();
1057 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
1058 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
1059 mem.usmblks + mem.uordblks);
1060 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
1061 mem.fsmblks + mem.fordblks);
1062 #endif /* HAVE_MALLINFO */
1063
1064 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
1065 cupsArrayCount(Clients));
1066 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
1067 cupsArrayCount(Jobs));
1068 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
1069 cupsArrayCount(ActiveJobs));
1070 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
1071 cupsArrayCount(Printers));
1072 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers-implicit=%d",
1073 cupsArrayCount(ImplicitPrinters));
1074
1075 string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
1076 cupsdLogMessage(CUPSD_LOG_DEBUG,
1077 "Report: stringpool-string-count=" CUPS_LLFMT,
1078 CUPS_LLCAST string_count);
1079 cupsdLogMessage(CUPSD_LOG_DEBUG,
1080 "Report: stringpool-alloc-bytes=" CUPS_LLFMT,
1081 CUPS_LLCAST alloc_bytes);
1082 cupsdLogMessage(CUPSD_LOG_DEBUG,
1083 "Report: stringpool-total-bytes=" CUPS_LLFMT,
1084 CUPS_LLCAST total_bytes);
1085
1086 report_time = current_time;
1087 }
1088
1089 /*
1090 * Handle OS-specific event notification for any events that have
1091 * accumulated. Don't send these more than once a second...
1092 */
1093
1094 if (LastEvent && (current_time - event_time) >= 1)
1095 {
1096 #ifdef HAVE_NOTIFY_POST
1097 if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
1098 CUPSD_EVENT_PRINTER_DELETED |
1099 CUPSD_EVENT_PRINTER_MODIFIED))
1100 {
1101 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1102 "notify_post(\"com.apple.printerListChange\")");
1103 notify_post("com.apple.printerListChange");
1104 }
1105
1106 if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
1107 {
1108 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1109 "notify_post(\"com.apple.printerHistoryChange\")");
1110 notify_post("com.apple.printerHistoryChange");
1111 }
1112
1113 if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
1114 CUPSD_EVENT_JOB_CONFIG_CHANGED |
1115 CUPSD_EVENT_JOB_PROGRESS))
1116 {
1117 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1118 "notify_post(\"com.apple.jobChange\")");
1119 notify_post("com.apple.jobChange");
1120 }
1121 #endif /* HAVE_NOTIFY_POST */
1122
1123 /*
1124 * Reset the accumulated events...
1125 */
1126
1127 LastEvent = CUPSD_EVENT_NONE;
1128 event_time = current_time;
1129 }
1130 }
1131
1132 /*
1133 * Log a message based on what happened...
1134 */
1135
1136 if (stop_scheduler)
1137 {
1138 cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
1139 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1140 "Scheduler shutting down normally.");
1141 }
1142 else
1143 {
1144 cupsdLogMessage(CUPSD_LOG_ERROR,
1145 "Scheduler shutting down due to program error.");
1146 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1147 "Scheduler shutting down due to program error.");
1148 }
1149
1150 /*
1151 * Close all network clients...
1152 */
1153
1154 cupsdStopServer();
1155
1156 #ifdef HAVE_LAUNCHD
1157 /*
1158 * Update the launchd KeepAlive file as needed...
1159 */
1160
1161 if (Launchd)
1162 launchd_checkout();
1163 #endif /* HAVE_LAUNCHD */
1164
1165 /*
1166 * Stop all jobs...
1167 */
1168
1169 cupsdFreeAllJobs();
1170
1171 #ifdef __APPLE__
1172 /*
1173 * Stop monitoring system event monitoring...
1174 */
1175
1176 if (use_sysman)
1177 cupsdStopSystemMonitor();
1178 #endif /* __APPLE__ */
1179
1180 #ifdef HAVE_GSSAPI
1181 /*
1182 * Free the scheduler's Kerberos context...
1183 */
1184
1185 # ifdef __APPLE__
1186 /*
1187 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1188 * to use it...
1189 */
1190
1191 if (krb5_init_context != NULL)
1192 # endif /* __APPLE__ */
1193 if (KerberosContext)
1194 krb5_free_context(KerberosContext);
1195 #endif /* HAVE_GSSAPI */
1196
1197 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
1198 /*
1199 * Unload Print Service quota enforcement library (X Server only)
1200 */
1201
1202 PSQUpdateQuotaProc = NULL;
1203 if (PSQLibRef)
1204 {
1205 dlclose(PSQLibRef);
1206 PSQLibRef = NULL;
1207 }
1208 #endif /* __APPLE__ && HAVE_DLFCN_H */
1209
1210 #ifdef __sgi
1211 /*
1212 * Remove the fake IRIX lpsched lock file, but only if the existing
1213 * file is not a FIFO which indicates that the real IRIX lpsched is
1214 * running...
1215 */
1216
1217 if (!stat("/var/spool/lp/FIFO", &statbuf))
1218 if (!S_ISFIFO(statbuf.st_mode))
1219 unlink("/var/spool/lp/SCHEDLOCK");
1220 #endif /* __sgi */
1221
1222 cupsdStopSelect();
1223
1224 return (!stop_scheduler);
1225 }
1226
1227
1228 /*
1229 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1230 */
1231
1232 void
1233 cupsdCheckProcess(void)
1234 {
1235 /*
1236 * Flag that we have dead children...
1237 */
1238
1239 dead_children = 1;
1240 }
1241
1242
1243 /*
1244 * 'cupsdClosePipe()' - Close a pipe as necessary.
1245 */
1246
1247 void
1248 cupsdClosePipe(int *fds) /* I - Pipe file descriptors (2) */
1249 {
1250 /*
1251 * Close file descriptors as needed...
1252 */
1253
1254 if (fds[0] >= 0)
1255 {
1256 close(fds[0]);
1257 fds[0] = -1;
1258 }
1259
1260 if (fds[1] >= 0)
1261 {
1262 close(fds[1]);
1263 fds[1] = -1;
1264 }
1265 }
1266
1267
1268 /*
1269 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1270 */
1271
1272 int /* O - 0 on success, -1 on error */
1273 cupsdOpenPipe(int *fds) /* O - Pipe file descriptors (2) */
1274 {
1275 /*
1276 * Create the pipe...
1277 */
1278
1279 if (pipe(fds))
1280 {
1281 fds[0] = -1;
1282 fds[1] = -1;
1283
1284 return (-1);
1285 }
1286
1287 /*
1288 * Set the "close on exec" flag on each end of the pipe...
1289 */
1290
1291 if (fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC))
1292 {
1293 close(fds[0]);
1294 close(fds[1]);
1295
1296 fds[0] = -1;
1297 fds[1] = -1;
1298
1299 return (-1);
1300 }
1301
1302 if (fcntl(fds[1], F_SETFD, fcntl(fds[1], F_GETFD) | FD_CLOEXEC))
1303 {
1304 close(fds[0]);
1305 close(fds[1]);
1306
1307 fds[0] = -1;
1308 fds[1] = -1;
1309
1310 return (-1);
1311 }
1312
1313 /*
1314 * Return 0 indicating success...
1315 */
1316
1317 return (0);
1318 }
1319
1320
1321 /*
1322 * 'cupsdClearString()' - Clear a string.
1323 */
1324
1325 void
1326 cupsdClearString(char **s) /* O - String value */
1327 {
1328 if (s && *s)
1329 {
1330 _cupsStrFree(*s);
1331 *s = NULL;
1332 }
1333 }
1334
1335
1336 /*
1337 * 'cupsdHoldSignals()' - Hold child and termination signals.
1338 */
1339
1340 void
1341 cupsdHoldSignals(void)
1342 {
1343 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1344 sigset_t newmask; /* New POSIX signal mask */
1345 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1346
1347
1348 holdcount ++;
1349 if (holdcount > 1)
1350 return;
1351
1352 #ifdef HAVE_SIGSET
1353 sighold(SIGTERM);
1354 sighold(SIGCHLD);
1355 #elif defined(HAVE_SIGACTION)
1356 sigemptyset(&newmask);
1357 sigaddset(&newmask, SIGTERM);
1358 sigaddset(&newmask, SIGCHLD);
1359 sigprocmask(SIG_BLOCK, &newmask, &holdmask);
1360 #endif /* HAVE_SIGSET */
1361 }
1362
1363
1364 /*
1365 * 'cupsdReleaseSignals()' - Release signals for delivery.
1366 */
1367
1368 void
1369 cupsdReleaseSignals(void)
1370 {
1371 holdcount --;
1372 if (holdcount > 0)
1373 return;
1374
1375 #ifdef HAVE_SIGSET
1376 sigrelse(SIGTERM);
1377 sigrelse(SIGCHLD);
1378 #elif defined(HAVE_SIGACTION)
1379 sigprocmask(SIG_SETMASK, &holdmask, NULL);
1380 #endif /* HAVE_SIGSET */
1381 }
1382
1383
1384 /*
1385 * 'cupsdSetString()' - Set a string value.
1386 */
1387
1388 void
1389 cupsdSetString(char **s, /* O - New string */
1390 const char *v) /* I - String value */
1391 {
1392 if (!s || *s == v)
1393 return;
1394
1395 if (*s)
1396 _cupsStrFree(*s);
1397
1398 if (v)
1399 *s = _cupsStrAlloc(v);
1400 else
1401 *s = NULL;
1402 }
1403
1404
1405 /*
1406 * 'cupsdSetStringf()' - Set a formatted string value.
1407 */
1408
1409 void
1410 cupsdSetStringf(char **s, /* O - New string */
1411 const char *f, /* I - Printf-style format string */
1412 ...) /* I - Additional args as needed */
1413 {
1414 char v[4096]; /* Formatting string value */
1415 va_list ap; /* Argument pointer */
1416 char *olds; /* Old string */
1417
1418
1419 if (!s)
1420 return;
1421
1422 olds = *s;
1423
1424 if (f)
1425 {
1426 va_start(ap, f);
1427 vsnprintf(v, sizeof(v), f, ap);
1428 va_end(ap);
1429
1430 *s = _cupsStrAlloc(v);
1431 }
1432 else
1433 *s = NULL;
1434
1435 if (olds)
1436 _cupsStrFree(olds);
1437 }
1438
1439
1440 #ifdef HAVE_LAUNCHD
1441 /*
1442 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1443 */
1444
1445 static void
1446 launchd_checkin(void)
1447 {
1448 size_t i, /* Looping var */
1449 count; /* Numebr of listeners */
1450 int portnum; /* Port number */
1451 launch_data_t ld_msg, /* Launch data message */
1452 ld_resp, /* Launch data response */
1453 ld_array, /* Launch data array */
1454 ld_sockets, /* Launch data sockets dictionary */
1455 tmp; /* Launch data */
1456 cupsd_listener_t *lis; /* Listeners array */
1457 http_addr_t addr; /* Address variable */
1458 socklen_t addrlen; /* Length of address */
1459 int fd; /* File descriptor */
1460 char s[256]; /* String addresss */
1461
1462
1463 cupsdLogMessage(CUPSD_LOG_DEBUG, "launchd_checkin: pid=%d", (int)getpid());
1464
1465 /*
1466 * Check-in with launchd...
1467 */
1468
1469 ld_msg = launch_data_new_string(LAUNCH_KEY_CHECKIN);
1470 if ((ld_resp = launch_msg(ld_msg)) == NULL)
1471 {
1472 cupsdLogMessage(CUPSD_LOG_ERROR,
1473 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1474 "\") IPC failure");
1475 exit(EXIT_FAILURE);
1476 return; /* anti-compiler-warning */
1477 }
1478
1479 if (launch_data_get_type(ld_resp) == LAUNCH_DATA_ERRNO)
1480 {
1481 errno = launch_data_get_errno(ld_resp);
1482 cupsdLogMessage(CUPSD_LOG_ERROR, "launchd_checkin: Check-in failed: %s",
1483 strerror(errno));
1484 exit(EXIT_FAILURE);
1485 return; /* anti-compiler-warning */
1486 }
1487
1488 /*
1489 * Get the sockets dictionary...
1490 */
1491
1492 if ((ld_sockets = launch_data_dict_lookup(ld_resp, LAUNCH_JOBKEY_SOCKETS))
1493 == NULL)
1494 {
1495 cupsdLogMessage(CUPSD_LOG_ERROR,
1496 "launchd_checkin: No sockets found to answer requests on!");
1497 exit(EXIT_FAILURE);
1498 return; /* anti-compiler-warning */
1499 }
1500
1501 /*
1502 * Get the array of listener sockets...
1503 */
1504
1505 if ((ld_array = launch_data_dict_lookup(ld_sockets, "Listeners")) == NULL)
1506 {
1507 cupsdLogMessage(CUPSD_LOG_ERROR,
1508 "launchd_checkin: No sockets found to answer requests on!");
1509 exit(EXIT_FAILURE);
1510 return; /* anti-compiler-warning */
1511 }
1512
1513 /*
1514 * Add listening fd(s) to the Listener array...
1515 */
1516
1517 if (launch_data_get_type(ld_array) == LAUNCH_DATA_ARRAY)
1518 {
1519 count = launch_data_array_get_count(ld_array);
1520
1521 for (i = 0; i < count; i ++)
1522 {
1523 /*
1524 * Get the launchd file descriptor and address...
1525 */
1526
1527 if ((tmp = launch_data_array_get_index(ld_array, i)) != NULL)
1528 {
1529 fd = launch_data_get_fd(tmp);
1530 addrlen = sizeof(addr);
1531
1532 if (getsockname(fd, (struct sockaddr *)&addr, &addrlen))
1533 {
1534 cupsdLogMessage(CUPSD_LOG_ERROR,
1535 "launchd_checkin: Unable to get local address - %s",
1536 strerror(errno));
1537 continue;
1538 }
1539
1540 /*
1541 * Try to match the launchd socket address to one of the listeners...
1542 */
1543
1544 for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
1545 lis;
1546 lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
1547 if (httpAddrEqual(&lis->address, &addr))
1548 break;
1549
1550 /*
1551 * Add a new listener If there's no match...
1552 */
1553
1554 if (lis)
1555 {
1556 cupsdLogMessage(CUPSD_LOG_DEBUG,
1557 "launchd_checkin: Matched existing listener %s with fd %d...",
1558 httpAddrString(&(lis->address), s, sizeof(s)), fd);
1559 }
1560 else
1561 {
1562 cupsdLogMessage(CUPSD_LOG_DEBUG,
1563 "launchd_checkin: Adding new listener %s with fd %d...",
1564 httpAddrString(&addr, s, sizeof(s)), fd);
1565
1566 if ((lis = calloc(1, sizeof(cupsd_listener_t))) == NULL)
1567 {
1568 cupsdLogMessage(CUPSD_LOG_ERROR,
1569 "launchd_checkin: Unable to allocate listener - %s.",
1570 strerror(errno));
1571 exit(EXIT_FAILURE);
1572 }
1573
1574 cupsArrayAdd(Listeners, lis);
1575
1576 memcpy(&lis->address, &addr, sizeof(lis->address));
1577 }
1578
1579 lis->fd = fd;
1580
1581 # ifdef HAVE_SSL
1582 portnum = 0;
1583
1584 # ifdef AF_INET6
1585 if (lis->address.addr.sa_family == AF_INET6)
1586 portnum = ntohs(lis->address.ipv6.sin6_port);
1587 else
1588 # endif /* AF_INET6 */
1589 if (lis->address.addr.sa_family == AF_INET)
1590 portnum = ntohs(lis->address.ipv4.sin_port);
1591
1592 if (portnum == 443)
1593 lis->encryption = HTTP_ENCRYPT_ALWAYS;
1594 # endif /* HAVE_SSL */
1595 }
1596 }
1597 }
1598
1599 launch_data_free(ld_msg);
1600 launch_data_free(ld_resp);
1601 }
1602
1603
1604 /*
1605 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1606 */
1607
1608 static void
1609 launchd_checkout(void)
1610 {
1611 int fd; /* File descriptor */
1612
1613
1614 /*
1615 * Create or remove the launchd KeepAlive file based on whether
1616 * there are active jobs, polling, browsing for remote printers or
1617 * shared printers to advertise...
1618 */
1619
1620 if ((cupsArrayCount(ActiveJobs) || NumPolled ||
1621 (Browsing &&
1622 (BrowseRemoteProtocols ||
1623 (BrowseLocalProtocols && NumBrowsers && cupsArrayCount(Printers))))))
1624 {
1625 cupsdLogMessage(CUPSD_LOG_DEBUG,
1626 "Creating launchd keepalive file \"" CUPS_KEEPALIVE "\"...");
1627
1628 if ((fd = open(CUPS_KEEPALIVE, O_RDONLY | O_CREAT | O_EXCL, S_IRUSR)) >= 0)
1629 close(fd);
1630 }
1631 else
1632 {
1633 cupsdLogMessage(CUPSD_LOG_DEBUG,
1634 "Removing launchd keepalive file \"" CUPS_KEEPALIVE "\"...");
1635
1636 unlink(CUPS_KEEPALIVE);
1637 }
1638 }
1639 #endif /* HAVE_LAUNCHD */
1640
1641
1642 /*
1643 * 'parent_handler()' - Catch USR1/CHLD signals...
1644 */
1645
1646 static void
1647 parent_handler(int sig) /* I - Signal */
1648 {
1649 /*
1650 * Store the signal we got from the OS and return...
1651 */
1652
1653 parent_signal = sig;
1654 }
1655
1656
1657 /*
1658 * 'process_children()' - Process all dead children...
1659 */
1660
1661 static void
1662 process_children(void)
1663 {
1664 int status; /* Exit status of child */
1665 int pid, /* Process ID of child */
1666 job_id; /* Job ID of child */
1667 cupsd_job_t *job; /* Current job */
1668 int i; /* Looping var */
1669 char name[1024]; /* Process name */
1670
1671
1672 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1673
1674 /*
1675 * Reset the dead_children flag...
1676 */
1677
1678 dead_children = 0;
1679
1680 /*
1681 * Collect the exit status of some children...
1682 */
1683
1684 #ifdef HAVE_WAITPID
1685 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1686 #elif defined(HAVE_WAIT3)
1687 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1688 #else
1689 if ((pid = wait(&status)) > 0)
1690 #endif /* HAVE_WAITPID */
1691 {
1692 /*
1693 * Collect the name of the process that finished...
1694 */
1695
1696 cupsdFinishProcess(pid, name, sizeof(name), &job_id);
1697
1698 /*
1699 * Delete certificates for CGI processes...
1700 */
1701
1702 if (pid)
1703 cupsdDeleteCert(pid);
1704
1705 /*
1706 * Handle completed job filters...
1707 */
1708
1709 if (job_id > 0 && (job = cupsdFindJob(job_id)) != NULL)
1710 {
1711 for (i = 0; job->filters[i]; i ++)
1712 if (job->filters[i] == pid)
1713 break;
1714
1715 if (job->filters[i] || job->backend == pid)
1716 {
1717 /*
1718 * OK, this process has gone away; what's left?
1719 */
1720
1721 if (job->filters[i])
1722 job->filters[i] = -pid;
1723 else
1724 job->backend = -pid;
1725
1726 if (status && status != SIGTERM && status != SIGKILL &&
1727 job->status >= 0)
1728 {
1729 /*
1730 * An error occurred; save the exit status so we know to stop
1731 * the printer or cancel the job when all of the filters finish...
1732 *
1733 * A negative status indicates that the backend failed and the
1734 * printer needs to be stopped.
1735 */
1736
1737 if (job->filters[i])
1738 job->status = status; /* Filter failed */
1739 else
1740 job->status = -status; /* Backend failed */
1741
1742 if (job->state_value == IPP_JOB_PROCESSING &&
1743 job->status_level > CUPSD_LOG_ERROR)
1744 {
1745 char message[1024]; /* New printer-state-message */
1746
1747
1748 job->status_level = CUPSD_LOG_ERROR;
1749
1750 snprintf(message, sizeof(message), "%s failed", name);
1751
1752 if (job->printer)
1753 {
1754 strlcpy(job->printer->state_message, message,
1755 sizeof(job->printer->state_message));
1756 cupsdAddPrinterHistory(job->printer);
1757 }
1758
1759 if (!job->attrs)
1760 cupsdLoadJob(job);
1761
1762 if (!job->printer_message && job->attrs)
1763 {
1764 if ((job->printer_message =
1765 ippFindAttribute(job->attrs, "job-printer-state-message",
1766 IPP_TAG_TEXT)) == NULL)
1767 job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB,
1768 IPP_TAG_TEXT,
1769 "job-printer-state-message",
1770 NULL, "");
1771 }
1772
1773 if (job->printer_message)
1774 cupsdSetString(&(job->printer_message->values[0].string.text),
1775 message);
1776 }
1777 }
1778
1779 /*
1780 * If this is not the last file in a job, see if all of the
1781 * filters are done, and if so move to the next file.
1782 */
1783
1784 if (job->current_file < job->num_files)
1785 {
1786 for (i = 0; job->filters[i] < 0; i ++);
1787
1788 if (!job->filters[i])
1789 {
1790 /*
1791 * Process the next file...
1792 */
1793
1794 cupsdContinueJob(job);
1795 }
1796 }
1797 else if (job->state_value == IPP_JOB_CANCELED)
1798 {
1799 /*
1800 * Remove the job from the active list if there are no processes still
1801 * running for it...
1802 */
1803
1804 for (i = 0; job->filters[i] < 0; i++);
1805
1806 if (!job->filters[i] && job->backend <= 0)
1807 cupsArrayRemove(ActiveJobs, job);
1808 }
1809 }
1810 }
1811
1812 /*
1813 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1814 * since they come when we kill/end a process...
1815 */
1816
1817 if (status == SIGTERM || status == SIGKILL)
1818 {
1819 cupsdLogMessage(CUPSD_LOG_DEBUG,
1820 "PID %d (%s) was terminated normally with signal %d.",
1821 pid, name, status);
1822 }
1823 else if (status)
1824 {
1825 if (WIFEXITED(status))
1826 cupsdLogMessage(CUPSD_LOG_DEBUG, "PID %d (%s) stopped with status %d!",
1827 pid, name, WEXITSTATUS(status));
1828 else
1829 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) crashed on signal %d!",
1830 pid, name, WTERMSIG(status));
1831
1832 if (LogLevel < CUPSD_LOG_DEBUG)
1833 cupsdLogMessage(CUPSD_LOG_INFO,
1834 "Hint: Try setting the LogLevel to \"debug\" to find "
1835 "out more.");
1836 }
1837 else
1838 cupsdLogMessage(CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
1839 pid, name);
1840 }
1841
1842 /*
1843 * If wait*() is interrupted by a signal, tell main() to call us again...
1844 */
1845
1846 if (pid < 0 && errno == EINTR)
1847 dead_children = 1;
1848 }
1849
1850
1851 /*
1852 * 'select_timeout()' - Calculate the select timeout value.
1853 *
1854 */
1855
1856 static long /* O - Number of seconds */
1857 select_timeout(int fds) /* I - Number of descriptors returned */
1858 {
1859 long timeout; /* Timeout for select */
1860 time_t now; /* Current time */
1861 cupsd_client_t *con; /* Client information */
1862 cupsd_printer_t *p; /* Printer information */
1863 cupsd_job_t *job; /* Job information */
1864 cupsd_subscription_t *sub; /* Subscription information */
1865 const char *why; /* Debugging aid */
1866
1867
1868 /*
1869 * Check to see if any of the clients have pending data to be
1870 * processed; if so, the timeout should be 0...
1871 */
1872
1873 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1874 con;
1875 con = (cupsd_client_t *)cupsArrayNext(Clients))
1876 if (con->http.used > 0)
1877 return (0);
1878
1879 /*
1880 * If select has been active in the last second (fds > 0) or we have
1881 * many resources in use then don't bother trying to optimize the
1882 * timeout, just make it 1 second.
1883 */
1884
1885 if (fds > 0 || cupsArrayCount(Clients) > 50)
1886 return (1);
1887
1888 /*
1889 * Otherwise, check all of the possible events that we need to wake for...
1890 */
1891
1892 now = time(NULL);
1893 timeout = now + 86400; /* 86400 == 1 day */
1894 why = "do nothing";
1895
1896 #ifdef __APPLE__
1897 /*
1898 * When going to sleep, wake up to cancel jobs that don't complete in time.
1899 */
1900
1901 if (SleepJobs > 0 && SleepJobs < timeout)
1902 {
1903 timeout = SleepJobs;
1904 why = "cancel jobs before sleeping";
1905 }
1906 #endif /* __APPLE__ */
1907
1908 /*
1909 * Check whether we are accepting new connections...
1910 */
1911
1912 if (ListeningPaused > 0 && cupsArrayCount(Clients) < MaxClients &&
1913 ListeningPaused < timeout)
1914 {
1915 if (ListeningPaused <= now)
1916 timeout = now;
1917 else
1918 timeout = ListeningPaused;
1919
1920 why = "resume listening";
1921 }
1922
1923 /*
1924 * Check the activity and close old clients...
1925 */
1926
1927 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1928 con;
1929 con = (cupsd_client_t *)cupsArrayNext(Clients))
1930 if ((con->http.activity + Timeout) < timeout)
1931 {
1932 timeout = con->http.activity + Timeout;
1933 why = "timeout a client connection";
1934 }
1935
1936 /*
1937 * Update the browse list as needed...
1938 */
1939
1940 if (Browsing && BrowseLocalProtocols)
1941 {
1942 #ifdef HAVE_LIBSLP
1943 if ((BrowseLocalProtocols & BROWSE_SLP) && (BrowseSLPRefresh < timeout))
1944 {
1945 timeout = BrowseSLPRefresh;
1946 why = "update SLP browsing";
1947 }
1948 #endif /* HAVE_LIBSLP */
1949
1950 #ifdef HAVE_LDAP
1951 if ((BrowseLocalProtocols & BROWSE_LDAP) && (BrowseLDAPRefresh < timeout))
1952 {
1953 timeout = BrowseLDAPRefresh;
1954 why = "update LDAP browsing";
1955 }
1956 #endif /* HAVE_LDAP */
1957
1958 if ((BrowseLocalProtocols & BROWSE_CUPS) && NumBrowsers)
1959 {
1960 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1961 p;
1962 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1963 {
1964 if (p->type & CUPS_PRINTER_REMOTE)
1965 {
1966 if ((p->browse_time + BrowseTimeout) < timeout)
1967 {
1968 timeout = p->browse_time + BrowseTimeout;
1969 why = "browse timeout a printer";
1970 }
1971 }
1972 else if (p->shared && !(p->type & CUPS_PRINTER_IMPLICIT))
1973 {
1974 if (BrowseInterval && (p->browse_time + BrowseInterval) < timeout)
1975 {
1976 timeout = p->browse_time + BrowseInterval;
1977 why = "send browse update";
1978 }
1979 }
1980 }
1981 }
1982 }
1983
1984 /*
1985 * Write out changes to configuration and state files...
1986 */
1987
1988 if (DirtyCleanTime && timeout > DirtyCleanTime)
1989 {
1990 timeout = DirtyCleanTime;
1991 why = "write dirty config/state files";
1992 }
1993
1994 /*
1995 * Check for any active jobs...
1996 */
1997
1998 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1999 job;
2000 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
2001 {
2002 if (job->kill_time && job->kill_time < timeout)
2003 {
2004 timeout = job->kill_time;
2005 why = "kill unresponsive jobs";
2006 }
2007
2008 if (job->state_value == IPP_JOB_HELD && job->hold_until < timeout)
2009 {
2010 timeout = job->hold_until;
2011 why = "release held jobs";
2012 }
2013 else if (job->state_value == IPP_JOB_PENDING && timeout > (now + 10))
2014 {
2015 timeout = now + 10;
2016 why = "start pending jobs";
2017 break;
2018 }
2019 }
2020
2021 #ifdef HAVE_MALLINFO
2022 /*
2023 * Log memory usage every minute...
2024 */
2025
2026 if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
2027 {
2028 timeout = mallinfo_time + 60;
2029 why = "display memory usage";
2030 }
2031 #endif /* HAVE_MALLINFO */
2032
2033 /*
2034 * Expire subscriptions as needed...
2035 */
2036
2037 for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
2038 sub;
2039 sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
2040 if (!sub->job && sub->expire && sub->expire < timeout)
2041 {
2042 timeout = sub->expire;
2043 why = "expire subscription";
2044 }
2045
2046 /*
2047 * Adjust from absolute to relative time. If p->browse_time above
2048 * was 0 then we can end up with a negative value here, so check.
2049 * We add 1 second to the timeout since events occur after the
2050 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2051 * to avoid select() timeout limits present on some operating
2052 * systems...
2053 */
2054
2055 timeout = timeout - now + 1;
2056
2057 if (timeout < 1)
2058 timeout = 1;
2059 else if (timeout > 86400)
2060 timeout = 86400;
2061
2062 /*
2063 * Log and return the timeout value...
2064 */
2065
2066 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
2067 fds, timeout, why);
2068
2069 return (timeout);
2070 }
2071
2072
2073 /*
2074 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2075 */
2076
2077 static void
2078 sigchld_handler(int sig) /* I - Signal number */
2079 {
2080 (void)sig;
2081
2082 /*
2083 * Flag that we have dead children...
2084 */
2085
2086 dead_children = 1;
2087
2088 /*
2089 * Reset the signal handler as needed...
2090 */
2091
2092 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2093 signal(SIGCLD, sigchld_handler);
2094 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2095 }
2096
2097
2098 /*
2099 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2100 */
2101
2102 static void
2103 sighup_handler(int sig) /* I - Signal number */
2104 {
2105 (void)sig;
2106
2107 NeedReload = RELOAD_ALL;
2108 ReloadTime = time(NULL);
2109
2110 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2111 signal(SIGHUP, sighup_handler);
2112 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2113 }
2114
2115
2116 /*
2117 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2118 */
2119
2120 static void
2121 sigterm_handler(int sig) /* I - Signal number */
2122 {
2123 (void)sig; /* remove compiler warnings... */
2124
2125 /*
2126 * Flag that we should stop and return...
2127 */
2128
2129 stop_scheduler = 1;
2130 }
2131
2132
2133 /*
2134 * 'usage()' - Show scheduler usage.
2135 */
2136
2137 static void
2138 usage(int status) /* O - Exit status */
2139 {
2140 _cupsLangPuts(status ? stderr : stdout,
2141 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
2142 "\n"
2143 "-c config-file Load alternate configuration file\n"
2144 "-f Run in the foreground\n"
2145 "-F Run in the foreground but detach\n"
2146 "-h Show this usage message\n"
2147 "-l Run cupsd from launchd(8)\n"));
2148 exit(status);
2149 }
2150
2151
2152 /*
2153 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".
2154 */