2 * "$Id: main.c 6493 2007-04-30 19:33:31Z mike $"
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636 USA
20 * Voice: (301) 373-9600
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
26 * main() - Main entry for the CUPS scheduler.
27 * cupsdClosePipe() - Close a pipe as necessary.
28 * cupsdOpenPipe() - Create a pipe which is closed on exec.
29 * cupsdHoldSignals() - Hold child and termination signals.
30 * cupsdReleaseSignals() - Release signals for delivery.
31 * cupsdSetString() - Set a string value.
32 * cupsdSetStringf() - Set a formatted string value.
33 * launchd_checkin() - Check-in with launchd and collect the
35 * launchd_checkout() - Check-out with launchd.
36 * parent_handler() - Catch USR1/CHLD signals...
37 * process_children() - Process all dead children...
38 * sigchld_handler() - Handle 'child' signals from old processes.
39 * sighup_handler() - Handle 'hangup' signals to reconfigure the
41 * sigterm_handler() - Handle 'terminate' signals that stop the
43 * select_timeout() - Calculate the select timeout value.
44 * usage() - Show scheduler usage.
48 * Include necessary headers...
53 #include <sys/resource.h>
60 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
61 /* Name of the launchd KeepAlive file */
62 # ifndef LAUNCH_JOBKEY_KEEPALIVE
63 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
64 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
65 # ifndef LAUNCH_JOBKEY_PATHSTATE
66 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
67 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
68 # ifndef LAUNCH_JOBKEY_SERVICEIPC
69 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
70 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
71 #endif /* HAVE_LAUNCH_H */
73 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
75 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
78 #endif /* HAVE_NOTIFY_H */
80 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
82 #endif /* __APPLE__ && HAVE_DLFCN_H */
90 static void launchd_checkin(void);
91 static void launchd_checkout(void);
92 #endif /* HAVE_LAUNCHD */
93 static void parent_handler(int sig
);
94 static void process_children(void);
95 static void sigchld_handler(int sig
);
96 static void sighup_handler(int sig
);
97 static void sigterm_handler(int sig
);
98 static long select_timeout(int fds
);
99 static void usage(int status
);
106 static int parent_signal
= 0;
107 /* Set to signal number from child */
108 static int holdcount
= 0; /* Number of times "hold" was called */
109 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
110 static sigset_t holdmask
; /* Old POSIX signal mask */
111 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
112 static int dead_children
= 0;
114 static int stop_scheduler
= 0;
115 /* Should the scheduler stop? */
117 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
118 static const char *PSQLibPath
= "/usr/lib/libPrintServiceQuota.dylib";
119 static const char *PSQLibFuncName
= "PSQUpdateQuota";
120 static void *PSQLibRef
; /* libPrintServiceQuota.dylib */
121 #endif /* HAVE_DLFCN_H */
125 * 'main()' - Main entry for the CUPS scheduler.
128 int /* O - Exit status */
129 main(int argc
, /* I - Number of command-line args */
130 char *argv
[]) /* I - Command-line arguments */
132 int i
; /* Looping var */
133 char *opt
; /* Option character */
134 int fg
; /* Run in the foreground */
135 int fds
; /* Number of ready descriptors */
136 cupsd_client_t
*con
; /* Current client */
137 cupsd_job_t
*job
; /* Current job */
138 cupsd_listener_t
*lis
; /* Current listener */
139 time_t current_time
, /* Current time */
140 activity
, /* Client activity timer */
141 browse_time
, /* Next browse send time */
142 senddoc_time
, /* Send-Document time */
143 expire_time
, /* Subscription expire time */
144 mallinfo_time
; /* Malloc information time */
145 size_t string_count
, /* String count */
146 alloc_bytes
, /* Allocated string bytes */
147 total_bytes
; /* Total string bytes */
148 long timeout
; /* Timeout for cupsdDoSelect() */
149 struct rlimit limit
; /* Runtime limit */
150 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
151 struct sigaction action
; /* Actions for POSIX signals */
152 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
154 cups_file_t
*fp
; /* Fake lpsched lock file */
155 struct stat statbuf
; /* Needed for checking lpsched FIFO */
158 int launchd_idle_exit
;
159 /* Idle exit on select timeout? */
160 #endif /* HAVE_LAUNCHD */
164 * Check for command-line arguments...
169 for (i
= 1; i
< argc
; i
++)
170 if (argv
[i
][0] == '-')
171 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
174 case 'c' : /* Configuration file */
178 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
179 "after \"-c\" option!\n"));
183 if (argv
[i
][0] == '/')
186 * Absolute directory...
189 cupsdSetString(&ConfigurationFile
, argv
[i
]);
194 * Relative directory...
197 char *current
; /* Current directory */
201 * Allocate a buffer for the current working directory to
202 * reduce run-time stack usage; this approximates the
203 * behavior of some implementations of getcwd() when they
204 * are passed a NULL pointer.
207 current
= malloc(1024);
208 getcwd(current
, 1024);
210 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
216 case 'f' : /* Run in foreground... */
220 case 'F' : /* Run in foreground, but disconnect from terminal... */
224 case 'h' : /* Show usage/help */
228 case 'l' : /* Started by launchd... */
233 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
234 "in, running in normal mode.\n"));
236 #endif /* HAVE_LAUNCHD */
239 case 'p' : /* Stop immediately for profiling */
240 puts("Warning: -p option is for internal testing use only!");
245 default : /* Unknown option */
246 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
247 "aborting!\n"), *opt
);
253 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
258 if (!ConfigurationFile
)
259 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
262 * If the user hasn't specified "-f", run in the background...
268 * Setup signal handlers for the parent...
271 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
272 sigset(SIGUSR1
, parent_handler
);
273 sigset(SIGCHLD
, parent_handler
);
275 sigset(SIGHUP
, SIG_IGN
);
276 #elif defined(HAVE_SIGACTION)
277 memset(&action
, 0, sizeof(action
));
278 sigemptyset(&action
.sa_mask
);
279 sigaddset(&action
.sa_mask
, SIGUSR1
);
280 action
.sa_handler
= parent_handler
;
281 sigaction(SIGUSR1
, &action
, NULL
);
282 sigaction(SIGCHLD
, &action
, NULL
);
284 sigemptyset(&action
.sa_mask
);
285 action
.sa_handler
= SIG_IGN
;
286 sigaction(SIGHUP
, &action
, NULL
);
288 signal(SIGUSR1
, parent_handler
);
289 signal(SIGCLD
, parent_handler
);
291 signal(SIGHUP
, SIG_IGN
);
292 #endif /* HAVE_SIGSET */
297 * OK, wait for the child to startup and send us SIGUSR1 or to crash
298 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
299 * might be sent by the init script to restart the scheduler...
302 for (; parent_signal
== 0;)
305 if (parent_signal
== SIGUSR1
)
313 else if (WIFEXITED(i
))
315 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
321 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
330 * Make sure we aren't tying up any filesystems...
337 * Disable core dumps...
340 getrlimit(RLIMIT_CORE
, &limit
);
342 setrlimit(RLIMIT_CORE
, &limit
);
345 * Disconnect from the controlling terminal...
351 * Close all open files...
354 getrlimit(RLIMIT_NOFILE
, &limit
);
356 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
362 * Set the timezone info...
368 setlocale(LC_TIME
, "");
372 * Set the maximum number of files...
375 getrlimit(RLIMIT_NOFILE
, &limit
);
377 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
378 if (limit
.rlim_max
> FD_SETSIZE
)
381 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
383 if (limit
.rlim_max
== RLIM_INFINITY
)
386 #endif /* RLIM_INFINITY */
387 MaxFDs
= limit
.rlim_max
;
389 limit
.rlim_cur
= MaxFDs
;
391 setrlimit(RLIMIT_NOFILE
, &limit
);
396 * Read configuration...
399 if (!cupsdReadConfiguration())
401 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
410 * If we were started by launchd get the listen sockets file descriptors...
415 #endif /* HAVE_LAUNCHD */
417 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
419 * Load Print Service quota enforcement library (X Server only)
422 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
425 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
426 #endif /* __APPLE__ && HAVE_DLFCN_H */
429 * Startup the server...
435 * Catch hangup and child signals and ignore broken pipes...
438 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
439 sigset(SIGCHLD
, sigchld_handler
);
440 sigset(SIGHUP
, sighup_handler
);
441 sigset(SIGPIPE
, SIG_IGN
);
442 sigset(SIGTERM
, sigterm_handler
);
443 #elif defined(HAVE_SIGACTION)
444 memset(&action
, 0, sizeof(action
));
446 sigemptyset(&action
.sa_mask
);
447 sigaddset(&action
.sa_mask
, SIGTERM
);
448 sigaddset(&action
.sa_mask
, SIGCHLD
);
449 action
.sa_handler
= sigchld_handler
;
450 sigaction(SIGCHLD
, &action
, NULL
);
452 sigemptyset(&action
.sa_mask
);
453 sigaddset(&action
.sa_mask
, SIGHUP
);
454 action
.sa_handler
= sighup_handler
;
455 sigaction(SIGHUP
, &action
, NULL
);
457 sigemptyset(&action
.sa_mask
);
458 action
.sa_handler
= SIG_IGN
;
459 sigaction(SIGPIPE
, &action
, NULL
);
461 sigemptyset(&action
.sa_mask
);
462 sigaddset(&action
.sa_mask
, SIGTERM
);
463 sigaddset(&action
.sa_mask
, SIGCHLD
);
464 action
.sa_handler
= sigterm_handler
;
465 sigaction(SIGTERM
, &action
, NULL
);
467 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
468 signal(SIGHUP
, sighup_handler
);
469 signal(SIGPIPE
, SIG_IGN
);
470 signal(SIGTERM
, sigterm_handler
);
471 #endif /* HAVE_SIGSET */
475 * Try to create a fake lpsched lock file if one is not already there.
476 * Some Adobe applications need it under IRIX in order to enable
480 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
482 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
483 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
488 fchmod(cupsFileNumber(fp
), 0644);
489 fchown(cupsFileNumber(fp
), User
, Group
);
496 * Initialize authentication certificates...
502 * If we are running in the background, signal the parent process that
503 * we are up and running...
509 * Send a signal to the parent process, but only if the parent is
510 * not PID 1 (init). This avoids accidentally shutting down the
511 * system on OpenBSD if you CTRL-C the server before it is up...
514 i
= getppid(); /* Save parent PID to avoid race condition */
522 * Start power management framework...
525 cupsdStartSystemMonitor();
526 #endif /* __APPLE__ */
529 * Start any pending print jobs...
539 browse_time
= time(NULL
);
540 senddoc_time
= time(NULL
);
541 expire_time
= time(NULL
);
544 while (!stop_scheduler
)
547 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
548 "main: Top of loop, dead_children=%d, NeedReload=%d",
549 dead_children
, NeedReload
);
553 * Check if there are dead children to handle...
560 * Check if we need to load the server configuration file...
566 * Close any idle clients...
569 if (cupsArrayCount(Clients
) > 0)
571 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
573 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
574 if (con
->http
.state
== HTTP_WAITING
)
575 cupsdCloseClient(con
);
577 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
579 cupsdPauseListening();
583 * Check for any active jobs...
586 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
588 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
589 if (job
->state_value
== IPP_JOB_PROCESSING
)
593 * Restart if all clients are closed and all jobs finished, or
594 * if the reload timeout has elapsed...
597 if ((cupsArrayCount(Clients
) == 0 &&
598 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
599 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
602 * Shutdown the server...
608 * Read configuration...
611 if (!cupsdReadConfiguration())
613 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
622 * If we were started by launchd get the listen sockets file descriptors...
627 #endif /* HAVE_LAUNCHD */
630 * Startup the server...
638 * Check for available input or ready output. If cupsdDoSelect()
639 * returns 0 or -1, something bad happened and we should exit
642 * Note that we at least have one listening socket open at all
646 timeout
= select_timeout(fds
);
650 * If no other work is scheduled and we're being controlled by
651 * launchd then timeout after 'LaunchdTimeout' seconds of
655 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
657 (!BrowseRemoteProtocols
&&
658 (!NumBrowsers
|| !BrowseLocalProtocols
||
659 cupsArrayCount(Printers
) == 0))))
661 timeout
= LaunchdTimeout
;
662 launchd_idle_exit
= 1;
665 launchd_idle_exit
= 0;
666 #endif /* HAVE_LAUNCHD */
668 if ((fds
= cupsdDoSelect(timeout
)) < 0)
671 * Got an error from select!
675 cupsd_printer_t
*p
; /* Current printer */
676 #endif /* HAVE_DNSSD */
679 if (errno
== EINTR
) /* Just interrupted by a signal */
683 * Log all sorts of debug info to help track down the problem.
686 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
689 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
691 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
692 cupsdLogMessage(CUPSD_LOG_EMERG
,
693 "Clients[%d] = %d, file = %d, state = %d",
694 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
696 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
698 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
699 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
701 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
703 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
706 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
708 #endif /* __APPLE__ */
710 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
712 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
713 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
715 job
->status_buffer
? job
->status_buffer
->fd
: -1,
716 job
->print_pipes
[0], job
->print_pipes
[1],
717 job
->back_pipes
[0], job
->back_pipes
[1]);
720 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
722 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
723 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] %d", p
->name
,
725 #endif /* HAVE_DNSSD */
730 current_time
= time(NULL
);
734 * If no other work was scheduled and we're being controlled by launchd
735 * then timeout after 'LaunchdTimeout' seconds of inactivity...
738 if (!fds
&& launchd_idle_exit
)
740 cupsdLogMessage(CUPSD_LOG_INFO
,
741 "Printer sharing is off and there are no jobs pending, "
742 "will restart on demand.");
746 #endif /* HAVE_LAUNCHD */
749 * Expire subscriptions and unload completed jobs as needed...
752 if (current_time
> expire_time
)
754 if (cupsArrayCount(Subscriptions
) > 0)
755 cupsdExpireSubscriptions(NULL
, NULL
);
757 cupsdUnloadCompletedJobs();
759 expire_time
= current_time
;
763 * Update the browse list as needed...
769 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
770 BrowseSLPRefresh
<= current_time
)
771 cupsdUpdateSLPBrowse();
772 #endif /* HAVE_LIBSLP */
775 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
776 BrowseLDAPRefresh
<= current_time
)
777 cupsdUpdateLDAPBrowse();
778 #endif /* HAVE_LDAP */
781 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
783 cupsdSendBrowseList();
784 browse_time
= current_time
;
788 * Update the root certificate once every 5 minutes if we have client
792 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
793 !RunUser
&& cupsArrayCount(Clients
))
796 * Update the root certificate...
800 cupsdAddCert(0, "root");
804 * Check for new data on the client sockets...
807 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
809 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
812 * Process pending data in the input buffer...
817 cupsdReadClient(con
);
822 * Check the activity and close old clients...
825 activity
= current_time
- Timeout
;
826 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
828 cupsdLogMessage(CUPSD_LOG_DEBUG
,
829 "Closing client %d after %d seconds of inactivity...",
830 con
->http
.fd
, Timeout
);
832 cupsdCloseClient(con
);
838 * Update any pending multi-file documents...
841 if ((current_time
- senddoc_time
) >= 10)
844 senddoc_time
= current_time
;
848 * Log memory usage every minute...
851 if ((current_time
- mallinfo_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG2
)
854 struct mallinfo mem
; /* Malloc information */
858 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
859 "mallinfo: arena = %d, used = %d, free = %d\n",
860 mem
.arena
, mem
.usmblks
+ mem
.uordblks
,
861 mem
.fsmblks
+ mem
.fordblks
);
862 #endif /* HAVE_MALLINFO */
864 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
865 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
866 "stringpool: " CUPS_LLFMT
" strings, "
867 CUPS_LLFMT
" allocated, " CUPS_LLFMT
" total bytes",
868 CUPS_LLCAST string_count
, CUPS_LLCAST alloc_bytes
,
869 CUPS_LLCAST total_bytes
);
871 mallinfo_time
= current_time
;
875 * Handle OS-specific event notification for any events that have
876 * accumulated. Don't send these more than once a second...
881 #ifdef HAVE_NOTIFY_POST
882 if (LastEvent
& CUPSD_EVENT_PRINTER_CHANGED
)
884 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
885 "notify_post(\"com.apple.printerListChange\")");
886 notify_post("com.apple.printerListChange");
889 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
891 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
892 "notify_post(\"com.apple.printerHistoryChange\")");
893 notify_post("com.apple.printerHistoryChange");
896 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
897 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
898 CUPSD_EVENT_JOB_PROGRESS
))
900 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
901 "notify_post(\"com.apple.jobChange\")");
902 notify_post("com.apple.jobChange");
904 #endif /* HAVE_NOTIFY_POST */
907 * Reset the accumulated events...
910 LastEvent
= CUPSD_EVENT_NONE
;
915 * Log a message based on what happened...
919 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
921 cupsdLogMessage(CUPSD_LOG_ERROR
,
922 "Scheduler shutting down due to program error.");
925 * Close all network clients and stop all jobs...
933 cupsdStopSystemMonitor();
934 #endif /* __APPLE__ */
938 * Update the launchd KeepAlive file as needed...
943 #endif /* HAVE_LAUNCHD */
948 * Unload Print Service quota enforcement library (X Server only)
951 PSQUpdateQuotaProc
= NULL
;
957 #endif /* HAVE_DLFCN_H */
958 #endif /* __APPLE__ */
962 * Remove the fake IRIX lpsched lock file, but only if the existing
963 * file is not a FIFO which indicates that the real IRIX lpsched is
967 if (!stat("/var/spool/lp/FIFO", &statbuf
))
968 if (!S_ISFIFO(statbuf
.st_mode
))
969 unlink("/var/spool/lp/SCHEDLOCK");
974 return (!stop_scheduler
);
979 * 'cupsdClosePipe()' - Close a pipe as necessary.
983 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
986 * Close file descriptors as needed...
1004 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1007 int /* O - 0 on success, -1 on error */
1008 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1011 * Create the pipe...
1023 * Set the "close on exec" flag on each end of the pipe...
1026 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1037 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1049 * Return 0 indicating success...
1057 * 'cupsdClearString()' - Clear a string.
1061 cupsdClearString(char **s
) /* O - String value */
1072 * 'cupsdHoldSignals()' - Hold child and termination signals.
1076 cupsdHoldSignals(void)
1078 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1079 sigset_t newmask
; /* New POSIX signal mask */
1080 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1090 #elif defined(HAVE_SIGACTION)
1091 sigemptyset(&newmask
);
1092 sigaddset(&newmask
, SIGTERM
);
1093 sigaddset(&newmask
, SIGCHLD
);
1094 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1095 #endif /* HAVE_SIGSET */
1100 * 'cupsdReleaseSignals()' - Release signals for delivery.
1104 cupsdReleaseSignals(void)
1113 #elif defined(HAVE_SIGACTION)
1114 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1115 #endif /* HAVE_SIGSET */
1120 * 'cupsdSetString()' - Set a string value.
1124 cupsdSetString(char **s
, /* O - New string */
1125 const char *v
) /* I - String value */
1134 *s
= _cupsStrAlloc(v
);
1141 * 'cupsdSetStringf()' - Set a formatted string value.
1145 cupsdSetStringf(char **s
, /* O - New string */
1146 const char *f
, /* I - Printf-style format string */
1147 ...) /* I - Additional args as needed */
1149 char v
[4096]; /* Formatting string value */
1150 va_list ap
; /* Argument pointer */
1151 char *olds
; /* Old string */
1162 vsnprintf(v
, sizeof(v
), f
, ap
);
1165 *s
= _cupsStrAlloc(v
);
1177 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1181 launchd_checkin(void)
1183 int i
, /* Looping var */
1184 count
, /* Numebr of listeners */
1185 portnum
; /* Port number */
1186 launch_data_t ld_msg
, /* Launch data message */
1187 ld_resp
, /* Launch data response */
1188 ld_array
, /* Launch data array */
1189 ld_sockets
, /* Launch data sockets dictionary */
1190 tmp
; /* Launch data */
1191 cupsd_listener_t
*lis
; /* Listeners array */
1192 http_addr_t addr
; /* Address variable */
1193 socklen_t addrlen
; /* Length of address */
1194 int fd
; /* File descriptor */
1195 char s
[256]; /* String addresss */
1198 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1201 * Check-in with launchd...
1204 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1205 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1207 cupsdLogMessage(CUPSD_LOG_ERROR
,
1208 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1213 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1215 errno
= launch_data_get_errno(ld_resp
);
1216 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1222 * Get the sockets dictionary...
1225 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1227 cupsdLogMessage(CUPSD_LOG_ERROR
,
1228 "launchd_checkin: No sockets found to answer requests on!");
1233 * Get the array of listener sockets...
1236 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1238 cupsdLogMessage(CUPSD_LOG_ERROR
,
1239 "launchd_checkin: No sockets found to answer requests on!");
1244 * Add listening fd(s) to the Listener array...
1247 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1249 count
= launch_data_array_get_count(ld_array
);
1251 for (i
= 0; i
< count
; i
++)
1254 * Get the launchd file descriptor and address...
1257 tmp
= launch_data_array_get_index(ld_array
, i
);
1258 fd
= launch_data_get_fd(tmp
);
1259 addrlen
= sizeof(addr
);
1261 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1263 cupsdLogMessage(CUPSD_LOG_ERROR
,
1264 "launchd_checkin: Unable to get local address - %s",
1270 * Try to match the launchd socket address to one of the listeners...
1273 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1275 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1276 if (httpAddrEqual(&lis
->address
, &addr
))
1280 * Add a new listener If there's no match...
1285 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1286 "launchd_checkin: Matched existing listener %s with fd %d...",
1287 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1291 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1292 "launchd_checkin: Adding new listener %s with fd %d...",
1293 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1295 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1297 cupsdLogMessage(CUPSD_LOG_ERROR
,
1298 "launchd_checkin: Unable to allocate listener - %s.",
1303 cupsArrayAdd(Listeners
, lis
);
1305 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1314 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1315 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1317 # endif /* AF_INET6 */
1318 if (lis
->address
.addr
.sa_family
== AF_INET
)
1319 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1322 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1323 # endif /* HAVE_SSL */
1327 launch_data_free(ld_msg
);
1328 launch_data_free(ld_resp
);
1333 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1337 launchd_checkout(void)
1339 int fd
; /* File descriptor */
1343 * Create or remove the launchd KeepAlive file based on whether
1344 * there are active jobs, polling, browsing for remote printers or
1345 * shared printers to advertise...
1348 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1350 (BrowseRemoteProtocols
||
1351 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1353 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1354 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1356 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1361 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1362 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1364 unlink(CUPS_KEEPALIVE
);
1368 #endif /* HAVE_LAUNCHD */
1372 * 'parent_handler()' - Catch USR1/CHLD signals...
1376 parent_handler(int sig
) /* I - Signal */
1379 * Store the signal we got from the OS and return...
1382 parent_signal
= sig
;
1387 * 'process_children()' - Process all dead children...
1391 process_children(void)
1393 int status
; /* Exit status of child */
1394 int pid
; /* Process ID of child */
1395 cupsd_job_t
*job
; /* Current job */
1396 int i
; /* Looping var */
1397 char name
[1024]; /* Process name */
1400 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1403 * Reset the dead_children flag...
1409 * Collect the exit status of some children...
1413 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1414 #elif defined(HAVE_WAIT3)
1415 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1417 if ((pid
= wait(&status
)) > 0)
1418 #endif /* HAVE_WAITPID */
1421 * Ignore SIGTERM errors - that comes when a job is canceled...
1424 cupsdFinishProcess(pid
, name
, sizeof(name
));
1426 if (status
== SIGTERM
)
1431 if (WIFEXITED(status
))
1432 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1433 pid
, name
, WEXITSTATUS(status
));
1435 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1436 pid
, name
, WTERMSIG(status
));
1438 if (LogLevel
< CUPSD_LOG_DEBUG
)
1439 cupsdLogMessage(CUPSD_LOG_INFO
,
1440 "Hint: Try setting the LogLevel to \"debug\" to find "
1444 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1448 * Delete certificates for CGI processes...
1452 cupsdDeleteCert(pid
);
1455 * Lookup the PID in the jobs list...
1458 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1460 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1461 if (job
->state_value
== IPP_JOB_PROCESSING
)
1463 for (i
= 0; job
->filters
[i
]; i
++)
1464 if (job
->filters
[i
] == pid
)
1467 if (job
->filters
[i
] || job
->backend
== pid
)
1470 * OK, this process has gone away; what's left?
1473 if (job
->filters
[i
])
1474 job
->filters
[i
] = -pid
;
1476 job
->backend
= -pid
;
1478 if (status
&& job
->status
>= 0)
1481 * An error occurred; save the exit status so we know to stop
1482 * the printer or cancel the job when all of the filters finish...
1484 * A negative status indicates that the backend failed and the
1485 * printer needs to be stopped.
1488 if (job
->filters
[i
])
1489 job
->status
= status
; /* Filter failed */
1491 job
->status
= -status
; /* Backend failed */
1493 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
))
1495 snprintf(job
->printer
->state_message
,
1496 sizeof(job
->printer
->state_message
), "%s failed", name
);
1497 cupsdAddPrinterHistory(job
->printer
);
1502 * If this is not the last file in a job, see if all of the
1503 * filters are done, and if so move to the next file.
1506 if (job
->current_file
< job
->num_files
)
1508 for (i
= 0; job
->filters
[i
] < 0; i
++);
1510 if (!job
->filters
[i
])
1513 * Process the next file...
1516 cupsdFinishJob(job
);
1527 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1531 sigchld_handler(int sig
) /* I - Signal number */
1536 * Flag that we have dead children...
1542 * Reset the signal handler as needed...
1545 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1546 signal(SIGCLD
, sigchld_handler
);
1547 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1552 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1556 sighup_handler(int sig
) /* I - Signal number */
1560 NeedReload
= RELOAD_ALL
;
1561 ReloadTime
= time(NULL
);
1563 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1564 signal(SIGHUP
, sighup_handler
);
1565 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1570 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1574 sigterm_handler(int sig
) /* I - Signal */
1576 (void)sig
; /* remove compiler warnings... */
1579 * Flag that we should stop and return...
1587 * 'select_timeout()' - Calculate the select timeout value.
1591 static long /* O - Number of seconds */
1592 select_timeout(int fds
) /* I - Number of descriptors returned */
1594 long timeout
; /* Timeout for select */
1595 time_t now
; /* Current time */
1596 cupsd_client_t
*con
; /* Client information */
1597 cupsd_printer_t
*p
; /* Printer information */
1598 cupsd_job_t
*job
; /* Job information */
1599 cupsd_subscription_t
*sub
; /* Subscription information */
1600 const char *why
; /* Debugging aid */
1604 * Check to see if any of the clients have pending data to be
1605 * processed; if so, the timeout should be 0...
1608 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1610 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1611 if (con
->http
.used
> 0)
1615 * If select has been active in the last second (fds > 0) or we have
1616 * many resources in use then don't bother trying to optimize the
1617 * timeout, just make it 1 second.
1620 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1624 * Otherwise, check all of the possible events that we need to wake for...
1628 timeout
= now
+ 86400; /* 86400 == 1 day */
1632 * Check the activity and close old clients...
1635 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1637 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1638 if ((con
->http
.activity
+ Timeout
) < timeout
)
1640 timeout
= con
->http
.activity
+ Timeout
;
1641 why
= "timeout a client connection";
1645 * Update the browse list as needed...
1648 if (Browsing
&& BrowseLocalProtocols
)
1651 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1653 timeout
= BrowseSLPRefresh
;
1654 why
= "update SLP browsing";
1656 #endif /* HAVE_LIBSLP */
1659 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1661 timeout
= BrowseLDAPRefresh
;
1662 why
= "update LDAP browsing";
1664 #endif /* HAVE_LDAP */
1666 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1668 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1670 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1672 if (p
->type
& CUPS_PRINTER_REMOTE
)
1674 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1676 timeout
= p
->browse_time
+ BrowseTimeout
;
1677 why
= "browse timeout a printer";
1680 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1682 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1684 timeout
= p
->browse_time
+ BrowseInterval
;
1685 why
= "send browse update";
1693 * Check for any active jobs...
1696 if (timeout
> (now
+ 10) && ActiveJobs
)
1698 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1700 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1701 if (job
->state_value
<= IPP_JOB_PROCESSING
)
1704 why
= "process active jobs";
1709 #ifdef HAVE_MALLINFO
1711 * Log memory usage every minute...
1714 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1716 timeout
= mallinfo_time
+ 60;
1717 why
= "display memory usage";
1719 #endif /* HAVE_MALLINFO */
1722 * Expire subscriptions as needed...
1725 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1727 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1728 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1730 timeout
= sub
->expire
;
1731 why
= "expire subscription";
1735 * Adjust from absolute to relative time. If p->browse_time above
1736 * was 0 then we can end up with a negative value here, so check.
1737 * We add 1 second to the timeout since events occur after the
1738 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1739 * to avoid select() timeout limits present on some operating
1743 timeout
= timeout
- now
+ 1;
1747 else if (timeout
> 86400)
1751 * Log and return the timeout value...
1754 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1762 * 'usage()' - Show scheduler usage.
1766 usage(int status
) /* O - Exit status */
1768 _cupsLangPuts(status
? stderr
: stdout
,
1769 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1771 "-c config-file Load alternate configuration file\n"
1772 "-f Run in the foreground\n"
1773 "-F Run in the foreground but detach\n"
1774 "-h Show this usage message\n"
1775 "-l Run cupsd from launchd(8)\n"));
1781 * End of "$Id: main.c 6493 2007-04-30 19:33:31Z mike $".