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