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 event notification time */
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 fputs("cupsd: -p (startup profiling) is for internal testing "
274 "use only!\n", stderr
);
279 case 'P' : /* Disable security profiles */
280 fputs("cupsd: -P (disable security profiles) is for internal "
281 "testing use only!\n", stderr
);
286 case 'S' : /* Disable system management functions */
287 fputs("cupsd: -S (disable system management) for internal "
288 "testing use only!\n", stderr
);
291 #endif /* __APPLE__ */
293 case 't' : /* Test the cupsd.conf file... */
298 default : /* Unknown option */
299 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
300 "aborting\n"), *opt
);
306 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting\n"),
311 if (!ConfigurationFile
)
312 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
315 * If the user hasn't specified "-f", run in the background...
321 * Setup signal handlers for the parent...
324 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
325 sigset(SIGUSR1
, parent_handler
);
326 sigset(SIGCHLD
, parent_handler
);
328 sigset(SIGHUP
, SIG_IGN
);
329 #elif defined(HAVE_SIGACTION)
330 memset(&action
, 0, sizeof(action
));
331 sigemptyset(&action
.sa_mask
);
332 sigaddset(&action
.sa_mask
, SIGUSR1
);
333 action
.sa_handler
= parent_handler
;
334 sigaction(SIGUSR1
, &action
, NULL
);
335 sigaction(SIGCHLD
, &action
, NULL
);
337 sigemptyset(&action
.sa_mask
);
338 action
.sa_handler
= SIG_IGN
;
339 sigaction(SIGHUP
, &action
, NULL
);
341 signal(SIGUSR1
, parent_handler
);
342 signal(SIGCLD
, parent_handler
);
344 signal(SIGHUP
, SIG_IGN
);
345 #endif /* HAVE_SIGSET */
350 * OK, wait for the child to startup and send us SIGUSR1 or to crash
351 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
352 * might be sent by the init script to restart the scheduler...
355 for (; parent_signal
== 0;)
358 if (parent_signal
== SIGUSR1
)
366 else if (WIFEXITED(i
))
368 fprintf(stderr
, "cupsd: Child exited with status %d\n",
374 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
381 * Call _thread_sys_closefrom() so the child process doesn't reset the
382 * parent's file descriptors to be blocking. This is a workaround for a
383 * limitation of userland libpthread on OpenBSD.
386 _thread_sys_closefrom(0);
387 #endif /* __OpenBSD__ */
390 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
391 * a program, and since this kind of really unfriendly behavior seems to be
392 * more common these days in system libraries, we need to re-execute the
393 * background cupsd with the "-C" option to avoid problems. Unfortunately,
394 * we also have to assume that argv[0] contains the name of the cupsd
395 * executable - there is no portable way to get the real pathname...
398 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
405 * Make sure we aren't tying up any filesystems...
412 * Disable core dumps...
415 getrlimit(RLIMIT_CORE
, &limit
);
417 setrlimit(RLIMIT_CORE
, &limit
);
420 * Disconnect from the controlling terminal...
426 * Close all open files...
429 getrlimit(RLIMIT_NOFILE
, &limit
);
431 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
435 * Redirect stdin/out/err to /dev/null...
438 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
444 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
450 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
459 * Set the timezone info...
465 setlocale(LC_TIME
, "");
469 * Set the maximum number of files...
472 getrlimit(RLIMIT_NOFILE
, &limit
);
474 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
475 if (limit
.rlim_max
> FD_SETSIZE
)
478 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
480 if (limit
.rlim_max
== RLIM_INFINITY
)
483 #endif /* RLIM_INFINITY */
484 MaxFDs
= limit
.rlim_max
;
486 limit
.rlim_cur
= MaxFDs
;
488 setrlimit(RLIMIT_NOFILE
, &limit
);
493 * Read configuration...
496 if (!cupsdReadConfiguration())
499 printf("%s contains errors\n", ConfigurationFile
);
501 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
505 else if (TestConfigFile
)
507 printf("%s is OK\n", ConfigurationFile
);
511 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
514 * Clean out the temporary directory...
517 cups_dir_t
*dir
; /* Temporary directory */
518 cups_dentry_t
*dent
; /* Directory entry */
519 char tempfile
[1024]; /* Temporary filename */
522 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
524 cupsdLogMessage(CUPSD_LOG_INFO
,
525 "Cleaning out old temporary files in \"%s\"...", TempDir
);
527 while ((dent
= cupsDirRead(dir
)) != NULL
)
529 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
531 if (unlink(tempfile
))
532 cupsdLogMessage(CUPSD_LOG_ERROR
,
533 "Unable to remove temporary file \"%s\" - %s",
534 tempfile
, strerror(errno
));
536 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
543 cupsdLogMessage(CUPSD_LOG_ERROR
,
544 "Unable to open temporary directory \"%s\" - %s",
545 TempDir
, strerror(errno
));
552 * If we were started by launchd get the listen sockets file descriptors...
558 #endif /* HAVE_LAUNCHD */
560 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
562 * Load Print Service quota enforcement library (X Server only)
565 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
568 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
569 #endif /* __APPLE__ && HAVE_DLFCN_H */
572 * Startup the server...
578 * Catch hangup and child signals and ignore broken pipes...
581 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
582 sigset(SIGCHLD
, sigchld_handler
);
583 sigset(SIGHUP
, sighup_handler
);
584 sigset(SIGPIPE
, SIG_IGN
);
585 sigset(SIGTERM
, sigterm_handler
);
586 #elif defined(HAVE_SIGACTION)
587 memset(&action
, 0, sizeof(action
));
589 sigemptyset(&action
.sa_mask
);
590 sigaddset(&action
.sa_mask
, SIGTERM
);
591 sigaddset(&action
.sa_mask
, SIGCHLD
);
592 action
.sa_handler
= sigchld_handler
;
593 sigaction(SIGCHLD
, &action
, NULL
);
595 sigemptyset(&action
.sa_mask
);
596 sigaddset(&action
.sa_mask
, SIGHUP
);
597 action
.sa_handler
= sighup_handler
;
598 sigaction(SIGHUP
, &action
, NULL
);
600 sigemptyset(&action
.sa_mask
);
601 action
.sa_handler
= SIG_IGN
;
602 sigaction(SIGPIPE
, &action
, NULL
);
604 sigemptyset(&action
.sa_mask
);
605 sigaddset(&action
.sa_mask
, SIGTERM
);
606 sigaddset(&action
.sa_mask
, SIGCHLD
);
607 action
.sa_handler
= sigterm_handler
;
608 sigaction(SIGTERM
, &action
, NULL
);
610 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
611 signal(SIGHUP
, sighup_handler
);
612 signal(SIGPIPE
, SIG_IGN
);
613 signal(SIGTERM
, sigterm_handler
);
614 #endif /* HAVE_SIGSET */
618 * Try to create a fake lpsched lock file if one is not already there.
619 * Some Adobe applications need it under IRIX in order to enable
623 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
625 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
626 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
631 fchmod(cupsFileNumber(fp
), 0644);
632 fchown(cupsFileNumber(fp
), User
, Group
);
639 * Initialize authentication certificates...
645 * If we are running in the background, signal the parent process that
646 * we are up and running...
649 if (!fg
|| run_as_child
)
652 * Send a signal to the parent process, but only if the parent is
653 * not PID 1 (init). This avoids accidentally shutting down the
654 * system on OpenBSD if you CTRL-C the server before it is up...
657 i
= getppid(); /* Save parent PID to avoid race condition */
665 * Start power management framework...
669 cupsdStartSystemMonitor();
670 #endif /* __APPLE__ */
673 * Send server-started event...
678 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
679 "Scheduler started via launchd.");
681 #endif /* HAVE_LAUNCHD */
683 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
684 "Scheduler started in foreground.");
686 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
687 "Scheduler started in background.");
690 * Start any pending print jobs...
699 current_time
= time(NULL
);
700 browse_time
= current_time
;
701 event_time
= current_time
;
702 expire_time
= current_time
;
705 senddoc_time
= current_time
;
707 while (!stop_scheduler
)
710 * Check if there are dead children to handle...
717 * Check if we need to load the server configuration file...
723 * Close any idle clients...
726 if (cupsArrayCount(Clients
) > 0)
728 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
730 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
731 if (con
->http
.state
== HTTP_WAITING
)
732 cupsdCloseClient(con
);
734 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
736 cupsdPauseListening();
740 * Restart if all clients are closed and all jobs finished, or
741 * if the reload timeout has elapsed...
744 if ((cupsArrayCount(Clients
) == 0 &&
745 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
746 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
749 * Shutdown the server...
755 * Read configuration...
758 if (!cupsdReadConfiguration())
760 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
769 * If we were started by launchd, get the listen socket file
776 #endif /* HAVE_LAUNCHD */
779 * Startup the server...
785 * Send a server-restarted event...
788 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
789 "Scheduler restarted.");
794 * Check for available input or ready output. If cupsdDoSelect()
795 * returns 0 or -1, something bad happened and we should exit
798 * Note that we at least have one listening socket open at all
802 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
807 * If no other work is scheduled and we're being controlled by
808 * launchd then timeout after 'LaunchdTimeout' seconds of
812 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
813 !cupsArrayCount(ActiveJobs
) &&
815 (!BrowseRemoteProtocols
&&
816 (!NumBrowsers
|| !BrowseLocalProtocols
||
817 cupsArrayCount(Printers
) == 0))))
819 timeout
= LaunchdTimeout
;
820 launchd_idle_exit
= 1;
823 launchd_idle_exit
= 0;
824 #endif /* HAVE_LAUNCHD */
826 if ((fds
= cupsdDoSelect(timeout
)) < 0)
829 * Got an error from select!
833 cupsd_printer_t
*p
; /* Current printer */
834 #endif /* HAVE_DNSSD */
837 if (errno
== EINTR
) /* Just interrupted by a signal */
841 * Log all sorts of debug info to help track down the problem.
844 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
847 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
849 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
850 cupsdLogMessage(CUPSD_LOG_EMERG
,
851 "Clients[%d] = %d, file = %d, state = %d",
852 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
854 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
856 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
857 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
859 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
861 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
864 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
866 #endif /* __APPLE__ */
868 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
870 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
871 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
873 job
->status_buffer
? job
->status_buffer
->fd
: -1,
874 job
->print_pipes
[0], job
->print_pipes
[1],
875 job
->back_pipes
[0], job
->back_pipes
[1]);
878 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
880 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
881 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
882 p
->reg_name
? p
->reg_name
: "(null)");
883 #endif /* HAVE_DNSSD */
888 current_time
= time(NULL
);
891 * Write dirty config/state files...
894 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
899 * If we are going to sleep and still have pending jobs, stop them after
900 * a period of time...
903 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
904 cupsArrayCount(PrintingJobs
) > 0)
907 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 10);
909 #endif /* __APPLE__ */
913 * Update the network interfaces once a minute...
916 if ((current_time
- netif_time
) >= 60)
918 netif_time
= current_time
;
921 #endif /* !__APPLE__ */
925 * If no other work was scheduled and we're being controlled by launchd
926 * then timeout after 'LaunchdTimeout' seconds of inactivity...
929 if (!fds
&& launchd_idle_exit
)
931 cupsdLogMessage(CUPSD_LOG_INFO
,
932 "Printer sharing is off and there are no jobs pending, "
933 "will restart on demand.");
937 #endif /* HAVE_LAUNCHD */
940 * Resume listening for new connections as needed...
943 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
944 cupsArrayCount(Clients
) < MaxClients
)
945 cupsdResumeListening();
948 * Expire subscriptions and unload completed jobs as needed...
951 if (current_time
> expire_time
)
953 if (cupsArrayCount(Subscriptions
) > 0)
954 cupsdExpireSubscriptions(NULL
, NULL
);
956 cupsdUnloadCompletedJobs();
958 expire_time
= current_time
;
962 * Update the browse list as needed...
968 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
969 BrowseSLPRefresh
<= current_time
)
970 cupsdUpdateSLPBrowse();
971 #endif /* HAVE_LIBSLP */
974 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
975 BrowseLDAPRefresh
<= current_time
)
976 cupsdUpdateLDAPBrowse();
977 #endif /* HAVE_LDAP */
980 if (Browsing
&& current_time
> browse_time
)
982 cupsdSendBrowseList();
983 browse_time
= current_time
;
987 * Update the root certificate once every 5 minutes if we have client
991 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
992 !RunUser
&& cupsArrayCount(Clients
))
995 * Update the root certificate...
999 cupsdAddCert(0, "root", NULL
);
1003 * Check for new data on the client sockets...
1006 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1008 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1011 * Process pending data in the input buffer...
1016 cupsdReadClient(con
);
1021 * Check the activity and close old clients...
1024 activity
= current_time
- Timeout
;
1025 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
1027 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1028 "Closing client %d after %d seconds of inactivity...",
1029 con
->http
.fd
, Timeout
);
1031 cupsdCloseClient(con
);
1037 * Update any pending multi-file documents...
1040 if ((current_time
- senddoc_time
) >= 10)
1044 senddoc_time
= current_time
;
1048 * Log statistics at most once a minute when in debug mode...
1051 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1053 size_t string_count
, /* String count */
1054 alloc_bytes
, /* Allocated string bytes */
1055 total_bytes
; /* Total string bytes */
1056 #ifdef HAVE_MALLINFO
1057 struct mallinfo mem
; /* Malloc information */
1061 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1062 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1063 mem
.usmblks
+ mem
.uordblks
);
1064 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1065 mem
.fsmblks
+ mem
.fordblks
);
1066 #endif /* HAVE_MALLINFO */
1068 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1069 cupsArrayCount(Clients
));
1070 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1071 cupsArrayCount(Jobs
));
1072 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1073 cupsArrayCount(ActiveJobs
));
1074 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1075 cupsArrayCount(Printers
));
1076 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1077 cupsArrayCount(ImplicitPrinters
));
1079 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1080 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1081 "Report: stringpool-string-count=" CUPS_LLFMT
,
1082 CUPS_LLCAST string_count
);
1083 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1084 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1085 CUPS_LLCAST alloc_bytes
);
1086 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1087 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1088 CUPS_LLCAST total_bytes
);
1090 report_time
= current_time
;
1094 * Handle OS-specific event notification for any events that have
1095 * accumulated. Don't send these more than once a second...
1098 if (LastEvent
&& (current_time
- event_time
) >= 1)
1100 #ifdef HAVE_NOTIFY_POST
1101 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1102 CUPSD_EVENT_PRINTER_DELETED
|
1103 CUPSD_EVENT_PRINTER_MODIFIED
))
1105 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1106 "notify_post(\"com.apple.printerListChange\")");
1107 notify_post("com.apple.printerListChange");
1110 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1112 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1113 "notify_post(\"com.apple.printerHistoryChange\")");
1114 notify_post("com.apple.printerHistoryChange");
1117 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1118 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1119 CUPSD_EVENT_JOB_PROGRESS
))
1121 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1122 "notify_post(\"com.apple.jobChange\")");
1123 notify_post("com.apple.jobChange");
1125 #endif /* HAVE_NOTIFY_POST */
1128 * Reset the accumulated events...
1131 LastEvent
= CUPSD_EVENT_NONE
;
1132 event_time
= current_time
;
1137 * Log a message based on what happened...
1142 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1143 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1144 "Scheduler shutting down normally.");
1148 cupsdLogMessage(CUPSD_LOG_ERROR
,
1149 "Scheduler shutting down due to program error.");
1150 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1151 "Scheduler shutting down due to program error.");
1155 * Close all network clients...
1162 * Update the launchd KeepAlive file as needed...
1167 #endif /* HAVE_LAUNCHD */
1177 * Stop monitoring system event monitoring...
1181 cupsdStopSystemMonitor();
1182 #endif /* __APPLE__ */
1186 * Free the scheduler's Kerberos context...
1191 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1195 if (krb5_init_context
!= NULL
)
1196 # endif /* __APPLE__ */
1197 if (KerberosContext
)
1198 krb5_free_context(KerberosContext
);
1199 #endif /* HAVE_GSSAPI */
1201 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
1203 * Unload Print Service quota enforcement library (X Server only)
1206 PSQUpdateQuotaProc
= NULL
;
1212 #endif /* __APPLE__ && HAVE_DLFCN_H */
1216 * Remove the fake IRIX lpsched lock file, but only if the existing
1217 * file is not a FIFO which indicates that the real IRIX lpsched is
1221 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1222 if (!S_ISFIFO(statbuf
.st_mode
))
1223 unlink("/var/spool/lp/SCHEDLOCK");
1228 return (!stop_scheduler
);
1233 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1237 cupsdCheckProcess(void)
1240 * Flag that we have dead children...
1248 * 'cupsdClosePipe()' - Close a pipe as necessary.
1252 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1255 * Close file descriptors as needed...
1273 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1276 int /* O - 0 on success, -1 on error */
1277 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1280 * Create the pipe...
1292 * Set the "close on exec" flag on each end of the pipe...
1295 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1306 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1318 * Return 0 indicating success...
1326 * 'cupsdClearString()' - Clear a string.
1330 cupsdClearString(char **s
) /* O - String value */
1341 * 'cupsdHoldSignals()' - Hold child and termination signals.
1345 cupsdHoldSignals(void)
1347 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1348 sigset_t newmask
; /* New POSIX signal mask */
1349 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1359 #elif defined(HAVE_SIGACTION)
1360 sigemptyset(&newmask
);
1361 sigaddset(&newmask
, SIGTERM
);
1362 sigaddset(&newmask
, SIGCHLD
);
1363 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1364 #endif /* HAVE_SIGSET */
1369 * 'cupsdReleaseSignals()' - Release signals for delivery.
1373 cupsdReleaseSignals(void)
1382 #elif defined(HAVE_SIGACTION)
1383 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1384 #endif /* HAVE_SIGSET */
1389 * 'cupsdSetString()' - Set a string value.
1393 cupsdSetString(char **s
, /* O - New string */
1394 const char *v
) /* I - String value */
1403 *s
= _cupsStrAlloc(v
);
1410 * 'cupsdSetStringf()' - Set a formatted string value.
1414 cupsdSetStringf(char **s
, /* O - New string */
1415 const char *f
, /* I - Printf-style format string */
1416 ...) /* I - Additional args as needed */
1418 char v
[4096]; /* Formatting string value */
1419 va_list ap
; /* Argument pointer */
1420 char *olds
; /* Old string */
1431 vsnprintf(v
, sizeof(v
), f
, ap
);
1434 *s
= _cupsStrAlloc(v
);
1446 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1450 launchd_checkin(void)
1452 size_t i
, /* Looping var */
1453 count
; /* Numebr of listeners */
1454 int portnum
; /* Port number */
1455 launch_data_t ld_msg
, /* Launch data message */
1456 ld_resp
, /* Launch data response */
1457 ld_array
, /* Launch data array */
1458 ld_sockets
, /* Launch data sockets dictionary */
1459 tmp
; /* Launch data */
1460 cupsd_listener_t
*lis
; /* Listeners array */
1461 http_addr_t addr
; /* Address variable */
1462 socklen_t addrlen
; /* Length of address */
1463 int fd
; /* File descriptor */
1464 char s
[256]; /* String addresss */
1467 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1470 * Check-in with launchd...
1473 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1474 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1476 cupsdLogMessage(CUPSD_LOG_ERROR
,
1477 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1480 return; /* anti-compiler-warning */
1483 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1485 errno
= launch_data_get_errno(ld_resp
);
1486 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1489 return; /* anti-compiler-warning */
1493 * Get the sockets dictionary...
1496 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1499 cupsdLogMessage(CUPSD_LOG_ERROR
,
1500 "launchd_checkin: No sockets found to answer requests on!");
1502 return; /* anti-compiler-warning */
1506 * Get the array of listener sockets...
1509 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1511 cupsdLogMessage(CUPSD_LOG_ERROR
,
1512 "launchd_checkin: No sockets found to answer requests on!");
1514 return; /* anti-compiler-warning */
1518 * Add listening fd(s) to the Listener array...
1521 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1523 count
= launch_data_array_get_count(ld_array
);
1525 for (i
= 0; i
< count
; i
++)
1528 * Get the launchd file descriptor and address...
1531 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1533 fd
= launch_data_get_fd(tmp
);
1534 addrlen
= sizeof(addr
);
1536 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1538 cupsdLogMessage(CUPSD_LOG_ERROR
,
1539 "launchd_checkin: Unable to get local address - %s",
1545 * Try to match the launchd socket address to one of the listeners...
1548 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1550 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1551 if (httpAddrEqual(&lis
->address
, &addr
))
1555 * Add a new listener If there's no match...
1560 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1561 "launchd_checkin: Matched existing listener %s with fd %d...",
1562 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1566 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1567 "launchd_checkin: Adding new listener %s with fd %d...",
1568 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1570 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1572 cupsdLogMessage(CUPSD_LOG_ERROR
,
1573 "launchd_checkin: Unable to allocate listener - "
1574 "%s.", strerror(errno
));
1578 cupsArrayAdd(Listeners
, lis
);
1580 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1589 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1590 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1592 # endif /* AF_INET6 */
1593 if (lis
->address
.addr
.sa_family
== AF_INET
)
1594 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1597 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1598 # endif /* HAVE_SSL */
1603 launch_data_free(ld_msg
);
1604 launch_data_free(ld_resp
);
1609 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1613 launchd_checkout(void)
1615 int fd
; /* File descriptor */
1619 * Create or remove the launchd KeepAlive file based on whether
1620 * there are active jobs, polling, browsing for remote printers or
1621 * shared printers to advertise...
1624 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1626 (BrowseRemoteProtocols
||
1627 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1629 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1630 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1633 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1638 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1639 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1642 unlink(CUPS_KEEPALIVE
);
1645 #endif /* HAVE_LAUNCHD */
1649 * 'parent_handler()' - Catch USR1/CHLD signals...
1653 parent_handler(int sig
) /* I - Signal */
1656 * Store the signal we got from the OS and return...
1659 parent_signal
= sig
;
1664 * 'process_children()' - Process all dead children...
1668 process_children(void)
1670 int status
; /* Exit status of child */
1671 int pid
, /* Process ID of child */
1672 job_id
; /* Job ID of child */
1673 cupsd_job_t
*job
; /* Current job */
1674 int i
; /* Looping var */
1675 char name
[1024]; /* Process name */
1678 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1681 * Reset the dead_children flag...
1687 * Collect the exit status of some children...
1691 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1692 #elif defined(HAVE_WAIT3)
1693 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1695 if ((pid
= wait(&status
)) > 0)
1696 #endif /* HAVE_WAITPID */
1699 * Collect the name of the process that finished...
1702 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1705 * Delete certificates for CGI processes...
1709 cupsdDeleteCert(pid
);
1712 * Handle completed job filters...
1715 if (job_id
> 0 && (job
= cupsdFindJob(job_id
)) != NULL
)
1717 for (i
= 0; job
->filters
[i
]; i
++)
1718 if (job
->filters
[i
] == pid
)
1721 if (job
->filters
[i
] || job
->backend
== pid
)
1724 * OK, this process has gone away; what's left?
1727 if (job
->filters
[i
])
1728 job
->filters
[i
] = -pid
;
1730 job
->backend
= -pid
;
1732 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1736 * An error occurred; save the exit status so we know to stop
1737 * the printer or cancel the job when all of the filters finish...
1739 * A negative status indicates that the backend failed and the
1740 * printer needs to be stopped.
1743 if (job
->filters
[i
])
1744 job
->status
= status
; /* Filter failed */
1746 job
->status
= -status
; /* Backend failed */
1748 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1749 job
->status_level
> CUPSD_LOG_ERROR
)
1751 char message
[1024]; /* New printer-state-message */
1754 job
->status_level
= CUPSD_LOG_ERROR
;
1756 snprintf(message
, sizeof(message
), "%s failed", name
);
1760 strlcpy(job
->printer
->state_message
, message
,
1761 sizeof(job
->printer
->state_message
));
1762 cupsdAddPrinterHistory(job
->printer
);
1768 if (!job
->printer_message
&& job
->attrs
)
1770 if ((job
->printer_message
=
1771 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1772 IPP_TAG_TEXT
)) == NULL
)
1773 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1775 "job-printer-state-message",
1779 if (job
->printer_message
)
1780 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1786 * If this is not the last file in a job, see if all of the
1787 * filters are done, and if so move to the next file.
1790 if (job
->current_file
< job
->num_files
&& job
->printer
)
1792 for (i
= 0; job
->filters
[i
] < 0; i
++);
1794 if (!job
->filters
[i
])
1797 * Process the next file...
1800 cupsdContinueJob(job
);
1803 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1806 * Remove the job from the active list if there are no processes still
1810 for (i
= 0; job
->filters
[i
] < 0; i
++);
1812 if (!job
->filters
[i
] && job
->backend
<= 0)
1813 cupsArrayRemove(ActiveJobs
, job
);
1819 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1820 * since they come when we kill/end a process...
1823 if (status
== SIGTERM
|| status
== SIGKILL
)
1825 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1826 "PID %d (%s) was terminated normally with signal %d.",
1831 if (WIFEXITED(status
))
1832 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) stopped with status %d!",
1833 pid
, name
, WEXITSTATUS(status
));
1835 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1836 pid
, name
, WTERMSIG(status
));
1838 if (LogLevel
< CUPSD_LOG_DEBUG
)
1839 cupsdLogMessage(CUPSD_LOG_INFO
,
1840 "Hint: Try setting the LogLevel to \"debug\" to find "
1844 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1849 * If wait*() is interrupted by a signal, tell main() to call us again...
1852 if (pid
< 0 && errno
== EINTR
)
1858 * 'select_timeout()' - Calculate the select timeout value.
1862 static long /* O - Number of seconds */
1863 select_timeout(int fds
) /* I - Number of descriptors returned */
1865 long timeout
; /* Timeout for select */
1866 time_t now
; /* Current time */
1867 cupsd_client_t
*con
; /* Client information */
1868 cupsd_printer_t
*p
; /* Printer information */
1869 cupsd_job_t
*job
; /* Job information */
1870 cupsd_subscription_t
*sub
; /* Subscription information */
1871 const char *why
; /* Debugging aid */
1875 * Check to see if any of the clients have pending data to be
1876 * processed; if so, the timeout should be 0...
1879 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1881 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1882 if (con
->http
.used
> 0)
1886 * If select has been active in the last second (fds > 0) or we have
1887 * many resources in use then don't bother trying to optimize the
1888 * timeout, just make it 1 second.
1891 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1895 * Otherwise, check all of the possible events that we need to wake for...
1899 timeout
= now
+ 86400; /* 86400 == 1 day */
1904 * When going to sleep, wake up to cancel jobs that don't complete in time.
1907 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1909 timeout
= SleepJobs
;
1910 why
= "cancel jobs before sleeping";
1912 #endif /* __APPLE__ */
1915 * Check whether we are accepting new connections...
1918 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1919 ListeningPaused
< timeout
)
1921 if (ListeningPaused
<= now
)
1924 timeout
= ListeningPaused
;
1926 why
= "resume listening";
1930 * Check the activity and close old clients...
1933 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1935 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1936 if ((con
->http
.activity
+ Timeout
) < timeout
)
1938 timeout
= con
->http
.activity
+ Timeout
;
1939 why
= "timeout a client connection";
1943 * Update the browse list as needed...
1946 if (Browsing
&& BrowseLocalProtocols
)
1949 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1951 timeout
= BrowseSLPRefresh
;
1952 why
= "update SLP browsing";
1954 #endif /* HAVE_LIBSLP */
1957 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1959 timeout
= BrowseLDAPRefresh
;
1960 why
= "update LDAP browsing";
1962 #endif /* HAVE_LDAP */
1964 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1966 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1968 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1970 if (p
->type
& CUPS_PRINTER_REMOTE
)
1972 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1974 timeout
= p
->browse_time
+ BrowseTimeout
;
1975 why
= "browse timeout a printer";
1978 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1980 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1982 timeout
= p
->browse_time
+ BrowseInterval
;
1983 why
= "send browse update";
1991 * Write out changes to configuration and state files...
1994 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1996 timeout
= DirtyCleanTime
;
1997 why
= "write dirty config/state files";
2001 * Check for any active jobs...
2004 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
2006 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2008 if (job
->kill_time
&& job
->kill_time
< timeout
)
2010 timeout
= job
->kill_time
;
2011 why
= "kill unresponsive jobs";
2014 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
2016 timeout
= job
->hold_until
;
2017 why
= "release held jobs";
2019 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
2022 why
= "start pending jobs";
2027 #ifdef HAVE_MALLINFO
2029 * Log memory usage every minute...
2032 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2034 timeout
= mallinfo_time
+ 60;
2035 why
= "display memory usage";
2037 #endif /* HAVE_MALLINFO */
2040 * Expire subscriptions as needed...
2043 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2045 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2046 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2048 timeout
= sub
->expire
;
2049 why
= "expire subscription";
2053 * Adjust from absolute to relative time. If p->browse_time above
2054 * was 0 then we can end up with a negative value here, so check.
2055 * We add 1 second to the timeout since events occur after the
2056 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2057 * to avoid select() timeout limits present on some operating
2061 timeout
= timeout
- now
+ 1;
2065 else if (timeout
> 86400)
2069 * Log and return the timeout value...
2072 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
2080 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2084 sigchld_handler(int sig
) /* I - Signal number */
2089 * Flag that we have dead children...
2095 * Reset the signal handler as needed...
2098 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2099 signal(SIGCLD
, sigchld_handler
);
2100 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2105 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2109 sighup_handler(int sig
) /* I - Signal number */
2113 NeedReload
= RELOAD_ALL
;
2114 ReloadTime
= time(NULL
);
2116 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2117 signal(SIGHUP
, sighup_handler
);
2118 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2123 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2127 sigterm_handler(int sig
) /* I - Signal number */
2129 (void)sig
; /* remove compiler warnings... */
2132 * Flag that we should stop and return...
2140 * 'usage()' - Show scheduler usage.
2144 usage(int status
) /* O - Exit status */
2146 _cupsLangPuts(status
? stderr
: stdout
,
2147 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
2149 "-c config-file Load alternate configuration file\n"
2150 "-f Run in the foreground\n"
2151 "-F Run in the foreground but detach\n"
2152 "-h Show this usage message\n"
2153 "-l Run cupsd from launchd(8)\n"));
2159 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".