2 * "$Id: main.c 5634 2006-06-06 17:48:27Z mike $"
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
6 * Copyright 1997-2006 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_reload() - Tell launchd to reload the configuration
36 * file to pick up the new listening directives.
37 * launchd_sync_conf() - Re-write the launchd(8) config file
38 * org.cups.cupsd.plist based on cupsd.conf.
39 * parent_handler() - Catch USR1/CHLD signals...
40 * process_children() - Process all dead children...
41 * sigchld_handler() - Handle 'child' signals from old processes.
42 * sighup_handler() - Handle 'hangup' signals to reconfigure the
44 * sigterm_handler() - Handle 'terminate' signals that stop the
46 * select_timeout() - Calculate the select timeout value.
47 * usage() - Show scheduler usage.
51 * Include necessary headers...
56 #include <sys/resource.h>
63 #endif /* HAVE_LAUNCH_H */
65 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
67 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
70 #endif /* HAVE_NOTIFY_H */
78 static void launchd_checkin(void);
79 static void launchd_reload(void);
80 static int launchd_sync_conf(void);
81 #endif /* HAVE_LAUNCHD */
83 static void parent_handler(int sig
);
84 static void process_children(void);
85 static void sigchld_handler(int sig
);
86 static void sighup_handler(int sig
);
87 static void sigterm_handler(int sig
);
88 static long select_timeout(int fds
);
89 static void usage(int status
);
96 static int parent_signal
= 0; /* Set to signal number from child */
97 static int holdcount
= 0; /* Number of times "hold" was called */
98 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
99 static sigset_t holdmask
; /* Old POSIX signal mask */
100 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
101 static int dead_children
= 0; /* Dead children? */
102 static int stop_scheduler
= 0; /* Should the scheduler stop? */
106 * 'main()' - Main entry for the CUPS scheduler.
109 int /* O - Exit status */
110 main(int argc
, /* I - Number of command-line args */
111 char *argv
[]) /* I - Command-line arguments */
113 int i
; /* Looping var */
114 char *opt
; /* Option character */
115 int fg
; /* Run in the foreground */
116 int fds
; /* Number of ready descriptors */
117 fd_set
*input
, /* Input set for select() */
118 *output
; /* Output set for select() */
119 cupsd_client_t
*con
; /* Current client */
120 cupsd_job_t
*job
; /* Current job */
121 cupsd_listener_t
*lis
; /* Current listener */
122 time_t current_time
, /* Current time */
123 activity
, /* Client activity timer */
124 browse_time
, /* Next browse send time */
125 senddoc_time
, /* Send-Document time */
126 expire_time
; /* Subscription expire time */
127 time_t mallinfo_time
; /* Malloc information time */
128 size_t string_count
, /* String count */
129 alloc_bytes
, /* Allocated string bytes */
130 total_bytes
; /* Total string bytes */
131 struct timeval timeout
; /* select() timeout */
132 struct rlimit limit
; /* Runtime limit */
133 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
134 struct sigaction action
; /* Actions for POSIX signals */
135 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
137 cups_file_t
*fp
; /* Fake lpsched lock file */
138 struct stat statbuf
; /* Needed for checking lpsched FIFO */
141 int launchd_idle_exit
;
142 /* Idle exit on select timeout? */
143 #endif /* HAVE_LAUNCHD */
147 * Check for command-line arguments...
152 for (i
= 1; i
< argc
; i
++)
153 if (argv
[i
][0] == '-')
154 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
157 case 'c' : /* Configuration file */
161 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
162 "after \"-c\" option!\n"));
166 if (argv
[i
][0] == '/')
169 * Absolute directory...
172 cupsdSetString(&ConfigurationFile
, argv
[i
]);
177 * Relative directory...
180 char *current
; /* Current directory */
184 * Allocate a buffer for the current working directory to
185 * reduce run-time stack usage; this approximates the
186 * behavior of some implementations of getcwd() when they
187 * are passed a NULL pointer.
190 current
= malloc(1024);
191 getcwd(current
, 1024);
193 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
199 case 'f' : /* Run in foreground... */
203 case 'F' : /* Run in foreground, but disconnect from terminal... */
207 case 'h' : /* Show usage/help */
211 case 'l' : /* Started by launchd... */
216 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
217 "in, running in normal mode.\n"));
219 #endif /* HAVE_LAUNCHD */
222 case 'p' : /* Stop immediately for profiling */
223 puts("Warning: -p option is for internal testing use only!");
228 default : /* Unknown option */
229 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
230 "aborting!\n"), *opt
);
236 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
241 if (!ConfigurationFile
)
242 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
245 * If the user hasn't specified "-f", run in the background...
251 * Setup signal handlers for the parent...
254 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
255 sigset(SIGUSR1
, parent_handler
);
256 sigset(SIGCHLD
, parent_handler
);
258 sigset(SIGHUP
, SIG_IGN
);
259 #elif defined(HAVE_SIGACTION)
260 memset(&action
, 0, sizeof(action
));
261 sigemptyset(&action
.sa_mask
);
262 sigaddset(&action
.sa_mask
, SIGUSR1
);
263 action
.sa_handler
= parent_handler
;
264 sigaction(SIGUSR1
, &action
, NULL
);
265 sigaction(SIGCHLD
, &action
, NULL
);
267 sigemptyset(&action
.sa_mask
);
268 action
.sa_handler
= SIG_IGN
;
269 sigaction(SIGHUP
, &action
, NULL
);
271 signal(SIGUSR1
, parent_handler
);
272 signal(SIGCLD
, parent_handler
);
274 signal(SIGHUP
, SIG_IGN
);
275 #endif /* HAVE_SIGSET */
280 * OK, wait for the child to startup and send us SIGUSR1 or to crash
281 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
282 * might be sent by the init script to restart the scheduler...
285 for (; parent_signal
== 0;)
288 if (parent_signal
== SIGUSR1
)
296 else if (WIFEXITED(i
))
298 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
304 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
313 * Make sure we aren't tying up any filesystems...
320 * Disable core dumps...
323 getrlimit(RLIMIT_CORE
, &limit
);
325 setrlimit(RLIMIT_CORE
, &limit
);
328 * Disconnect from the controlling terminal...
334 * Close all open files...
337 getrlimit(RLIMIT_NOFILE
, &limit
);
339 for (i
= 0; i
< limit
.rlim_cur
; i
++)
345 * Set the timezone info...
351 setlocale(LC_TIME
, "");
355 * Set the maximum number of files...
358 getrlimit(RLIMIT_NOFILE
, &limit
);
360 if (limit
.rlim_max
> FD_SETSIZE
)
363 MaxFDs
= limit
.rlim_max
;
365 limit
.rlim_cur
= MaxFDs
;
367 setrlimit(RLIMIT_NOFILE
, &limit
);
370 * Allocate memory for the input and output sets...
373 SetSize
= (MaxFDs
+ 31) / 8 + 4;
374 if (SetSize
< sizeof(fd_set
))
375 SetSize
= sizeof(fd_set
);
377 InputSet
= (fd_set
*)calloc(1, SetSize
);
378 OutputSet
= (fd_set
*)calloc(1, SetSize
);
379 input
= (fd_set
*)calloc(1, SetSize
);
380 output
= (fd_set
*)calloc(1, SetSize
);
382 if (InputSet
== NULL
|| OutputSet
== NULL
|| input
== NULL
|| output
== NULL
)
384 syslog(LOG_LPR
, "Unable to allocate memory for select() sets - exiting!");
389 * Read configuration...
392 if (!cupsdReadConfiguration())
394 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
403 * If we were started by launchd make sure the cupsd plist file contains the
404 * same listeners as cupsd.conf; If it didn't then reload it before getting
405 * the list of listening file descriptors...
408 if (launchd_sync_conf())
413 * Until rdar://3854821 is fixed we have to exit after the reload...
416 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Exiting on launchd_reload");
422 #endif /* HAVE_LAUNCHD */
425 * Startup the server...
431 * Catch hangup and child signals and ignore broken pipes...
434 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
435 sigset(SIGCHLD
, sigchld_handler
);
436 sigset(SIGHUP
, sighup_handler
);
437 sigset(SIGPIPE
, SIG_IGN
);
438 sigset(SIGTERM
, sigterm_handler
);
439 #elif defined(HAVE_SIGACTION)
440 memset(&action
, 0, sizeof(action
));
442 sigemptyset(&action
.sa_mask
);
443 sigaddset(&action
.sa_mask
, SIGTERM
);
444 sigaddset(&action
.sa_mask
, SIGCHLD
);
445 action
.sa_handler
= sigchld_handler
;
446 sigaction(SIGCHLD
, &action
, NULL
);
448 sigemptyset(&action
.sa_mask
);
449 sigaddset(&action
.sa_mask
, SIGHUP
);
450 action
.sa_handler
= sighup_handler
;
451 sigaction(SIGHUP
, &action
, NULL
);
453 sigemptyset(&action
.sa_mask
);
454 action
.sa_handler
= SIG_IGN
;
455 sigaction(SIGPIPE
, &action
, NULL
);
457 sigemptyset(&action
.sa_mask
);
458 sigaddset(&action
.sa_mask
, SIGTERM
);
459 sigaddset(&action
.sa_mask
, SIGCHLD
);
460 action
.sa_handler
= sigterm_handler
;
461 sigaction(SIGTERM
, &action
, NULL
);
463 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
464 signal(SIGHUP
, sighup_handler
);
465 signal(SIGPIPE
, SIG_IGN
);
466 signal(SIGTERM
, sigterm_handler
);
467 #endif /* HAVE_SIGSET */
471 * Try to create a fake lpsched lock file if one is not already there.
472 * Some Adobe applications need it under IRIX in order to enable
476 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
478 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
479 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
484 fchmod(cupsFileNumber(fp
), 0644);
485 fchown(cupsFileNumber(fp
), User
, Group
);
492 * Initialize authentication certificates...
498 * If we are running in the background, signal the parent process that
499 * we are up and running...
505 * Send a signal to the parent process, but only if the parent is
506 * not PID 1 (init). This avoids accidentally shutting down the
507 * system on OpenBSD if you CTRL-C the server before it is up...
510 i
= getppid(); /* Save parent PID to avoid race condition */
518 * Start power management framework...
521 cupsdStartSystemMonitor();
522 #endif /* __APPLE__ */
525 * Start any pending print jobs...
535 browse_time
= time(NULL
);
536 senddoc_time
= time(NULL
);
537 expire_time
= time(NULL
);
540 while (!stop_scheduler
)
543 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
544 "main: Top of loop, dead_children=%d, NeedReload=%d",
545 dead_children
, NeedReload
);
549 * Check if there are dead children to handle...
556 * Check if we need to load the server configuration file...
562 * Close any idle clients...
565 if (cupsArrayCount(Clients
) > 0)
567 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
569 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
570 if (con
->http
.state
== HTTP_WAITING
)
571 cupsdCloseClient(con
);
573 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
575 cupsdPauseListening();
579 * Check for any active jobs...
582 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
584 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
585 if (job
->state_value
== IPP_JOB_PROCESSING
)
589 * Restart if all clients are closed and all jobs finished, or
590 * if the reload timeout has elapsed...
593 if ((cupsArrayCount(Clients
) == 0 &&
594 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
595 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
598 * Shutdown the server...
604 * Read configuration...
607 if (!cupsdReadConfiguration())
609 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
617 if (launchd_sync_conf())
622 * Until rdar://3854821 is fixed we have to exit after the reload...
625 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "Exiting on launchd_reload");
632 #endif /* HAVE_LAUNCHD */
635 * Startup the server...
643 * Check for available input or ready output. If select() returns
644 * 0 or -1, something bad happened and we should exit immediately.
646 * Note that we at least have one listening socket open at all
650 memcpy(input
, InputSet
, SetSize
);
651 memcpy(output
, OutputSet
, SetSize
);
653 timeout
.tv_sec
= select_timeout(fds
);
658 * If no other work is scheduled and we're being controlled by
659 * launchd(8) then timeout after 'LaunchdTimeout' seconds of
663 if (timeout
.tv_sec
== 86400 && Launchd
&& LaunchdTimeout
&&
664 (!Browsing
|| !(BrowseLocalProtocols
& BROWSE_DNSSD
) ||
665 cupsArrayCount(Printers
) == 0))
667 timeout
.tv_sec
= LaunchdTimeout
;
668 launchd_idle_exit
= 1;
671 launchd_idle_exit
= 0;
672 #endif /* HAVE_LAUNCHD */
674 if (timeout
.tv_sec
< 86400) /* Only use timeout for < 1 day */
675 fds
= select(MaxFDs
, input
, output
, NULL
, &timeout
);
677 fds
= select(MaxFDs
, input
, output
, NULL
, NULL
);
681 char s
[16384], /* String buffer */
682 *sptr
; /* Pointer into buffer */
683 int slen
; /* Length of string buffer */
687 * Got an error from select!
690 if (errno
== EINTR
) /* Just interrupted by a signal */
694 * Log all sorts of debug info to help track down the problem.
697 cupsdLogMessage(CUPSD_LOG_EMERG
, "select() failed - %s!",
700 strcpy(s
, "InputSet =");
704 for (i
= 0; i
< MaxFDs
; i
++)
705 if (FD_ISSET(i
, InputSet
))
707 snprintf(sptr
, sizeof(s
) - slen
, " %d", i
);
708 slen
+= strlen(sptr
);
709 sptr
+= strlen(sptr
);
712 cupsdLogMessage(CUPSD_LOG_EMERG
, "%s", s
);
714 strcpy(s
, "OutputSet =");
718 for (i
= 0; i
< MaxFDs
; i
++)
719 if (FD_ISSET(i
, OutputSet
))
721 snprintf(sptr
, sizeof(s
) - slen
, " %d", i
);
722 slen
+= strlen(sptr
);
723 sptr
+= strlen(sptr
);
726 cupsdLogMessage(CUPSD_LOG_EMERG
, "%s", s
);
728 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
730 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
731 cupsdLogMessage(CUPSD_LOG_EMERG
,
732 "Clients[%d] = %d, file = %d, state = %d",
733 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
735 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
737 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
738 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
740 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
742 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
745 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
747 #endif /* __APPLE__ */
749 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
751 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
752 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
754 job
->status_buffer
? job
->status_buffer
->fd
: -1,
755 job
->print_pipes
[0], job
->print_pipes
[1],
756 job
->back_pipes
[0], job
->back_pipes
[1]);
760 current_time
= time(NULL
);
764 * If no other work was scheduled and we're being controlled by launchd(8)
765 * then timeout after 'LaunchdTimeout' seconds of inactivity...
768 if (!fds
&& launchd_idle_exit
)
770 cupsdLogMessage(CUPSD_LOG_INFO
,
771 "Printer sharing is off and there are no jobs pending, "
772 "will restart on demand.");
776 #endif /* HAVE_LAUNCHD */
779 * Check for status info from job filters...
782 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
784 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
785 if (job
->status_buffer
&& FD_ISSET(job
->status_buffer
->fd
, input
))
788 * Clear the input bit to avoid updating the next job
789 * using the same status pipe file descriptor...
792 FD_CLR(job
->status_buffer
->fd
, input
);
795 * Read any status messages from the filters...
802 * Update CGI messages as needed...
805 if (CGIPipes
[0] >= 0 && FD_ISSET(CGIPipes
[0], input
))
809 * Handle system management events as needed...
813 if (SysEventPipes
[0] >= 0 && FD_ISSET(SysEventPipes
[0], input
))
814 cupsdUpdateSystemMonitor();
815 #endif /* __APPLE__ */
818 * Update notifier messages as needed...
821 if (NotifierPipes
[0] >= 0 && FD_ISSET(NotifierPipes
[0], input
))
822 cupsdUpdateNotifierStatus();
825 * Expire subscriptions and unload completed jobs as needed...
828 if (current_time
> expire_time
)
830 if (cupsArrayCount(Subscriptions
) > 0)
831 cupsdExpireSubscriptions(NULL
, NULL
);
833 cupsdUnloadCompletedJobs();
835 expire_time
= current_time
;
839 * Update the browse list as needed...
842 if (Browsing
&& BrowseRemoteProtocols
)
844 if (BrowseSocket
>= 0 && FD_ISSET(BrowseSocket
, input
))
845 cupsdUpdateCUPSBrowse();
847 if (PollPipe
>= 0 && FD_ISSET(PollPipe
, input
))
848 cupsdUpdatePolling();
851 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
852 BrowseSLPRefresh
<= current_time
)
853 cupsdUpdateSLPBrowse();
854 #endif /* HAVE_LIBSLP */
857 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
858 BrowseLDAPRefresh
<= current_time
)
859 cupsdUpdateLDAPBrowse();
860 #endif /* HAVE_LDAP */
863 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
865 cupsdSendBrowseList();
866 browse_time
= current_time
;
870 * Check for new connections on the "listen" sockets...
873 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
875 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
876 if (lis
->fd
>= 0 && FD_ISSET(lis
->fd
, input
))
878 FD_CLR(lis
->fd
, input
);
879 cupsdAcceptClient(lis
);
883 * Check for new data on the client sockets...
886 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
888 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
891 * Process the input buffer...
894 if (FD_ISSET(con
->http
.fd
, input
) || con
->http
.used
)
899 FD_CLR(con
->http
.fd
, input
);
901 if (!cupsdReadClient(con
))
911 * Write data as needed...
914 if (con
->pipe_pid
&& FD_ISSET(con
->file
, input
))
917 * Keep track of pending input from the file/pipe separately
918 * so that we don't needlessly spin on select() when the web
919 * client is not ready to receive data...
922 FD_CLR(con
->file
, input
);
926 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "main: Data ready file %d!",
930 if (!FD_ISSET(con
->http
.fd
, output
))
932 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
933 "main: Removing fd %d from InputSet...", con
->file
);
934 FD_CLR(con
->file
, input
);
935 FD_CLR(con
->file
, InputSet
);
939 if (FD_ISSET(con
->http
.fd
, output
))
941 FD_CLR(con
->http
.fd
, output
);
943 if (!con
->pipe_pid
|| con
->file_ready
)
944 if (!cupsdWriteClient(con
))
949 * Check the activity and close old clients...
952 activity
= current_time
- Timeout
;
953 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
955 cupsdLogMessage(CUPSD_LOG_DEBUG
,
956 "Closing client %d after %d seconds of inactivity...",
957 con
->http
.fd
, Timeout
);
959 cupsdCloseClient(con
);
965 * Update any pending multi-file documents...
968 if ((current_time
- senddoc_time
) >= 10)
971 senddoc_time
= current_time
;
975 * Log memory usage every minute...
978 if ((current_time
- mallinfo_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG2
)
981 struct mallinfo mem
; /* Malloc information */
985 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
986 "mallinfo: arena = %d, used = %d, free = %d\n",
987 mem
.arena
, mem
.usmblks
+ mem
.uordblks
,
988 mem
.fsmblks
+ mem
.fordblks
);
989 #endif /* HAVE_MALLINFO */
991 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
992 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
993 "stringpool: " CUPS_LLFMT
" strings, "
994 CUPS_LLFMT
" allocated, " CUPS_LLFMT
" total bytes",
995 CUPS_LLCAST string_count
, CUPS_LLCAST alloc_bytes
,
996 CUPS_LLCAST total_bytes
);
998 mallinfo_time
= current_time
;
1002 * Update the root certificate once every 5 minutes if we have client
1006 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
1007 !RunUser
&& cupsArrayCount(Clients
))
1010 * Update the root certificate...
1014 cupsdAddCert(0, "root");
1018 * Handle OS-specific event notification for any events that have
1019 * accumulated. Don't send these more than once a second...
1024 #ifdef HAVE_NOTIFY_POST
1025 if (LastEvent
& CUPSD_EVENT_PRINTER_CHANGED
)
1027 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1028 "notify_post(\"com.apple.printerListChange\")");
1029 notify_post("com.apple.printerListChange");
1032 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1034 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1035 "notify_post(\"com.apple.printerHistoryChange\")");
1036 notify_post("com.apple.printerHistoryChange");
1039 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1040 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1041 CUPSD_EVENT_JOB_PROGRESS
))
1043 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1044 "notify_post(\"com.apple.jobChange\")");
1045 notify_post("com.apple.jobChange");
1047 #endif /* HAVE_NOTIFY_POST */
1050 * Reset the accumulated events...
1053 LastEvent
= CUPSD_EVENT_NONE
;
1058 * Log a message based on what happened...
1062 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1064 cupsdLogMessage(CUPSD_LOG_ERROR
,
1065 "Scheduler shutting down due to program error.");
1068 * Close all network clients and stop all jobs...
1076 cupsdStopSystemMonitor();
1077 #endif /* __APPLE__ */
1081 * Update the launchd config file as needed...
1084 launchd_sync_conf();
1085 #endif /* HAVE_LAUNCHD */
1089 * Remove the fake IRIX lpsched lock file, but only if the existing
1090 * file is not a FIFO which indicates that the real IRIX lpsched is
1094 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1095 if (!S_ISFIFO(statbuf
.st_mode
))
1096 unlink("/var/spool/lp/SCHEDLOCK");
1100 * Free memory used by FD sets and return...
1108 return (!stop_scheduler
);
1113 * 'cupsdClosePipe()' - Close a pipe as necessary.
1117 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1120 * Close file descriptors as needed...
1138 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1141 int /* O - 0 on success, -1 on error */
1142 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1145 * Create the pipe...
1157 * Set the "close on exec" flag on each end of the pipe...
1160 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1171 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1183 * Return 0 indicating success...
1191 * 'cupsdClearString()' - Clear a string.
1195 cupsdClearString(char **s
) /* O - String value */
1206 * 'cupsdHoldSignals()' - Hold child and termination signals.
1210 cupsdHoldSignals(void)
1212 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1213 sigset_t newmask
; /* New POSIX signal mask */
1214 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1224 #elif defined(HAVE_SIGACTION)
1225 sigemptyset(&newmask
);
1226 sigaddset(&newmask
, SIGTERM
);
1227 sigaddset(&newmask
, SIGCHLD
);
1228 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1229 #endif /* HAVE_SIGSET */
1234 * 'cupsdReleaseSignals()' - Release signals for delivery.
1238 cupsdReleaseSignals(void)
1247 #elif defined(HAVE_SIGACTION)
1248 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1249 #endif /* HAVE_SIGSET */
1254 * 'cupsdSetString()' - Set a string value.
1258 cupsdSetString(char **s
, /* O - New string */
1259 const char *v
) /* I - String value */
1268 *s
= _cupsStrAlloc(v
);
1275 * 'cupsdSetStringf()' - Set a formatted string value.
1279 cupsdSetStringf(char **s
, /* O - New string */
1280 const char *f
, /* I - Printf-style format string */
1281 ...) /* I - Additional args as needed */
1283 char v
[4096]; /* Formatting string value */
1284 va_list ap
; /* Argument pointer */
1285 char *olds
; /* Old string */
1296 vsnprintf(v
, sizeof(v
), f
, ap
);
1299 *s
= _cupsStrAlloc(v
);
1311 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1315 launchd_checkin(void)
1317 int i
, /* Looping var */
1318 count
, /* Numebr of listeners */
1319 portnum
; /* Port number */
1320 launch_data_t ld_msg
, /* Launch data message */
1321 ld_resp
, /* Launch data response */
1322 ld_array
, /* Launch data array */
1323 ld_sockets
, /* Launch data sockets dictionary */
1324 tmp
; /* Launch data */
1325 cupsd_listener_t
*lis
; /* Listeners array */
1326 http_addr_t addr
; /* Address variable */
1327 socklen_t addrlen
; /* Length of address */
1330 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1333 * Check-in with launchd...
1336 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1337 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1339 cupsdLogMessage(CUPSD_LOG_ERROR
,
1340 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1345 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1347 errno
= launch_data_get_errno(ld_resp
);
1348 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1354 * Get the sockets dictionary...
1357 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1359 cupsdLogMessage(CUPSD_LOG_ERROR
,
1360 "launchd_checkin: No sockets found to answer requests on!");
1365 * Get the array of listener sockets...
1368 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1370 cupsdLogMessage(CUPSD_LOG_ERROR
,
1371 "launchd_checkin: No sockets found to answer requests on!");
1376 * Add listening fd(s) to the Listener array...
1379 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1382 * Free the listeners array built from cupsd.conf...
1385 cupsdDeleteAllListeners();
1388 * Create a new array of listeners from the launchd data...
1391 Listeners
= cupsArrayNew(NULL
, NULL
);
1392 count
= launch_data_array_get_count(ld_array
);
1394 for (i
= 0; i
< count
; i
++)
1397 * Copy the current address and log it...
1400 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1402 cupsdLogMessage(CUPSD_LOG_ERROR
,
1403 "launchd_checkin: Unable to allocate listener - %s.",
1408 cupsArrayAdd(Listeners
, lis
);
1410 tmp
= launch_data_array_get_index(ld_array
, i
);
1411 lis
->fd
= launch_data_get_fd(tmp
);
1412 addrlen
= sizeof(lis
->address
);
1414 if (getsockname(lis
->fd
, (struct sockaddr
*)&(lis
->address
), &addrlen
))
1416 cupsdLogMessage(CUPSD_LOG_ERROR
,
1417 "launchd_checkin: Unable to get local address - %s",
1425 if (addr
.addr
.sa_family
== AF_INET6
)
1426 portnum
= ntohs(addr
.ipv6
.sin6_port
);
1428 # endif /* AF_INET6 */
1429 if (addr
.addr
.sa_family
== AF_INET
)
1430 portnum
= ntohs(addr
.ipv4
.sin_port
);
1433 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1434 # endif /* HAVE_SSL */
1439 * Collect the browse socket (if there is one)...
1442 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "BrowseSockets")))
1444 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1446 if ((tmp
= launch_data_array_get_index(ld_array
, 0)))
1448 if (launch_data_get_type(tmp
) == LAUNCH_DATA_FD
)
1450 if (BrowseSocket
!= -1)
1451 close(BrowseSocket
);
1453 BrowseSocket
= launch_data_get_fd(tmp
);
1456 cupsdLogMessage(CUPSD_LOG_WARN
,
1457 "launchd_checkin: BrowseSocket not a fd!");
1460 cupsdLogMessage(CUPSD_LOG_WARN
,
1461 "launchd_checkin: BrowseSockets is an empty array!");
1464 cupsdLogMessage(CUPSD_LOG_WARN
,
1465 "launchd_checkin: BrowseSockets is not an array!");
1468 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: No BrowseSockets");
1470 launch_data_free(ld_msg
);
1471 launch_data_free(ld_resp
);
1476 * 'launchd_reload()' - Tell launchd to reload the configuration file to pick
1477 * up the new listening directives.
1481 launchd_reload(void)
1483 int child_status
; /* Exit status of child process */
1484 pid_t child_pid
, /* Child PID */
1485 waitpid_status
; /* Child process exit status */
1486 char *argv
[4]; /* Argument strings */
1490 * The current launchd doesn't support a reload option (rdar://3854821).
1491 * Until this is fixed we need to reload the config file by execing launchctl
1492 * twice (to unload then load). NOTE: This will cause us to exit on SIGTERM
1493 * which will cancel all client & job activity.
1495 * After this is fixed we'll be able to tell launchd to reload the file
1496 * and pick up the new listening descriptors without disrupting current
1501 * Unloading the current configuration will cause launchd to send us a SIGTERM;
1502 * block it for now so we can get our work done...
1508 * Set up the unload arguments to launchctl...
1511 argv
[0] = "/bin/launchctl";
1513 argv
[2] = LaunchdConf
;
1516 if (cupsdStartProcess(argv
[0], argv
, NULL
, -1, -1, -1, -1, 1, &child_pid
) < 0)
1517 cupsdLogMessage(CUPSD_LOG_ERROR
,
1518 "launchd_reload: Unable to execute %s - %s", argv
[0],
1524 waitpid_status
= waitpid(child_pid
, &child_status
, 0);
1526 while (waitpid_status
== (pid_t
)-1 && errno
== EINTR
);
1528 if (WIFSIGNALED(child_status
))
1529 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1530 "launchd_reload: %s pid %d crashed on signal %d!",
1531 basename(argv
[0]), child_pid
, WTERMSIG(child_status
));
1533 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1534 "launchd_reload: %s pid %d stopped with status %d!",
1535 basename(argv
[0]), child_pid
, WEXITSTATUS(child_status
));
1538 * Do it again with the load command...
1543 if (cupsdStartProcess(argv
[0], argv
, NULL
, -1, -1, -1, -1, 1,
1546 cupsdLogMessage(CUPSD_LOG_ERROR
,
1547 "launchd_reload: Unable to fork for %s - %s", argv
[0],
1554 waitpid_status
= waitpid(child_pid
, &child_status
, 0);
1555 } while (waitpid_status
== (pid_t
)-1 && errno
== EINTR
);
1557 if (WIFSIGNALED(child_status
))
1558 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1559 "launchd_reload: %s pid %d crashed on signal %d!",
1560 basename(argv
[0]), child_pid
, WTERMSIG(child_status
));
1562 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1563 "launchd_reload: %s pid %d stopped with status %d",
1564 basename(argv
[0]), child_pid
,
1565 WEXITSTATUS(child_status
));
1570 * Leave signals blocked since exit() will be called momentarily anyways...
1576 * 'launchd_sync_conf()' - Re-write the launchd(8) config file
1577 * org.cups.cupsd.plist based on cupsd.conf.
1580 static int /* O - 1 if the file was updated */
1581 launchd_sync_conf(void)
1583 int portnum
; /* Port number */
1584 CFMutableDictionaryRef cupsd_dict
, /* org.cups.cupsd.plist dictionary */
1585 sockets
, /* Sockets dictionary */
1586 listener
; /* Listener dictionary */
1587 CFDataRef resourceData
; /* XML property list */
1588 CFMutableArrayRef array
; /* Array */
1589 CFNumberRef socket_mode
; /* Domain socket mode bits */
1590 CFStringRef socket_path
; /* Domain socket path */
1591 CFTypeRef value
; /* CF value */
1592 CFURLRef fileURL
; /* File URL */
1593 SInt32 errorCode
; /* Error code */
1594 cupsd_listener_t
*lis
; /* Current listening socket */
1595 struct servent
*service
; /* Services data base entry */
1596 char temp
[1024]; /* Temporary buffer for value */
1597 struct stat cupsd_sb
, /* File info for cupsd.conf */
1598 launchd_sb
; /* File info for org.cups.cupsd.plist */
1602 * If the launchd conf file modification time is newer than the cupsd.conf
1603 * time then there's nothing to do...
1606 if (!stat(ConfigurationFile
, &cupsd_sb
) &&
1607 !stat(LaunchdConf
, &launchd_sb
) &&
1608 launchd_sb
.st_mtimespec
.tv_sec
>= cupsd_sb
.st_mtimespec
.tv_sec
)
1610 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1611 "launchd_sync_conf: Nothing to do, pid=%d.",
1617 * Time to write a new 'org.cups.cupsd.plist' file.
1618 * Create the new dictionary and populate it with values...
1621 if ((cupsd_dict
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
1622 &kCFTypeDictionaryKeyCallBacks
,
1623 &kCFTypeDictionaryValueCallBacks
)) != NULL
)
1625 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_LABEL
),
1626 CFSTR("org.cups.cupsd"));
1627 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_ONDEMAND
),
1630 if ((Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)) ||
1631 cupsArrayCount(ActiveJobs
))
1632 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_RUNATLOAD
),
1635 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_RUNATLOAD
),
1638 #ifdef LAUNCH_JOBKEY_SERVICEIPC
1639 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_SERVICEIPC
),
1641 #endif /* LAUNCH_JOBKEY_SERVICEIPC */
1643 if ((array
= CFArrayCreateMutable(kCFAllocatorDefault
, 2,
1644 &kCFTypeArrayCallBacks
)) != NULL
)
1646 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_PROGRAMARGUMENTS
),
1648 CFArrayAppendValue(array
, CFSTR("/usr/sbin/cupsd"));
1649 CFArrayAppendValue(array
, CFSTR("-l"));
1654 * Add a sockets dictionary...
1657 if ((sockets
= (CFMutableDictionaryRef
)CFDictionaryCreateMutable(
1658 kCFAllocatorDefault
, 0,
1659 &kCFTypeDictionaryKeyCallBacks
,
1660 &kCFTypeDictionaryValueCallBacks
)) != NULL
)
1662 CFDictionaryAddValue(cupsd_dict
, CFSTR(LAUNCH_JOBKEY_SOCKETS
), sockets
);
1665 * Add a Listeners array to the sockets dictionary...
1668 if ((array
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
1669 &kCFTypeArrayCallBacks
)) != NULL
)
1671 CFDictionaryAddValue(sockets
, CFSTR("Listeners"), array
);
1674 * For each listener add a dictionary to the listeners array...
1677 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1679 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1681 if ((listener
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
1682 &kCFTypeDictionaryKeyCallBacks
,
1683 &kCFTypeDictionaryValueCallBacks
)) != NULL
)
1685 CFArrayAppendValue(array
, listener
);
1688 if (lis
->address
.addr
.sa_family
== AF_LOCAL
)
1690 if ((socket_path
= CFStringCreateWithCString(kCFAllocatorDefault
,
1691 lis
->address
.un
.sun_path
,
1692 kCFStringEncodingUTF8
)))
1694 CFDictionaryAddValue(listener
,
1695 CFSTR(LAUNCH_JOBSOCKETKEY_PATHNAME
),
1697 CFRelease(socket_path
);
1699 portnum
= 0140777; /* (S_IFSOCK|S_IRWXU|S_IRWXG|S_IRWXO) or *
1701 if ((socket_mode
= CFNumberCreate(kCFAllocatorDefault
,
1702 kCFNumberIntType
, &portnum
)))
1704 CFDictionaryAddValue(listener
, CFSTR("SockPathMode"),
1706 CFRelease(socket_mode
);
1710 # endif /* AF_LOCAL */
1713 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1715 CFDictionaryAddValue(listener
,
1716 CFSTR(LAUNCH_JOBSOCKETKEY_FAMILY
),
1718 portnum
= lis
->address
.ipv6
.sin6_port
;
1721 # endif /* AF_INET6 */
1723 CFDictionaryAddValue(listener
,
1724 CFSTR(LAUNCH_JOBSOCKETKEY_FAMILY
),
1726 portnum
= lis
->address
.ipv4
.sin_port
;
1729 if ((service
= getservbyport(portnum
, NULL
)))
1730 value
= CFStringCreateWithCString(kCFAllocatorDefault
,
1732 kCFStringEncodingUTF8
);
1734 value
= CFNumberCreate(kCFAllocatorDefault
,
1735 kCFNumberIntType
, &portnum
);
1739 CFDictionaryAddValue(listener
,
1740 CFSTR(LAUNCH_JOBSOCKETKEY_SERVICENAME
),
1745 httpAddrString(&lis
->address
, temp
, sizeof(temp
));
1746 if ((value
= CFStringCreateWithCString(kCFAllocatorDefault
, temp
,
1747 kCFStringEncodingUTF8
)))
1749 CFDictionaryAddValue(listener
,
1750 CFSTR(LAUNCH_JOBSOCKETKEY_NODENAME
),
1756 CFRelease(listener
);
1764 * Add the BrowseSocket to the sockets dictionary...
1767 if (Browsing
&& (BrowseRemoteProtocols
& BROWSE_CUPS
))
1769 if ((array
= CFArrayCreateMutable(kCFAllocatorDefault
, 0,
1770 &kCFTypeArrayCallBacks
)) != NULL
)
1772 CFDictionaryAddValue(sockets
, CFSTR("BrowseSockets"), array
);
1774 if ((listener
= CFDictionaryCreateMutable(kCFAllocatorDefault
, 0,
1775 &kCFTypeDictionaryKeyCallBacks
,
1776 &kCFTypeDictionaryValueCallBacks
)) != NULL
)
1778 CFArrayAppendValue(array
, listener
);
1780 CFDictionaryAddValue(listener
, CFSTR(LAUNCH_JOBSOCKETKEY_FAMILY
),
1782 CFDictionaryAddValue(listener
, CFSTR(LAUNCH_JOBSOCKETKEY_TYPE
),
1785 if ((service
= getservbyport(BrowsePort
, NULL
)))
1786 value
= CFStringCreateWithCString(kCFAllocatorDefault
,
1788 kCFStringEncodingUTF8
);
1790 value
= CFNumberCreate(kCFAllocatorDefault
, kCFNumberIntType
,
1793 CFDictionaryAddValue(listener
,
1794 CFSTR(LAUNCH_JOBSOCKETKEY_SERVICENAME
), value
);
1797 CFRelease(listener
);
1807 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1808 "launchd_sync_conf: Updating \"%s\", pid=%d\n",
1809 LaunchdConf
, (int)getpid());
1811 if ((fileURL
= CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault
,
1812 (const unsigned char *)LaunchdConf
,
1813 strlen(LaunchdConf
), false)))
1815 if ((resourceData
= CFPropertyListCreateXMLData(kCFAllocatorDefault
,
1818 if (!CFURLWriteDataAndPropertiesToResource(fileURL
, resourceData
,
1821 cupsdLogMessage(CUPSD_LOG_WARN
,
1822 "launchd_sync_conf: "
1823 "CFURLWriteDataAndPropertiesToResource(\"%s\") "
1825 LaunchdConf
, (int)errorCode
);
1828 CFRelease(resourceData
);
1834 CFRelease(cupsd_dict
);
1838 * Let the caller know we updated the file...
1843 #endif /* HAVE_LAUNCHD */
1847 * 'parent_handler()' - Catch USR1/CHLD signals...
1851 parent_handler(int sig
) /* I - Signal */
1854 * Store the signal we got from the OS and return...
1857 parent_signal
= sig
;
1862 * 'process_children()' - Process all dead children...
1866 process_children(void)
1868 int status
; /* Exit status of child */
1869 int pid
; /* Process ID of child */
1870 cupsd_job_t
*job
; /* Current job */
1871 int i
; /* Looping var */
1872 char name
[1024]; /* Process name */
1875 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1878 * Reset the dead_children flag...
1884 * Collect the exit status of some children...
1888 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1889 #elif defined(HAVE_WAIT3)
1890 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1892 if ((pid
= wait(&status
)) > 0)
1893 #endif /* HAVE_WAITPID */
1896 * Ignore SIGTERM errors - that comes when a job is cancelled...
1899 cupsdFinishProcess(pid
, name
, sizeof(name
));
1901 if (status
== SIGTERM
)
1906 if (WIFEXITED(status
))
1907 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1908 pid
, name
, WEXITSTATUS(status
));
1910 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1911 pid
, name
, WTERMSIG(status
));
1913 if (LogLevel
< CUPSD_LOG_DEBUG
)
1914 cupsdLogMessage(CUPSD_LOG_INFO
,
1915 "Hint: Try setting the LogLevel to \"debug\" to find "
1919 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1923 * Delete certificates for CGI processes...
1927 cupsdDeleteCert(pid
);
1930 * Lookup the PID in the jobs list...
1933 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1935 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1936 if (job
->state_value
== IPP_JOB_PROCESSING
)
1938 for (i
= 0; job
->filters
[i
]; i
++)
1939 if (job
->filters
[i
] == pid
)
1942 if (job
->filters
[i
] || job
->backend
== pid
)
1945 * OK, this process has gone away; what's left?
1948 if (job
->filters
[i
])
1949 job
->filters
[i
] = -pid
;
1951 job
->backend
= -pid
;
1953 if (status
&& job
->status
>= 0)
1956 * An error occurred; save the exit status so we know to stop
1957 * the printer or cancel the job when all of the filters finish...
1959 * A negative status indicates that the backend failed and the
1960 * printer needs to be stopped.
1963 if (job
->filters
[i
])
1964 job
->status
= status
; /* Filter failed */
1966 job
->status
= -status
; /* Backend failed */
1968 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
))
1970 snprintf(job
->printer
->state_message
,
1971 sizeof(job
->printer
->state_message
), "%s failed", name
);
1972 cupsdAddPrinterHistory(job
->printer
);
1977 * If this is not the last file in a job, see if all of the
1978 * filters are done, and if so move to the next file.
1981 if (job
->current_file
< job
->num_files
)
1983 for (i
= 0; job
->filters
[i
] < 0; i
++);
1985 if (!job
->filters
[i
])
1988 * Process the next file...
1991 cupsdFinishJob(job
);
2002 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2006 sigchld_handler(int sig
) /* I - Signal number */
2011 * Flag that we have dead children...
2017 * Reset the signal handler as needed...
2020 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2021 signal(SIGCLD
, sigchld_handler
);
2022 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2027 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2031 sighup_handler(int sig
) /* I - Signal number */
2035 NeedReload
= RELOAD_ALL
;
2036 ReloadTime
= time(NULL
);
2038 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2039 signal(SIGHUP
, sighup_handler
);
2040 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2045 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2049 sigterm_handler(int sig
) /* I - Signal */
2051 (void)sig
; /* remove compiler warnings... */
2054 * Flag that we should stop and return...
2062 * 'select_timeout()' - Calculate the select timeout value.
2066 static long /* O - Number of seconds */
2067 select_timeout(int fds
) /* I - Number of descriptors returned */
2069 long timeout
; /* Timeout for select */
2070 time_t now
; /* Current time */
2071 cupsd_client_t
*con
; /* Client information */
2072 cupsd_printer_t
*p
; /* Printer information */
2073 cupsd_job_t
*job
; /* Job information */
2074 cupsd_subscription_t
*sub
; /* Subscription information */
2075 const char *why
; /* Debugging aid */
2079 * Check to see if any of the clients have pending data to be
2080 * processed; if so, the timeout should be 0...
2083 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
2085 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
2086 if (con
->http
.used
> 0)
2090 * If select has been active in the last second (fds != 0) or we have
2091 * many resources in use then don't bother trying to optimize the
2092 * timeout, just make it 1 second.
2095 if (fds
|| cupsArrayCount(Clients
) > 50)
2099 * Otherwise, check all of the possible events that we need to wake for...
2103 timeout
= now
+ 86400; /* 86400 == 1 day */
2107 * Check the activity and close old clients...
2110 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
2112 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
2113 if ((con
->http
.activity
+ Timeout
) < timeout
)
2115 timeout
= con
->http
.activity
+ Timeout
;
2116 why
= "timeout a client connection";
2120 * Update the browse list as needed...
2123 if (Browsing
&& BrowseLocalProtocols
)
2126 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
2128 timeout
= BrowseSLPRefresh
;
2129 why
= "update SLP browsing";
2131 #endif /* HAVE_LIBSLP */
2134 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
2136 timeout
= BrowseLDAPRefresh
;
2137 why
= "update LDAP browsing";
2139 #endif /* HAVE_LDAP */
2141 if (BrowseLocalProtocols
& BROWSE_CUPS
)
2143 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
2145 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
2147 if (p
->type
& CUPS_PRINTER_REMOTE
)
2149 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
2151 timeout
= p
->browse_time
+ BrowseTimeout
;
2152 why
= "browse timeout a printer";
2155 else if (!(p
->type
& CUPS_PRINTER_IMPLICIT
))
2157 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
2159 timeout
= p
->browse_time
+ BrowseInterval
;
2160 why
= "send browse update";
2168 * Check for any active jobs...
2171 if (timeout
> (now
+ 10) && ActiveJobs
)
2173 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
2175 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2176 if (job
->state_value
<= IPP_JOB_PROCESSING
)
2179 why
= "process active jobs";
2184 #ifdef HAVE_MALLINFO
2186 * Log memory usage every minute...
2189 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2191 timeout
= mallinfo_time
+ 60;
2192 why
= "display memory usage";
2194 #endif /* HAVE_MALLINFO */
2197 * Expire subscriptions as needed...
2200 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2202 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2203 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2205 timeout
= sub
->expire
;
2206 why
= "expire subscription";
2210 * Adjust from absolute to relative time. If p->browse_time above
2211 * was 0 then we can end up with a negative value here, so check.
2212 * We add 1 second to the timeout since events occur after the
2213 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2214 * to avoid select() timeout limits present on some operating
2218 timeout
= timeout
- now
+ 1;
2222 else if (timeout
> 86400)
2226 * Log and return the timeout value...
2229 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: %ld seconds to %s",
2237 * 'usage()' - Show scheduler usage.
2241 usage(int status
) /* O - Exit status */
2243 _cupsLangPuts(status
? stderr
: stdout
,
2244 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
2246 "-c config-file Load alternate configuration file\n"
2247 "-f Run in the foreground\n"
2248 "-F Run in the foreground but detach\n"
2249 "-h Show this usage message\n"
2250 "-l Run cupsd from launchd(8)\n"));
2256 * End of "$Id: main.c 5634 2006-06-06 17:48:27Z mike $".