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