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