]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/main.c
Merge changes from CUPS 1.5svn-r9105.
[thirdparty/cups.git] / scheduler / main.c
1 /*
2 * "$Id: main.c 7925 2008-09-10 17:47:26Z mike $"
3 *
4 * Main loop for the CUPS scheduler.
5 *
6 * Copyright 2007-2010 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 * cupsd_clean_files() - Clean out old files.
25 * launchd_checkin() - Check-in with launchd and collect the
26 * listening fds.
27 * launchd_checkout() - Check-out with launchd.
28 * parent_handler() - Catch USR1/CHLD signals...
29 * process_children() - Process all dead children...
30 * select_timeout() - Calculate the select timeout value.
31 * sigchld_handler() - Handle 'child' signals from old processes.
32 * sighup_handler() - Handle 'hangup' signals to reconfigure the
33 * scheduler.
34 * sigterm_handler() - Handle 'terminate' signals that stop the
35 * scheduler.
36 * usage() - Show scheduler usage.
37 */
38
39 /*
40 * Include necessary headers...
41 */
42
43 #define _MAIN_C_
44 #include "cupsd.h"
45 #include <sys/resource.h>
46 #include <syslog.h>
47 #include <grp.h>
48 #include <cups/dir.h>
49 #include <fnmatch.h>
50
51 #ifdef HAVE_LAUNCH_H
52 # include <launch.h>
53 # include <libgen.h>
54 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
55 /* Name of the launchd KeepAlive file */
56 # ifndef LAUNCH_JOBKEY_KEEPALIVE
57 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
58 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
59 # ifndef LAUNCH_JOBKEY_PATHSTATE
60 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
61 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
62 # ifndef LAUNCH_JOBKEY_SERVICEIPC
63 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
64 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
65 #endif /* HAVE_LAUNCH_H */
66
67 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
68 # include <malloc.h>
69 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
70 #ifdef HAVE_NOTIFY_H
71 # include <notify.h>
72 #endif /* HAVE_NOTIFY_H */
73
74
75 /*
76 * Local functions...
77 */
78
79 static void cupsd_clean_files(const char *path,
80 const char *pattern);
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
110 /*
111 * 'main()' - Main entry for the CUPS scheduler.
112 */
113
114 int /* O - Exit status */
115 main(int argc, /* I - Number of command-line args */
116 char *argv[]) /* I - Command-line arguments */
117 {
118 int i; /* Looping var */
119 char *opt; /* Option character */
120 int fg; /* Run in the foreground */
121 int fds; /* Number of ready descriptors */
122 cupsd_client_t *con; /* Current client */
123 cupsd_job_t *job; /* Current job */
124 cupsd_listener_t *lis; /* Current listener */
125 time_t current_time, /* Current time */
126 activity, /* Client activity timer */
127 browse_time, /* Next browse send time */
128 senddoc_time, /* Send-Document time */
129 expire_time, /* Subscription expire time */
130 report_time, /* Malloc/client/job report time */
131 event_time; /* Last event notification time */
132 long timeout; /* Timeout for cupsdDoSelect() */
133 struct rlimit limit; /* Runtime limit */
134 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
135 struct sigaction action; /* Actions for POSIX signals */
136 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
137 #ifdef __sgi
138 cups_file_t *fp; /* Fake lpsched lock file */
139 struct stat statbuf; /* Needed for checking lpsched FIFO */
140 #endif /* __sgi */
141 int run_as_child = 0;
142 /* Needed for background fork/exec */
143 #ifdef __APPLE__
144 int use_sysman = !getuid();
145 /* Use system management functions? */
146 #else
147 time_t netif_time = 0; /* Time since last network update */
148 #endif /* __APPLE__ */
149 #if HAVE_LAUNCHD
150 int launchd_idle_exit;
151 /* Idle exit on select timeout? */
152 #endif /* HAVE_LAUNCHD */
153
154
155 #ifdef HAVE_GETEUID
156 /*
157 * Check for setuid invocation, which we do not support!
158 */
159
160 if (getuid() != geteuid())
161 {
162 fputs("cupsd: Cannot run as a setuid program\n", stderr);
163 return (1);
164 }
165 #endif /* HAVE_GETEUID */
166
167 /*
168 * Check for command-line arguments...
169 */
170
171 fg = 0;
172
173 #ifdef HAVE_LAUNCHD
174 if (getenv("CUPSD_LAUNCHD"))
175 {
176 Launchd = 1;
177 fg = 1;
178 }
179 #endif /* HAVE_LAUNCHD */
180
181 for (i = 1; i < argc; i ++)
182 if (argv[i][0] == '-')
183 for (opt = argv[i] + 1; *opt != '\0'; opt ++)
184 switch (*opt)
185 {
186 case 'C' : /* Run as child with config file */
187 run_as_child = 1;
188 fg = -1;
189
190 case 'c' : /* Configuration file */
191 i ++;
192 if (i >= argc)
193 {
194 _cupsLangPuts(stderr, _("cupsd: Expected config filename "
195 "after \"-c\" option\n"));
196 usage(1);
197 }
198
199 if (argv[i][0] == '/')
200 {
201 /*
202 * Absolute directory...
203 */
204
205 cupsdSetString(&ConfigurationFile, argv[i]);
206 }
207 else
208 {
209 /*
210 * Relative directory...
211 */
212
213 char *current; /* Current directory */
214
215
216 /*
217 * Allocate a buffer for the current working directory to
218 * reduce run-time stack usage; this approximates the
219 * behavior of some implementations of getcwd() when they
220 * are passed a NULL pointer.
221 */
222
223 if ((current = malloc(1024)) == NULL)
224 {
225 _cupsLangPuts(stderr,
226 _("cupsd: Unable to get current directory\n"));
227 return (1);
228 }
229
230 if (!getcwd(current, 1024))
231 {
232 _cupsLangPuts(stderr,
233 _("cupsd: Unable to get current directory\n"));
234 free(current);
235 return (1);
236 }
237
238 cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
239 free(current);
240 }
241 break;
242
243 case 'f' : /* Run in foreground... */
244 fg = 1;
245 break;
246
247 case 'F' : /* Run in foreground, but disconnect from terminal... */
248 fg = -1;
249 break;
250
251 case 'h' : /* Show usage/help */
252 usage(0);
253 break;
254
255 case 'l' : /* Started by launchd... */
256 #ifdef HAVE_LAUNCHD
257 Launchd = 1;
258 fg = 1;
259 #else
260 _cupsLangPuts(stderr, _("cupsd: launchd(8) support not compiled "
261 "in, running in normal mode.\n"));
262 fg = 0;
263 #endif /* HAVE_LAUNCHD */
264 break;
265
266 case 'p' : /* Stop immediately for profiling */
267 fputs("cupsd: -p (startup profiling) is for internal testing "
268 "use only!\n", stderr);
269 stop_scheduler = 1;
270 fg = 1;
271 break;
272
273 case 'P' : /* Disable security profiles */
274 fputs("cupsd: -P (disable security profiles) is for internal "
275 "testing use only!\n", stderr);
276 UseProfiles = 0;
277 break;
278
279 #ifdef __APPLE__
280 case 'S' : /* Disable system management functions */
281 fputs("cupsd: -S (disable system management) for internal "
282 "testing use only!\n", stderr);
283 use_sysman = 0;
284 break;
285 #endif /* __APPLE__ */
286
287 case 't' : /* Test the cupsd.conf file... */
288 TestConfigFile = 1;
289 fg = 1;
290 break;
291
292 default : /* Unknown option */
293 _cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
294 "aborting\n"), *opt);
295 usage(1);
296 break;
297 }
298 else
299 {
300 _cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting\n"),
301 argv[i]);
302 usage(1);
303 }
304
305 if (!ConfigurationFile)
306 cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
307
308 /*
309 * If the user hasn't specified "-f", run in the background...
310 */
311
312 if (!fg)
313 {
314 /*
315 * Setup signal handlers for the parent...
316 */
317
318 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
319 sigset(SIGUSR1, parent_handler);
320 sigset(SIGCHLD, parent_handler);
321
322 sigset(SIGHUP, SIG_IGN);
323 #elif defined(HAVE_SIGACTION)
324 memset(&action, 0, sizeof(action));
325 sigemptyset(&action.sa_mask);
326 sigaddset(&action.sa_mask, SIGUSR1);
327 action.sa_handler = parent_handler;
328 sigaction(SIGUSR1, &action, NULL);
329 sigaction(SIGCHLD, &action, NULL);
330
331 sigemptyset(&action.sa_mask);
332 action.sa_handler = SIG_IGN;
333 sigaction(SIGHUP, &action, NULL);
334 #else
335 signal(SIGUSR1, parent_handler);
336 signal(SIGCLD, parent_handler);
337
338 signal(SIGHUP, SIG_IGN);
339 #endif /* HAVE_SIGSET */
340
341 if (fork() > 0)
342 {
343 /*
344 * OK, wait for the child to startup and send us SIGUSR1 or to crash
345 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
346 * might be sent by the init script to restart the scheduler...
347 */
348
349 for (; parent_signal == 0;)
350 sleep(1);
351
352 if (parent_signal == SIGUSR1)
353 return (0);
354
355 if (wait(&i) < 0)
356 {
357 perror("cupsd");
358 return (1);
359 }
360 else if (WIFEXITED(i))
361 {
362 fprintf(stderr, "cupsd: Child exited with status %d\n",
363 WEXITSTATUS(i));
364 return (2);
365 }
366 else
367 {
368 fprintf(stderr, "cupsd: Child exited on signal %d\n", WTERMSIG(i));
369 return (3);
370 }
371 }
372
373 #ifdef __OpenBSD__
374 /*
375 * Call _thread_sys_closefrom() so the child process doesn't reset the
376 * parent's file descriptors to be blocking. This is a workaround for a
377 * limitation of userland libpthread on OpenBSD.
378 */
379
380 _thread_sys_closefrom(0);
381 #endif /* __OpenBSD__ */
382
383 /*
384 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
385 * a program, and since this kind of really unfriendly behavior seems to be
386 * more common these days in system libraries, we need to re-execute the
387 * background cupsd with the "-C" option to avoid problems. Unfortunately,
388 * we also have to assume that argv[0] contains the name of the cupsd
389 * executable - there is no portable way to get the real pathname...
390 */
391
392 execlp(argv[0], argv[0], "-C", ConfigurationFile, (char *)0);
393 exit(errno);
394 }
395
396 if (fg < 1)
397 {
398 /*
399 * Make sure we aren't tying up any filesystems...
400 */
401
402 chdir("/");
403
404 #ifndef DEBUG
405 /*
406 * Disable core dumps...
407 */
408
409 getrlimit(RLIMIT_CORE, &limit);
410 limit.rlim_cur = 0;
411 setrlimit(RLIMIT_CORE, &limit);
412
413 /*
414 * Disconnect from the controlling terminal...
415 */
416
417 setsid();
418
419 /*
420 * Close all open files...
421 */
422
423 getrlimit(RLIMIT_NOFILE, &limit);
424
425 for (i = 0; i < limit.rlim_cur && i < 1024; i ++)
426 close(i);
427
428 /*
429 * Redirect stdin/out/err to /dev/null...
430 */
431
432 if ((i = open("/dev/null", O_RDONLY)) != 0)
433 {
434 dup2(i, 0);
435 close(i);
436 }
437
438 if ((i = open("/dev/null", O_WRONLY)) != 1)
439 {
440 dup2(i, 1);
441 close(i);
442 }
443
444 if ((i = open("/dev/null", O_WRONLY)) != 2)
445 {
446 dup2(i, 2);
447 close(i);
448 }
449 #endif /* DEBUG */
450 }
451
452 /*
453 * Set the timezone info...
454 */
455
456 tzset();
457
458 #ifdef LC_TIME
459 setlocale(LC_TIME, "");
460 #endif /* LC_TIME */
461
462 /*
463 * Set the maximum number of files...
464 */
465
466 getrlimit(RLIMIT_NOFILE, &limit);
467
468 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
469 if (limit.rlim_max > FD_SETSIZE)
470 MaxFDs = FD_SETSIZE;
471 else
472 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
473 #ifdef RLIM_INFINITY
474 if (limit.rlim_max == RLIM_INFINITY)
475 MaxFDs = 16384;
476 else
477 #endif /* RLIM_INFINITY */
478 MaxFDs = limit.rlim_max;
479
480 limit.rlim_cur = MaxFDs;
481
482 setrlimit(RLIMIT_NOFILE, &limit);
483
484 cupsdStartSelect();
485
486 /*
487 * Read configuration...
488 */
489
490 if (!cupsdReadConfiguration())
491 {
492 if (TestConfigFile)
493 printf("%s contains errors\n", ConfigurationFile);
494 else
495 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
496 ConfigurationFile);
497 return (1);
498 }
499 else if (TestConfigFile)
500 {
501 printf("%s is OK\n", ConfigurationFile);
502 return (0);
503 }
504
505 /*
506 * Clean out old temp files and printer cache data.
507 */
508
509 if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)))
510 cupsd_clean_files(TempDir, NULL);
511
512 cupsd_clean_files(CacheDir, "*.ipp");
513
514 #if HAVE_LAUNCHD
515 if (Launchd)
516 {
517 /*
518 * If we were started by launchd get the listen sockets file descriptors...
519 */
520
521 launchd_checkin();
522 launchd_checkout();
523 }
524 #endif /* HAVE_LAUNCHD */
525
526 /*
527 * Startup the server...
528 */
529
530 httpInitialize();
531
532 cupsdStartServer();
533
534 /*
535 * Catch hangup and child signals and ignore broken pipes...
536 */
537
538 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
539 sigset(SIGCHLD, sigchld_handler);
540 sigset(SIGHUP, sighup_handler);
541 sigset(SIGPIPE, SIG_IGN);
542 sigset(SIGTERM, sigterm_handler);
543 #elif defined(HAVE_SIGACTION)
544 memset(&action, 0, sizeof(action));
545
546 sigemptyset(&action.sa_mask);
547 sigaddset(&action.sa_mask, SIGTERM);
548 sigaddset(&action.sa_mask, SIGCHLD);
549 action.sa_handler = sigchld_handler;
550 sigaction(SIGCHLD, &action, NULL);
551
552 sigemptyset(&action.sa_mask);
553 sigaddset(&action.sa_mask, SIGHUP);
554 action.sa_handler = sighup_handler;
555 sigaction(SIGHUP, &action, NULL);
556
557 sigemptyset(&action.sa_mask);
558 action.sa_handler = SIG_IGN;
559 sigaction(SIGPIPE, &action, NULL);
560
561 sigemptyset(&action.sa_mask);
562 sigaddset(&action.sa_mask, SIGTERM);
563 sigaddset(&action.sa_mask, SIGCHLD);
564 action.sa_handler = sigterm_handler;
565 sigaction(SIGTERM, &action, NULL);
566 #else
567 signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */
568 signal(SIGHUP, sighup_handler);
569 signal(SIGPIPE, SIG_IGN);
570 signal(SIGTERM, sigterm_handler);
571 #endif /* HAVE_SIGSET */
572
573 #ifdef __sgi
574 /*
575 * Try to create a fake lpsched lock file if one is not already there.
576 * Some Adobe applications need it under IRIX in order to enable
577 * printing...
578 */
579
580 if ((fp = cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL)
581 {
582 syslog(LOG_LPR, "Unable to create fake lpsched lock file "
583 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
584 strerror(errno));
585 }
586 else
587 {
588 fchmod(cupsFileNumber(fp), 0644);
589 fchown(cupsFileNumber(fp), User, Group);
590
591 cupsFileClose(fp);
592 }
593 #endif /* __sgi */
594
595 /*
596 * Initialize authentication certificates...
597 */
598
599 cupsdInitCerts();
600
601 /*
602 * If we are running in the background, signal the parent process that
603 * we are up and running...
604 */
605
606 if (!fg || run_as_child)
607 {
608 /*
609 * Send a signal to the parent process, but only if the parent is
610 * not PID 1 (init). This avoids accidentally shutting down the
611 * system on OpenBSD if you CTRL-C the server before it is up...
612 */
613
614 i = getppid(); /* Save parent PID to avoid race condition */
615
616 if (i != 1)
617 kill(i, SIGUSR1);
618 }
619
620 #ifdef __APPLE__
621 /*
622 * Start power management framework...
623 */
624
625 if (use_sysman)
626 cupsdStartSystemMonitor();
627 #endif /* __APPLE__ */
628
629 /*
630 * Send server-started event...
631 */
632
633 #ifdef HAVE_LAUNCHD
634 if (Launchd)
635 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
636 "Scheduler started via launchd.");
637 else
638 #endif /* HAVE_LAUNCHD */
639 if (fg)
640 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
641 "Scheduler started in foreground.");
642 else
643 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
644 "Scheduler started in background.");
645
646 /*
647 * Start any pending print jobs...
648 */
649
650 cupsdCheckJobs();
651
652 /*
653 * Loop forever...
654 */
655
656 current_time = time(NULL);
657 browse_time = current_time;
658 event_time = current_time;
659 expire_time = current_time;
660 fds = 1;
661 report_time = 0;
662 senddoc_time = current_time;
663
664 while (!stop_scheduler)
665 {
666 /*
667 * Check if there are dead children to handle...
668 */
669
670 if (dead_children)
671 process_children();
672
673 /*
674 * Check if we need to load the server configuration file...
675 */
676
677 if (NeedReload)
678 {
679 /*
680 * Close any idle clients...
681 */
682
683 if (cupsArrayCount(Clients) > 0)
684 {
685 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
686 con;
687 con = (cupsd_client_t *)cupsArrayNext(Clients))
688 if (con->http.state == HTTP_WAITING)
689 cupsdCloseClient(con);
690 else
691 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
692
693 cupsdPauseListening();
694 }
695
696 /*
697 * Restart if all clients are closed and all jobs finished, or
698 * if the reload timeout has elapsed...
699 */
700
701 if ((cupsArrayCount(Clients) == 0 &&
702 (cupsArrayCount(PrintingJobs) == 0 || NeedReload != RELOAD_ALL)) ||
703 (time(NULL) - ReloadTime) >= ReloadTimeout)
704 {
705 /*
706 * Shutdown the server...
707 */
708
709 cupsdStopServer();
710
711 /*
712 * Read configuration...
713 */
714
715 if (!cupsdReadConfiguration())
716 {
717 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
718 ConfigurationFile);
719 break;
720 }
721
722 #if HAVE_LAUNCHD
723 if (Launchd)
724 {
725 /*
726 * If we were started by launchd, get the listen socket file
727 * descriptors...
728 */
729
730 launchd_checkin();
731 launchd_checkout();
732 }
733 #endif /* HAVE_LAUNCHD */
734
735 /*
736 * Startup the server...
737 */
738
739 cupsdStartServer();
740
741 /*
742 * Send a server-restarted event...
743 */
744
745 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED, NULL, NULL,
746 "Scheduler restarted.");
747 }
748 }
749
750 /*
751 * Check for available input or ready output. If cupsdDoSelect()
752 * returns 0 or -1, something bad happened and we should exit
753 * immediately.
754 *
755 * Note that we at least have one listening socket open at all
756 * times.
757 */
758
759 if ((timeout = select_timeout(fds)) > 1 && LastEvent)
760 timeout = 1;
761
762 #if HAVE_LAUNCHD
763 /*
764 * If no other work is scheduled and we're being controlled by
765 * launchd then timeout after 'LaunchdTimeout' seconds of
766 * inactivity...
767 */
768
769 if (timeout == 86400 && Launchd && LaunchdTimeout && !NumPolled &&
770 !cupsArrayCount(ActiveJobs) &&
771 (!Browsing ||
772 (!BrowseRemoteProtocols &&
773 (!NumBrowsers || !BrowseLocalProtocols ||
774 cupsArrayCount(Printers) == 0))))
775 {
776 timeout = LaunchdTimeout;
777 launchd_idle_exit = 1;
778 }
779 else
780 launchd_idle_exit = 0;
781 #endif /* HAVE_LAUNCHD */
782
783 if ((fds = cupsdDoSelect(timeout)) < 0)
784 {
785 /*
786 * Got an error from select!
787 */
788
789 #ifdef HAVE_DNSSD
790 cupsd_printer_t *p; /* Current printer */
791 #endif /* HAVE_DNSSD */
792
793
794 if (errno == EINTR) /* Just interrupted by a signal */
795 continue;
796
797 /*
798 * Log all sorts of debug info to help track down the problem.
799 */
800
801 cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
802 strerror(errno));
803
804 for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
805 con;
806 i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
807 cupsdLogMessage(CUPSD_LOG_EMERG,
808 "Clients[%d] = %d, file = %d, state = %d",
809 i, con->http.fd, con->file, con->http.state);
810
811 for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
812 lis;
813 i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
814 cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
815
816 cupsdLogMessage(CUPSD_LOG_EMERG, "BrowseSocket = %d", BrowseSocket);
817
818 cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);
819
820 #ifdef __APPLE__
821 cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
822 SysEventPipes[0]);
823 #endif /* __APPLE__ */
824
825 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
826 job;
827 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
828 cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
829 job->id,
830 job->status_buffer ? job->status_buffer->fd : -1,
831 job->print_pipes[0], job->print_pipes[1],
832 job->back_pipes[0], job->back_pipes[1]);
833
834 #ifdef HAVE_DNSSD
835 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
836 p;
837 p = (cupsd_printer_t *)cupsArrayNext(Printers))
838 cupsdLogMessage(CUPSD_LOG_EMERG, "printer[%s] reg_name=\"%s\"", p->name,
839 p->reg_name ? p->reg_name : "(null)");
840 #endif /* HAVE_DNSSD */
841
842 break;
843 }
844
845 current_time = time(NULL);
846
847 /*
848 * Write dirty config/state files...
849 */
850
851 if (DirtyCleanTime && current_time >= DirtyCleanTime)
852 cupsdCleanDirty();
853
854 #ifdef __APPLE__
855 /*
856 * If we are going to sleep and still have pending jobs, stop them after
857 * a period of time...
858 */
859
860 if (SleepJobs > 0 && current_time >= SleepJobs &&
861 cupsArrayCount(PrintingJobs) > 0)
862 {
863 SleepJobs = 0;
864 cupsdStopAllJobs(CUPSD_JOB_DEFAULT, 10);
865 }
866 #endif /* __APPLE__ */
867
868 #ifndef __APPLE__
869 /*
870 * Update the network interfaces once a minute...
871 */
872
873 if ((current_time - netif_time) >= 60)
874 {
875 netif_time = current_time;
876 NetIFUpdate = 1;
877 }
878 #endif /* !__APPLE__ */
879
880 #if HAVE_LAUNCHD
881 /*
882 * If no other work was scheduled and we're being controlled by launchd
883 * then timeout after 'LaunchdTimeout' seconds of inactivity...
884 */
885
886 if (!fds && launchd_idle_exit)
887 {
888 cupsdLogMessage(CUPSD_LOG_INFO,
889 "Printer sharing is off and there are no jobs pending, "
890 "will restart on demand.");
891 stop_scheduler = 1;
892 break;
893 }
894 #endif /* HAVE_LAUNCHD */
895
896 /*
897 * Resume listening for new connections as needed...
898 */
899
900 if (ListeningPaused && ListeningPaused <= current_time &&
901 cupsArrayCount(Clients) < MaxClients)
902 cupsdResumeListening();
903
904 /*
905 * Expire subscriptions and unload completed jobs as needed...
906 */
907
908 if (current_time > expire_time)
909 {
910 if (cupsArrayCount(Subscriptions) > 0)
911 cupsdExpireSubscriptions(NULL, NULL);
912
913 cupsdUnloadCompletedJobs();
914
915 expire_time = current_time;
916 }
917
918 /*
919 * Update the browse list as needed...
920 */
921
922 if (Browsing)
923 {
924 #ifdef HAVE_LIBSLP
925 if ((BrowseRemoteProtocols & BROWSE_SLP) &&
926 BrowseSLPRefresh <= current_time)
927 cupsdUpdateSLPBrowse();
928 #endif /* HAVE_LIBSLP */
929
930 #ifdef HAVE_LDAP
931 if ((BrowseRemoteProtocols & BROWSE_LDAP) &&
932 BrowseLDAPRefresh <= current_time)
933 cupsdUpdateLDAPBrowse();
934 #endif /* HAVE_LDAP */
935 }
936
937 if (Browsing && current_time > browse_time)
938 {
939 cupsdSendBrowseList();
940 browse_time = current_time;
941 }
942
943 /*
944 * Update the root certificate once every 5 minutes if we have client
945 * connections...
946 */
947
948 if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
949 !RunUser && cupsArrayCount(Clients))
950 {
951 /*
952 * Update the root certificate...
953 */
954
955 cupsdDeleteCert(0);
956 cupsdAddCert(0, "root", NULL);
957 }
958
959 /*
960 * Check for new data on the client sockets...
961 */
962
963 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
964 con;
965 con = (cupsd_client_t *)cupsArrayNext(Clients))
966 {
967 /*
968 * Process pending data in the input buffer...
969 */
970
971 if (con->http.used)
972 {
973 cupsdReadClient(con);
974 continue;
975 }
976
977 /*
978 * Check the activity and close old clients...
979 */
980
981 activity = current_time - Timeout;
982 if (con->http.activity < activity && !con->pipe_pid)
983 {
984 cupsdLogMessage(CUPSD_LOG_DEBUG,
985 "Closing client %d after %d seconds of inactivity...",
986 con->http.fd, Timeout);
987
988 cupsdCloseClient(con);
989 continue;
990 }
991 }
992
993 /*
994 * Update any pending multi-file documents...
995 */
996
997 if ((current_time - senddoc_time) >= 10)
998 {
999 cupsdCheckJobs();
1000 cupsdCleanJobs();
1001 senddoc_time = current_time;
1002 }
1003
1004 /*
1005 * Log statistics at most once a minute when in debug mode...
1006 */
1007
1008 if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
1009 {
1010 size_t string_count, /* String count */
1011 alloc_bytes, /* Allocated string bytes */
1012 total_bytes; /* Total string bytes */
1013 #ifdef HAVE_MALLINFO
1014 struct mallinfo mem; /* Malloc information */
1015
1016
1017 mem = mallinfo();
1018 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
1019 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
1020 mem.usmblks + mem.uordblks);
1021 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
1022 mem.fsmblks + mem.fordblks);
1023 #endif /* HAVE_MALLINFO */
1024
1025 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
1026 cupsArrayCount(Clients));
1027 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
1028 cupsArrayCount(Jobs));
1029 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
1030 cupsArrayCount(ActiveJobs));
1031 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
1032 cupsArrayCount(Printers));
1033 cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers-implicit=%d",
1034 cupsArrayCount(ImplicitPrinters));
1035
1036 string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
1037 cupsdLogMessage(CUPSD_LOG_DEBUG,
1038 "Report: stringpool-string-count=" CUPS_LLFMT,
1039 CUPS_LLCAST string_count);
1040 cupsdLogMessage(CUPSD_LOG_DEBUG,
1041 "Report: stringpool-alloc-bytes=" CUPS_LLFMT,
1042 CUPS_LLCAST alloc_bytes);
1043 cupsdLogMessage(CUPSD_LOG_DEBUG,
1044 "Report: stringpool-total-bytes=" CUPS_LLFMT,
1045 CUPS_LLCAST total_bytes);
1046
1047 report_time = current_time;
1048 }
1049
1050 /*
1051 * Handle OS-specific event notification for any events that have
1052 * accumulated. Don't send these more than once a second...
1053 */
1054
1055 if (LastEvent && (current_time - event_time) >= 1)
1056 {
1057 #ifdef HAVE_NOTIFY_POST
1058 if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
1059 CUPSD_EVENT_PRINTER_DELETED |
1060 CUPSD_EVENT_PRINTER_MODIFIED))
1061 {
1062 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1063 "notify_post(\"com.apple.printerListChange\")");
1064 notify_post("com.apple.printerListChange");
1065 }
1066
1067 if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
1068 {
1069 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1070 "notify_post(\"com.apple.printerHistoryChange\")");
1071 notify_post("com.apple.printerHistoryChange");
1072 }
1073
1074 if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
1075 CUPSD_EVENT_JOB_CONFIG_CHANGED |
1076 CUPSD_EVENT_JOB_PROGRESS))
1077 {
1078 cupsdLogMessage(CUPSD_LOG_DEBUG2,
1079 "notify_post(\"com.apple.jobChange\")");
1080 notify_post("com.apple.jobChange");
1081 }
1082 #endif /* HAVE_NOTIFY_POST */
1083
1084 /*
1085 * Reset the accumulated events...
1086 */
1087
1088 LastEvent = CUPSD_EVENT_NONE;
1089 event_time = current_time;
1090 }
1091 }
1092
1093 /*
1094 * Log a message based on what happened...
1095 */
1096
1097 if (stop_scheduler)
1098 {
1099 cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
1100 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1101 "Scheduler shutting down normally.");
1102 }
1103 else
1104 {
1105 cupsdLogMessage(CUPSD_LOG_ERROR,
1106 "Scheduler shutting down due to program error.");
1107 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
1108 "Scheduler shutting down due to program error.");
1109 }
1110
1111 /*
1112 * Close all network clients...
1113 */
1114
1115 cupsdStopServer();
1116
1117 #ifdef HAVE_LAUNCHD
1118 /*
1119 * Update the launchd KeepAlive file as needed...
1120 */
1121
1122 if (Launchd)
1123 launchd_checkout();
1124 #endif /* HAVE_LAUNCHD */
1125
1126 /*
1127 * Stop all jobs...
1128 */
1129
1130 cupsdFreeAllJobs();
1131
1132 #ifdef __APPLE__
1133 /*
1134 * Stop monitoring system event monitoring...
1135 */
1136
1137 if (use_sysman)
1138 cupsdStopSystemMonitor();
1139 #endif /* __APPLE__ */
1140
1141 #ifdef HAVE_GSSAPI
1142 /*
1143 * Free the scheduler's Kerberos context...
1144 */
1145
1146 # ifdef __APPLE__
1147 /*
1148 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1149 * to use it...
1150 */
1151
1152 if (krb5_init_context != NULL)
1153 # endif /* __APPLE__ */
1154 if (KerberosContext)
1155 krb5_free_context(KerberosContext);
1156 #endif /* HAVE_GSSAPI */
1157
1158 #ifdef __sgi
1159 /*
1160 * Remove the fake IRIX lpsched lock file, but only if the existing
1161 * file is not a FIFO which indicates that the real IRIX lpsched is
1162 * running...
1163 */
1164
1165 if (!stat("/var/spool/lp/FIFO", &statbuf))
1166 if (!S_ISFIFO(statbuf.st_mode))
1167 unlink("/var/spool/lp/SCHEDLOCK");
1168 #endif /* __sgi */
1169
1170 cupsdStopSelect();
1171
1172 return (!stop_scheduler);
1173 }
1174
1175
1176 /*
1177 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1178 */
1179
1180 void
1181 cupsdCheckProcess(void)
1182 {
1183 /*
1184 * Flag that we have dead children...
1185 */
1186
1187 dead_children = 1;
1188 }
1189
1190
1191 /*
1192 * 'cupsdClosePipe()' - Close a pipe as necessary.
1193 */
1194
1195 void
1196 cupsdClosePipe(int *fds) /* I - Pipe file descriptors (2) */
1197 {
1198 /*
1199 * Close file descriptors as needed...
1200 */
1201
1202 if (fds[0] >= 0)
1203 {
1204 close(fds[0]);
1205 fds[0] = -1;
1206 }
1207
1208 if (fds[1] >= 0)
1209 {
1210 close(fds[1]);
1211 fds[1] = -1;
1212 }
1213 }
1214
1215
1216 /*
1217 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1218 */
1219
1220 int /* O - 0 on success, -1 on error */
1221 cupsdOpenPipe(int *fds) /* O - Pipe file descriptors (2) */
1222 {
1223 /*
1224 * Create the pipe...
1225 */
1226
1227 if (pipe(fds))
1228 {
1229 fds[0] = -1;
1230 fds[1] = -1;
1231
1232 return (-1);
1233 }
1234
1235 /*
1236 * Set the "close on exec" flag on each end of the pipe...
1237 */
1238
1239 if (fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC))
1240 {
1241 close(fds[0]);
1242 close(fds[1]);
1243
1244 fds[0] = -1;
1245 fds[1] = -1;
1246
1247 return (-1);
1248 }
1249
1250 if (fcntl(fds[1], F_SETFD, fcntl(fds[1], F_GETFD) | FD_CLOEXEC))
1251 {
1252 close(fds[0]);
1253 close(fds[1]);
1254
1255 fds[0] = -1;
1256 fds[1] = -1;
1257
1258 return (-1);
1259 }
1260
1261 /*
1262 * Return 0 indicating success...
1263 */
1264
1265 return (0);
1266 }
1267
1268
1269 /*
1270 * 'cupsdClearString()' - Clear a string.
1271 */
1272
1273 void
1274 cupsdClearString(char **s) /* O - String value */
1275 {
1276 if (s && *s)
1277 {
1278 _cupsStrFree(*s);
1279 *s = NULL;
1280 }
1281 }
1282
1283
1284 /*
1285 * 'cupsdHoldSignals()' - Hold child and termination signals.
1286 */
1287
1288 void
1289 cupsdHoldSignals(void)
1290 {
1291 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1292 sigset_t newmask; /* New POSIX signal mask */
1293 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1294
1295
1296 holdcount ++;
1297 if (holdcount > 1)
1298 return;
1299
1300 #ifdef HAVE_SIGSET
1301 sighold(SIGTERM);
1302 sighold(SIGCHLD);
1303 #elif defined(HAVE_SIGACTION)
1304 sigemptyset(&newmask);
1305 sigaddset(&newmask, SIGTERM);
1306 sigaddset(&newmask, SIGCHLD);
1307 sigprocmask(SIG_BLOCK, &newmask, &holdmask);
1308 #endif /* HAVE_SIGSET */
1309 }
1310
1311
1312 /*
1313 * 'cupsdReleaseSignals()' - Release signals for delivery.
1314 */
1315
1316 void
1317 cupsdReleaseSignals(void)
1318 {
1319 holdcount --;
1320 if (holdcount > 0)
1321 return;
1322
1323 #ifdef HAVE_SIGSET
1324 sigrelse(SIGTERM);
1325 sigrelse(SIGCHLD);
1326 #elif defined(HAVE_SIGACTION)
1327 sigprocmask(SIG_SETMASK, &holdmask, NULL);
1328 #endif /* HAVE_SIGSET */
1329 }
1330
1331
1332 /*
1333 * 'cupsdSetString()' - Set a string value.
1334 */
1335
1336 void
1337 cupsdSetString(char **s, /* O - New string */
1338 const char *v) /* I - String value */
1339 {
1340 if (!s || *s == v)
1341 return;
1342
1343 if (*s)
1344 _cupsStrFree(*s);
1345
1346 if (v)
1347 *s = _cupsStrAlloc(v);
1348 else
1349 *s = NULL;
1350 }
1351
1352
1353 /*
1354 * 'cupsdSetStringf()' - Set a formatted string value.
1355 */
1356
1357 void
1358 cupsdSetStringf(char **s, /* O - New string */
1359 const char *f, /* I - Printf-style format string */
1360 ...) /* I - Additional args as needed */
1361 {
1362 char v[4096]; /* Formatting string value */
1363 va_list ap; /* Argument pointer */
1364 char *olds; /* Old string */
1365
1366
1367 if (!s)
1368 return;
1369
1370 olds = *s;
1371
1372 if (f)
1373 {
1374 va_start(ap, f);
1375 vsnprintf(v, sizeof(v), f, ap);
1376 va_end(ap);
1377
1378 *s = _cupsStrAlloc(v);
1379 }
1380 else
1381 *s = NULL;
1382
1383 if (olds)
1384 _cupsStrFree(olds);
1385 }
1386
1387
1388 /*
1389 * 'cupsd_clean_files()' - Clean out old files.
1390 */
1391
1392 static void
1393 cupsd_clean_files(const char *path, /* I - Directory to clean */
1394 const char *pattern) /* I - Filename pattern or NULL */
1395 {
1396 cups_dir_t *dir; /* Directory */
1397 cups_dentry_t *dent; /* Directory entry */
1398 char filename[1024]; /* Filename */
1399 int status; /* Status from unlink/rmdir */
1400
1401
1402 cupsdLogMessage(CUPSD_LOG_DEBUG,
1403 "cupsd_clean_files(path=\"%s\", pattern=\"%s\")", path,
1404 pattern ? pattern : "(null)");
1405
1406 if ((dir = cupsDirOpen(path)) == NULL)
1407 {
1408 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to open directory \"%s\" - %s",
1409 path, strerror(errno));
1410 return;
1411 }
1412
1413 cupsdLogMessage(CUPSD_LOG_INFO, "Cleaning out old files in \"%s\"...", path);
1414
1415 while ((dent = cupsDirRead(dir)) != NULL)
1416 {
1417 if (pattern && fnmatch(pattern, dent->filename, 0))
1418 continue;
1419
1420 snprintf(filename, sizeof(filename), "%s/%s", path, dent->filename);
1421
1422 if (S_ISDIR(dent->fileinfo.st_mode))
1423 {
1424 cupsd_clean_files(filename, pattern);
1425
1426 status = rmdir(filename);
1427 }
1428 else
1429 status = unlink(filename);
1430
1431 if (status)
1432 cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to remove \"%s\" - %s", filename,
1433 strerror(errno));
1434 else
1435 cupsdLogMessage(CUPSD_LOG_DEBUG, "Removed \"%s\"...", filename);
1436 }
1437
1438 cupsDirClose(dir);
1439 }
1440
1441
1442 #ifdef HAVE_LAUNCHD
1443 /*
1444 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1445 */
1446
1447 static void
1448 launchd_checkin(void)
1449 {
1450 size_t i, /* Looping var */
1451 count; /* Number of listeners */
1452 # ifdef HAVE_SSL
1453 int portnum; /* Port number */
1454 # endif /* HAVE_SSL */
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 */