2 * "$Id: main.c 7925 2008-09-10 17:47:26Z mike $"
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
6 * Copyright 2007-2009 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * "LICENSE" which should have been included with this file. If this
13 * file is missing or damaged, see the license at "http://www.cups.org/".
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.
20 * cupsdHoldSignals() - Hold child and termination signals.
21 * cupsdReleaseSignals() - Release signals for delivery.
22 * cupsdSetString() - Set a string value.
23 * cupsdSetStringf() - Set a formatted string value.
24 * launchd_checkin() - Check-in with launchd and collect the
26 * launchd_checkout() - Check-out with launchd.
27 * parent_handler() - Catch USR1/CHLD signals...
28 * process_children() - Process all dead children...
29 * select_timeout() - Calculate the select timeout value.
30 * sigchld_handler() - Handle 'child' signals from old processes.
31 * sighup_handler() - Handle 'hangup' signals to reconfigure the
33 * sigterm_handler() - Handle 'terminate' signals that stop the
35 * usage() - Show scheduler usage.
39 * Include necessary headers...
44 #include <sys/resource.h>
52 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
53 /* Name of the launchd KeepAlive file */
54 # ifndef LAUNCH_JOBKEY_KEEPALIVE
55 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
56 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
57 # ifndef LAUNCH_JOBKEY_PATHSTATE
58 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
59 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
60 # ifndef LAUNCH_JOBKEY_SERVICEIPC
61 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
62 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
63 #endif /* HAVE_LAUNCH_H */
65 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
67 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
70 #endif /* HAVE_NOTIFY_H */
72 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
74 #endif /* __APPLE__ && HAVE_DLFCN_H */
82 static void launchd_checkin(void);
83 static void launchd_checkout(void);
84 #endif /* HAVE_LAUNCHD */
85 static void parent_handler(int sig
);
86 static void process_children(void);
87 static void sigchld_handler(int sig
);
88 static void sighup_handler(int sig
);
89 static void sigterm_handler(int sig
);
90 static long select_timeout(int fds
);
91 static void usage(int status
);
98 static int parent_signal
= 0;
99 /* Set to signal number from child */
100 static int holdcount
= 0; /* Number of times "hold" was called */
101 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
102 static sigset_t holdmask
; /* Old POSIX signal mask */
103 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
104 static int dead_children
= 0;
106 static int stop_scheduler
= 0;
107 /* Should the scheduler stop? */
109 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
110 static const char *PSQLibPath
= "/usr/lib/libPrintServiceQuota.dylib";
111 static const char *PSQLibFuncName
= "PSQUpdateQuota";
112 static void *PSQLibRef
; /* libPrintServiceQuota.dylib */
113 #endif /* HAVE_DLFCN_H */
117 * 'main()' - Main entry for the CUPS scheduler.
120 int /* O - Exit status */
121 main(int argc
, /* I - Number of command-line args */
122 char *argv
[]) /* I - Command-line arguments */
124 int i
; /* Looping var */
125 char *opt
; /* Option character */
126 int fg
; /* Run in the foreground */
127 int fds
; /* Number of ready descriptors */
128 cupsd_client_t
*con
; /* Current client */
129 cupsd_job_t
*job
; /* Current job */
130 cupsd_listener_t
*lis
; /* Current listener */
131 time_t current_time
, /* Current time */
132 activity
, /* Client activity timer */
133 browse_time
, /* Next browse send time */
134 senddoc_time
, /* Send-Document time */
135 expire_time
, /* Subscription expire time */
136 report_time
, /* Malloc/client/job report time */
137 event_time
; /* Last time an event notification was done */
138 long timeout
; /* Timeout for cupsdDoSelect() */
139 struct rlimit limit
; /* Runtime limit */
140 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
141 struct sigaction action
; /* Actions for POSIX signals */
142 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
144 cups_file_t
*fp
; /* Fake lpsched lock file */
145 struct stat statbuf
; /* Needed for checking lpsched FIFO */
147 int run_as_child
= 0;
148 /* Needed for background fork/exec */
150 int use_sysman
= !getuid();
151 /* Use system management functions? */
153 time_t netif_time
= 0; /* Time since last network update */
154 #endif /* __APPLE__ */
156 int launchd_idle_exit
;
157 /* Idle exit on select timeout? */
158 #endif /* HAVE_LAUNCHD */
163 * Check for setuid invocation, which we do not support!
166 if (getuid() != geteuid())
168 fputs("cupsd: Cannot run as a setuid program!\n", stderr
);
171 #endif /* HAVE_GETEUID */
174 * Check for command-line arguments...
180 if (getenv("CUPSD_LAUNCHD"))
185 #endif /* HAVE_LAUNCHD */
187 for (i
= 1; i
< argc
; i
++)
188 if (argv
[i
][0] == '-')
189 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
192 case 'C' : /* Run as child with config file */
196 case 'c' : /* Configuration file */
200 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
201 "after \"-c\" option!\n"));
205 if (argv
[i
][0] == '/')
208 * Absolute directory...
211 cupsdSetString(&ConfigurationFile
, argv
[i
]);
216 * Relative directory...
219 char *current
; /* Current directory */
223 * Allocate a buffer for the current working directory to
224 * reduce run-time stack usage; this approximates the
225 * behavior of some implementations of getcwd() when they
226 * are passed a NULL pointer.
229 if ((current
= malloc(1024)) == NULL
)
231 _cupsLangPuts(stderr
,
232 _("cupsd: Unable to get current directory!\n"));
236 if (!getcwd(current
, 1024))
238 _cupsLangPuts(stderr
,
239 _("cupsd: Unable to get current directory!\n"));
244 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
249 case 'f' : /* Run in foreground... */
253 case 'F' : /* Run in foreground, but disconnect from terminal... */
257 case 'h' : /* Show usage/help */
261 case 'l' : /* Started by launchd... */
266 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
267 "in, running in normal mode.\n"));
269 #endif /* HAVE_LAUNCHD */
272 case 'p' : /* Stop immediately for profiling */
273 puts("Warning: -p (startup profiling) is for internal testing use only!");
278 case 'P' : /* Disable security profiles */
279 puts("Warning: -P (disable security profiles) is for internal testing use only!");
284 case 'S' : /* Disable system management functions */
285 puts("Warning: -S (disable system management) for internal testing use only!");
288 #endif /* __APPLE__ */
290 case 't' : /* Test the cupsd.conf file... */
295 default : /* Unknown option */
296 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
297 "aborting!\n"), *opt
);
303 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
308 if (!ConfigurationFile
)
309 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
312 * If the user hasn't specified "-f", run in the background...
318 * Setup signal handlers for the parent...
321 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
322 sigset(SIGUSR1
, parent_handler
);
323 sigset(SIGCHLD
, parent_handler
);
325 sigset(SIGHUP
, SIG_IGN
);
326 #elif defined(HAVE_SIGACTION)
327 memset(&action
, 0, sizeof(action
));
328 sigemptyset(&action
.sa_mask
);
329 sigaddset(&action
.sa_mask
, SIGUSR1
);
330 action
.sa_handler
= parent_handler
;
331 sigaction(SIGUSR1
, &action
, NULL
);
332 sigaction(SIGCHLD
, &action
, NULL
);
334 sigemptyset(&action
.sa_mask
);
335 action
.sa_handler
= SIG_IGN
;
336 sigaction(SIGHUP
, &action
, NULL
);
338 signal(SIGUSR1
, parent_handler
);
339 signal(SIGCLD
, parent_handler
);
341 signal(SIGHUP
, SIG_IGN
);
342 #endif /* HAVE_SIGSET */
347 * OK, wait for the child to startup and send us SIGUSR1 or to crash
348 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
349 * might be sent by the init script to restart the scheduler...
352 for (; parent_signal
== 0;)
355 if (parent_signal
== SIGUSR1
)
363 else if (WIFEXITED(i
))
365 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
371 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
378 * Call _thread_sys_closefrom() so the child process doesn't reset the
379 * parent's file descriptors to be blocking. This is a workaround for a
380 * limitation of userland libpthread on OpenBSD.
383 _thread_sys_closefrom(0);
384 #endif /* __OpenBSD__ */
387 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
388 * a program, and since this kind of really unfriendly behavior seems to be
389 * more common these days in system libraries, we need to re-execute the
390 * background cupsd with the "-C" option to avoid problems. Unfortunately,
391 * we also have to assume that argv[0] contains the name of the cupsd
392 * executable - there is no portable way to get the real pathname...
395 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
402 * Make sure we aren't tying up any filesystems...
409 * Disable core dumps...
412 getrlimit(RLIMIT_CORE
, &limit
);
414 setrlimit(RLIMIT_CORE
, &limit
);
417 * Disconnect from the controlling terminal...
423 * Close all open files...
426 getrlimit(RLIMIT_NOFILE
, &limit
);
428 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
432 * Redirect stdin/out/err to /dev/null...
435 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
441 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
447 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
456 * Set the timezone info...
462 setlocale(LC_TIME
, "");
466 * Set the maximum number of files...
469 getrlimit(RLIMIT_NOFILE
, &limit
);
471 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
472 if (limit
.rlim_max
> FD_SETSIZE
)
475 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
477 if (limit
.rlim_max
== RLIM_INFINITY
)
480 #endif /* RLIM_INFINITY */
481 MaxFDs
= limit
.rlim_max
;
483 limit
.rlim_cur
= MaxFDs
;
485 setrlimit(RLIMIT_NOFILE
, &limit
);
490 * Read configuration...
493 if (!cupsdReadConfiguration())
496 printf("%s contains errors\n", ConfigurationFile
);
498 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
502 else if (TestConfigFile
)
504 printf("%s is OK\n", ConfigurationFile
);
508 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
511 * Clean out the temporary directory...
514 cups_dir_t
*dir
; /* Temporary directory */
515 cups_dentry_t
*dent
; /* Directory entry */
516 char tempfile
[1024]; /* Temporary filename */
519 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
521 cupsdLogMessage(CUPSD_LOG_INFO
,
522 "Cleaning out old temporary files in \"%s\"...", TempDir
);
524 while ((dent
= cupsDirRead(dir
)) != NULL
)
526 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
528 if (unlink(tempfile
))
529 cupsdLogMessage(CUPSD_LOG_ERROR
,
530 "Unable to remove temporary file \"%s\" - %s",
531 tempfile
, strerror(errno
));
533 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
540 cupsdLogMessage(CUPSD_LOG_ERROR
,
541 "Unable to open temporary directory \"%s\" - %s",
542 TempDir
, strerror(errno
));
549 * If we were started by launchd get the listen sockets file descriptors...
555 #endif /* HAVE_LAUNCHD */
557 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
559 * Load Print Service quota enforcement library (X Server only)
562 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
565 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
566 #endif /* __APPLE__ && HAVE_DLFCN_H */
569 * Startup the server...
575 * Catch hangup and child signals and ignore broken pipes...
578 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
579 sigset(SIGCHLD
, sigchld_handler
);
580 sigset(SIGHUP
, sighup_handler
);
581 sigset(SIGPIPE
, SIG_IGN
);
582 sigset(SIGTERM
, sigterm_handler
);
583 #elif defined(HAVE_SIGACTION)
584 memset(&action
, 0, sizeof(action
));
586 sigemptyset(&action
.sa_mask
);
587 sigaddset(&action
.sa_mask
, SIGTERM
);
588 sigaddset(&action
.sa_mask
, SIGCHLD
);
589 action
.sa_handler
= sigchld_handler
;
590 sigaction(SIGCHLD
, &action
, NULL
);
592 sigemptyset(&action
.sa_mask
);
593 sigaddset(&action
.sa_mask
, SIGHUP
);
594 action
.sa_handler
= sighup_handler
;
595 sigaction(SIGHUP
, &action
, NULL
);
597 sigemptyset(&action
.sa_mask
);
598 action
.sa_handler
= SIG_IGN
;
599 sigaction(SIGPIPE
, &action
, NULL
);
601 sigemptyset(&action
.sa_mask
);
602 sigaddset(&action
.sa_mask
, SIGTERM
);
603 sigaddset(&action
.sa_mask
, SIGCHLD
);
604 action
.sa_handler
= sigterm_handler
;
605 sigaction(SIGTERM
, &action
, NULL
);
607 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
608 signal(SIGHUP
, sighup_handler
);
609 signal(SIGPIPE
, SIG_IGN
);
610 signal(SIGTERM
, sigterm_handler
);
611 #endif /* HAVE_SIGSET */
615 * Try to create a fake lpsched lock file if one is not already there.
616 * Some Adobe applications need it under IRIX in order to enable
620 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
622 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
623 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
628 fchmod(cupsFileNumber(fp
), 0644);
629 fchown(cupsFileNumber(fp
), User
, Group
);
636 * Initialize authentication certificates...
642 * If we are running in the background, signal the parent process that
643 * we are up and running...
646 if (!fg
|| run_as_child
)
649 * Send a signal to the parent process, but only if the parent is
650 * not PID 1 (init). This avoids accidentally shutting down the
651 * system on OpenBSD if you CTRL-C the server before it is up...
654 i
= getppid(); /* Save parent PID to avoid race condition */
662 * Start power management framework...
666 cupsdStartSystemMonitor();
667 #endif /* __APPLE__ */
670 * Send server-started event...
675 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
676 "Scheduler started via launchd.");
678 #endif /* HAVE_LAUNCHD */
680 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
681 "Scheduler started in foreground.");
683 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
684 "Scheduler started in background.");
687 * Start any pending print jobs...
696 current_time
= time(NULL
);
697 browse_time
= current_time
;
698 event_time
= current_time
;
699 expire_time
= current_time
;
702 senddoc_time
= current_time
;
704 while (!stop_scheduler
)
707 * Check if there are dead children to handle...
714 * Check if we need to load the server configuration file...
720 * Close any idle clients...
723 if (cupsArrayCount(Clients
) > 0)
725 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
727 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
728 if (con
->http
.state
== HTTP_WAITING
)
729 cupsdCloseClient(con
);
731 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
733 cupsdPauseListening();
737 * Restart if all clients are closed and all jobs finished, or
738 * if the reload timeout has elapsed...
741 if ((cupsArrayCount(Clients
) == 0 &&
742 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
743 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
746 * Shutdown the server...
752 * Read configuration...
755 if (!cupsdReadConfiguration())
757 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
766 * If we were started by launchd get the listen sockets file descriptors...
772 #endif /* HAVE_LAUNCHD */
775 * Startup the server...
781 * Send a server-restarted event...
784 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
785 "Scheduler restarted.");
790 * Check for available input or ready output. If cupsdDoSelect()
791 * returns 0 or -1, something bad happened and we should exit
794 * Note that we at least have one listening socket open at all
798 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
803 * If no other work is scheduled and we're being controlled by
804 * launchd then timeout after 'LaunchdTimeout' seconds of
808 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
809 !cupsArrayCount(ActiveJobs
) &&
811 (!BrowseRemoteProtocols
&&
812 (!NumBrowsers
|| !BrowseLocalProtocols
||
813 cupsArrayCount(Printers
) == 0))))
815 timeout
= LaunchdTimeout
;
816 launchd_idle_exit
= 1;
819 launchd_idle_exit
= 0;
820 #endif /* HAVE_LAUNCHD */
822 if ((fds
= cupsdDoSelect(timeout
)) < 0)
825 * Got an error from select!
829 cupsd_printer_t
*p
; /* Current printer */
830 #endif /* HAVE_DNSSD */
833 if (errno
== EINTR
) /* Just interrupted by a signal */
837 * Log all sorts of debug info to help track down the problem.
840 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
843 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
845 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
846 cupsdLogMessage(CUPSD_LOG_EMERG
,
847 "Clients[%d] = %d, file = %d, state = %d",
848 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
850 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
852 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
853 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
855 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
857 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
860 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
862 #endif /* __APPLE__ */
864 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
866 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
867 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
869 job
->status_buffer
? job
->status_buffer
->fd
: -1,
870 job
->print_pipes
[0], job
->print_pipes
[1],
871 job
->back_pipes
[0], job
->back_pipes
[1]);
874 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
876 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
877 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
878 p
->reg_name
? p
->reg_name
: "(null)");
879 #endif /* HAVE_DNSSD */
884 current_time
= time(NULL
);
887 * Write dirty config/state files...
890 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
895 * If we are going to sleep and still have pending jobs, stop them after
896 * a period of time...
899 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
900 cupsArrayCount(PrintingJobs
) > 0)
903 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 10);
905 #endif /* __APPLE__ */
909 * Update the network interfaces once a minute...
912 if ((current_time
- netif_time
) >= 60)
914 netif_time
= current_time
;
917 #endif /* !__APPLE__ */
921 * If no other work was scheduled and we're being controlled by launchd
922 * then timeout after 'LaunchdTimeout' seconds of inactivity...
925 if (!fds
&& launchd_idle_exit
)
927 cupsdLogMessage(CUPSD_LOG_INFO
,
928 "Printer sharing is off and there are no jobs pending, "
929 "will restart on demand.");
933 #endif /* HAVE_LAUNCHD */
936 * Resume listening for new connections as needed...
939 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
940 cupsArrayCount(Clients
) < MaxClients
)
941 cupsdResumeListening();
944 * Expire subscriptions and unload completed jobs as needed...
947 if (current_time
> expire_time
)
949 if (cupsArrayCount(Subscriptions
) > 0)
950 cupsdExpireSubscriptions(NULL
, NULL
);
952 cupsdUnloadCompletedJobs();
954 expire_time
= current_time
;
958 * Update the browse list as needed...
964 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
965 BrowseSLPRefresh
<= current_time
)
966 cupsdUpdateSLPBrowse();
967 #endif /* HAVE_LIBSLP */
970 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
971 BrowseLDAPRefresh
<= current_time
)
972 cupsdUpdateLDAPBrowse();
973 #endif /* HAVE_LDAP */
976 if (Browsing
&& current_time
> browse_time
)
978 cupsdSendBrowseList();
979 browse_time
= current_time
;
983 * Update the root certificate once every 5 minutes if we have client
987 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
988 !RunUser
&& cupsArrayCount(Clients
))
991 * Update the root certificate...
995 cupsdAddCert(0, "root", NULL
);
999 * Check for new data on the client sockets...
1002 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1004 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1007 * Process pending data in the input buffer...
1012 cupsdReadClient(con
);
1017 * Check the activity and close old clients...
1020 activity
= current_time
- Timeout
;
1021 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
1023 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1024 "Closing client %d after %d seconds of inactivity...",
1025 con
->http
.fd
, Timeout
);
1027 cupsdCloseClient(con
);
1033 * Update any pending multi-file documents...
1036 if ((current_time
- senddoc_time
) >= 10)
1039 senddoc_time
= current_time
;
1043 * Log statistics at most once a minute when in debug mode...
1046 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1048 size_t string_count
, /* String count */
1049 alloc_bytes
, /* Allocated string bytes */
1050 total_bytes
; /* Total string bytes */
1051 #ifdef HAVE_MALLINFO
1052 struct mallinfo mem
; /* Malloc information */
1056 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1057 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1058 mem
.usmblks
+ mem
.uordblks
);
1059 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1060 mem
.fsmblks
+ mem
.fordblks
);
1061 #endif /* HAVE_MALLINFO */
1063 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1064 cupsArrayCount(Clients
));
1065 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1066 cupsArrayCount(Jobs
));
1067 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1068 cupsArrayCount(ActiveJobs
));
1069 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1070 cupsArrayCount(Printers
));
1071 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1072 cupsArrayCount(ImplicitPrinters
));
1074 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1075 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1076 "Report: stringpool-string-count=" CUPS_LLFMT
,
1077 CUPS_LLCAST string_count
);
1078 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1079 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1080 CUPS_LLCAST alloc_bytes
);
1081 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1082 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1083 CUPS_LLCAST total_bytes
);
1085 report_time
= current_time
;
1089 * Handle OS-specific event notification for any events that have
1090 * accumulated. Don't send these more than once a second...
1093 if (LastEvent
&& (current_time
- event_time
) >= 1)
1095 #ifdef HAVE_NOTIFY_POST
1096 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1097 CUPSD_EVENT_PRINTER_DELETED
|
1098 CUPSD_EVENT_PRINTER_MODIFIED
))
1100 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1101 "notify_post(\"com.apple.printerListChange\")");
1102 notify_post("com.apple.printerListChange");
1105 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1107 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1108 "notify_post(\"com.apple.printerHistoryChange\")");
1109 notify_post("com.apple.printerHistoryChange");
1112 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1113 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1114 CUPSD_EVENT_JOB_PROGRESS
))
1116 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1117 "notify_post(\"com.apple.jobChange\")");
1118 notify_post("com.apple.jobChange");
1120 #endif /* HAVE_NOTIFY_POST */
1123 * Reset the accumulated events...
1126 LastEvent
= CUPSD_EVENT_NONE
;
1127 event_time
= current_time
;
1132 * Log a message based on what happened...
1137 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1138 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1139 "Scheduler shutting down normally.");
1143 cupsdLogMessage(CUPSD_LOG_ERROR
,
1144 "Scheduler shutting down due to program error.");
1145 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1146 "Scheduler shutting down due to program error.");
1150 * Close all network clients...
1157 * Update the launchd KeepAlive file as needed...
1162 #endif /* HAVE_LAUNCHD */
1172 * Stop monitoring system event monitoring...
1176 cupsdStopSystemMonitor();
1177 #endif /* __APPLE__ */
1181 * Free the scheduler's Kerberos context...
1186 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1190 if (krb5_init_context
!= NULL
)
1191 # endif /* __APPLE__ */
1192 if (KerberosContext
)
1193 krb5_free_context(KerberosContext
);
1194 #endif /* HAVE_GSSAPI */
1196 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
1198 * Unload Print Service quota enforcement library (X Server only)
1201 PSQUpdateQuotaProc
= NULL
;
1207 #endif /* __APPLE__ && HAVE_DLFCN_H */
1211 * Remove the fake IRIX lpsched lock file, but only if the existing
1212 * file is not a FIFO which indicates that the real IRIX lpsched is
1216 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1217 if (!S_ISFIFO(statbuf
.st_mode
))
1218 unlink("/var/spool/lp/SCHEDLOCK");
1223 return (!stop_scheduler
);
1228 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1232 cupsdCheckProcess(void)
1235 * Flag that we have dead children...
1243 * 'cupsdClosePipe()' - Close a pipe as necessary.
1247 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1250 * Close file descriptors as needed...
1268 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1271 int /* O - 0 on success, -1 on error */
1272 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1275 * Create the pipe...
1287 * Set the "close on exec" flag on each end of the pipe...
1290 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1301 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1313 * Return 0 indicating success...
1321 * 'cupsdClearString()' - Clear a string.
1325 cupsdClearString(char **s
) /* O - String value */
1336 * 'cupsdHoldSignals()' - Hold child and termination signals.
1340 cupsdHoldSignals(void)
1342 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1343 sigset_t newmask
; /* New POSIX signal mask */
1344 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1354 #elif defined(HAVE_SIGACTION)
1355 sigemptyset(&newmask
);
1356 sigaddset(&newmask
, SIGTERM
);
1357 sigaddset(&newmask
, SIGCHLD
);
1358 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1359 #endif /* HAVE_SIGSET */
1364 * 'cupsdReleaseSignals()' - Release signals for delivery.
1368 cupsdReleaseSignals(void)
1377 #elif defined(HAVE_SIGACTION)
1378 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1379 #endif /* HAVE_SIGSET */
1384 * 'cupsdSetString()' - Set a string value.
1388 cupsdSetString(char **s
, /* O - New string */
1389 const char *v
) /* I - String value */
1398 *s
= _cupsStrAlloc(v
);
1405 * 'cupsdSetStringf()' - Set a formatted string value.
1409 cupsdSetStringf(char **s
, /* O - New string */
1410 const char *f
, /* I - Printf-style format string */
1411 ...) /* I - Additional args as needed */
1413 char v
[4096]; /* Formatting string value */
1414 va_list ap
; /* Argument pointer */
1415 char *olds
; /* Old string */
1426 vsnprintf(v
, sizeof(v
), f
, ap
);
1429 *s
= _cupsStrAlloc(v
);
1441 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1445 launchd_checkin(void)
1447 size_t i
, /* Looping var */
1448 count
; /* Numebr of listeners */
1449 int portnum
; /* Port number */
1450 launch_data_t ld_msg
, /* Launch data message */
1451 ld_resp
, /* Launch data response */
1452 ld_array
, /* Launch data array */
1453 ld_sockets
, /* Launch data sockets dictionary */
1454 tmp
; /* Launch data */
1455 cupsd_listener_t
*lis
; /* Listeners array */
1456 http_addr_t addr
; /* Address variable */
1457 socklen_t addrlen
; /* Length of address */
1458 int fd
; /* File descriptor */
1459 char s
[256]; /* String addresss */
1462 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1465 * Check-in with launchd...
1468 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1469 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1471 cupsdLogMessage(CUPSD_LOG_ERROR
,
1472 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1475 return; /* anti-compiler-warning */
1478 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1480 errno
= launch_data_get_errno(ld_resp
);
1481 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1484 return; /* anti-compiler-warning */
1488 * Get the sockets dictionary...
1491 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1494 cupsdLogMessage(CUPSD_LOG_ERROR
,
1495 "launchd_checkin: No sockets found to answer requests on!");
1497 return; /* anti-compiler-warning */
1501 * Get the array of listener sockets...
1504 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1506 cupsdLogMessage(CUPSD_LOG_ERROR
,
1507 "launchd_checkin: No sockets found to answer requests on!");
1509 return; /* anti-compiler-warning */
1513 * Add listening fd(s) to the Listener array...
1516 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1518 count
= launch_data_array_get_count(ld_array
);
1520 for (i
= 0; i
< count
; i
++)
1523 * Get the launchd file descriptor and address...
1526 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1528 fd
= launch_data_get_fd(tmp
);
1529 addrlen
= sizeof(addr
);
1531 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1533 cupsdLogMessage(CUPSD_LOG_ERROR
,
1534 "launchd_checkin: Unable to get local address - %s",
1540 * Try to match the launchd socket address to one of the listeners...
1543 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1545 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1546 if (httpAddrEqual(&lis
->address
, &addr
))
1550 * Add a new listener If there's no match...
1555 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1556 "launchd_checkin: Matched existing listener %s with fd %d...",
1557 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1561 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1562 "launchd_checkin: Adding new listener %s with fd %d...",
1563 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1565 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1567 cupsdLogMessage(CUPSD_LOG_ERROR
,
1568 "launchd_checkin: Unable to allocate listener - %s.",
1573 cupsArrayAdd(Listeners
, lis
);
1575 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1584 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1585 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1587 # endif /* AF_INET6 */
1588 if (lis
->address
.addr
.sa_family
== AF_INET
)
1589 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1592 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1593 # endif /* HAVE_SSL */
1598 launch_data_free(ld_msg
);
1599 launch_data_free(ld_resp
);
1604 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1608 launchd_checkout(void)
1610 int fd
; /* File descriptor */
1614 * Create or remove the launchd KeepAlive file based on whether
1615 * there are active jobs, polling, browsing for remote printers or
1616 * shared printers to advertise...
1619 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1621 (BrowseRemoteProtocols
||
1622 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1624 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1625 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1627 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1632 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1633 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1635 unlink(CUPS_KEEPALIVE
);
1638 #endif /* HAVE_LAUNCHD */
1642 * 'parent_handler()' - Catch USR1/CHLD signals...
1646 parent_handler(int sig
) /* I - Signal */
1649 * Store the signal we got from the OS and return...
1652 parent_signal
= sig
;
1657 * 'process_children()' - Process all dead children...
1661 process_children(void)
1663 int status
; /* Exit status of child */
1664 int pid
, /* Process ID of child */
1665 job_id
; /* Job ID of child */
1666 cupsd_job_t
*job
; /* Current job */
1667 int i
; /* Looping var */
1668 char name
[1024]; /* Process name */
1671 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1674 * Reset the dead_children flag...
1680 * Collect the exit status of some children...
1684 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1685 #elif defined(HAVE_WAIT3)
1686 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1688 if ((pid
= wait(&status
)) > 0)
1689 #endif /* HAVE_WAITPID */
1692 * Collect the name of the process that finished...
1695 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1698 * Delete certificates for CGI processes...
1702 cupsdDeleteCert(pid
);
1705 * Handle completed job filters...
1708 if (job_id
> 0 && (job
= cupsdFindJob(job_id
)) != NULL
)
1710 for (i
= 0; job
->filters
[i
]; i
++)
1711 if (job
->filters
[i
] == pid
)
1714 if (job
->filters
[i
] || job
->backend
== pid
)
1717 * OK, this process has gone away; what's left?
1720 if (job
->filters
[i
])
1721 job
->filters
[i
] = -pid
;
1723 job
->backend
= -pid
;
1725 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1729 * An error occurred; save the exit status so we know to stop
1730 * the printer or cancel the job when all of the filters finish...
1732 * A negative status indicates that the backend failed and the
1733 * printer needs to be stopped.
1736 if (job
->filters
[i
])
1737 job
->status
= status
; /* Filter failed */
1739 job
->status
= -status
; /* Backend failed */
1741 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1742 job
->status_level
> CUPSD_LOG_ERROR
)
1744 char message
[1024]; /* New printer-state-message */
1747 job
->status_level
= CUPSD_LOG_ERROR
;
1749 snprintf(message
, sizeof(message
), "%s failed", name
);
1753 strlcpy(job
->printer
->state_message
, message
,
1754 sizeof(job
->printer
->state_message
));
1755 cupsdAddPrinterHistory(job
->printer
);
1761 if (!job
->printer_message
&& job
->attrs
)
1763 if ((job
->printer_message
=
1764 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1765 IPP_TAG_TEXT
)) == NULL
)
1766 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1768 "job-printer-state-message",
1772 if (job
->printer_message
)
1773 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1779 * If this is not the last file in a job, see if all of the
1780 * filters are done, and if so move to the next file.
1783 if (job
->current_file
< job
->num_files
)
1785 for (i
= 0; job
->filters
[i
] < 0; i
++);
1787 if (!job
->filters
[i
])
1790 * Process the next file...
1793 cupsdContinueJob(job
);
1796 else if (job
->state_value
== IPP_JOB_CANCELED
)
1799 * Remove the job from the active list if there are no processes still
1803 for (i
= 0; job
->filters
[i
] < 0; i
++);
1805 if (!job
->filters
[i
] && job
->backend
<= 0)
1806 cupsArrayRemove(ActiveJobs
, job
);
1812 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1813 * since they come when we kill/end a process...
1816 if (status
== SIGTERM
|| status
== SIGKILL
)
1818 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1819 "PID %d (%s) was terminated normally with signal %d.",
1824 if (WIFEXITED(status
))
1825 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) stopped with status %d!",
1826 pid
, name
, WEXITSTATUS(status
));
1828 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1829 pid
, name
, WTERMSIG(status
));
1831 if (LogLevel
< CUPSD_LOG_DEBUG
)
1832 cupsdLogMessage(CUPSD_LOG_INFO
,
1833 "Hint: Try setting the LogLevel to \"debug\" to find "
1837 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1842 * If wait*() is interrupted by a signal, tell main() to call us again...
1845 if (pid
< 0 && errno
== EINTR
)
1851 * 'select_timeout()' - Calculate the select timeout value.
1855 static long /* O - Number of seconds */
1856 select_timeout(int fds
) /* I - Number of descriptors returned */
1858 long timeout
; /* Timeout for select */
1859 time_t now
; /* Current time */
1860 cupsd_client_t
*con
; /* Client information */
1861 cupsd_printer_t
*p
; /* Printer information */
1862 cupsd_job_t
*job
; /* Job information */
1863 cupsd_subscription_t
*sub
; /* Subscription information */
1864 const char *why
; /* Debugging aid */
1868 * Check to see if any of the clients have pending data to be
1869 * processed; if so, the timeout should be 0...
1872 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1874 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1875 if (con
->http
.used
> 0)
1879 * If select has been active in the last second (fds > 0) or we have
1880 * many resources in use then don't bother trying to optimize the
1881 * timeout, just make it 1 second.
1884 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1888 * Otherwise, check all of the possible events that we need to wake for...
1892 timeout
= now
+ 86400; /* 86400 == 1 day */
1897 * When going to sleep, wake up to cancel jobs that don't complete in time.
1900 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1902 timeout
= SleepJobs
;
1903 why
= "cancel jobs before sleeping";
1905 #endif /* __APPLE__ */
1908 * Check whether we are accepting new connections...
1911 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1912 ListeningPaused
< timeout
)
1914 if (ListeningPaused
<= now
)
1917 timeout
= ListeningPaused
;
1919 why
= "resume listening";
1923 * Check the activity and close old clients...
1926 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1928 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1929 if ((con
->http
.activity
+ Timeout
) < timeout
)
1931 timeout
= con
->http
.activity
+ Timeout
;
1932 why
= "timeout a client connection";
1936 * Update the browse list as needed...
1939 if (Browsing
&& BrowseLocalProtocols
)
1942 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1944 timeout
= BrowseSLPRefresh
;
1945 why
= "update SLP browsing";
1947 #endif /* HAVE_LIBSLP */
1950 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1952 timeout
= BrowseLDAPRefresh
;
1953 why
= "update LDAP browsing";
1955 #endif /* HAVE_LDAP */
1957 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1959 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1961 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1963 if (p
->type
& CUPS_PRINTER_REMOTE
)
1965 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1967 timeout
= p
->browse_time
+ BrowseTimeout
;
1968 why
= "browse timeout a printer";
1971 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1973 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1975 timeout
= p
->browse_time
+ BrowseInterval
;
1976 why
= "send browse update";
1984 * Write out changes to configuration and state files...
1987 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1989 timeout
= DirtyCleanTime
;
1990 why
= "write dirty config/state files";
1994 * Check for any active jobs...
1997 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1999 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2001 if (job
->kill_time
&& job
->kill_time
< timeout
)
2003 timeout
= job
->kill_time
;
2004 why
= "kill unresponsive jobs";
2007 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
2009 timeout
= job
->hold_until
;
2010 why
= "release held jobs";
2012 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
2015 why
= "start pending jobs";
2020 #ifdef HAVE_MALLINFO
2022 * Log memory usage every minute...
2025 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2027 timeout
= mallinfo_time
+ 60;
2028 why
= "display memory usage";
2030 #endif /* HAVE_MALLINFO */
2033 * Expire subscriptions as needed...
2036 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2038 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2039 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2041 timeout
= sub
->expire
;
2042 why
= "expire subscription";
2046 * Adjust from absolute to relative time. If p->browse_time above
2047 * was 0 then we can end up with a negative value here, so check.
2048 * We add 1 second to the timeout since events occur after the
2049 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2050 * to avoid select() timeout limits present on some operating
2054 timeout
= timeout
- now
+ 1;
2058 else if (timeout
> 86400)
2062 * Log and return the timeout value...
2065 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
2073 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2077 sigchld_handler(int sig
) /* I - Signal number */
2082 * Flag that we have dead children...
2088 * Reset the signal handler as needed...
2091 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2092 signal(SIGCLD
, sigchld_handler
);
2093 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2098 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2102 sighup_handler(int sig
) /* I - Signal number */
2106 NeedReload
= RELOAD_ALL
;
2107 ReloadTime
= time(NULL
);
2109 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2110 signal(SIGHUP
, sighup_handler
);
2111 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2116 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2120 sigterm_handler(int sig
) /* I - Signal number */
2122 (void)sig
; /* remove compiler warnings... */
2125 * Flag that we should stop and return...
2133 * 'usage()' - Show scheduler usage.
2137 usage(int status
) /* O - Exit status */
2139 _cupsLangPuts(status
? stderr
: stdout
,
2140 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
2142 "-c config-file Load alternate configuration file\n"
2143 "-f Run in the foreground\n"
2144 "-F Run in the foreground but detach\n"
2145 "-h Show this usage message\n"
2146 "-l Run cupsd from launchd(8)\n"));
2152 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".