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