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