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