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