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