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