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-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...
533 * Catch hangup and child signals and ignore broken pipes...
536 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
537 sigset(SIGCHLD
, sigchld_handler
);
538 sigset(SIGHUP
, sighup_handler
);
539 sigset(SIGPIPE
, SIG_IGN
);
540 sigset(SIGTERM
, sigterm_handler
);
541 #elif defined(HAVE_SIGACTION)
542 memset(&action
, 0, sizeof(action
));
544 sigemptyset(&action
.sa_mask
);
545 sigaddset(&action
.sa_mask
, SIGTERM
);
546 sigaddset(&action
.sa_mask
, SIGCHLD
);
547 action
.sa_handler
= sigchld_handler
;
548 sigaction(SIGCHLD
, &action
, NULL
);
550 sigemptyset(&action
.sa_mask
);
551 sigaddset(&action
.sa_mask
, SIGHUP
);
552 action
.sa_handler
= sighup_handler
;
553 sigaction(SIGHUP
, &action
, NULL
);
555 sigemptyset(&action
.sa_mask
);
556 action
.sa_handler
= SIG_IGN
;
557 sigaction(SIGPIPE
, &action
, NULL
);
559 sigemptyset(&action
.sa_mask
);
560 sigaddset(&action
.sa_mask
, SIGTERM
);
561 sigaddset(&action
.sa_mask
, SIGCHLD
);
562 action
.sa_handler
= sigterm_handler
;
563 sigaction(SIGTERM
, &action
, NULL
);
565 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
566 signal(SIGHUP
, sighup_handler
);
567 signal(SIGPIPE
, SIG_IGN
);
568 signal(SIGTERM
, sigterm_handler
);
569 #endif /* HAVE_SIGSET */
573 * Try to create a fake lpsched lock file if one is not already there.
574 * Some Adobe applications need it under IRIX in order to enable
578 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
580 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
581 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
586 fchmod(cupsFileNumber(fp
), 0644);
587 fchown(cupsFileNumber(fp
), User
, Group
);
594 * Initialize authentication certificates...
600 * If we are running in the background, signal the parent process that
601 * we are up and running...
604 if (!fg
|| run_as_child
)
607 * Send a signal to the parent process, but only if the parent is
608 * not PID 1 (init). This avoids accidentally shutting down the
609 * system on OpenBSD if you CTRL-C the server before it is up...
612 i
= getppid(); /* Save parent PID to avoid race condition */
620 * Start power management framework...
624 cupsdStartSystemMonitor();
625 #endif /* __APPLE__ */
628 * Send server-started event...
633 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
634 "Scheduler started via launchd.");
636 #endif /* HAVE_LAUNCHD */
638 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
639 "Scheduler started in foreground.");
641 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
642 "Scheduler started in background.");
645 * Start any pending print jobs...
654 current_time
= time(NULL
);
655 browse_time
= current_time
;
656 event_time
= current_time
;
657 expire_time
= current_time
;
660 senddoc_time
= current_time
;
662 while (!stop_scheduler
)
665 * Check if there are dead children to handle...
672 * Check if we need to load the server configuration file...
678 * Close any idle clients...
681 if (cupsArrayCount(Clients
) > 0)
683 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
685 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
686 if (con
->http
.state
== HTTP_WAITING
)
687 cupsdCloseClient(con
);
689 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
691 cupsdPauseListening();
695 * Restart if all clients are closed and all jobs finished, or
696 * if the reload timeout has elapsed...
699 if ((cupsArrayCount(Clients
) == 0 &&
700 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
701 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
704 * Shutdown the server...
710 * Read configuration...
713 if (!cupsdReadConfiguration())
715 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
724 * If we were started by launchd, get the listen socket file
731 #endif /* HAVE_LAUNCHD */
734 * Startup the server...
740 * Send a server-restarted event...
743 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
744 "Scheduler restarted.");
749 * Check for available input or ready output. If cupsdDoSelect()
750 * returns 0 or -1, something bad happened and we should exit
753 * Note that we at least have one listening socket open at all
757 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
762 * If no other work is scheduled and we're being controlled by
763 * launchd then timeout after 'LaunchdTimeout' seconds of
767 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
768 !cupsArrayCount(ActiveJobs
) &&
770 (!BrowseRemoteProtocols
&&
771 (!NumBrowsers
|| !BrowseLocalProtocols
||
772 cupsArrayCount(Printers
) == 0))))
774 timeout
= LaunchdTimeout
;
775 launchd_idle_exit
= 1;
778 launchd_idle_exit
= 0;
779 #endif /* HAVE_LAUNCHD */
781 if ((fds
= cupsdDoSelect(timeout
)) < 0)
784 * Got an error from select!
788 cupsd_printer_t
*p
; /* Current printer */
789 #endif /* HAVE_DNSSD */
792 if (errno
== EINTR
) /* Just interrupted by a signal */
796 * Log all sorts of debug info to help track down the problem.
799 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
802 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
804 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
805 cupsdLogMessage(CUPSD_LOG_EMERG
,
806 "Clients[%d] = %d, file = %d, state = %d",
807 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
809 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
811 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
812 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
814 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
816 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
819 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
821 #endif /* __APPLE__ */
823 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
825 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
826 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
828 job
->status_buffer
? job
->status_buffer
->fd
: -1,
829 job
->print_pipes
[0], job
->print_pipes
[1],
830 job
->back_pipes
[0], job
->back_pipes
[1]);
833 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
835 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
836 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
837 p
->reg_name
? p
->reg_name
: "(null)");
838 #endif /* HAVE_DNSSD */
843 current_time
= time(NULL
);
846 * Write dirty config/state files...
849 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
854 * If we are going to sleep and still have pending jobs, stop them after
855 * a period of time...
858 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
859 cupsArrayCount(PrintingJobs
) > 0)
862 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 10);
864 #endif /* __APPLE__ */
868 * Update the network interfaces once a minute...
871 if ((current_time
- netif_time
) >= 60)
873 netif_time
= current_time
;
876 #endif /* !__APPLE__ */
880 * If no other work was scheduled and we're being controlled by launchd
881 * then timeout after 'LaunchdTimeout' seconds of inactivity...
884 if (!fds
&& launchd_idle_exit
)
886 cupsdLogMessage(CUPSD_LOG_INFO
,
887 "Printer sharing is off and there are no jobs pending, "
888 "will restart on demand.");
892 #endif /* HAVE_LAUNCHD */
895 * Resume listening for new connections as needed...
898 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
899 cupsArrayCount(Clients
) < MaxClients
)
900 cupsdResumeListening();
903 * Expire subscriptions and unload completed jobs as needed...
906 if (current_time
> expire_time
)
908 if (cupsArrayCount(Subscriptions
) > 0)
909 cupsdExpireSubscriptions(NULL
, NULL
);
911 cupsdUnloadCompletedJobs();
913 expire_time
= current_time
;
917 * Update the browse list as needed...
923 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
924 BrowseSLPRefresh
<= current_time
)
925 cupsdUpdateSLPBrowse();
926 #endif /* HAVE_LIBSLP */
929 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
930 BrowseLDAPRefresh
<= current_time
)
931 cupsdUpdateLDAPBrowse();
932 #endif /* HAVE_LDAP */
935 if (Browsing
&& current_time
> browse_time
)
937 cupsdSendBrowseList();
938 browse_time
= current_time
;
942 * Update the root certificate once every 5 minutes if we have client
946 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
947 !RunUser
&& cupsArrayCount(Clients
))
950 * Update the root certificate...
954 cupsdAddCert(0, "root", NULL
);
958 * Check for new data on the client sockets...
961 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
963 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
966 * Process pending data in the input buffer...
971 cupsdReadClient(con
);
976 * Check the activity and close old clients...
979 activity
= current_time
- Timeout
;
980 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
982 cupsdLogMessage(CUPSD_LOG_DEBUG
,
983 "Closing client %d after %d seconds of inactivity...",
984 con
->http
.fd
, Timeout
);
986 cupsdCloseClient(con
);
992 * Update any pending multi-file documents...
995 if ((current_time
- senddoc_time
) >= 10)
999 senddoc_time
= current_time
;
1003 * Log statistics at most once a minute when in debug mode...
1006 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1008 size_t string_count
, /* String count */
1009 alloc_bytes
, /* Allocated string bytes */
1010 total_bytes
; /* Total string bytes */
1011 #ifdef HAVE_MALLINFO
1012 struct mallinfo mem
; /* Malloc information */
1016 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1017 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1018 mem
.usmblks
+ mem
.uordblks
);
1019 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1020 mem
.fsmblks
+ mem
.fordblks
);
1021 #endif /* HAVE_MALLINFO */
1023 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1024 cupsArrayCount(Clients
));
1025 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1026 cupsArrayCount(Jobs
));
1027 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1028 cupsArrayCount(ActiveJobs
));
1029 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1030 cupsArrayCount(Printers
));
1031 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1032 cupsArrayCount(ImplicitPrinters
));
1034 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1035 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1036 "Report: stringpool-string-count=" CUPS_LLFMT
,
1037 CUPS_LLCAST string_count
);
1038 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1039 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1040 CUPS_LLCAST alloc_bytes
);
1041 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1042 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1043 CUPS_LLCAST total_bytes
);
1045 report_time
= current_time
;
1049 * Handle OS-specific event notification for any events that have
1050 * accumulated. Don't send these more than once a second...
1053 if (LastEvent
&& (current_time
- event_time
) >= 1)
1055 #ifdef HAVE_NOTIFY_POST
1056 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1057 CUPSD_EVENT_PRINTER_DELETED
|
1058 CUPSD_EVENT_PRINTER_MODIFIED
))
1060 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1061 "notify_post(\"com.apple.printerListChange\")");
1062 notify_post("com.apple.printerListChange");
1065 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1067 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1068 "notify_post(\"com.apple.printerHistoryChange\")");
1069 notify_post("com.apple.printerHistoryChange");
1072 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1073 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1074 CUPSD_EVENT_JOB_PROGRESS
))
1076 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1077 "notify_post(\"com.apple.jobChange\")");
1078 notify_post("com.apple.jobChange");
1080 #endif /* HAVE_NOTIFY_POST */
1083 * Reset the accumulated events...
1086 LastEvent
= CUPSD_EVENT_NONE
;
1087 event_time
= current_time
;
1092 * Log a message based on what happened...
1097 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1098 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1099 "Scheduler shutting down normally.");
1103 cupsdLogMessage(CUPSD_LOG_ERROR
,
1104 "Scheduler shutting down due to program error.");
1105 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1106 "Scheduler shutting down due to program error.");
1110 * Close all network clients...
1117 * Update the launchd KeepAlive file as needed...
1122 #endif /* HAVE_LAUNCHD */
1132 * Stop monitoring system event monitoring...
1136 cupsdStopSystemMonitor();
1137 #endif /* __APPLE__ */
1141 * Free the scheduler's Kerberos context...
1146 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1150 if (krb5_init_context
!= NULL
)
1151 # endif /* __APPLE__ */
1152 if (KerberosContext
)
1153 krb5_free_context(KerberosContext
);
1154 #endif /* HAVE_GSSAPI */
1158 * Remove the fake IRIX lpsched lock file, but only if the existing
1159 * file is not a FIFO which indicates that the real IRIX lpsched is
1163 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1164 if (!S_ISFIFO(statbuf
.st_mode
))
1165 unlink("/var/spool/lp/SCHEDLOCK");
1170 return (!stop_scheduler
);
1175 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1179 cupsdCheckProcess(void)
1182 * Flag that we have dead children...
1190 * 'cupsdClosePipe()' - Close a pipe as necessary.
1194 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1197 * Close file descriptors as needed...
1215 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1218 int /* O - 0 on success, -1 on error */
1219 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1222 * Create the pipe...
1234 * Set the "close on exec" flag on each end of the pipe...
1237 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1248 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1260 * Return 0 indicating success...
1268 * 'cupsdClearString()' - Clear a string.
1272 cupsdClearString(char **s
) /* O - String value */
1283 * 'cupsdHoldSignals()' - Hold child and termination signals.
1287 cupsdHoldSignals(void)
1289 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1290 sigset_t newmask
; /* New POSIX signal mask */
1291 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1301 #elif defined(HAVE_SIGACTION)
1302 sigemptyset(&newmask
);
1303 sigaddset(&newmask
, SIGTERM
);
1304 sigaddset(&newmask
, SIGCHLD
);
1305 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1306 #endif /* HAVE_SIGSET */
1311 * 'cupsdReleaseSignals()' - Release signals for delivery.
1315 cupsdReleaseSignals(void)
1324 #elif defined(HAVE_SIGACTION)
1325 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1326 #endif /* HAVE_SIGSET */
1331 * 'cupsdSetString()' - Set a string value.
1335 cupsdSetString(char **s
, /* O - New string */
1336 const char *v
) /* I - String value */
1345 *s
= _cupsStrAlloc(v
);
1352 * 'cupsdSetStringf()' - Set a formatted string value.
1356 cupsdSetStringf(char **s
, /* O - New string */
1357 const char *f
, /* I - Printf-style format string */
1358 ...) /* I - Additional args as needed */
1360 char v
[4096]; /* Formatting string value */
1361 va_list ap
; /* Argument pointer */
1362 char *olds
; /* Old string */
1373 vsnprintf(v
, sizeof(v
), f
, ap
);
1376 *s
= _cupsStrAlloc(v
);
1387 * 'cupsd_clean_files()' - Clean out old files.
1391 cupsd_clean_files(const char *path
, /* I - Directory to clean */
1392 const char *pattern
) /* I - Filename pattern or NULL */
1394 cups_dir_t
*dir
; /* Directory */
1395 cups_dentry_t
*dent
; /* Directory entry */
1396 char filename
[1024]; /* Filename */
1397 int status
; /* Status from unlink/rmdir */
1400 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1401 "cupsd_clean_files(path=\"%s\", pattern=\"%s\")", path
,
1402 pattern
? pattern
: "(null)");
1404 if ((dir
= cupsDirOpen(path
)) == NULL
)
1406 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open directory \"%s\" - %s",
1407 path
, strerror(errno
));
1411 cupsdLogMessage(CUPSD_LOG_INFO
, "Cleaning out old files in \"%s\"...", path
);
1413 while ((dent
= cupsDirRead(dir
)) != NULL
)
1415 if (pattern
&& fnmatch(pattern
, dent
->filename
, 0))
1418 snprintf(filename
, sizeof(filename
), "%s/%s", path
, dent
->filename
);
1420 if (S_ISDIR(dent
->fileinfo
.st_mode
))
1422 cupsd_clean_files(filename
, pattern
);
1424 status
= rmdir(filename
);
1427 status
= unlink(filename
);
1430 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to remove \"%s\" - %s", filename
,
1433 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed \"%s\"...", filename
);
1442 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1446 launchd_checkin(void)
1448 size_t i
, /* Looping var */
1449 count
; /* Number of listeners */
1451 int portnum
; /* Port number */
1452 # endif /* HAVE_SSL */
1453 launch_data_t ld_msg
, /* Launch data message */
1454 ld_resp
, /* Launch data response */
1455 ld_array
, /* Launch data array */
1456 ld_sockets
, /* Launch data sockets dictionary */
1457 tmp
; /* Launch data */
1458 cupsd_listener_t
*lis
; /* Listeners array */
1459 http_addr_t addr
; /* Address variable */
1460 socklen_t addrlen
; /* Length of address */
1461 int fd
; /* File descriptor */
1462 char s
[256]; /* String addresss */
1465 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1468 * Check-in with launchd...
1471 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1472 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1474 cupsdLogMessage(CUPSD_LOG_ERROR
,
1475 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1478 return; /* anti-compiler-warning */
1481 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1483 errno
= launch_data_get_errno(ld_resp
);
1484 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1487 return; /* anti-compiler-warning */
1491 * Get the sockets dictionary...
1494 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1497 cupsdLogMessage(CUPSD_LOG_ERROR
,
1498 "launchd_checkin: No sockets found to answer requests on!");
1500 return; /* anti-compiler-warning */
1504 * Get the array of listener sockets...
1507 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1509 cupsdLogMessage(CUPSD_LOG_ERROR
,
1510 "launchd_checkin: No sockets found to answer requests on!");
1512 return; /* anti-compiler-warning */
1516 * Add listening fd(s) to the Listener array...
1519 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1521 count
= launch_data_array_get_count(ld_array
);
1523 for (i
= 0; i
< count
; i
++)
1526 * Get the launchd file descriptor and address...
1529 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1531 fd
= launch_data_get_fd(tmp
);
1532 addrlen
= sizeof(addr
);
1534 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1536 cupsdLogMessage(CUPSD_LOG_ERROR
,
1537 "launchd_checkin: Unable to get local address - %s",
1543 * Try to match the launchd socket address to one of the listeners...
1546 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1548 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1549 if (httpAddrEqual(&lis
->address
, &addr
))
1553 * Add a new listener If there's no match...
1558 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1559 "launchd_checkin: Matched existing listener %s with fd %d...",
1560 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1564 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1565 "launchd_checkin: Adding new listener %s with fd %d...",
1566 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1568 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1570 cupsdLogMessage(CUPSD_LOG_ERROR
,
1571 "launchd_checkin: Unable to allocate listener - "
1572 "%s.", strerror(errno
));
1576 cupsArrayAdd(Listeners
, lis
);
1578 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1587 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1588 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1590 # endif /* AF_INET6 */
1591 if (lis
->address
.addr
.sa_family
== AF_INET
)
1592 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1595 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1596 # endif /* HAVE_SSL */
1601 launch_data_free(ld_msg
);
1602 launch_data_free(ld_resp
);
1607 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1611 launchd_checkout(void)
1613 int fd
; /* File descriptor */
1617 * Create or remove the launchd KeepAlive file based on whether
1618 * there are active jobs, polling, browsing for remote printers or
1619 * shared printers to advertise...
1622 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1624 (BrowseRemoteProtocols
||
1625 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1627 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1628 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1631 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1636 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1637 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1640 unlink(CUPS_KEEPALIVE
);
1643 #endif /* HAVE_LAUNCHD */
1647 * 'parent_handler()' - Catch USR1/CHLD signals...
1651 parent_handler(int sig
) /* I - Signal */
1654 * Store the signal we got from the OS and return...
1657 parent_signal
= sig
;
1662 * 'process_children()' - Process all dead children...
1666 process_children(void)
1668 int status
; /* Exit status of child */
1669 int pid
, /* Process ID of child */
1670 job_id
; /* Job ID of child */
1671 cupsd_job_t
*job
; /* Current job */
1672 int i
; /* Looping var */
1673 char name
[1024]; /* Process name */
1676 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1679 * Reset the dead_children flag...
1685 * Collect the exit status of some children...
1689 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1690 #elif defined(HAVE_WAIT3)
1691 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1693 if ((pid
= wait(&status
)) > 0)
1694 #endif /* HAVE_WAITPID */
1697 * Collect the name of the process that finished...
1700 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1703 * Delete certificates for CGI processes...
1707 cupsdDeleteCert(pid
);
1710 * Handle completed job filters...
1713 if (job_id
> 0 && (job
= cupsdFindJob(job_id
)) != NULL
)
1715 for (i
= 0; job
->filters
[i
]; i
++)
1716 if (job
->filters
[i
] == pid
)
1719 if (job
->filters
[i
] || job
->backend
== pid
)
1722 * OK, this process has gone away; what's left?
1725 if (job
->filters
[i
])
1726 job
->filters
[i
] = -pid
;
1728 job
->backend
= -pid
;
1730 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1731 status
!= SIGPIPE
&& job
->status
>= 0)
1734 * An error occurred; save the exit status so we know to stop
1735 * the printer or cancel the job when all of the filters finish...
1737 * A negative status indicates that the backend failed and the
1738 * printer needs to be stopped.
1741 if (job
->filters
[i
])
1742 job
->status
= status
; /* Filter failed */
1744 job
->status
= -status
; /* Backend failed */
1746 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1747 job
->status_level
> CUPSD_LOG_ERROR
)
1749 char message
[1024]; /* New printer-state-message */
1752 job
->status_level
= CUPSD_LOG_ERROR
;
1754 snprintf(message
, sizeof(message
), "%s failed", name
);
1758 strlcpy(job
->printer
->state_message
, message
,
1759 sizeof(job
->printer
->state_message
));
1760 cupsdAddPrinterHistory(job
->printer
);
1766 if (!job
->printer_message
&& job
->attrs
)
1768 if ((job
->printer_message
=
1769 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1770 IPP_TAG_TEXT
)) == NULL
)
1771 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1773 "job-printer-state-message",
1777 if (job
->printer_message
)
1778 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1784 * If this is not the last file in a job, see if all of the
1785 * filters are done, and if so move to the next file.
1788 if (job
->current_file
< job
->num_files
&& job
->printer
)
1790 for (i
= 0; job
->filters
[i
] < 0; i
++);
1792 if (!job
->filters
[i
])
1795 * Process the next file...
1798 cupsdContinueJob(job
);
1801 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1804 * Remove the job from the active list if there are no processes still
1808 for (i
= 0; job
->filters
[i
] < 0; i
++);
1810 if (!job
->filters
[i
] && job
->backend
<= 0)
1811 cupsArrayRemove(ActiveJobs
, job
);
1817 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1818 * since they come when we kill/end a process...
1821 if (status
== SIGTERM
|| status
== SIGKILL
)
1823 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1824 "PID %d (%s) was terminated normally with signal %d.",
1827 else if (status
== SIGPIPE
)
1829 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1830 "PID %d (%s) did not catch or ignore signal %d.",
1835 if (WIFEXITED(status
))
1836 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) stopped with status %d!",
1837 pid
, name
, WEXITSTATUS(status
));
1839 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1840 pid
, name
, WTERMSIG(status
));
1842 if (LogLevel
< CUPSD_LOG_DEBUG
)
1843 cupsdLogMessage(CUPSD_LOG_INFO
,
1844 "Hint: Try setting the LogLevel to \"debug\" to find "
1848 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1853 * If wait*() is interrupted by a signal, tell main() to call us again...
1856 if (pid
< 0 && errno
== EINTR
)
1862 * 'select_timeout()' - Calculate the select timeout value.
1866 static long /* O - Number of seconds */
1867 select_timeout(int fds
) /* I - Number of descriptors returned */
1869 long timeout
; /* Timeout for select */
1870 time_t now
; /* Current time */
1871 cupsd_client_t
*con
; /* Client information */
1872 cupsd_printer_t
*p
; /* Printer information */
1873 cupsd_job_t
*job
; /* Job information */
1874 cupsd_subscription_t
*sub
; /* Subscription information */
1875 const char *why
; /* Debugging aid */
1879 * Check to see if any of the clients have pending data to be
1880 * processed; if so, the timeout should be 0...
1883 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1885 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1886 if (con
->http
.used
> 0)
1890 * If select has been active in the last second (fds > 0) or we have
1891 * many resources in use then don't bother trying to optimize the
1892 * timeout, just make it 1 second.
1895 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1899 * Otherwise, check all of the possible events that we need to wake for...
1903 timeout
= now
+ 86400; /* 86400 == 1 day */
1908 * When going to sleep, wake up to cancel jobs that don't complete in time.
1911 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1913 timeout
= SleepJobs
;
1914 why
= "cancel jobs before sleeping";
1916 #endif /* __APPLE__ */
1919 * Check whether we are accepting new connections...
1922 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1923 ListeningPaused
< timeout
)
1925 if (ListeningPaused
<= now
)
1928 timeout
= ListeningPaused
;
1930 why
= "resume listening";
1934 * Check the activity and close old clients...
1937 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1939 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1940 if ((con
->http
.activity
+ Timeout
) < timeout
)
1942 timeout
= con
->http
.activity
+ Timeout
;
1943 why
= "timeout a client connection";
1947 * Update the browse list as needed...
1950 if (Browsing
&& BrowseLocalProtocols
)
1953 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1955 timeout
= BrowseSLPRefresh
;
1956 why
= "update SLP browsing";
1958 #endif /* HAVE_LIBSLP */
1961 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1963 timeout
= BrowseLDAPRefresh
;
1964 why
= "update LDAP browsing";
1966 #endif /* HAVE_LDAP */
1968 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1970 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1972 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1974 if (p
->type
& CUPS_PRINTER_REMOTE
)
1976 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1978 timeout
= p
->browse_time
+ BrowseTimeout
;
1979 why
= "browse timeout a printer";
1982 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1984 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1986 timeout
= p
->browse_time
+ BrowseInterval
;
1987 why
= "send browse update";
1995 * Write out changes to configuration and state files...
1998 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
2000 timeout
= DirtyCleanTime
;
2001 why
= "write dirty config/state files";
2005 * Check for any active jobs...
2008 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
2010 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2012 if (job
->kill_time
&& job
->kill_time
< timeout
)
2014 timeout
= job
->kill_time
;
2015 why
= "kill unresponsive jobs";
2018 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
2020 timeout
= job
->hold_until
;
2021 why
= "release held jobs";
2023 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
2026 why
= "start pending jobs";
2031 #ifdef HAVE_MALLINFO
2033 * Log memory usage every minute...
2036 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2038 timeout
= mallinfo_time
+ 60;
2039 why
= "display memory usage";
2041 #endif /* HAVE_MALLINFO */
2044 * Expire subscriptions as needed...
2047 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2049 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2050 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2052 timeout
= sub
->expire
;
2053 why
= "expire subscription";
2057 * Adjust from absolute to relative time. If p->browse_time above
2058 * was 0 then we can end up with a negative value here, so check.
2059 * We add 1 second to the timeout since events occur after the
2060 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2061 * to avoid select() timeout limits present on some operating
2065 timeout
= timeout
- now
+ 1;
2069 else if (timeout
> 86400)
2073 * Log and return the timeout value...
2076 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
2084 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2088 sigchld_handler(int sig
) /* I - Signal number */
2093 * Flag that we have dead children...
2099 * Reset the signal handler as needed...
2102 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2103 signal(SIGCLD
, sigchld_handler
);
2104 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2109 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2113 sighup_handler(int sig
) /* I - Signal number */
2117 NeedReload
= RELOAD_ALL
;
2118 ReloadTime
= time(NULL
);
2120 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2121 signal(SIGHUP
, sighup_handler
);
2122 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2127 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2131 sigterm_handler(int sig
) /* I - Signal number */
2133 (void)sig
; /* remove compiler warnings... */
2136 * Flag that we should stop and return...
2144 * 'usage()' - Show scheduler usage.
2148 usage(int status
) /* O - Exit status */
2150 _cupsLangPuts(status
? stderr
: stdout
,
2151 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
2153 "-c config-file Load alternate configuration file\n"
2154 "-f Run in the foreground\n"
2155 "-F Run in the foreground but detach\n"
2156 "-h Show this usage message\n"
2157 "-l Run cupsd from launchd(8)\n"));
2163 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".