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