2 * "$Id: main.c 7925 2008-09-10 17:47:26Z mike $"
4 * Main loop for the CUPS scheduler.
6 * Copyright 2007-2010 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 * cupsd_clean_files() - Clean out old files.
25 * launchd_checkin() - Check-in with launchd and collect the
27 * launchd_checkout() - Check-out with launchd.
28 * parent_handler() - Catch USR1/CHLD signals...
29 * process_children() - Process all dead children...
30 * select_timeout() - Calculate the select timeout value.
31 * sigchld_handler() - Handle 'child' signals from old processes.
32 * sighup_handler() - Handle 'hangup' signals to reconfigure the
34 * sigterm_handler() - Handle 'terminate' signals that stop the
36 * usage() - Show scheduler usage.
40 * Include necessary headers...
45 #include <sys/resource.h>
54 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
55 /* Name of the launchd KeepAlive file */
56 # ifndef LAUNCH_JOBKEY_KEEPALIVE
57 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
58 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
59 # ifndef LAUNCH_JOBKEY_PATHSTATE
60 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
61 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
62 # ifndef LAUNCH_JOBKEY_SERVICEIPC
63 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
64 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
65 #endif /* HAVE_LAUNCH_H */
67 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
69 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
72 #endif /* HAVE_NOTIFY_H */
79 static void cupsd_clean_files(const char *path
,
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? */
111 * 'main()' - Main entry for the CUPS scheduler.
114 int /* O - Exit status */
115 main(int argc
, /* I - Number of command-line args */
116 char *argv
[]) /* I - Command-line arguments */
118 int i
; /* Looping var */
119 char *opt
; /* Option character */
120 int fg
; /* Run in the foreground */
121 int fds
; /* Number of ready descriptors */
122 cupsd_client_t
*con
; /* Current client */
123 cupsd_job_t
*job
; /* Current job */
124 cupsd_listener_t
*lis
; /* Current listener */
125 time_t current_time
, /* Current time */
126 activity
, /* Client activity timer */
127 browse_time
, /* Next browse send time */
128 senddoc_time
, /* Send-Document time */
129 expire_time
, /* Subscription expire time */
130 report_time
, /* Malloc/client/job report time */
131 event_time
; /* Last event notification time */
132 long timeout
; /* Timeout for cupsdDoSelect() */
133 struct rlimit limit
; /* Runtime limit */
134 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
135 struct sigaction action
; /* Actions for POSIX signals */
136 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
138 cups_file_t
*fp
; /* Fake lpsched lock file */
139 struct stat statbuf
; /* Needed for checking lpsched FIFO */
141 int run_as_child
= 0;
142 /* Needed for background fork/exec */
144 int use_sysman
= !getuid();
145 /* Use system management functions? */
147 time_t netif_time
= 0; /* Time since last network update */
148 #endif /* __APPLE__ */
150 int launchd_idle_exit
;
151 /* Idle exit on select timeout? */
152 #endif /* HAVE_LAUNCHD */
157 * Check for setuid invocation, which we do not support!
160 if (getuid() != geteuid())
162 fputs("cupsd: Cannot run as a setuid program\n", stderr
);
165 #endif /* HAVE_GETEUID */
168 * Check for command-line arguments...
174 if (getenv("CUPSD_LAUNCHD"))
179 #endif /* HAVE_LAUNCHD */
181 for (i
= 1; i
< argc
; i
++)
182 if (argv
[i
][0] == '-')
183 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
186 case 'C' : /* Run as child with config file */
190 case 'c' : /* Configuration file */
194 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
195 "after \"-c\" option\n"));
199 if (argv
[i
][0] == '/')
202 * Absolute directory...
205 cupsdSetString(&ConfigurationFile
, argv
[i
]);
210 * Relative directory...
213 char *current
; /* Current directory */
217 * Allocate a buffer for the current working directory to
218 * reduce run-time stack usage; this approximates the
219 * behavior of some implementations of getcwd() when they
220 * are passed a NULL pointer.
223 if ((current
= malloc(1024)) == NULL
)
225 _cupsLangPuts(stderr
,
226 _("cupsd: Unable to get current directory\n"));
230 if (!getcwd(current
, 1024))
232 _cupsLangPuts(stderr
,
233 _("cupsd: Unable to get current directory\n"));
238 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
243 case 'f' : /* Run in foreground... */
247 case 'F' : /* Run in foreground, but disconnect from terminal... */
251 case 'h' : /* Show usage/help */
255 case 'l' : /* Started by launchd... */
260 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
261 "in, running in normal mode.\n"));
263 #endif /* HAVE_LAUNCHD */
266 case 'p' : /* Stop immediately for profiling */
267 fputs("cupsd: -p (startup profiling) is for internal testing "
268 "use only!\n", stderr
);
273 case 'P' : /* Disable security profiles */
274 fputs("cupsd: -P (disable security profiles) is for internal "
275 "testing use only!\n", stderr
);
280 case 'S' : /* Disable system management functions */
281 fputs("cupsd: -S (disable system management) for internal "
282 "testing use only!\n", stderr
);
285 #endif /* __APPLE__ */
287 case 't' : /* Test the cupsd.conf file... */
292 default : /* Unknown option */
293 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
294 "aborting\n"), *opt
);
300 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting\n"),
305 if (!ConfigurationFile
)
306 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
309 * If the user hasn't specified "-f", run in the background...
315 * Setup signal handlers for the parent...
318 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
319 sigset(SIGUSR1
, parent_handler
);
320 sigset(SIGCHLD
, parent_handler
);
322 sigset(SIGHUP
, SIG_IGN
);
323 #elif defined(HAVE_SIGACTION)
324 memset(&action
, 0, sizeof(action
));
325 sigemptyset(&action
.sa_mask
);
326 sigaddset(&action
.sa_mask
, SIGUSR1
);
327 action
.sa_handler
= parent_handler
;
328 sigaction(SIGUSR1
, &action
, NULL
);
329 sigaction(SIGCHLD
, &action
, NULL
);
331 sigemptyset(&action
.sa_mask
);
332 action
.sa_handler
= SIG_IGN
;
333 sigaction(SIGHUP
, &action
, NULL
);
335 signal(SIGUSR1
, parent_handler
);
336 signal(SIGCLD
, parent_handler
);
338 signal(SIGHUP
, SIG_IGN
);
339 #endif /* HAVE_SIGSET */
344 * OK, wait for the child to startup and send us SIGUSR1 or to crash
345 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
346 * might be sent by the init script to restart the scheduler...
349 for (; parent_signal
== 0;)
352 if (parent_signal
== SIGUSR1
)
360 else if (WIFEXITED(i
))
362 fprintf(stderr
, "cupsd: Child exited with status %d\n",
368 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
375 * Call _thread_sys_closefrom() so the child process doesn't reset the
376 * parent's file descriptors to be blocking. This is a workaround for a
377 * limitation of userland libpthread on OpenBSD.
380 _thread_sys_closefrom(0);
381 #endif /* __OpenBSD__ */
384 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
385 * a program, and since this kind of really unfriendly behavior seems to be
386 * more common these days in system libraries, we need to re-execute the
387 * background cupsd with the "-C" option to avoid problems. Unfortunately,
388 * we also have to assume that argv[0] contains the name of the cupsd
389 * executable - there is no portable way to get the real pathname...
392 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
399 * Make sure we aren't tying up any filesystems...
406 * Disable core dumps...
409 getrlimit(RLIMIT_CORE
, &limit
);
411 setrlimit(RLIMIT_CORE
, &limit
);
414 * Disconnect from the controlling terminal...
420 * Close all open files...
423 getrlimit(RLIMIT_NOFILE
, &limit
);
425 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
429 * Redirect stdin/out/err to /dev/null...
432 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
438 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
444 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
453 * Set the timezone info...
459 setlocale(LC_TIME
, "");
463 * Set the maximum number of files...
466 getrlimit(RLIMIT_NOFILE
, &limit
);
468 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
469 if (limit
.rlim_max
> FD_SETSIZE
)
472 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
474 if (limit
.rlim_max
== RLIM_INFINITY
)
477 #endif /* RLIM_INFINITY */
478 MaxFDs
= limit
.rlim_max
;
480 limit
.rlim_cur
= MaxFDs
;
482 setrlimit(RLIMIT_NOFILE
, &limit
);
487 * Read configuration...
490 if (!cupsdReadConfiguration())
493 printf("%s contains errors\n", ConfigurationFile
);
495 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
499 else if (TestConfigFile
)
501 printf("%s is OK\n", ConfigurationFile
);
506 * Clean out old temp files and printer cache data.
509 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
510 cupsd_clean_files(TempDir
, NULL
);
512 cupsd_clean_files(CacheDir
, "*.ipp");
518 * If we were started by launchd get the listen sockets file descriptors...
524 #endif /* HAVE_LAUNCHD */
527 * Startup the server...
535 * Catch hangup and child signals and ignore broken pipes...
538 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
539 sigset(SIGCHLD
, sigchld_handler
);
540 sigset(SIGHUP
, sighup_handler
);
541 sigset(SIGPIPE
, SIG_IGN
);
542 sigset(SIGTERM
, sigterm_handler
);
543 #elif defined(HAVE_SIGACTION)
544 memset(&action
, 0, sizeof(action
));
546 sigemptyset(&action
.sa_mask
);
547 sigaddset(&action
.sa_mask
, SIGTERM
);
548 sigaddset(&action
.sa_mask
, SIGCHLD
);
549 action
.sa_handler
= sigchld_handler
;
550 sigaction(SIGCHLD
, &action
, NULL
);
552 sigemptyset(&action
.sa_mask
);
553 sigaddset(&action
.sa_mask
, SIGHUP
);
554 action
.sa_handler
= sighup_handler
;
555 sigaction(SIGHUP
, &action
, NULL
);
557 sigemptyset(&action
.sa_mask
);
558 action
.sa_handler
= SIG_IGN
;
559 sigaction(SIGPIPE
, &action
, NULL
);
561 sigemptyset(&action
.sa_mask
);
562 sigaddset(&action
.sa_mask
, SIGTERM
);
563 sigaddset(&action
.sa_mask
, SIGCHLD
);
564 action
.sa_handler
= sigterm_handler
;
565 sigaction(SIGTERM
, &action
, NULL
);
567 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
568 signal(SIGHUP
, sighup_handler
);
569 signal(SIGPIPE
, SIG_IGN
);
570 signal(SIGTERM
, sigterm_handler
);
571 #endif /* HAVE_SIGSET */
575 * Try to create a fake lpsched lock file if one is not already there.
576 * Some Adobe applications need it under IRIX in order to enable
580 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
582 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
583 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
588 fchmod(cupsFileNumber(fp
), 0644);
589 fchown(cupsFileNumber(fp
), User
, Group
);
596 * Initialize authentication certificates...
602 * If we are running in the background, signal the parent process that
603 * we are up and running...
606 if (!fg
|| run_as_child
)
609 * Send a signal to the parent process, but only if the parent is
610 * not PID 1 (init). This avoids accidentally shutting down the
611 * system on OpenBSD if you CTRL-C the server before it is up...
614 i
= getppid(); /* Save parent PID to avoid race condition */
622 * Start power management framework...
626 cupsdStartSystemMonitor();
627 #endif /* __APPLE__ */
630 * Send server-started event...
635 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
636 "Scheduler started via launchd.");
638 #endif /* HAVE_LAUNCHD */
640 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
641 "Scheduler started in foreground.");
643 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
644 "Scheduler started in background.");
647 * Start any pending print jobs...
656 current_time
= time(NULL
);
657 browse_time
= current_time
;
658 event_time
= current_time
;
659 expire_time
= current_time
;
662 senddoc_time
= current_time
;
664 while (!stop_scheduler
)
667 * Check if there are dead children to handle...
674 * Check if we need to load the server configuration file...
680 * Close any idle clients...
683 if (cupsArrayCount(Clients
) > 0)
685 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
687 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
688 if (con
->http
.state
== HTTP_WAITING
)
689 cupsdCloseClient(con
);
691 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
693 cupsdPauseListening();
697 * Restart if all clients are closed and all jobs finished, or
698 * if the reload timeout has elapsed...
701 if ((cupsArrayCount(Clients
) == 0 &&
702 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
703 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
706 * Shutdown the server...
712 * Read configuration...
715 if (!cupsdReadConfiguration())
717 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
726 * If we were started by launchd, get the listen socket file
733 #endif /* HAVE_LAUNCHD */
736 * Startup the server...
742 * Send a server-restarted event...
745 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
746 "Scheduler restarted.");
751 * Check for available input or ready output. If cupsdDoSelect()
752 * returns 0 or -1, something bad happened and we should exit
755 * Note that we at least have one listening socket open at all
759 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
764 * If no other work is scheduled and we're being controlled by
765 * launchd then timeout after 'LaunchdTimeout' seconds of
769 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
770 !cupsArrayCount(ActiveJobs
) &&
772 (!BrowseRemoteProtocols
&&
773 (!NumBrowsers
|| !BrowseLocalProtocols
||
774 cupsArrayCount(Printers
) == 0))))
776 timeout
= LaunchdTimeout
;
777 launchd_idle_exit
= 1;
780 launchd_idle_exit
= 0;
781 #endif /* HAVE_LAUNCHD */
783 if ((fds
= cupsdDoSelect(timeout
)) < 0)
786 * Got an error from select!
790 cupsd_printer_t
*p
; /* Current printer */
791 #endif /* HAVE_DNSSD */
794 if (errno
== EINTR
) /* Just interrupted by a signal */
798 * Log all sorts of debug info to help track down the problem.
801 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
804 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
806 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
807 cupsdLogMessage(CUPSD_LOG_EMERG
,
808 "Clients[%d] = %d, file = %d, state = %d",
809 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
811 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
813 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
814 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
816 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
818 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
821 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
823 #endif /* __APPLE__ */
825 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
827 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
828 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
830 job
->status_buffer
? job
->status_buffer
->fd
: -1,
831 job
->print_pipes
[0], job
->print_pipes
[1],
832 job
->back_pipes
[0], job
->back_pipes
[1]);
835 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
837 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
838 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
839 p
->reg_name
? p
->reg_name
: "(null)");
840 #endif /* HAVE_DNSSD */
845 current_time
= time(NULL
);
848 * Write dirty config/state files...
851 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
856 * If we are going to sleep and still have pending jobs, stop them after
857 * a period of time...
860 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
861 cupsArrayCount(PrintingJobs
) > 0)
864 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 10);
866 #endif /* __APPLE__ */
870 * Update the network interfaces once a minute...
873 if ((current_time
- netif_time
) >= 60)
875 netif_time
= current_time
;
878 #endif /* !__APPLE__ */
882 * If no other work was scheduled and we're being controlled by launchd
883 * then timeout after 'LaunchdTimeout' seconds of inactivity...
886 if (!fds
&& launchd_idle_exit
)
888 cupsdLogMessage(CUPSD_LOG_INFO
,
889 "Printer sharing is off and there are no jobs pending, "
890 "will restart on demand.");
894 #endif /* HAVE_LAUNCHD */
897 * Resume listening for new connections as needed...
900 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
901 cupsArrayCount(Clients
) < MaxClients
)
902 cupsdResumeListening();
905 * Expire subscriptions and unload completed jobs as needed...
908 if (current_time
> expire_time
)
910 if (cupsArrayCount(Subscriptions
) > 0)
911 cupsdExpireSubscriptions(NULL
, NULL
);
913 cupsdUnloadCompletedJobs();
915 expire_time
= current_time
;
919 * Update the browse list as needed...
925 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
926 BrowseSLPRefresh
<= current_time
)
927 cupsdUpdateSLPBrowse();
928 #endif /* HAVE_LIBSLP */
931 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
932 BrowseLDAPRefresh
<= current_time
)
933 cupsdUpdateLDAPBrowse();
934 #endif /* HAVE_LDAP */
937 if (Browsing
&& current_time
> browse_time
)
939 cupsdSendBrowseList();
940 browse_time
= current_time
;
944 * Update the root certificate once every 5 minutes if we have client
948 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
949 !RunUser
&& cupsArrayCount(Clients
))
952 * Update the root certificate...
956 cupsdAddCert(0, "root", NULL
);
960 * Check for new data on the client sockets...
963 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
965 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
968 * Process pending data in the input buffer...
973 cupsdReadClient(con
);
978 * Check the activity and close old clients...
981 activity
= current_time
- Timeout
;
982 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
984 cupsdLogMessage(CUPSD_LOG_DEBUG
,
985 "Closing client %d after %d seconds of inactivity...",
986 con
->http
.fd
, Timeout
);
988 cupsdCloseClient(con
);
994 * Update any pending multi-file documents...
997 if ((current_time
- senddoc_time
) >= 10)
1001 senddoc_time
= current_time
;
1005 * Log statistics at most once a minute when in debug mode...
1008 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1010 size_t string_count
, /* String count */
1011 alloc_bytes
, /* Allocated string bytes */
1012 total_bytes
; /* Total string bytes */
1013 #ifdef HAVE_MALLINFO
1014 struct mallinfo mem
; /* Malloc information */
1018 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1019 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1020 mem
.usmblks
+ mem
.uordblks
);
1021 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1022 mem
.fsmblks
+ mem
.fordblks
);
1023 #endif /* HAVE_MALLINFO */
1025 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1026 cupsArrayCount(Clients
));
1027 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1028 cupsArrayCount(Jobs
));
1029 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1030 cupsArrayCount(ActiveJobs
));
1031 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1032 cupsArrayCount(Printers
));
1033 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1034 cupsArrayCount(ImplicitPrinters
));
1036 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1037 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1038 "Report: stringpool-string-count=" CUPS_LLFMT
,
1039 CUPS_LLCAST string_count
);
1040 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1041 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1042 CUPS_LLCAST alloc_bytes
);
1043 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1044 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1045 CUPS_LLCAST total_bytes
);
1047 report_time
= current_time
;
1051 * Handle OS-specific event notification for any events that have
1052 * accumulated. Don't send these more than once a second...
1055 if (LastEvent
&& (current_time
- event_time
) >= 1)
1057 #ifdef HAVE_NOTIFY_POST
1058 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1059 CUPSD_EVENT_PRINTER_DELETED
|
1060 CUPSD_EVENT_PRINTER_MODIFIED
))
1062 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1063 "notify_post(\"com.apple.printerListChange\")");
1064 notify_post("com.apple.printerListChange");
1067 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1069 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1070 "notify_post(\"com.apple.printerHistoryChange\")");
1071 notify_post("com.apple.printerHistoryChange");
1074 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1075 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1076 CUPSD_EVENT_JOB_PROGRESS
))
1078 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1079 "notify_post(\"com.apple.jobChange\")");
1080 notify_post("com.apple.jobChange");
1082 #endif /* HAVE_NOTIFY_POST */
1085 * Reset the accumulated events...
1088 LastEvent
= CUPSD_EVENT_NONE
;
1089 event_time
= current_time
;
1094 * Log a message based on what happened...
1099 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1100 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1101 "Scheduler shutting down normally.");
1105 cupsdLogMessage(CUPSD_LOG_ERROR
,
1106 "Scheduler shutting down due to program error.");
1107 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1108 "Scheduler shutting down due to program error.");
1112 * Close all network clients...
1119 * Update the launchd KeepAlive file as needed...
1124 #endif /* HAVE_LAUNCHD */
1134 * Stop monitoring system event monitoring...
1138 cupsdStopSystemMonitor();
1139 #endif /* __APPLE__ */
1143 * Free the scheduler's Kerberos context...
1148 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1152 if (krb5_init_context
!= NULL
)
1153 # endif /* __APPLE__ */
1154 if (KerberosContext
)
1155 krb5_free_context(KerberosContext
);
1156 #endif /* HAVE_GSSAPI */
1160 * Remove the fake IRIX lpsched lock file, but only if the existing
1161 * file is not a FIFO which indicates that the real IRIX lpsched is
1165 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1166 if (!S_ISFIFO(statbuf
.st_mode
))
1167 unlink("/var/spool/lp/SCHEDLOCK");
1172 return (!stop_scheduler
);
1177 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1181 cupsdCheckProcess(void)
1184 * Flag that we have dead children...
1192 * 'cupsdClosePipe()' - Close a pipe as necessary.
1196 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1199 * Close file descriptors as needed...
1217 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1220 int /* O - 0 on success, -1 on error */
1221 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1224 * Create the pipe...
1236 * Set the "close on exec" flag on each end of the pipe...
1239 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1250 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1262 * Return 0 indicating success...
1270 * 'cupsdClearString()' - Clear a string.
1274 cupsdClearString(char **s
) /* O - String value */
1285 * 'cupsdHoldSignals()' - Hold child and termination signals.
1289 cupsdHoldSignals(void)
1291 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1292 sigset_t newmask
; /* New POSIX signal mask */
1293 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1303 #elif defined(HAVE_SIGACTION)
1304 sigemptyset(&newmask
);
1305 sigaddset(&newmask
, SIGTERM
);
1306 sigaddset(&newmask
, SIGCHLD
);
1307 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1308 #endif /* HAVE_SIGSET */
1313 * 'cupsdReleaseSignals()' - Release signals for delivery.
1317 cupsdReleaseSignals(void)
1326 #elif defined(HAVE_SIGACTION)
1327 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1328 #endif /* HAVE_SIGSET */
1333 * 'cupsdSetString()' - Set a string value.
1337 cupsdSetString(char **s
, /* O - New string */
1338 const char *v
) /* I - String value */
1347 *s
= _cupsStrAlloc(v
);
1354 * 'cupsdSetStringf()' - Set a formatted string value.
1358 cupsdSetStringf(char **s
, /* O - New string */
1359 const char *f
, /* I - Printf-style format string */
1360 ...) /* I - Additional args as needed */
1362 char v
[4096]; /* Formatting string value */
1363 va_list ap
; /* Argument pointer */
1364 char *olds
; /* Old string */
1375 vsnprintf(v
, sizeof(v
), f
, ap
);
1378 *s
= _cupsStrAlloc(v
);
1389 * 'cupsd_clean_files()' - Clean out old files.
1393 cupsd_clean_files(const char *path
, /* I - Directory to clean */
1394 const char *pattern
) /* I - Filename pattern or NULL */
1396 cups_dir_t
*dir
; /* Directory */
1397 cups_dentry_t
*dent
; /* Directory entry */
1398 char filename
[1024]; /* Filename */
1399 int status
; /* Status from unlink/rmdir */
1402 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1403 "cupsd_clean_files(path=\"%s\", pattern=\"%s\")", path
,
1404 pattern
? pattern
: "(null)");
1406 if ((dir
= cupsDirOpen(path
)) == NULL
)
1408 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open directory \"%s\" - %s",
1409 path
, strerror(errno
));
1413 cupsdLogMessage(CUPSD_LOG_INFO
, "Cleaning out old files in \"%s\"...", path
);
1415 while ((dent
= cupsDirRead(dir
)) != NULL
)
1417 if (pattern
&& fnmatch(pattern
, dent
->filename
, 0))
1420 snprintf(filename
, sizeof(filename
), "%s/%s", path
, dent
->filename
);
1422 if (S_ISDIR(dent
->fileinfo
.st_mode
))
1424 cupsd_clean_files(filename
, pattern
);
1426 status
= rmdir(filename
);
1429 status
= unlink(filename
);
1432 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to remove \"%s\" - %s", filename
,
1435 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed \"%s\"...", filename
);
1444 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1448 launchd_checkin(void)
1450 size_t i
, /* Looping var */
1451 count
; /* Number of listeners */
1453 int portnum
; /* Port number */
1454 # endif /* HAVE_SSL */
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
&&
1733 status
!= SIGPIPE
&& job
->status
>= 0)
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.",
1829 else if (status
== SIGPIPE
)
1831 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1832 "PID %d (%s) did not catch or ignore signal %d.",
1837 if (WIFEXITED(status
))
1838 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) stopped with status %d!",
1839 pid
, name
, WEXITSTATUS(status
));
1841 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1842 pid
, name
, WTERMSIG(status
));
1844 if (LogLevel
< CUPSD_LOG_DEBUG
)
1845 cupsdLogMessage(CUPSD_LOG_INFO
,
1846 "Hint: Try setting the LogLevel to \"debug\" to find "
1850 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1855 * If wait*() is interrupted by a signal, tell main() to call us again...
1858 if (pid
< 0 && errno
== EINTR
)
1864 * 'select_timeout()' - Calculate the select timeout value.
1868 static long /* O - Number of seconds */
1869 select_timeout(int fds
) /* I - Number of descriptors returned */
1871 long timeout
; /* Timeout for select */
1872 time_t now
; /* Current time */
1873 cupsd_client_t
*con
; /* Client information */
1874 cupsd_printer_t
*p
; /* Printer information */
1875 cupsd_job_t
*job
; /* Job information */
1876 cupsd_subscription_t
*sub
; /* Subscription information */
1877 const char *why
; /* Debugging aid */
1881 * Check to see if any of the clients have pending data to be
1882 * processed; if so, the timeout should be 0...
1885 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1887 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1888 if (con
->http
.used
> 0)
1892 * If select has been active in the last second (fds > 0) or we have
1893 * many resources in use then don't bother trying to optimize the
1894 * timeout, just make it 1 second.
1897 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1901 * Otherwise, check all of the possible events that we need to wake for...
1905 timeout
= now
+ 86400; /* 86400 == 1 day */
1910 * When going to sleep, wake up to cancel jobs that don't complete in time.
1913 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1915 timeout
= SleepJobs
;
1916 why
= "cancel jobs before sleeping";
1918 #endif /* __APPLE__ */
1921 * Check whether we are accepting new connections...
1924 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1925 ListeningPaused
< timeout
)
1927 if (ListeningPaused
<= now
)
1930 timeout
= ListeningPaused
;
1932 why
= "resume listening";
1936 * Check the activity and close old clients...
1939 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1941 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1942 if ((con
->http
.activity
+ Timeout
) < timeout
)
1944 timeout
= con
->http
.activity
+ Timeout
;
1945 why
= "timeout a client connection";
1949 * Update the browse list as needed...
1952 if (Browsing
&& BrowseLocalProtocols
)
1955 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1957 timeout
= BrowseSLPRefresh
;
1958 why
= "update SLP browsing";
1960 #endif /* HAVE_LIBSLP */
1963 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1965 timeout
= BrowseLDAPRefresh
;
1966 why
= "update LDAP browsing";
1968 #endif /* HAVE_LDAP */
1970 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1972 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1974 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1976 if (p
->type
& CUPS_PRINTER_REMOTE
)
1978 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1980 timeout
= p
->browse_time
+ BrowseTimeout
;
1981 why
= "browse timeout a printer";
1984 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1986 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1988 timeout
= p
->browse_time
+ BrowseInterval
;
1989 why
= "send browse update";
1997 * Write out changes to configuration and state files...
2000 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
2002 timeout
= DirtyCleanTime
;
2003 why
= "write dirty config/state files";
2007 * Check for any active jobs...
2010 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
2012 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2014 if (job
->kill_time
&& job
->kill_time
< timeout
)
2016 timeout
= job
->kill_time
;
2017 why
= "kill unresponsive jobs";
2020 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
2022 timeout
= job
->hold_until
;
2023 why
= "release held jobs";
2025 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
2028 why
= "start pending jobs";
2033 #ifdef HAVE_MALLINFO
2035 * Log memory usage every minute...
2038 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2040 timeout
= mallinfo_time
+ 60;
2041 why
= "display memory usage";
2043 #endif /* HAVE_MALLINFO */
2046 * Expire subscriptions as needed...
2049 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2051 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2052 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2054 timeout
= sub
->expire
;
2055 why
= "expire subscription";
2059 * Adjust from absolute to relative time. If p->browse_time above
2060 * was 0 then we can end up with a negative value here, so check.
2061 * We add 1 second to the timeout since events occur after the
2062 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2063 * to avoid select() timeout limits present on some operating
2067 timeout
= timeout
- now
+ 1;
2071 else if (timeout
> 86400)
2075 * Log and return the timeout value...
2078 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
2086 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2090 sigchld_handler(int sig
) /* I - Signal number */
2095 * Flag that we have dead children...
2101 * Reset the signal handler as needed...
2104 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2105 signal(SIGCLD
, sigchld_handler
);
2106 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2111 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2115 sighup_handler(int sig
) /* I - Signal number */
2119 NeedReload
= RELOAD_ALL
;
2120 ReloadTime
= time(NULL
);
2122 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2123 signal(SIGHUP
, sighup_handler
);
2124 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2129 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2133 sigterm_handler(int sig
) /* I - Signal number */
2135 (void)sig
; /* remove compiler warnings... */
2138 * Flag that we should stop and return...
2146 * 'usage()' - Show scheduler usage.
2150 usage(int status
) /* O - Exit status */
2152 _cupsLangPuts(status
? stderr
: stdout
,
2153 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
2155 "-c config-file Load alternate configuration file\n"
2156 "-f Run in the foreground\n"
2157 "-F Run in the foreground but detach\n"
2158 "-h Show this usage message\n"
2159 "-l Run cupsd from launchd(8)\n"));
2165 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".