]> git.ipfire.org Git - thirdparty/cups.git/blob - scheduler/main.c
Load cups into easysw/current.
[thirdparty/cups.git] / scheduler / main.c
1 /*
2 * "$Id: main.c 6493 2007-04-30 19:33:31Z mike $"
3 *
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
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.
29 * cupsdHoldSignals() - Hold child and termination signals.
30 * cupsdReleaseSignals() - Release signals for delivery.
31 * cupsdSetString() - Set a string value.
32 * cupsdSetStringf() - Set a formatted string value.
33 * launchd_checkin() - Check-in with launchd and collect the
34 * listening fds.
35 * launchd_checkout() - Check-out with launchd.
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
57 #ifdef HAVE_LAUNCH_H
58 # include <launch.h>
59 # include <libgen.h>
60 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
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 */
71 #endif /* HAVE_LAUNCH_H */
72
73 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
74 # include <malloc.h>
75 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
76 #ifdef HAVE_NOTIFY_H
77 # include <notify.h>
78 #endif /* HAVE_NOTIFY_H */
79
80 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
81 # include <dlfcn.h>
82 #endif /* __APPLE__ && HAVE_DLFCN_H */
83
84
85 /*
86 * Local functions...
87 */
88
89 #ifdef HAVE_LAUNCHD
90 static void launchd_checkin(void);
91 static void launchd_checkout(void);
92 #endif /* HAVE_LAUNCHD */
93 static void parent_handler(int sig);
94 static void process_children(void);
95 static void sigchld_handler(int sig);
96 static void sighup_handler(int sig);
97 static void sigterm_handler(int sig);
98 static long select_timeout(int fds);
99 static void usage(int status);
100
101
102 /*
103 * Local globals...
104 */
105
106 static int parent_signal = 0;
107 /* Set to signal number from child */
108 static int holdcount = 0; /* Number of times "hold" was called */
109 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
110 static sigset_t holdmask; /* Old POSIX signal mask */
111 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
112 static int dead_children = 0;
113 /* Dead children? */
114 static int stop_scheduler = 0;
115 /* Should the scheduler stop? */
116
117 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
118 static const char *PSQLibPath = "/usr/lib/libPrintServiceQuota.dylib";
119 static const char *PSQLibFuncName = "PSQUpdateQuota";
120 static void *PSQLibRef; /* libPrintServiceQuota.dylib */
121 #endif /* HAVE_DLFCN_H */
122
123
124 /*
125 * 'main()' - Main entry for the CUPS scheduler.
126 */
127
128 int /* O - Exit status */
129 main(int argc, /* I - Number of command-line args */
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 */
135 int fds; /* Number of ready descriptors */
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 */
140 activity, /* Client activity timer */
141 browse_time, /* Next browse send time */
142 senddoc_time, /* Send-Document time */
143 expire_time, /* Subscription expire time */
144 mallinfo_time; /* Malloc information time */
145 size_t string_count, /* String count */
146 alloc_bytes, /* Allocated string bytes */
147 total_bytes; /* Total string bytes */
148 long timeout; /* Timeout for cupsdDoSelect() */
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 */
157 #if HAVE_LAUNCHD
158 int launchd_idle_exit;
159 /* Idle exit on select timeout? */
160 #endif /* HAVE_LAUNCHD */
161
162
163 /*
164 * Check for command-line arguments...
165 */
166
167 fg = 0;
168
169 for (i = 1; i < argc; i ++)
170 if (argv[i][0] == '-')
171 for (opt = argv[i] + 1; *opt != '\0'; opt ++)
172 switch (*opt)
173 {
174 case 'c' : /* Configuration file */
175 i ++;
176 if (i >= argc)
177 {
178 _cupsLangPuts(stderr, _("cupsd: Expected config filename "
179 "after \"-c\" option!\n"));
180 usage(1);
181 }
182
183 if (argv[i][0] == '/')
184 {
185 /*
186 * Absolute directory...
187 */
188
189 cupsdSetString(&ConfigurationFile, argv[i]);
190 }
191 else
192 {
193 /*
194 * Relative directory...
195 */
196
197 char *current; /* Current directory */
198
199
200 /*
201 * Allocate a buffer for the current working directory to
202 * reduce run-time stack usage; this approximates the
203 * behavior of some implementations of getcwd() when they
204 * are passed a NULL pointer.
205 */
206
207 current = malloc(1024);
208 getcwd(current, 1024);
209
210 cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
211
212 free(current);
213 }
214 break;
215
216 case 'f' : /* Run in foreground... */
217 fg = 1;
218 break;
219
220 case 'F' : /* Run in foreground, but disconnect from terminal... */
221 fg = -1;
222 break;
223
224 case 'h' : /* Show usage/help */
225 usage(0);
226 break;
227
228 case 'l' : /* Started by launchd... */
229 #ifdef HAVE_LAUNCHD
230 Launchd = 1;
231 fg = 1;
232 #else
233 _cupsLangPuts(stderr, _("cupsd: launchd(8) support not compiled "
234 "in, running in normal mode.\n"));
235 fg = 0;
236 #endif /* HAVE_LAUNCHD */
237 break;
238
239 case 'p' : /* Stop immediately for profiling */
240 puts("Warning: -p option is for internal testing use only!");
241 stop_scheduler = 1;
242 fg = 1;
243 break;
244
245 default : /* Unknown option */
246 _cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
247 "aborting!\n"), *opt);
248 usage(1);
249 break;
250 }
251 else
252 {
253 _cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
254 argv[i]);
255 usage(1);
256 }
257
258 if (!ConfigurationFile)
259 cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
260
261 /*
262 * If the user hasn't specified "-f", run in the background...
263 */
264
265 if (!fg)
266 {
267 /*
268 * Setup signal handlers for the parent...
269 */
270
271 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
272 sigset(SIGUSR1, parent_handler);
273 sigset(SIGCHLD, parent_handler);
274
275 sigset(SIGHUP, SIG_IGN);
276 #elif defined(HAVE_SIGACTION)
277 memset(&action, 0, sizeof(action));
278 sigemptyset(&action.sa_mask);
279 sigaddset(&action.sa_mask, SIGUSR1);
280 action.sa_handler = parent_handler;
281 sigaction(SIGUSR1, &action, NULL);
282 sigaction(SIGCHLD, &action, NULL);
283
284 sigemptyset(&action.sa_mask);
285 action.sa_handler = SIG_IGN;
286 sigaction(SIGHUP, &action, NULL);
287 #else
288 signal(SIGUSR1, parent_handler);
289 signal(SIGCLD, parent_handler);
290
291 signal(SIGHUP, SIG_IGN);
292 #endif /* HAVE_SIGSET */
293
294 if (fork() > 0)
295 {
296 /*
297 * OK, wait for the child to startup and send us SIGUSR1 or to crash
298 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
299 * might be sent by the init script to restart the scheduler...
300 */
301
302 for (; parent_signal == 0;)
303 sleep(1);
304
305 if (parent_signal == SIGUSR1)
306 return (0);
307
308 if (wait(&i) < 0)
309 {
310 perror("cupsd");
311 return (1);
312 }
313 else if (WIFEXITED(i))
314 {
315 fprintf(stderr, "cupsd: Child exited with status %d!\n",
316 WEXITSTATUS(i));
317 return (2);
318 }
319 else
320 {
321 fprintf(stderr, "cupsd: Child exited on signal %d!\n", WTERMSIG(i));
322 return (3);
323 }
324 }
325 }
326
327 if (fg < 1)
328 {
329 /*
330 * Make sure we aren't tying up any filesystems...
331 */
332
333 chdir("/");
334
335 #ifndef DEBUG
336 /*
337 * Disable core dumps...
338 */
339
340 getrlimit(RLIMIT_CORE, &limit);
341 limit.rlim_cur = 0;
342 setrlimit(RLIMIT_CORE, &limit);
343
344 /*
345 * Disconnect from the controlling terminal...
346 */
347
348 setsid();
349
350 /*
351 * Close all open files...
352 */
353
354 getrlimit(RLIMIT_NOFILE, &limit);
355
356 for (i = 0; i < limit.rlim_cur && i < 1024; i ++)
357 close(i);
358 #endif /* DEBUG */
359 }
360
361 /*
362 * Set the timezone info...
363 */
364
365 tzset();
366
367 #ifdef LC_TIME
368 setlocale(LC_TIME, "");
369 #endif /* LC_TIME */
370
371 /*
372 * Set the maximum number of files...
373 */
374
375 getrlimit(RLIMIT_NOFILE, &limit);
376
377 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
378 if (limit.rlim_max > FD_SETSIZE)
379 MaxFDs = FD_SETSIZE;
380 else
381 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
382 #ifdef RLIM_INFINITY
383 if (limit.rlim_max == RLIM_INFINITY)
384 MaxFDs = 16384;
385 else
386 #endif /* RLIM_INFINITY */
387 MaxFDs = limit.rlim_max;
388
389 limit.rlim_cur = MaxFDs;
390
391 setrlimit(RLIMIT_NOFILE, &limit);
392
393 cupsdStartSelect();
394
395 /*
396 * Read configuration...
397 */
398
399 if (!cupsdReadConfiguration())
400 {
401 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
402 ConfigurationFile);
403 return (1);
404 }
405
406 #if HAVE_LAUNCHD
407 if (Launchd)
408 {
409 /*
410 * If we were started by launchd get the listen sockets file descriptors...
411 */
412
413 launchd_checkin();
414 }
415 #endif /* HAVE_LAUNCHD */
416
417 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
418 /*
419 * Load Print Service quota enforcement library (X Server only)
420 */
421
422 PSQLibRef = dlopen(PSQLibPath, RTLD_LAZY);
423
424 if (PSQLibRef)
425 PSQUpdateQuotaProc = dlsym(PSQLibRef, PSQLibFuncName);
426 #endif /* __APPLE__ && HAVE_DLFCN_H */
427
428 /*
429 * Startup the server...
430 */
431
432 cupsdStartServer();
433
434 /*
435 * Catch hangup and child signals and ignore broken pipes...
436 */
437
438 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
439 sigset(SIGCHLD, sigchld_handler);
440 sigset(SIGHUP, sighup_handler);
441 sigset(SIGPIPE, SIG_IGN);
442 sigset(SIGTERM, sigterm_handler);
443 #elif defined(HAVE_SIGACTION)
444 memset(&action, 0, sizeof(action));
445
446 sigemptyset(&action.sa_mask);
447 sigaddset(&action.sa_mask, SIGTERM);
448 sigaddset(&action.sa_mask, SIGCHLD);
449 action.sa_handler = sigchld_handler;
450 sigaction(SIGCHLD, &action, NULL);
451
452 sigemptyset(&action.sa_mask);
453 sigaddset(&action.sa_mask, SIGHUP);
454 action.sa_handler = sighup_handler;
455 sigaction(SIGHUP, &action, NULL);
456
457 sigemptyset(&action.sa_mask);
458 action.sa_handler = SIG_IGN;
459 sigaction(SIGPIPE, &action, NULL);
460
461 sigemptyset(&action.sa_mask);
462 sigaddset(&action.sa_mask, SIGTERM);
463 sigaddset(&action.sa_mask, SIGCHLD);
464 action.sa_handler = sigterm_handler;
465 sigaction(SIGTERM, &action, NULL);
466 #else
467 signal(SIGCLD, sigchld_handler); /* No, SIGCLD isn't a typo... */
468 signal(SIGHUP, sighup_handler);
469 signal(SIGPIPE, SIG_IGN);
470 signal(SIGTERM, sigterm_handler);
471 #endif /* HAVE_SIGSET */
472
473 #ifdef __sgi
474 /*
475 * Try to create a fake lpsched lock file if one is not already there.
476 * Some Adobe applications need it under IRIX in order to enable
477 * printing...
478 */
479
480 if ((fp = cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL)
481 {
482 syslog(LOG_LPR, "Unable to create fake lpsched lock file "
483 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
484 strerror(errno));
485 }
486 else
487 {
488 fchmod(cupsFileNumber(fp), 0644);
489 fchown(cupsFileNumber(fp), User, Group);
490
491 cupsFileClose(fp);
492 }
493 #endif /* __sgi */
494
495 /*
496 * Initialize authentication certificates...
497 */
498
499 cupsdInitCerts();
500
501 /*
502 * If we are running in the background, signal the parent process that
503 * we are up and running...
504 */
505
506 if (!fg)
507 {
508 /*
509 * Send a signal to the parent process, but only if the parent is
510 * not PID 1 (init). This avoids accidentally shutting down the
511 * system on OpenBSD if you CTRL-C the server before it is up...
512 */
513
514 i = getppid(); /* Save parent PID to avoid race condition */
515
516 if (i != 1)
517 kill(i, SIGUSR1);
518 }
519
520 #ifdef __APPLE__
521 /*
522 * Start power management framework...
523 */
524
525 cupsdStartSystemMonitor();
526 #endif /* __APPLE__ */
527
528 /*
529 * Start any pending print jobs...
530 */
531
532 cupsdCheckJobs();
533
534 /*
535 * Loop forever...
536 */
537
538 mallinfo_time = 0;
539 browse_time = time(NULL);
540 senddoc_time = time(NULL);
541 expire_time = time(NULL);
542 fds = 1;
543
544 while (!stop_scheduler)
545 {
546 #ifdef DEBUG
547 cupsdLogMessage(CUPSD_LOG_DEBUG2,
548 "main: Top of loop, dead_children=%d, NeedReload=%d",
549 dead_children, NeedReload);
550 #endif /* DEBUG */
551
552 /*
553 * Check if there are dead children to handle...
554 */
555
556 if (dead_children)
557 process_children();
558
559 /*
560 * Check if we need to load the server configuration file...
561 */
562
563 if (NeedReload)
564 {
565 /*
566 * Close any idle clients...
567 */
568
569 if (cupsArrayCount(Clients) > 0)
570 {
571 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
572 con;
573 con = (cupsd_client_t *)cupsArrayNext(Clients))
574 if (con->http.state == HTTP_WAITING)
575 cupsdCloseClient(con);
576 else
577 con->http.keep_alive = HTTP_KEEPALIVE_OFF;
578
579 cupsdPauseListening();
580 }
581
582 /*
583 * Check for any active jobs...
584 */
585
586 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
587 job;
588 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
589 if (job->state_value == IPP_JOB_PROCESSING)
590 break;
591
592 /*
593 * Restart if all clients are closed and all jobs finished, or
594 * if the reload timeout has elapsed...
595 */
596
597 if ((cupsArrayCount(Clients) == 0 &&
598 (!job || NeedReload != RELOAD_ALL)) ||
599 (time(NULL) - ReloadTime) >= ReloadTimeout)
600 {
601 /*
602 * Shutdown the server...
603 */
604
605 cupsdStopServer();
606
607 /*
608 * Read configuration...
609 */
610
611 if (!cupsdReadConfiguration())
612 {
613 syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
614 ConfigurationFile);
615 break;
616 }
617
618 #if HAVE_LAUNCHD
619 if (Launchd)
620 {
621 /*
622 * If we were started by launchd get the listen sockets file descriptors...
623 */
624
625 launchd_checkin();
626 }
627 #endif /* HAVE_LAUNCHD */
628
629 /*
630 * Startup the server...
631 */
632
633 cupsdStartServer();
634 }
635 }
636
637 /*
638 * Check for available input or ready output. If cupsdDoSelect()
639 * returns 0 or -1, something bad happened and we should exit
640 * immediately.
641 *
642 * Note that we at least have one listening socket open at all
643 * times.
644 */
645
646 timeout = select_timeout(fds);
647
648 #if HAVE_LAUNCHD
649 /*
650 * If no other work is scheduled and we're being controlled by
651 * launchd then timeout after 'LaunchdTimeout' seconds of
652 * inactivity...
653 */
654
655 if (timeout == 86400 && Launchd && LaunchdTimeout && !NumPolled &&
656 (!Browsing ||
657 (!BrowseRemoteProtocols &&
658 (!NumBrowsers || !BrowseLocalProtocols ||
659 cupsArrayCount(Printers) == 0))))
660 {
661 timeout = LaunchdTimeout;
662 launchd_idle_exit = 1;
663 }
664 else
665 launchd_idle_exit = 0;
666 #endif /* HAVE_LAUNCHD */
667
668 if ((fds = cupsdDoSelect(timeout)) < 0)
669 {
670 /*
671 * Got an error from select!
672 */
673
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 */
680 continue;
681
682 /*
683 * Log all sorts of debug info to help track down the problem.
684 */
685
686 cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
687 strerror(errno));
688
689 for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
690 con;
691 i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
692 cupsdLogMessage(CUPSD_LOG_EMERG,
693 "Clients[%d] = %d, file = %d, state = %d",
694 i, con->http.fd, con->file, con->http.state);
695
696 for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
697 lis;
698 i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
699 cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
700
701 cupsdLogMessage(CUPSD_LOG_EMERG, "BrowseSocket = %d", BrowseSocket);
702
703 cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);
704
705 #ifdef __APPLE__
706 cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
707 SysEventPipes[0]);
708 #endif /* __APPLE__ */
709
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]);
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
727 break;
728 }
729
730 current_time = time(NULL);
731
732 #if HAVE_LAUNCHD
733 /*
734 * If no other work was scheduled and we're being controlled by launchd
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
748 /*
749 * Expire subscriptions and unload completed jobs as needed...
750 */
751
752 if (current_time > expire_time)
753 {
754 if (cupsArrayCount(Subscriptions) > 0)
755 cupsdExpireSubscriptions(NULL, NULL);
756
757 cupsdUnloadCompletedJobs();
758
759 expire_time = current_time;
760 }
761
762 /*
763 * Update the browse list as needed...
764 */
765
766 if (Browsing)
767 {
768 #ifdef HAVE_LIBSLP
769 if ((BrowseRemoteProtocols & BROWSE_SLP) &&
770 BrowseSLPRefresh <= current_time)
771 cupsdUpdateSLPBrowse();
772 #endif /* HAVE_LIBSLP */
773
774 #ifdef HAVE_LDAP
775 if ((BrowseRemoteProtocols & BROWSE_LDAP) &&
776 BrowseLDAPRefresh <= current_time)
777 cupsdUpdateLDAPBrowse();
778 #endif /* HAVE_LDAP */
779 }
780
781 if (Browsing && BrowseLocalProtocols && current_time > browse_time)
782 {
783 cupsdSendBrowseList();
784 browse_time = current_time;
785 }
786
787 /*
788 * Update the root certificate once every 5 minutes if we have client
789 * connections...
790 */
791
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 }
802
803 /*
804 * Check for new data on the client sockets...
805 */
806
807 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
808 con;
809 con = (cupsd_client_t *)cupsArrayNext(Clients))
810 {
811 /*
812 * Process pending data in the input buffer...
813 */
814
815 if (con->http.used)
816 {
817 cupsdReadClient(con);
818 continue;
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);
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
847 /*
848 * Log memory usage every minute...
849 */
850
851 if ((current_time - mallinfo_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG2)
852 {
853 #ifdef HAVE_MALLINFO
854 struct mallinfo mem; /* Malloc information */
855
856
857 mem = mallinfo();
858 cupsdLogMessage(CUPSD_LOG_DEBUG2,
859 "mallinfo: arena = %d, used = %d, free = %d\n",
860 mem.arena, mem.usmblks + mem.uordblks,
861 mem.fsmblks + mem.fordblks);
862 #endif /* HAVE_MALLINFO */
863
864 string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
865 cupsdLogMessage(CUPSD_LOG_DEBUG2,
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
871 mallinfo_time = current_time;
872 }
873
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
879 if (LastEvent)
880 {
881 #ifdef HAVE_NOTIFY_POST
882 if (LastEvent & CUPSD_EVENT_PRINTER_CHANGED)
883 {
884 cupsdLogMessage(CUPSD_LOG_DEBUG2,
885 "notify_post(\"com.apple.printerListChange\")");
886 notify_post("com.apple.printerListChange");
887 }
888
889 if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
890 {
891 cupsdLogMessage(CUPSD_LOG_DEBUG2,
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 {
900 cupsdLogMessage(CUPSD_LOG_DEBUG2,
901 "notify_post(\"com.apple.jobChange\")");
902 notify_post("com.apple.jobChange");
903 }
904 #endif /* HAVE_NOTIFY_POST */
905
906 /*
907 * Reset the accumulated events...
908 */
909
910 LastEvent = CUPSD_EVENT_NONE;
911 }
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
930 cupsdFreeAllJobs();
931
932 #ifdef __APPLE__
933 cupsdStopSystemMonitor();
934 #endif /* __APPLE__ */
935
936 #ifdef HAVE_LAUNCHD
937 /*
938 * Update the launchd KeepAlive file as needed...
939 */
940
941 if (Launchd)
942 launchd_checkout();
943 #endif /* HAVE_LAUNCHD */
944
945 #ifdef __APPLE__
946 #ifdef HAVE_DLFCN_H
947 /*
948 * Unload Print Service quota enforcement library (X Server only)
949 */
950
951 PSQUpdateQuotaProc = NULL;
952 if (PSQLibRef)
953 {
954 dlclose(PSQLibRef);
955 PSQLibRef = NULL;
956 }
957 #endif /* HAVE_DLFCN_H */
958 #endif /* __APPLE__ */
959
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
972 cupsdStopSelect();
973
974 return (!stop_scheduler);
975 }
976
977
978 /*
979 * 'cupsdClosePipe()' - Close a pipe as necessary.
980 */
981
982 void
983 cupsdClosePipe(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
1007 int /* O - 0 on success, -1 on error */
1008 cupsdOpenPipe(int *fds) /* O - Pipe file descriptors (2) */
1009 {
1010 /*
1011 * Create the pipe...
1012 */
1013
1014 if (pipe(fds))
1015 {
1016 fds[0] = -1;
1017 fds[1] = -1;
1018
1019 return (-1);
1020 }
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]);
1030
1031 fds[0] = -1;
1032 fds[1] = -1;
1033
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]);
1041
1042 fds[0] = -1;
1043 fds[1] = -1;
1044
1045 return (-1);
1046 }
1047
1048 /*
1049 * Return 0 indicating success...
1050 */
1051
1052 return (0);
1053 }
1054
1055
1056 /*
1057 * 'cupsdClearString()' - Clear a string.
1058 */
1059
1060 void
1061 cupsdClearString(char **s) /* O - String value */
1062 {
1063 if (s && *s)
1064 {
1065 _cupsStrFree(*s);
1066 *s = NULL;
1067 }
1068 }
1069
1070
1071 /*
1072 * 'cupsdHoldSignals()' - Hold child and termination signals.
1073 */
1074
1075 void
1076 cupsdHoldSignals(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
1099 /*
1100 * 'cupsdReleaseSignals()' - Release signals for delivery.
1101 */
1102
1103 void
1104 cupsdReleaseSignals(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
1123 void
1124 cupsdSetString(char **s, /* O - New string */
1125 const char *v) /* I - String value */
1126 {
1127 if (!s || *s == v)
1128 return;
1129
1130 if (*s)
1131 _cupsStrFree(*s);
1132
1133 if (v)
1134 *s = _cupsStrAlloc(v);
1135 else
1136 *s = NULL;
1137 }
1138
1139
1140 /*
1141 * 'cupsdSetStringf()' - Set a formatted string value.
1142 */
1143
1144 void
1145 cupsdSetStringf(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
1165 *s = _cupsStrAlloc(v);
1166 }
1167 else
1168 *s = NULL;
1169
1170 if (olds)
1171 _cupsStrFree(olds);
1172 }
1173
1174
1175 #ifdef HAVE_LAUNCHD
1176 /*
1177 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1178 */
1179
1180 static void
1181 launchd_checkin(void)
1182 {
1183 int i, /* Looping var */
1184 count, /* Numebr of listeners */
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 */
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 */
1194 int fd; /* File descriptor */
1195 char s[256]; /* String addresss */
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 {
1207 cupsdLogMessage(CUPSD_LOG_ERROR,
1208 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1209 "\") IPC failure");
1210 exit(EXIT_FAILURE);
1211 }
1212
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
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 }
1231
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 {
1249 count = launch_data_array_get_count(ld_array);
1250
1251 for (i = 0; i < count; i ++)
1252 {
1253 /*
1254 * Get the launchd file descriptor and address...
1255 */
1256
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))
1262 {
1263 cupsdLogMessage(CUPSD_LOG_ERROR,
1264 "launchd_checkin: Unable to get local address - %s",
1265 strerror(errno));
1266 continue;
1267 }
1268
1269 /*
1270 * Try to match the launchd socket address to one of the listeners...
1271 */
1272
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 */
1282
1283 if (lis)
1284 {
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));
1306 }
1307
1308 lis->fd = fd;
1309
1310 # ifdef HAVE_SSL
1311 portnum = 0;
1312
1313 # ifdef AF_INET6
1314 if (lis->address.addr.sa_family == AF_INET6)
1315 portnum = ntohs(lis->address.ipv6.sin6_port);
1316 else
1317 # endif /* AF_INET6 */
1318 if (lis->address.addr.sa_family == AF_INET)
1319 portnum = ntohs(lis->address.ipv4.sin_port);
1320
1321 if (portnum == 443)
1322 lis->encryption = HTTP_ENCRYPT_ALWAYS;
1323 # endif /* HAVE_SSL */
1324 }
1325 }
1326
1327 launch_data_free(ld_msg);
1328 launch_data_free(ld_resp);
1329 }
1330
1331
1332 /*
1333 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1334 */
1335
1336 static void
1337 launchd_checkout(void)
1338 {
1339 int fd; /* File descriptor */
1340
1341
1342 /*
1343 * Create or remove the launchd KeepAlive file based on whether
1344 * there are active jobs, polling, browsing for remote printers or
1345 * shared printers to advertise...
1346 */
1347
1348 if ((cupsArrayCount(ActiveJobs) || NumPolled ||
1349 (Browsing &&
1350 (BrowseRemoteProtocols ||
1351 (BrowseLocalProtocols && NumBrowsers && cupsArrayCount(Printers))))))
1352 {
1353 cupsdLogMessage(CUPSD_LOG_DEBUG,
1354 "Creating launchd keepalive file \"" CUPS_KEEPALIVE "\"...");
1355
1356 if ((fd = open(CUPS_KEEPALIVE, O_RDONLY | O_CREAT | O_EXCL, S_IRUSR)) >= 0)
1357 close(fd);
1358 }
1359 else
1360 {
1361 cupsdLogMessage(CUPSD_LOG_DEBUG,
1362 "Removing launchd keepalive file \"" CUPS_KEEPALIVE "\"...");
1363
1364 unlink(CUPS_KEEPALIVE);
1365 }
1366 }
1367
1368 #endif /* HAVE_LAUNCHD */
1369
1370
1371 /*
1372 * 'parent_handler()' - Catch USR1/CHLD signals...
1373 */
1374
1375 static void
1376 parent_handler(int sig) /* I - Signal */
1377 {
1378 /*
1379 * Store the signal we got from the OS and return...
1380 */
1381
1382 parent_signal = sig;
1383 }
1384
1385
1386 /*
1387 * 'process_children()' - Process all dead children...
1388 */
1389
1390 static void
1391 process_children(void)
1392 {
1393 int status; /* Exit status of child */
1394 int pid; /* Process ID of child */
1395 cupsd_job_t *job; /* Current job */
1396 int i; /* Looping var */
1397 char name[1024]; /* Process name */
1398
1399
1400 cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
1401
1402 /*
1403 * Reset the dead_children flag...
1404 */
1405
1406 dead_children = 0;
1407
1408 /*
1409 * Collect the exit status of some children...
1410 */
1411
1412 #ifdef HAVE_WAITPID
1413 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1414 #elif defined(HAVE_WAIT3)
1415 while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
1416 #else
1417 if ((pid = wait(&status)) > 0)
1418 #endif /* HAVE_WAITPID */
1419 {
1420 /*
1421 * Ignore SIGTERM errors - that comes when a job is canceled...
1422 */
1423
1424 cupsdFinishProcess(pid, name, sizeof(name));
1425
1426 if (status == SIGTERM)
1427 status = 0;
1428
1429 if (status)
1430 {
1431 if (WIFEXITED(status))
1432 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) stopped with status %d!",
1433 pid, name, WEXITSTATUS(status));
1434 else
1435 cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) crashed on signal %d!",
1436 pid, name, WTERMSIG(status));
1437
1438 if (LogLevel < CUPSD_LOG_DEBUG)
1439 cupsdLogMessage(CUPSD_LOG_INFO,
1440 "Hint: Try setting the LogLevel to \"debug\" to find "
1441 "out more.");
1442 }
1443 else
1444 cupsdLogMessage(CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
1445 pid, name);
1446
1447 /*
1448 * Delete certificates for CGI processes...
1449 */
1450
1451 if (pid)
1452 cupsdDeleteCert(pid);
1453
1454 /*
1455 * Lookup the PID in the jobs list...
1456 */
1457
1458 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1459 job;
1460 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1461 if (job->state_value == IPP_JOB_PROCESSING)
1462 {
1463 for (i = 0; job->filters[i]; i ++)
1464 if (job->filters[i] == pid)
1465 break;
1466
1467 if (job->filters[i] || job->backend == pid)
1468 {
1469 /*
1470 * OK, this process has gone away; what's left?
1471 */
1472
1473 if (job->filters[i])
1474 job->filters[i] = -pid;
1475 else
1476 job->backend = -pid;
1477
1478 if (status && job->status >= 0)
1479 {
1480 /*
1481 * An error occurred; save the exit status so we know to stop
1482 * the printer or cancel the job when all of the filters finish...
1483 *
1484 * A negative status indicates that the backend failed and the
1485 * printer needs to be stopped.
1486 */
1487
1488 if (job->filters[i])
1489 job->status = status; /* Filter failed */
1490 else
1491 job->status = -status; /* Backend failed */
1492
1493 if (job->printer && !(job->printer->type & CUPS_PRINTER_FAX))
1494 {
1495 snprintf(job->printer->state_message,
1496 sizeof(job->printer->state_message), "%s failed", name);
1497 cupsdAddPrinterHistory(job->printer);
1498 }
1499 }
1500
1501 /*
1502 * If this is not the last file in a job, see if all of the
1503 * filters are done, and if so move to the next file.
1504 */
1505
1506 if (job->current_file < job->num_files)
1507 {
1508 for (i = 0; job->filters[i] < 0; i ++);
1509
1510 if (!job->filters[i])
1511 {
1512 /*
1513 * Process the next file...
1514 */
1515
1516 cupsdFinishJob(job);
1517 }
1518 }
1519 break;
1520 }
1521 }
1522 }
1523 }
1524
1525
1526 /*
1527 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1528 */
1529
1530 static void
1531 sigchld_handler(int sig) /* I - Signal number */
1532 {
1533 (void)sig;
1534
1535 /*
1536 * Flag that we have dead children...
1537 */
1538
1539 dead_children = 1;
1540
1541 /*
1542 * Reset the signal handler as needed...
1543 */
1544
1545 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1546 signal(SIGCLD, sigchld_handler);
1547 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1548 }
1549
1550
1551 /*
1552 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1553 */
1554
1555 static void
1556 sighup_handler(int sig) /* I - Signal number */
1557 {
1558 (void)sig;
1559
1560 NeedReload = RELOAD_ALL;
1561 ReloadTime = time(NULL);
1562
1563 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1564 signal(SIGHUP, sighup_handler);
1565 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1566 }
1567
1568
1569 /*
1570 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1571 */
1572
1573 static void
1574 sigterm_handler(int sig) /* I - Signal */
1575 {
1576 (void)sig; /* remove compiler warnings... */
1577
1578 /*
1579 * Flag that we should stop and return...
1580 */
1581
1582 stop_scheduler = 1;
1583 }
1584
1585
1586 /*
1587 * 'select_timeout()' - Calculate the select timeout value.
1588 *
1589 */
1590
1591 static long /* O - Number of seconds */
1592 select_timeout(int fds) /* I - Number of descriptors returned */
1593 {
1594 long timeout; /* Timeout for select */
1595 time_t now; /* Current time */
1596 cupsd_client_t *con; /* Client information */
1597 cupsd_printer_t *p; /* Printer information */
1598 cupsd_job_t *job; /* Job information */
1599 cupsd_subscription_t *sub; /* Subscription information */
1600 const char *why; /* Debugging aid */
1601
1602
1603 /*
1604 * Check to see if any of the clients have pending data to be
1605 * processed; if so, the timeout should be 0...
1606 */
1607
1608 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1609 con;
1610 con = (cupsd_client_t *)cupsArrayNext(Clients))
1611 if (con->http.used > 0)
1612 return (0);
1613
1614 /*
1615 * If select has been active in the last second (fds > 0) or we have
1616 * many resources in use then don't bother trying to optimize the
1617 * timeout, just make it 1 second.
1618 */
1619
1620 if (fds > 0 || cupsArrayCount(Clients) > 50)
1621 return (1);
1622
1623 /*
1624 * Otherwise, check all of the possible events that we need to wake for...
1625 */
1626
1627 now = time(NULL);
1628 timeout = now + 86400; /* 86400 == 1 day */
1629 why = "do nothing";
1630
1631 /*
1632 * Check the activity and close old clients...
1633 */
1634
1635 for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
1636 con;
1637 con = (cupsd_client_t *)cupsArrayNext(Clients))
1638 if ((con->http.activity + Timeout) < timeout)
1639 {
1640 timeout = con->http.activity + Timeout;
1641 why = "timeout a client connection";
1642 }
1643
1644 /*
1645 * Update the browse list as needed...
1646 */
1647
1648 if (Browsing && BrowseLocalProtocols)
1649 {
1650 #ifdef HAVE_LIBSLP
1651 if ((BrowseLocalProtocols & BROWSE_SLP) && (BrowseSLPRefresh < timeout))
1652 {
1653 timeout = BrowseSLPRefresh;
1654 why = "update SLP browsing";
1655 }
1656 #endif /* HAVE_LIBSLP */
1657
1658 #ifdef HAVE_LDAP
1659 if ((BrowseLocalProtocols & BROWSE_LDAP) && (BrowseLDAPRefresh < timeout))
1660 {
1661 timeout = BrowseLDAPRefresh;
1662 why = "update LDAP browsing";
1663 }
1664 #endif /* HAVE_LDAP */
1665
1666 if ((BrowseLocalProtocols & BROWSE_CUPS) && NumBrowsers)
1667 {
1668 for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
1669 p;
1670 p = (cupsd_printer_t *)cupsArrayNext(Printers))
1671 {
1672 if (p->type & CUPS_PRINTER_REMOTE)
1673 {
1674 if ((p->browse_time + BrowseTimeout) < timeout)
1675 {
1676 timeout = p->browse_time + BrowseTimeout;
1677 why = "browse timeout a printer";
1678 }
1679 }
1680 else if (p->shared && !(p->type & CUPS_PRINTER_IMPLICIT))
1681 {
1682 if (BrowseInterval && (p->browse_time + BrowseInterval) < timeout)
1683 {
1684 timeout = p->browse_time + BrowseInterval;
1685 why = "send browse update";
1686 }
1687 }
1688 }
1689 }
1690 }
1691
1692 /*
1693 * Check for any active jobs...
1694 */
1695
1696 if (timeout > (now + 10) && ActiveJobs)
1697 {
1698 for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
1699 job;
1700 job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
1701 if (job->state_value <= IPP_JOB_PROCESSING)
1702 {
1703 timeout = now + 10;
1704 why = "process active jobs";
1705 break;
1706 }
1707 }
1708
1709 #ifdef HAVE_MALLINFO
1710 /*
1711 * Log memory usage every minute...
1712 */
1713
1714 if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
1715 {
1716 timeout = mallinfo_time + 60;
1717 why = "display memory usage";
1718 }
1719 #endif /* HAVE_MALLINFO */
1720
1721 /*
1722 * Expire subscriptions as needed...
1723 */
1724
1725 for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
1726 sub;
1727 sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
1728 if (!sub->job && sub->expire && sub->expire < timeout)
1729 {
1730 timeout = sub->expire;
1731 why = "expire subscription";
1732 }
1733
1734 /*
1735 * Adjust from absolute to relative time. If p->browse_time above
1736 * was 0 then we can end up with a negative value here, so check.
1737 * We add 1 second to the timeout since events occur after the
1738 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1739 * to avoid select() timeout limits present on some operating
1740 * systems...
1741 */
1742
1743 timeout = timeout - now + 1;
1744
1745 if (timeout < 1)
1746 timeout = 1;
1747 else if (timeout > 86400)
1748 timeout = 86400;
1749
1750 /*
1751 * Log and return the timeout value...
1752 */
1753
1754 cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
1755 fds, timeout, why);
1756
1757 return (timeout);
1758 }
1759
1760
1761 /*
1762 * 'usage()' - Show scheduler usage.
1763 */
1764
1765 static void
1766 usage(int status) /* O - Exit status */
1767 {
1768 _cupsLangPuts(status ? stderr : stdout,
1769 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1770 "\n"
1771 "-c config-file Load alternate configuration file\n"
1772 "-f Run in the foreground\n"
1773 "-F Run in the foreground but detach\n"
1774 "-h Show this usage message\n"
1775 "-l Run cupsd from launchd(8)\n"));
1776 exit(status);
1777 }
1778
1779
1780 /*
1781 * End of "$Id: main.c 6493 2007-04-30 19:33:31Z mike $".
1782 */