]> 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/*
bc44d920 2 * "$Id: main.c 6654 2007-07-12 22:07:57Z mike $"
ef416fc2 3 *
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
5 *
bc44d920 6 * Copyright 2007 by Apple Inc.
f7deaa1a 7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
ef416fc2 8 *
9 * These coded instructions, statements, and computer programs are the
bc44d920 10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
ef416fc2 12 * "LICENSE" which should have been included with this file. If this
bc44d920 13 * file is missing or damaged, see the license at "http://www.cups.org/".
ef416fc2 14 *
15 * Contents:
16 *
17 * main() - Main entry for the CUPS scheduler.
18 * cupsdClosePipe() - Close a pipe as necessary.
19 * cupsdOpenPipe() - Create a pipe which is closed on exec.
ef416fc2 20 * cupsdHoldSignals() - Hold child and termination signals.
ef416fc2 21 * cupsdReleaseSignals() - Release signals for delivery.
22 * cupsdSetString() - Set a string value.
23 * cupsdSetStringf() - Set a formatted string value.
a4d04587 24 * launchd_checkin() - Check-in with launchd and collect the
25 * listening fds.
f7deaa1a 26 * launchd_checkout() - Check-out with launchd.
ef416fc2 27 * parent_handler() - Catch USR1/CHLD signals...
28 * process_children() - Process all dead children...
29 * sigchld_handler() - Handle 'child' signals from old processes.
30 * sighup_handler() - Handle 'hangup' signals to reconfigure the
31 * scheduler.
32 * sigterm_handler() - Handle 'terminate' signals that stop the
33 * scheduler.
34 * select_timeout() - Calculate the select timeout value.
35 * usage() - Show scheduler usage.
36 */
37
38/*
39 * Include necessary headers...
40 */
41
42#define _MAIN_C_
43#include "cupsd.h"
44#include <sys/resource.h>
45#include <syslog.h>
46#include <grp.h>
47
a4d04587 48#ifdef HAVE_LAUNCH_H
49# include <launch.h>
50# include <libgen.h>
7594b224 51# define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
f7deaa1a 52 /* Name of the launchd KeepAlive file */
53# ifndef LAUNCH_JOBKEY_KEEPALIVE
54# define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
55# endif /* !LAUNCH_JOBKEY_KEEPALIVE */
56# ifndef LAUNCH_JOBKEY_PATHSTATE
57# define LAUNCH_JOBKEY_PATHSTATE "PathState"
58# endif /* !LAUNCH_JOBKEY_PATHSTATE */
59# ifndef LAUNCH_JOBKEY_SERVICEIPC
60# define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
61# endif /* !LAUNCH_JOBKEY_SERVICEIPC */
a4d04587 62#endif /* HAVE_LAUNCH_H */
63
ef416fc2 64#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
65# include <malloc.h>
66#endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
fa73b229 67#ifdef HAVE_NOTIFY_H
68# include <notify.h>
69#endif /* HAVE_NOTIFY_H */
ef416fc2 70
7594b224 71#if defined(__APPLE__) && defined(HAVE_DLFCN_H)
72# include <dlfcn.h>
73#endif /* __APPLE__ && HAVE_DLFCN_H */
74
ef416fc2 75
76/*
77 * Local functions...
78 */
79
a4d04587 80#ifdef HAVE_LAUNCHD
411affcf 81static void launchd_checkin(void);
f7deaa1a 82static void launchd_checkout(void);
a4d04587 83#endif /* HAVE_LAUNCHD */
411affcf 84static void parent_handler(int sig);
85static void process_children(void);
86static void sigchld_handler(int sig);
87static void sighup_handler(int sig);
88static void sigterm_handler(int sig);
89static long select_timeout(int fds);
90static void usage(int status);
ef416fc2 91
92
93/*
94 * Local globals...
95 */
96
411affcf 97static int parent_signal = 0;
98 /* Set to signal number from child */
99static int holdcount = 0; /* Number of times "hold" was called */
ef416fc2 100#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
411affcf 101static sigset_t holdmask; /* Old POSIX signal mask */
ef416fc2 102#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
411affcf 103static int dead_children = 0;
104 /* Dead children? */
105static int stop_scheduler = 0;
106 /* Should the scheduler stop? */
107
7594b224 108#if defined(__APPLE__) && defined(HAVE_DLFCN_H)
109static const char *PSQLibPath = "/usr/lib/libPrintServiceQuota.dylib";
110static const char *PSQLibFuncName = "PSQUpdateQuota";
111static void *PSQLibRef; /* libPrintServiceQuota.dylib */
112#endif /* HAVE_DLFCN_H */
113
ef416fc2 114
115/*
116 * 'main()' - Main entry for the CUPS scheduler.
117 */
118
119int /* O - Exit status */
bd7854cb 120main(int argc, /* I - Number of command-line args */
ef416fc2 121 char *argv[]) /* I - Command-line arguments */
122{
123 int i; /* Looping var */
124 char *opt; /* Option character */
125 int fg; /* Run in the foreground */
bd7854cb 126 int fds; /* Number of ready descriptors */
ef416fc2 127 cupsd_client_t *con; /* Current client */
128 cupsd_job_t *job; /* Current job */
129 cupsd_listener_t *lis; /* Current listener */
130 time_t current_time, /* Current time */
a4d04587 131 activity, /* Client activity timer */
ef416fc2 132 browse_time, /* Next browse send time */
133 senddoc_time, /* Send-Document time */
411affcf 134 expire_time, /* Subscription expire time */
411affcf 135 mallinfo_time; /* Malloc information time */
4400e98d 136 size_t string_count, /* String count */
137 alloc_bytes, /* Allocated string bytes */
138 total_bytes; /* Total string bytes */
f7deaa1a 139 long timeout; /* Timeout for cupsdDoSelect() */
ef416fc2 140 struct rlimit limit; /* Runtime limit */
141#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
142 struct sigaction action; /* Actions for POSIX signals */
143#endif /* HAVE_SIGACTION && !HAVE_SIGSET */
144#ifdef __sgi
145 cups_file_t *fp; /* Fake lpsched lock file */
146 struct stat statbuf; /* Needed for checking lpsched FIFO */
147#endif /* __sgi */
a4d04587 148#if HAVE_LAUNCHD
4400e98d 149 int launchd_idle_exit;
a4d04587 150 /* Idle exit on select timeout? */
151#endif /* HAVE_LAUNCHD */
ef416fc2 152
153
154 /*
155 * Check for command-line arguments...
156 */
157
4400e98d 158 fg = 0;
ef416fc2 159
09a101d6 160#ifdef HAVE_LAUNCHD
161 if (getenv("CUPSD_LAUNCHD"))
162 {
163 Launchd = 1;
164 fg = 1;
165 }
166#endif /* HAVE_LAUNCHD */
167
ef416fc2 168 for (i = 1; i < argc; i ++)
169 if (argv[i][0] == '-')
170 for (opt = argv[i] + 1; *opt != '\0'; opt ++)
171 switch (*opt)
172 {
173 case 'c' : /* Configuration file */
174 i ++;
175 if (i >= argc)
a4d04587 176 {
177 _cupsLangPuts(stderr, _("cupsd: Expected config filename "
178 "after \"-c\" option!\n"));
179 usage(1);
180 }
ef416fc2 181
182 if (argv[i][0] == '/')
183 {
184 /*
185 * Absolute directory...
186 */
187
188 cupsdSetString(&ConfigurationFile, argv[i]);
189 }
190 else
191 {
192 /*
193 * Relative directory...
194 */
195
09ec0018 196 char *current; /* Current directory */
ef416fc2 197
198
09ec0018 199 /*
200 * Allocate a buffer for the current working directory to
201 * reduce run-time stack usage; this approximates the
202 * behavior of some implementations of getcwd() when they
203 * are passed a NULL pointer.
204 */
205
206 current = malloc(1024);
207 getcwd(current, 1024);
208
ef416fc2 209 cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
09ec0018 210
211 free(current);
ef416fc2 212 }
213 break;
214
215 case 'f' : /* Run in foreground... */
216 fg = 1;
217 break;
218
bd7854cb 219 case 'F' : /* Run in foreground, but disconnect from terminal... */
ef416fc2 220 fg = -1;
221 break;
222
a4d04587 223 case 'h' : /* Show usage/help */
224 usage(0);
225 break;
226
227 case 'l' : /* Started by launchd... */
228#ifdef HAVE_LAUNCHD
4400e98d 229 Launchd = 1;
a4d04587 230 fg = 1;
231#else
232 _cupsLangPuts(stderr, _("cupsd: launchd(8) support not compiled "
233 "in, running in normal mode.\n"));
234 fg = 0;
235#endif /* HAVE_LAUNCHD */
236 break;
237
a74454a7 238 case 'p' : /* Stop immediately for profiling */
239 puts("Warning: -p option is for internal testing use only!");
240 stop_scheduler = 1;
241 fg = 1;
242 break;
243
ef416fc2 244 default : /* Unknown option */
a4d04587 245 _cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
246 "aborting!\n"), *opt);
247 usage(1);
ef416fc2 248 break;
249 }
250 else
251 {
a4d04587 252 _cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
253 argv[i]);
254 usage(1);
ef416fc2 255 }
256
257 if (!ConfigurationFile)
258 cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
259
260 /*
261 * If the user hasn't specified "-f", run in the background...
262 */
263
264 if (!fg)
265 {
266 /*
267 * Setup signal handlers for the parent...
268 */
269
270#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
271 sigset(SIGUSR1, parent_handler);
272 sigset(SIGCHLD, parent_handler);
273
274 sigset(SIGHUP, SIG_IGN);
275#elif defined(HAVE_SIGACTION)
276 memset(&action, 0, sizeof(action));
277 sigemptyset(&action.sa_mask);
278 sigaddset(&action.sa_mask, SIGUSR1);
279 action.sa_handler = parent_handler;
280 sigaction(SIGUSR1, &action, NULL);
281 sigaction(SIGCHLD, &action, NULL);
282
283 sigemptyset(&action.sa_mask);
284 action.sa_handler = SIG_IGN;
285 sigaction(SIGHUP, &action, NULL);
286#else
287 signal(SIGUSR1, parent_handler);
288 signal(SIGCLD, parent_handler);
289
290 signal(SIGHUP, SIG_IGN);
291#endif /* HAVE_SIGSET */
292
293 if (fork() > 0)
294 {
295 /*
296 * OK, wait for the child to startup and send us SIGUSR1 or to crash
297 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
298 * might be sent by the init script to restart the scheduler...
299 */
300
301 for (; parent_signal == 0;)
302 sleep(1);
303
304 if (parent_signal == SIGUSR1)
305 return (0);
306
307 if (wait(&i) < 0)
308 {
309 perror("cupsd");
310 return (1);
311 }
312 else if (WIFEXITED(i))
313 {
bd7854cb 314 fprintf(stderr, "cupsd: Child exited with status %d!\n",
315 WEXITSTATUS(i));
ef416fc2 316 return (2);
317 }
318 else
319 {
320 fprintf(stderr, "cupsd: Child exited on signal %d!\n", WTERMSIG(i));
321 return (3);
322 }
323 }
324 }
325
326 if (fg < 1)
327 {
328 /*
329 * Make sure we aren't tying up any filesystems...
330 */
331
332 chdir("/");
333
334#ifndef DEBUG
335 /*
336 * Disable core dumps...
337 */
338
339 getrlimit(RLIMIT_CORE, &limit);
340 limit.rlim_cur = 0;
341 setrlimit(RLIMIT_CORE, &limit);
342
343 /*
344 * Disconnect from the controlling terminal...
345 */
346
347 setsid();
348
349 /*
350 * Close all open files...
351 */
352
353 getrlimit(RLIMIT_NOFILE, &limit);
354
b94498cf 355 for (i = 0; i < limit.rlim_cur && i < 1024; i ++)
ef416fc2 356 close(i);
357#endif /* DEBUG */
358 }
359
360 /*
361 * Set the timezone info...
362 */
363
364 tzset();
365
366#ifdef LC_TIME
367 setlocale(LC_TIME, "");
368#endif /* LC_TIME */
369
370 /*
371 * Set the maximum number of files...
372 */
373
374 getrlimit(RLIMIT_NOFILE, &limit);
375
f7deaa1a 376#if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
f7faf1f5 377 if (limit.rlim_max > FD_SETSIZE)
378 MaxFDs = FD_SETSIZE;
ef416fc2 379 else
f7deaa1a 380#endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
381#ifdef RLIM_INFINITY
382 if (limit.rlim_max == RLIM_INFINITY)
383 MaxFDs = 16384;
384 else
385#endif /* RLIM_INFINITY */
ef416fc2 386 MaxFDs = limit.rlim_max;
387
388 limit.rlim_cur = MaxFDs;
389
390 setrlimit(RLIMIT_NOFILE, &limit);
391
f7deaa1a 392 cupsdStartSelect();
ef416fc2 393
394 /*
395 * Read configuration...
396 */
397
398 if (!cupsdReadConfiguration())
399 {
400 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
401 ConfigurationFile);
402 return (1);
403 }
404
a4d04587 405#if HAVE_LAUNCHD
4400e98d 406 if (Launchd)
a4d04587 407 {
408 /*
b94498cf 409 * If we were started by launchd get the listen sockets file descriptors...
f7deaa1a 410 */
a4d04587 411
412 launchd_checkin();
413 }
414#endif /* HAVE_LAUNCHD */
415
7594b224 416#if defined(__APPLE__) && defined(HAVE_DLFCN_H)
417 /*
418 * Load Print Service quota enforcement library (X Server only)
419 */
420
421 PSQLibRef = dlopen(PSQLibPath, RTLD_LAZY);
422
423 if (PSQLibRef)
424 PSQUpdateQuotaProc = dlsym(PSQLibRef, PSQLibFuncName);
425#endif /* __APPLE__ && HAVE_DLFCN_H */
426
a4d04587 427 /*
428 * Startup the server...
429 */
430
431 cupsdStartServer();
432
ef416fc2 433 /*
434 * Catch hangup and child signals and ignore broken pipes...
435 */
436
437#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
e1d6a774 438 sigset(SIGCHLD, sigchld_handler);
4744bd90 439 sigset(SIGHUP, sighup_handler);
ef416fc2 440 sigset(SIGPIPE, SIG_IGN);
441 sigset(SIGTERM, sigterm_handler);
442#elif defined(HAVE_SIGACTION)
443 memset(&action, 0, sizeof(action));
444
e1d6a774 445 sigemptyset(&action.sa_mask);
446 sigaddset(&action.sa_mask, SIGTERM);
447 sigaddset(&action.sa_mask, SIGCHLD);
448 action.sa_handler = sigchld_handler;
449 sigaction(SIGCHLD, &action, NULL);
450
ef416fc2 451 sigemptyset(&action.sa_mask);
452 sigaddset(&action.sa_mask, SIGHUP);
4744bd90 453 action.sa_handler = sighup_handler;
ef416fc2 454 sigaction(SIGHUP, &action, NULL);
455
456 sigemptyset(&action.sa_mask);
457 action.sa_handler = SIG_IGN;
458 sigaction(SIGPIPE, &action, NULL);
459
460 sigemptyset(&action.sa_mask);
461 sigaddset(&action.sa_mask, SIGTERM);
462 sigaddset(&action.sa_mask, SIGCHLD);
463 action.sa_handler = sigterm_handler;
464 sigaction(SIGTERM, &action, NULL);
465#else
e1d6a774 466 signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */
4744bd90 467 signal(SIGHUP, sighup_handler);
ef416fc2 468 signal(SIGPIPE, SIG_IGN);
469 signal(SIGTERM, sigterm_handler);
470#endif /* HAVE_SIGSET */
471
472#ifdef __sgi
473 /*
474 * Try to create a fake lpsched lock file if one is not already there.
475 * Some Adobe applications need it under IRIX in order to enable
476 * printing...
477 */
478
479 if ((fp = cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL)
480 {
481 syslog(LOG_LPR, "Unable to create fake lpsched lock file "
482 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
483 strerror(errno));
484 }
485 else
486 {
487 fchmod(cupsFileNumber(fp), 0644);
488 fchown(cupsFileNumber(fp), User, Group);
489
490 cupsFileClose(fp);
491 }
492#endif /* __sgi */
493
494 /*
495 * Initialize authentication certificates...
496 */
497
498 cupsdInitCerts();
499
500 /*
501 * If we are running in the background, signal the parent process that
502 * we are up and running...
503 */
504
505 if (!fg)
506 {
507 /*
508 * Send a signal to the parent process, but only if the parent is
509 * not PID 1 (init). This avoids accidentally shutting down the
510 * system on OpenBSD if you CTRL-C the server before it is up...
511 */
512
513 i = getppid(); /* Save parent PID to avoid race condition */
514
515 if (i != 1)
516 kill(i, SIGUSR1);
517 }
518
e1d6a774 519#ifdef __APPLE__
09ec0018 520 /*
521 * Start power management framework...
522 */
523
524 cupsdStartSystemMonitor();
e1d6a774 525#endif /* __APPLE__ */
ef416fc2 526
527 /*
528 * Start any pending print jobs...
529 */
530
531 cupsdCheckJobs();
532
533 /*
534 * Loop forever...
535 */
536
ef416fc2 537 mallinfo_time = 0;
ef416fc2 538 browse_time = time(NULL);
539 senddoc_time = time(NULL);
540 expire_time = time(NULL);
541 fds = 1;
542
543 while (!stop_scheduler)
544 {
545#ifdef DEBUG
546 cupsdLogMessage(CUPSD_LOG_DEBUG2,
547 "main: Top of loop, dead_children=%d, NeedReload=%d",
548 dead_children, NeedReload);
549#endif /* DEBUG */
550
551 /*
552 * Check if there are dead children to handle...
553 */
554
555 if (dead_children)
556 process_children();
557
558 /*
559 * Check if we need to load the server configuration file...
560 */
561
562 if (NeedReload)
563 {
564 /*
565 * Close any idle clients...
566 */
567
bd7854cb 568 if (cupsArrayCount(Clients) > 0)
ef416fc2 569 {
bd7854cb 570 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
571 con;
572 con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 573 if (con->http.state == HTTP_WAITING)
ef416fc2 574 cupsdCloseClient(con);
ef416fc2 575 else
576 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
577
578 cupsdPauseListening();
579 }
580
581 /*
582 * Check for any active jobs...
583 */
584
585 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
586 job;
587 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
bd7854cb 588 if (job->state_value == IPP_JOB_PROCESSING)
ef416fc2 589 break;
590
591 /*
592 * Restart if all clients are closed and all jobs finished, or
593 * if the reload timeout has elapsed...
594 */
595
bd7854cb 596 if ((cupsArrayCount(Clients) == 0 &&
597 (!job || NeedReload != RELOAD_ALL)) ||
ef416fc2 598 (time(NULL) - ReloadTime) >= ReloadTimeout)
599 {
a4d04587 600 /*
601 * Shutdown the server...
602 */
603
604 cupsdStopServer();
605
606 /*
607 * Read configuration...
608 */
609
ef416fc2 610 if (!cupsdReadConfiguration())
611 {
612 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
613 ConfigurationFile);
614 break;
615 }
a4d04587 616
617#if HAVE_LAUNCHD
4400e98d 618 if (Launchd)
a4d04587 619 {
b94498cf 620 /*
621 * If we were started by launchd get the listen sockets file descriptors...
622 */
623
a4d04587 624 launchd_checkin();
625 }
626#endif /* HAVE_LAUNCHD */
627
628 /*
629 * Startup the server...
630 */
631
632 cupsdStartServer();
ef416fc2 633 }
634 }
635
636 /*
f7deaa1a 637 * Check for available input or ready output. If cupsdDoSelect()
638 * returns 0 or -1, something bad happened and we should exit
639 * immediately.
ef416fc2 640 *
641 * Note that we at least have one listening socket open at all
642 * times.
643 */
644
f7deaa1a 645 timeout = select_timeout(fds);
ef416fc2 646
a4d04587 647#if HAVE_LAUNCHD
648 /*
649 * If no other work is scheduled and we're being controlled by
411affcf 650 * launchd then timeout after 'LaunchdTimeout' seconds of
a4d04587 651 * inactivity...
652 */
653
f7deaa1a 654 if (timeout == 86400 && Launchd && LaunchdTimeout && !NumPolled &&
bc44d920 655 !cupsArrayCount(ActiveJobs) &&
f7deaa1a 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}
a4d04587 1367#endif /* HAVE_LAUNCHD */
1368
1369
ef416fc2 1370/*
1371 * 'parent_handler()' - Catch USR1/CHLD signals...
1372 */
1373
1374static void
1375parent_handler(int sig) /* I - Signal */
1376{
1377 /*
1378 * Store the signal we got from the OS and return...
1379 */
1380
1381 parent_signal = sig;
1382}
1383
1384
1385/*
1386 * 'process_children()' - Process all dead children...
1387 */
1388
1389static void
1390process_children(void)
1391{
1392 int status; /* Exit status of child */
1393 int pid; /* Process ID of child */
1394 cupsd_job_t *job; /* Current job */
1395 int i; /* Looping var */
e00b005a 1396 char name[1024]; /* Process name */
ef416fc2 1397
1398
1399 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1400
1401 /*
1402 * Reset the dead_children flag...
1403 */
1404
1405 dead_children = 0;
1406
1407 /*
1408 * Collect the exit status of some children...
1409 */
1410
1411#ifdef HAVE_WAITPID
1412 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1413#elif defined(HAVE_WAIT3)
1414 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1415#else
1416 if ((pid = wait(&status)) > 0)
1417#endif /* HAVE_WAITPID */
1418 {
ef416fc2 1419 /*
d09495fa 1420 * Ignore SIGTERM errors - that comes when a job is canceled...
ef416fc2 1421 */
1422
e00b005a 1423 cupsdFinishProcess(pid, name, sizeof(name));
1424
ef416fc2 1425 if (status == SIGTERM)
1426 status = 0;
1427
1428 if (status)
1429 {
1430 if (WIFEXITED(status))
e00b005a 1431 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) stopped with status %d!",
1432 pid, name, WEXITSTATUS(status));
ef416fc2 1433 else
e00b005a 1434 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) crashed on signal %d!",
1435 pid, name, WTERMSIG(status));
ef416fc2 1436
1437 if (LogLevel < CUPSD_LOG_DEBUG)
1438 cupsdLogMessage(CUPSD_LOG_INFO,
bd7854cb 1439 "Hint: Try setting the LogLevel to \"debug\" to find "
1440 "out more.");
ef416fc2 1441 }
1442 else
e00b005a 1443 cupsdLogMessage(CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
1444 pid, name);
ef416fc2 1445
1446 /*
1447 * Delete certificates for CGI processes...
1448 */
1449
1450 if (pid)
1451 cupsdDeleteCert(pid);
1452
1453 /*
1454 * Lookup the PID in the jobs list...
1455 */
1456
1457 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1458 job;
1459 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
bd7854cb 1460 if (job->state_value == IPP_JOB_PROCESSING)
ef416fc2 1461 {
1462 for (i = 0; job->filters[i]; i ++)
1463 if (job->filters[i] == pid)
1464 break;
1465
1466 if (job->filters[i] || job->backend == pid)
1467 {
1468 /*
1469 * OK, this process has gone away; what's left?
1470 */
1471
1472 if (job->filters[i])
1473 job->filters[i] = -pid;
1474 else
1475 job->backend = -pid;
1476
1477 if (status && job->status >= 0)
1478 {
1479 /*
1480 * An error occurred; save the exit status so we know to stop
1481 * the printer or cancel the job when all of the filters finish...
1482 *
1483 * A negative status indicates that the backend failed and the
1484 * printer needs to be stopped.
1485 */
1486
1487 if (job->filters[i])
1488 job->status = status; /* Filter failed */
1489 else
1490 job->status = -status; /* Backend failed */
e00b005a 1491
1492 if (job->printer && !(job->printer->type & CUPS_PRINTER_FAX))
1493 {
1494 snprintf(job->printer->state_message,
1495 sizeof(job->printer->state_message), "%s failed", name);
1496 cupsdAddPrinterHistory(job->printer);
1497 }
ef416fc2 1498 }
1499
1500 /*
1501 * If this is not the last file in a job, see if all of the
1502 * filters are done, and if so move to the next file.
1503 */
1504
1505 if (job->current_file < job->num_files)
1506 {
1507 for (i = 0; job->filters[i] < 0; i ++);
1508
1509 if (!job->filters[i])
1510 {
1511 /*
1512 * Process the next file...
1513 */
1514
1515 cupsdFinishJob(job);
1516 }
1517 }
1518 break;
1519 }
1520 }
1521 }
1522}
1523
1524
1525/*
1526 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1527 */
1528
1529static void
1530sigchld_handler(int sig) /* I - Signal number */
1531{
1532 (void)sig;
1533
1534 /*
1535 * Flag that we have dead children...
1536 */
1537
1538 dead_children = 1;
1539
1540 /*
1541 * Reset the signal handler as needed...
1542 */
1543
1544#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1545 signal(SIGCLD, sigchld_handler);
1546#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1547}
1548
1549
1550/*
1551 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1552 */
1553
1554static void
1555sighup_handler(int sig) /* I - Signal number */
1556{
1557 (void)sig;
1558
1559 NeedReload = RELOAD_ALL;
1560 ReloadTime = time(NULL);
1561
1562#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1563 signal(SIGHUP, sighup_handler);
1564#endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1565}
1566
1567
1568/*
1569 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1570 */
1571
1572static void
1573sigterm_handler(int sig) /* I - Signal */
1574{
1575 (void)sig; /* remove compiler warnings... */
1576
1577 /*
1578 * Flag that we should stop and return...
1579 */
1580
1581 stop_scheduler = 1;
1582}
1583
1584
1585/*
1586 * 'select_timeout()' - Calculate the select timeout value.
1587 *
1588 */
1589
1590static long /* O - Number of seconds */
bd7854cb 1591select_timeout(int fds) /* I - Number of descriptors returned */
ef416fc2 1592{
ef416fc2 1593 long timeout; /* Timeout for select */
1594 time_t now; /* Current time */
1595 cupsd_client_t *con; /* Client information */
1596 cupsd_printer_t *p; /* Printer information */
1597 cupsd_job_t *job; /* Job information */
1598 cupsd_subscription_t *sub; /* Subscription information */
1599 const char *why; /* Debugging aid */
1600
1601
1602 /*
1603 * Check to see if any of the clients have pending data to be
1604 * processed; if so, the timeout should be 0...
1605 */
1606
bd7854cb 1607 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1608 con;
1609 con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 1610 if (con->http.used > 0)
1611 return (0);
1612
1613 /*
f7deaa1a 1614 * If select has been active in the last second (fds > 0) or we have
ef416fc2 1615 * many resources in use then don't bother trying to optimize the
1616 * timeout, just make it 1 second.
1617 */
1618
f7deaa1a 1619 if (fds > 0 || cupsArrayCount(Clients) > 50)
ef416fc2 1620 return (1);
1621
1622 /*
1623 * Otherwise, check all of the possible events that we need to wake for...
1624 */
1625
1626 now = time(NULL);
1627 timeout = now + 86400; /* 86400 == 1 day */
1628 why = "do nothing";
1629
1630 /*
1631 * Check the activity and close old clients...
1632 */
1633
bd7854cb 1634 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1635 con;
1636 con = (cupsd_client_t *)cupsArrayNext(Clients))
ef416fc2 1637 if ((con->http.activity + Timeout) < timeout)
1638 {
1639 timeout = con->http.activity + Timeout;
1640 why = "timeout a client connection";
1641 }
1642
1643 /*
1644 * Update the browse list as needed...
1645 */
1646
1647 if (Browsing && BrowseLocalProtocols)
1648 {
1649#ifdef HAVE_LIBSLP
1650 if ((BrowseLocalProtocols & BROWSE_SLP) && (BrowseSLPRefresh < timeout))
1651 {
1652 timeout = BrowseSLPRefresh;
1653 why = "update SLP browsing";
1654 }
1655#endif /* HAVE_LIBSLP */
1656
b423cd4c 1657#ifdef HAVE_LDAP
1658 if ((BrowseLocalProtocols & BROWSE_LDAP) && (BrowseLDAPRefresh < timeout))
1659 {
1660 timeout = BrowseLDAPRefresh;
1661 why = "update LDAP browsing";
1662 }
1663#endif /* HAVE_LDAP */
1664
f7deaa1a 1665 if ((BrowseLocalProtocols & BROWSE_CUPS) && NumBrowsers)
ef416fc2 1666 {
1667 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1668 p;
1669 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1670 {
1671 if (p->type & CUPS_PRINTER_REMOTE)
1672 {
1673 if ((p->browse_time + BrowseTimeout) < timeout)
1674 {
1675 timeout = p->browse_time + BrowseTimeout;
1676 why = "browse timeout a printer";
1677 }
1678 }
f7deaa1a 1679 else if (p->shared && !(p->type & CUPS_PRINTER_IMPLICIT))
ef416fc2 1680 {
1681 if (BrowseInterval && (p->browse_time + BrowseInterval) < timeout)
1682 {
1683 timeout = p->browse_time + BrowseInterval;
1684 why = "send browse update";
1685 }
1686 }
1687 }
1688 }
1689 }
1690
1691 /*
1692 * Check for any active jobs...
1693 */
1694
1695 if (timeout > (now + 10) && ActiveJobs)
1696 {
1697 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1698 job;
1699 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
bd7854cb 1700 if (job->state_value <= IPP_JOB_PROCESSING)
ef416fc2 1701 {
1702 timeout = now + 10;
1703 why = "process active jobs";
1704 break;
1705 }
1706 }
1707
1708#ifdef HAVE_MALLINFO
1709 /*
1710 * Log memory usage every minute...
1711 */
1712
1713 if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
1714 {
1715 timeout = mallinfo_time + 60;
1716 why = "display memory usage";
1717 }
1718#endif /* HAVE_MALLINFO */
1719
ef416fc2 1720 /*
1721 * Expire subscriptions as needed...
1722 */
1723
1724 for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
1725 sub;
1726 sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
bd7854cb 1727 if (!sub->job && sub->expire && sub->expire < timeout)
ef416fc2 1728 {
1729 timeout = sub->expire;
1730 why = "expire subscription";
1731 }
1732
1733 /*
1734 * Adjust from absolute to relative time. If p->browse_time above
1735 * was 0 then we can end up with a negative value here, so check.
1736 * We add 1 second to the timeout since events occur after the
1737 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1738 * to avoid select() timeout limits present on some operating
1739 * systems...
1740 */
1741
1742 timeout = timeout - now + 1;
1743
1744 if (timeout < 1)
1745 timeout = 1;
1746 else if (timeout > 86400)
1747 timeout = 86400;
1748
1749 /*
1750 * Log and return the timeout value...
1751 */
1752
f7deaa1a 1753 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
1754 fds, timeout, why);
ef416fc2 1755
1756 return (timeout);
1757}
1758
1759
1760/*
1761 * 'usage()' - Show scheduler usage.
1762 */
1763
1764static void
a4d04587 1765usage(int status) /* O - Exit status */
ef416fc2 1766{
a4d04587 1767 _cupsLangPuts(status ? stderr : stdout,
1768 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1769 "\n"
1770 "-c config-file Load alternate configuration file\n"
1771 "-f Run in the foreground\n"
1772 "-F Run in the foreground but detach\n"
1773 "-h Show this usage message\n"
1774 "-l Run cupsd from launchd(8)\n"));
1775 exit(status);
ef416fc2 1776}
1777
1778
1779/*
bc44d920 1780 * End of "$Id: main.c 6654 2007-07-12 22:07:57Z mike $".
ef416fc2 1781 */