2 * "$Id: main.c 6914 2007-09-05 21:05:04Z mike $"
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
6 * Copyright 2007 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * "LICENSE" which should have been included with this file. If this
13 * file is missing or damaged, see the license at "http://www.cups.org/".
17 * main() - Main entry for the CUPS scheduler.
18 * cupsdClosePipe() - Close a pipe as necessary.
19 * cupsdOpenPipe() - Create a pipe which is closed on exec.
20 * cupsdHoldSignals() - Hold child and termination signals.
21 * cupsdReleaseSignals() - Release signals for delivery.
22 * cupsdSetString() - Set a string value.
23 * cupsdSetStringf() - Set a formatted string value.
24 * launchd_checkin() - Check-in with launchd and collect the
26 * launchd_checkout() - Check-out with launchd.
27 * parent_handler() - Catch USR1/CHLD signals...
28 * process_children() - Process all dead children...
29 * sigchld_handler() - Handle 'child' signals from old processes.
30 * sighup_handler() - Handle 'hangup' signals to reconfigure the
32 * sigterm_handler() - Handle 'terminate' signals that stop the
34 * select_timeout() - Calculate the select timeout value.
35 * usage() - Show scheduler usage.
39 * Include necessary headers...
44 #include <sys/resource.h>
52 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
53 /* Name of the launchd KeepAlive file */
54 # ifndef LAUNCH_JOBKEY_KEEPALIVE
55 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
56 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
57 # ifndef LAUNCH_JOBKEY_PATHSTATE
58 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
59 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
60 # ifndef LAUNCH_JOBKEY_SERVICEIPC
61 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
62 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
63 #endif /* HAVE_LAUNCH_H */
65 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
67 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
70 #endif /* HAVE_NOTIFY_H */
72 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
74 #endif /* __APPLE__ && HAVE_DLFCN_H */
82 static void launchd_checkin(void);
83 static void launchd_checkout(void);
84 #endif /* HAVE_LAUNCHD */
85 static void parent_handler(int sig
);
86 static void process_children(void);
87 static void sigchld_handler(int sig
);
88 static void sighup_handler(int sig
);
89 static void sigterm_handler(int sig
);
90 static long select_timeout(int fds
);
91 static void usage(int status
);
98 static int parent_signal
= 0;
99 /* Set to signal number from child */
100 static int holdcount
= 0; /* Number of times "hold" was called */
101 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
102 static sigset_t holdmask
; /* Old POSIX signal mask */
103 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
104 static int dead_children
= 0;
106 static int stop_scheduler
= 0;
107 /* Should the scheduler stop? */
109 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
110 static const char *PSQLibPath
= "/usr/lib/libPrintServiceQuota.dylib";
111 static const char *PSQLibFuncName
= "PSQUpdateQuota";
112 static void *PSQLibRef
; /* libPrintServiceQuota.dylib */
113 #endif /* HAVE_DLFCN_H */
117 * 'main()' - Main entry for the CUPS scheduler.
120 int /* O - Exit status */
121 main(int argc
, /* I - Number of command-line args */
122 char *argv
[]) /* I - Command-line arguments */
124 int i
; /* Looping var */
125 char *opt
; /* Option character */
126 int fg
; /* Run in the foreground */
127 int fds
; /* Number of ready descriptors */
128 cupsd_client_t
*con
; /* Current client */
129 cupsd_job_t
*job
; /* Current job */
130 cupsd_listener_t
*lis
; /* Current listener */
131 time_t current_time
, /* Current time */
132 activity
, /* Client activity timer */
133 browse_time
, /* Next browse send time */
134 senddoc_time
, /* Send-Document time */
135 expire_time
, /* Subscription expire time */
136 mallinfo_time
; /* Malloc information time */
137 size_t string_count
, /* String count */
138 alloc_bytes
, /* Allocated string bytes */
139 total_bytes
; /* Total string bytes */
140 long timeout
; /* Timeout for cupsdDoSelect() */
141 struct rlimit limit
; /* Runtime limit */
142 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
143 struct sigaction action
; /* Actions for POSIX signals */
144 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
146 cups_file_t
*fp
; /* Fake lpsched lock file */
147 struct stat statbuf
; /* Needed for checking lpsched FIFO */
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' : /* Configuration file */
190 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
191 "after \"-c\" option!\n"));
195 if (argv
[i
][0] == '/')
198 * Absolute directory...
201 cupsdSetString(&ConfigurationFile
, argv
[i
]);
206 * Relative directory...
209 char *current
; /* Current directory */
213 * Allocate a buffer for the current working directory to
214 * reduce run-time stack usage; this approximates the
215 * behavior of some implementations of getcwd() when they
216 * are passed a NULL pointer.
219 current
= malloc(1024);
220 getcwd(current
, 1024);
222 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
228 case 'f' : /* Run in foreground... */
232 case 'F' : /* Run in foreground, but disconnect from terminal... */
236 case 'h' : /* Show usage/help */
240 case 'l' : /* Started by launchd... */
245 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
246 "in, running in normal mode.\n"));
248 #endif /* HAVE_LAUNCHD */
251 case 'p' : /* Stop immediately for profiling */
252 puts("Warning: -p option is for internal testing use only!");
257 case 't' : /* Test the cupsd.conf file... */
262 default : /* Unknown option */
263 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
264 "aborting!\n"), *opt
);
270 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
275 if (!ConfigurationFile
)
276 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
279 * If the user hasn't specified "-f", run in the background...
285 * Setup signal handlers for the parent...
288 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
289 sigset(SIGUSR1
, parent_handler
);
290 sigset(SIGCHLD
, parent_handler
);
292 sigset(SIGHUP
, SIG_IGN
);
293 #elif defined(HAVE_SIGACTION)
294 memset(&action
, 0, sizeof(action
));
295 sigemptyset(&action
.sa_mask
);
296 sigaddset(&action
.sa_mask
, SIGUSR1
);
297 action
.sa_handler
= parent_handler
;
298 sigaction(SIGUSR1
, &action
, NULL
);
299 sigaction(SIGCHLD
, &action
, NULL
);
301 sigemptyset(&action
.sa_mask
);
302 action
.sa_handler
= SIG_IGN
;
303 sigaction(SIGHUP
, &action
, NULL
);
305 signal(SIGUSR1
, parent_handler
);
306 signal(SIGCLD
, parent_handler
);
308 signal(SIGHUP
, SIG_IGN
);
309 #endif /* HAVE_SIGSET */
314 * OK, wait for the child to startup and send us SIGUSR1 or to crash
315 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
316 * might be sent by the init script to restart the scheduler...
319 for (; parent_signal
== 0;)
322 if (parent_signal
== SIGUSR1
)
330 else if (WIFEXITED(i
))
332 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
338 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
347 * Make sure we aren't tying up any filesystems...
354 * Disable core dumps...
357 getrlimit(RLIMIT_CORE
, &limit
);
359 setrlimit(RLIMIT_CORE
, &limit
);
362 * Disconnect from the controlling terminal...
368 * Close all open files...
371 getrlimit(RLIMIT_NOFILE
, &limit
);
373 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
379 * Set the timezone info...
385 setlocale(LC_TIME
, "");
389 * Set the maximum number of files...
392 getrlimit(RLIMIT_NOFILE
, &limit
);
394 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
395 if (limit
.rlim_max
> FD_SETSIZE
)
398 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
400 if (limit
.rlim_max
== RLIM_INFINITY
)
403 #endif /* RLIM_INFINITY */
404 MaxFDs
= limit
.rlim_max
;
406 limit
.rlim_cur
= MaxFDs
;
408 setrlimit(RLIMIT_NOFILE
, &limit
);
413 * Read configuration...
416 if (!cupsdReadConfiguration())
419 printf("%s contains errors\n", ConfigurationFile
);
421 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
425 else if (TestConfigFile
)
427 printf("%s is OK\n", ConfigurationFile
);
431 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
434 * Clean out the temporary directory...
437 cups_dir_t
*dir
; /* Temporary directory */
438 cups_dentry_t
*dent
; /* Directory entry */
439 char tempfile
[1024]; /* Temporary filename */
442 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
444 cupsdLogMessage(CUPSD_LOG_INFO
,
445 "Cleaning out old temporary files in \"%s\"...", TempDir
);
447 while ((dent
= cupsDirRead(dir
)) != NULL
)
449 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
451 if (cupsdRemoveFile(tempfile
))
452 cupsdLogMessage(CUPSD_LOG_ERROR
,
453 "Unable to remove temporary file \"%s\" - %s",
454 tempfile
, strerror(errno
));
456 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
463 cupsdLogMessage(CUPSD_LOG_ERROR
,
464 "Unable to open temporary directory \"%s\" - %s",
465 TempDir
, strerror(errno
));
472 * If we were started by launchd get the listen sockets file descriptors...
477 #endif /* HAVE_LAUNCHD */
479 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
481 * Load Print Service quota enforcement library (X Server only)
484 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
487 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
488 #endif /* __APPLE__ && HAVE_DLFCN_H */
493 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
497 if (krb5_init_context
!= NULL
)
498 # endif /* __APPLE__ */
501 * Setup a Kerberos context for the scheduler to use...
504 if (krb5_init_context(&KerberosContext
))
505 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
506 #endif /* HAVE_GSSAPI */
509 * Startup the server...
515 * Catch hangup and child signals and ignore broken pipes...
518 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
519 sigset(SIGCHLD
, sigchld_handler
);
520 sigset(SIGHUP
, sighup_handler
);
521 sigset(SIGPIPE
, SIG_IGN
);
522 sigset(SIGTERM
, sigterm_handler
);
523 #elif defined(HAVE_SIGACTION)
524 memset(&action
, 0, sizeof(action
));
526 sigemptyset(&action
.sa_mask
);
527 sigaddset(&action
.sa_mask
, SIGTERM
);
528 sigaddset(&action
.sa_mask
, SIGCHLD
);
529 action
.sa_handler
= sigchld_handler
;
530 sigaction(SIGCHLD
, &action
, NULL
);
532 sigemptyset(&action
.sa_mask
);
533 sigaddset(&action
.sa_mask
, SIGHUP
);
534 action
.sa_handler
= sighup_handler
;
535 sigaction(SIGHUP
, &action
, NULL
);
537 sigemptyset(&action
.sa_mask
);
538 action
.sa_handler
= SIG_IGN
;
539 sigaction(SIGPIPE
, &action
, NULL
);
541 sigemptyset(&action
.sa_mask
);
542 sigaddset(&action
.sa_mask
, SIGTERM
);
543 sigaddset(&action
.sa_mask
, SIGCHLD
);
544 action
.sa_handler
= sigterm_handler
;
545 sigaction(SIGTERM
, &action
, NULL
);
547 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
548 signal(SIGHUP
, sighup_handler
);
549 signal(SIGPIPE
, SIG_IGN
);
550 signal(SIGTERM
, sigterm_handler
);
551 #endif /* HAVE_SIGSET */
555 * Try to create a fake lpsched lock file if one is not already there.
556 * Some Adobe applications need it under IRIX in order to enable
560 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
562 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
563 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
568 fchmod(cupsFileNumber(fp
), 0644);
569 fchown(cupsFileNumber(fp
), User
, Group
);
576 * Initialize authentication certificates...
582 * If we are running in the background, signal the parent process that
583 * we are up and running...
589 * Send a signal to the parent process, but only if the parent is
590 * not PID 1 (init). This avoids accidentally shutting down the
591 * system on OpenBSD if you CTRL-C the server before it is up...
594 i
= getppid(); /* Save parent PID to avoid race condition */
602 * Start power management framework...
605 cupsdStartSystemMonitor();
606 #endif /* __APPLE__ */
609 * Start any pending print jobs...
619 browse_time
= time(NULL
);
620 senddoc_time
= time(NULL
);
621 expire_time
= time(NULL
);
624 while (!stop_scheduler
)
627 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
628 "main: Top of loop, dead_children=%d, NeedReload=%d",
629 dead_children
, NeedReload
);
633 * Check if there are dead children to handle...
640 * Check if we need to load the server configuration file...
646 * Close any idle clients...
649 if (cupsArrayCount(Clients
) > 0)
651 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
653 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
654 if (con
->http
.state
== HTTP_WAITING
)
655 cupsdCloseClient(con
);
657 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
659 cupsdPauseListening();
663 * Check for any active jobs...
666 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
668 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
669 if (job
->state_value
== IPP_JOB_PROCESSING
)
673 * Restart if all clients are closed and all jobs finished, or
674 * if the reload timeout has elapsed...
677 if ((cupsArrayCount(Clients
) == 0 &&
678 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
679 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
682 * Shutdown the server...
688 * Read configuration...
691 if (!cupsdReadConfiguration())
693 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
702 * If we were started by launchd get the listen sockets file descriptors...
707 #endif /* HAVE_LAUNCHD */
710 * Startup the server...
718 * Check for available input or ready output. If cupsdDoSelect()
719 * returns 0 or -1, something bad happened and we should exit
722 * Note that we at least have one listening socket open at all
726 timeout
= select_timeout(fds
);
730 * If no other work is scheduled and we're being controlled by
731 * launchd then timeout after 'LaunchdTimeout' seconds of
735 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
736 !cupsArrayCount(ActiveJobs
) &&
738 (!BrowseRemoteProtocols
&&
739 (!NumBrowsers
|| !BrowseLocalProtocols
||
740 cupsArrayCount(Printers
) == 0))))
742 timeout
= LaunchdTimeout
;
743 launchd_idle_exit
= 1;
746 launchd_idle_exit
= 0;
747 #endif /* HAVE_LAUNCHD */
749 if ((fds
= cupsdDoSelect(timeout
)) < 0)
752 * Got an error from select!
756 cupsd_printer_t
*p
; /* Current printer */
757 #endif /* HAVE_DNSSD */
760 if (errno
== EINTR
) /* Just interrupted by a signal */
764 * Log all sorts of debug info to help track down the problem.
767 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
770 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
772 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
773 cupsdLogMessage(CUPSD_LOG_EMERG
,
774 "Clients[%d] = %d, file = %d, state = %d",
775 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
777 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
779 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
780 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
782 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
784 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
787 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
789 #endif /* __APPLE__ */
791 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
793 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
794 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
796 job
->status_buffer
? job
->status_buffer
->fd
: -1,
797 job
->print_pipes
[0], job
->print_pipes
[1],
798 job
->back_pipes
[0], job
->back_pipes
[1]);
801 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
803 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
804 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] %d", p
->name
,
806 #endif /* HAVE_DNSSD */
811 current_time
= time(NULL
);
815 * If no other work was scheduled and we're being controlled by launchd
816 * then timeout after 'LaunchdTimeout' seconds of inactivity...
819 if (!fds
&& launchd_idle_exit
)
821 cupsdLogMessage(CUPSD_LOG_INFO
,
822 "Printer sharing is off and there are no jobs pending, "
823 "will restart on demand.");
827 #endif /* HAVE_LAUNCHD */
830 * Resume listening for new connections as needed...
833 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
834 cupsArrayCount(Clients
) < MaxClients
)
835 cupsdResumeListening();
838 * Expire subscriptions and unload completed jobs as needed...
841 if (current_time
> expire_time
)
843 if (cupsArrayCount(Subscriptions
) > 0)
844 cupsdExpireSubscriptions(NULL
, NULL
);
846 cupsdUnloadCompletedJobs();
848 expire_time
= current_time
;
852 * Update the browse list as needed...
858 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
859 BrowseSLPRefresh
<= current_time
)
860 cupsdUpdateSLPBrowse();
861 #endif /* HAVE_LIBSLP */
864 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
865 BrowseLDAPRefresh
<= current_time
)
866 cupsdUpdateLDAPBrowse();
867 #endif /* HAVE_LDAP */
870 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
872 cupsdSendBrowseList();
873 browse_time
= current_time
;
877 * Update the root certificate once every 5 minutes if we have client
881 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
882 !RunUser
&& cupsArrayCount(Clients
))
885 * Update the root certificate...
889 cupsdAddCert(0, "root");
893 * Check for new data on the client sockets...
896 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
898 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
901 * Process pending data in the input buffer...
906 cupsdReadClient(con
);
911 * Check the activity and close old clients...
914 activity
= current_time
- Timeout
;
915 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
917 cupsdLogMessage(CUPSD_LOG_DEBUG
,
918 "Closing client %d after %d seconds of inactivity...",
919 con
->http
.fd
, Timeout
);
921 cupsdCloseClient(con
);
927 * Update any pending multi-file documents...
930 if ((current_time
- senddoc_time
) >= 10)
933 senddoc_time
= current_time
;
937 * Log memory usage every minute...
940 if ((current_time
- mallinfo_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG2
)
943 struct mallinfo mem
; /* Malloc information */
947 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
948 "mallinfo: arena = %d, used = %d, free = %d\n",
949 mem
.arena
, mem
.usmblks
+ mem
.uordblks
,
950 mem
.fsmblks
+ mem
.fordblks
);
951 #endif /* HAVE_MALLINFO */
953 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
954 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
955 "stringpool: " CUPS_LLFMT
" strings, "
956 CUPS_LLFMT
" allocated, " CUPS_LLFMT
" total bytes",
957 CUPS_LLCAST string_count
, CUPS_LLCAST alloc_bytes
,
958 CUPS_LLCAST total_bytes
);
960 mallinfo_time
= current_time
;
964 * Handle OS-specific event notification for any events that have
965 * accumulated. Don't send these more than once a second...
970 #ifdef HAVE_NOTIFY_POST
971 if (LastEvent
& CUPSD_EVENT_PRINTER_CHANGED
)
973 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
974 "notify_post(\"com.apple.printerListChange\")");
975 notify_post("com.apple.printerListChange");
978 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
980 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
981 "notify_post(\"com.apple.printerHistoryChange\")");
982 notify_post("com.apple.printerHistoryChange");
985 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
986 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
987 CUPSD_EVENT_JOB_PROGRESS
))
989 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
990 "notify_post(\"com.apple.jobChange\")");
991 notify_post("com.apple.jobChange");
993 #endif /* HAVE_NOTIFY_POST */
996 * Reset the accumulated events...
999 LastEvent
= CUPSD_EVENT_NONE
;
1004 * Log a message based on what happened...
1008 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1010 cupsdLogMessage(CUPSD_LOG_ERROR
,
1011 "Scheduler shutting down due to program error.");
1014 * Close all network clients...
1021 * Update the launchd KeepAlive file as needed...
1026 #endif /* HAVE_LAUNCHD */
1036 * Stop monitoring system event monitoring...
1039 cupsdStopSystemMonitor();
1040 #endif /* __APPLE__ */
1044 * Free the scheduler's Kerberos context...
1049 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1053 if (krb5_init_context
!= NULL
)
1054 # endif /* __APPLE__ */
1055 krb5_free_context(KerberosContext
);
1056 #endif /* HAVE_GSSAPI */
1061 * Unload Print Service quota enforcement library (X Server only)
1064 PSQUpdateQuotaProc
= NULL
;
1070 #endif /* HAVE_DLFCN_H */
1071 #endif /* __APPLE__ */
1075 * Remove the fake IRIX lpsched lock file, but only if the existing
1076 * file is not a FIFO which indicates that the real IRIX lpsched is
1080 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1081 if (!S_ISFIFO(statbuf
.st_mode
))
1082 unlink("/var/spool/lp/SCHEDLOCK");
1087 return (!stop_scheduler
);
1092 * 'cupsdClosePipe()' - Close a pipe as necessary.
1096 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1099 * Close file descriptors as needed...
1117 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1120 int /* O - 0 on success, -1 on error */
1121 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1124 * Create the pipe...
1136 * Set the "close on exec" flag on each end of the pipe...
1139 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1150 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1162 * Return 0 indicating success...
1170 * 'cupsdClearString()' - Clear a string.
1174 cupsdClearString(char **s
) /* O - String value */
1185 * 'cupsdHoldSignals()' - Hold child and termination signals.
1189 cupsdHoldSignals(void)
1191 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1192 sigset_t newmask
; /* New POSIX signal mask */
1193 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1203 #elif defined(HAVE_SIGACTION)
1204 sigemptyset(&newmask
);
1205 sigaddset(&newmask
, SIGTERM
);
1206 sigaddset(&newmask
, SIGCHLD
);
1207 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1208 #endif /* HAVE_SIGSET */
1213 * 'cupsdReleaseSignals()' - Release signals for delivery.
1217 cupsdReleaseSignals(void)
1226 #elif defined(HAVE_SIGACTION)
1227 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1228 #endif /* HAVE_SIGSET */
1233 * 'cupsdSetString()' - Set a string value.
1237 cupsdSetString(char **s
, /* O - New string */
1238 const char *v
) /* I - String value */
1247 *s
= _cupsStrAlloc(v
);
1254 * 'cupsdSetStringf()' - Set a formatted string value.
1258 cupsdSetStringf(char **s
, /* O - New string */
1259 const char *f
, /* I - Printf-style format string */
1260 ...) /* I - Additional args as needed */
1262 char v
[4096]; /* Formatting string value */
1263 va_list ap
; /* Argument pointer */
1264 char *olds
; /* Old string */
1275 vsnprintf(v
, sizeof(v
), f
, ap
);
1278 *s
= _cupsStrAlloc(v
);
1290 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1294 launchd_checkin(void)
1296 int i
, /* Looping var */
1297 count
, /* Numebr of listeners */
1298 portnum
; /* Port number */
1299 launch_data_t ld_msg
, /* Launch data message */
1300 ld_resp
, /* Launch data response */
1301 ld_array
, /* Launch data array */
1302 ld_sockets
, /* Launch data sockets dictionary */
1303 tmp
; /* Launch data */
1304 cupsd_listener_t
*lis
; /* Listeners array */
1305 http_addr_t addr
; /* Address variable */
1306 socklen_t addrlen
; /* Length of address */
1307 int fd
; /* File descriptor */
1308 char s
[256]; /* String addresss */
1311 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1314 * Check-in with launchd...
1317 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1318 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1320 cupsdLogMessage(CUPSD_LOG_ERROR
,
1321 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1326 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1328 errno
= launch_data_get_errno(ld_resp
);
1329 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1335 * Get the sockets dictionary...
1338 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1340 cupsdLogMessage(CUPSD_LOG_ERROR
,
1341 "launchd_checkin: No sockets found to answer requests on!");
1346 * Get the array of listener sockets...
1349 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1351 cupsdLogMessage(CUPSD_LOG_ERROR
,
1352 "launchd_checkin: No sockets found to answer requests on!");
1357 * Add listening fd(s) to the Listener array...
1360 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1362 count
= launch_data_array_get_count(ld_array
);
1364 for (i
= 0; i
< count
; i
++)
1367 * Get the launchd file descriptor and address...
1370 tmp
= launch_data_array_get_index(ld_array
, i
);
1371 fd
= launch_data_get_fd(tmp
);
1372 addrlen
= sizeof(addr
);
1374 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1376 cupsdLogMessage(CUPSD_LOG_ERROR
,
1377 "launchd_checkin: Unable to get local address - %s",
1383 * Try to match the launchd socket address to one of the listeners...
1386 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1388 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1389 if (httpAddrEqual(&lis
->address
, &addr
))
1393 * Add a new listener If there's no match...
1398 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1399 "launchd_checkin: Matched existing listener %s with fd %d...",
1400 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1404 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1405 "launchd_checkin: Adding new listener %s with fd %d...",
1406 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1408 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1410 cupsdLogMessage(CUPSD_LOG_ERROR
,
1411 "launchd_checkin: Unable to allocate listener - %s.",
1416 cupsArrayAdd(Listeners
, lis
);
1418 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1427 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1428 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1430 # endif /* AF_INET6 */
1431 if (lis
->address
.addr
.sa_family
== AF_INET
)
1432 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1435 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1436 # endif /* HAVE_SSL */
1440 launch_data_free(ld_msg
);
1441 launch_data_free(ld_resp
);
1446 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1450 launchd_checkout(void)
1452 int fd
; /* File descriptor */
1456 * Create or remove the launchd KeepAlive file based on whether
1457 * there are active jobs, polling, browsing for remote printers or
1458 * shared printers to advertise...
1461 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1463 (BrowseRemoteProtocols
||
1464 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1466 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1467 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1469 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1474 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1475 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1477 unlink(CUPS_KEEPALIVE
);
1480 #endif /* HAVE_LAUNCHD */
1484 * 'parent_handler()' - Catch USR1/CHLD signals...
1488 parent_handler(int sig
) /* I - Signal */
1491 * Store the signal we got from the OS and return...
1494 parent_signal
= sig
;
1499 * 'process_children()' - Process all dead children...
1503 process_children(void)
1505 int status
; /* Exit status of child */
1506 int pid
; /* Process ID of child */
1507 cupsd_job_t
*job
; /* Current job */
1508 int i
; /* Looping var */
1509 char name
[1024]; /* Process name */
1512 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1515 * Reset the dead_children flag...
1521 * Collect the exit status of some children...
1525 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1526 #elif defined(HAVE_WAIT3)
1527 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1529 if ((pid
= wait(&status
)) > 0)
1530 #endif /* HAVE_WAITPID */
1533 * Ignore SIGTERM errors - that comes when a job is canceled...
1536 cupsdFinishProcess(pid
, name
, sizeof(name
));
1538 if (status
== SIGTERM
)
1543 if (WIFEXITED(status
))
1544 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1545 pid
, name
, WEXITSTATUS(status
));
1547 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1548 pid
, name
, WTERMSIG(status
));
1550 if (LogLevel
< CUPSD_LOG_DEBUG
)
1551 cupsdLogMessage(CUPSD_LOG_INFO
,
1552 "Hint: Try setting the LogLevel to \"debug\" to find "
1556 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1560 * Delete certificates for CGI processes...
1564 cupsdDeleteCert(pid
);
1567 * Lookup the PID in the jobs list...
1570 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1572 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1573 if (job
->state_value
== IPP_JOB_PROCESSING
)
1575 for (i
= 0; job
->filters
[i
]; i
++)
1576 if (job
->filters
[i
] == pid
)
1579 if (job
->filters
[i
] || job
->backend
== pid
)
1582 * OK, this process has gone away; what's left?
1585 if (job
->filters
[i
])
1586 job
->filters
[i
] = -pid
;
1588 job
->backend
= -pid
;
1590 if (status
&& job
->status
>= 0)
1593 * An error occurred; save the exit status so we know to stop
1594 * the printer or cancel the job when all of the filters finish...
1596 * A negative status indicates that the backend failed and the
1597 * printer needs to be stopped.
1600 if (job
->filters
[i
])
1601 job
->status
= status
; /* Filter failed */
1603 job
->status
= -status
; /* Backend failed */
1605 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
))
1607 snprintf(job
->printer
->state_message
,
1608 sizeof(job
->printer
->state_message
), "%s failed", name
);
1609 cupsdAddPrinterHistory(job
->printer
);
1614 * If this is not the last file in a job, see if all of the
1615 * filters are done, and if so move to the next file.
1618 if (job
->current_file
< job
->num_files
)
1620 for (i
= 0; job
->filters
[i
] < 0; i
++);
1622 if (!job
->filters
[i
])
1625 * Process the next file...
1628 cupsdFinishJob(job
);
1639 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1643 sigchld_handler(int sig
) /* I - Signal number */
1648 * Flag that we have dead children...
1654 * Reset the signal handler as needed...
1657 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1658 signal(SIGCLD
, sigchld_handler
);
1659 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1664 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1668 sighup_handler(int sig
) /* I - Signal number */
1672 NeedReload
= RELOAD_ALL
;
1673 ReloadTime
= time(NULL
);
1675 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1676 signal(SIGHUP
, sighup_handler
);
1677 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1682 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1686 sigterm_handler(int sig
) /* I - Signal */
1688 (void)sig
; /* remove compiler warnings... */
1691 * Flag that we should stop and return...
1699 * 'select_timeout()' - Calculate the select timeout value.
1703 static long /* O - Number of seconds */
1704 select_timeout(int fds
) /* I - Number of descriptors returned */
1706 long timeout
; /* Timeout for select */
1707 time_t now
; /* Current time */
1708 cupsd_client_t
*con
; /* Client information */
1709 cupsd_printer_t
*p
; /* Printer information */
1710 cupsd_job_t
*job
; /* Job information */
1711 cupsd_subscription_t
*sub
; /* Subscription information */
1712 const char *why
; /* Debugging aid */
1716 * Check to see if any of the clients have pending data to be
1717 * processed; if so, the timeout should be 0...
1720 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1722 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1723 if (con
->http
.used
> 0)
1727 * If select has been active in the last second (fds > 0) or we have
1728 * many resources in use then don't bother trying to optimize the
1729 * timeout, just make it 1 second.
1732 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1736 * Otherwise, check all of the possible events that we need to wake for...
1740 timeout
= now
+ 86400; /* 86400 == 1 day */
1744 * Check whether we are accepting new connections...
1747 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1748 ListeningPaused
< timeout
)
1750 if (ListeningPaused
<= now
)
1753 timeout
= ListeningPaused
;
1755 why
= "resume listening";
1759 * Check the activity and close old clients...
1762 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1764 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1765 if ((con
->http
.activity
+ Timeout
) < timeout
)
1767 timeout
= con
->http
.activity
+ Timeout
;
1768 why
= "timeout a client connection";
1772 * Update the browse list as needed...
1775 if (Browsing
&& BrowseLocalProtocols
)
1778 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1780 timeout
= BrowseSLPRefresh
;
1781 why
= "update SLP browsing";
1783 #endif /* HAVE_LIBSLP */
1786 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1788 timeout
= BrowseLDAPRefresh
;
1789 why
= "update LDAP browsing";
1791 #endif /* HAVE_LDAP */
1793 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1795 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1797 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1799 if (p
->type
& CUPS_PRINTER_REMOTE
)
1801 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1803 timeout
= p
->browse_time
+ BrowseTimeout
;
1804 why
= "browse timeout a printer";
1807 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1809 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1811 timeout
= p
->browse_time
+ BrowseInterval
;
1812 why
= "send browse update";
1820 * Check for any active jobs...
1823 if (timeout
> (now
+ 10) && ActiveJobs
)
1825 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1827 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1828 if (job
->state_value
<= IPP_JOB_PROCESSING
)
1831 why
= "process active jobs";
1836 #ifdef HAVE_MALLINFO
1838 * Log memory usage every minute...
1841 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1843 timeout
= mallinfo_time
+ 60;
1844 why
= "display memory usage";
1846 #endif /* HAVE_MALLINFO */
1849 * Expire subscriptions as needed...
1852 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1854 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1855 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1857 timeout
= sub
->expire
;
1858 why
= "expire subscription";
1862 * Adjust from absolute to relative time. If p->browse_time above
1863 * was 0 then we can end up with a negative value here, so check.
1864 * We add 1 second to the timeout since events occur after the
1865 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1866 * to avoid select() timeout limits present on some operating
1870 timeout
= timeout
- now
+ 1;
1874 else if (timeout
> 86400)
1878 * Log and return the timeout value...
1881 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1889 * 'usage()' - Show scheduler usage.
1893 usage(int status
) /* O - Exit status */
1895 _cupsLangPuts(status
? stderr
: stdout
,
1896 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1898 "-c config-file Load alternate configuration file\n"
1899 "-f Run in the foreground\n"
1900 "-F Run in the foreground but detach\n"
1901 "-h Show this usage message\n"
1902 "-l Run cupsd from launchd(8)\n"));
1908 * End of "$Id: main.c 6914 2007-09-05 21:05:04Z mike $".