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