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