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