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