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