2 * "$Id: main.c 6915 2007-09-05 21:05:17Z 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 default : /* Unknown option */
258 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
259 "aborting!\n"), *opt
);
265 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
270 if (!ConfigurationFile
)
271 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
274 * If the user hasn't specified "-f", run in the background...
280 * Setup signal handlers for the parent...
283 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
284 sigset(SIGUSR1
, parent_handler
);
285 sigset(SIGCHLD
, parent_handler
);
287 sigset(SIGHUP
, SIG_IGN
);
288 #elif defined(HAVE_SIGACTION)
289 memset(&action
, 0, sizeof(action
));
290 sigemptyset(&action
.sa_mask
);
291 sigaddset(&action
.sa_mask
, SIGUSR1
);
292 action
.sa_handler
= parent_handler
;
293 sigaction(SIGUSR1
, &action
, NULL
);
294 sigaction(SIGCHLD
, &action
, NULL
);
296 sigemptyset(&action
.sa_mask
);
297 action
.sa_handler
= SIG_IGN
;
298 sigaction(SIGHUP
, &action
, NULL
);
300 signal(SIGUSR1
, parent_handler
);
301 signal(SIGCLD
, parent_handler
);
303 signal(SIGHUP
, SIG_IGN
);
304 #endif /* HAVE_SIGSET */
309 * OK, wait for the child to startup and send us SIGUSR1 or to crash
310 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
311 * might be sent by the init script to restart the scheduler...
314 for (; parent_signal
== 0;)
317 if (parent_signal
== SIGUSR1
)
325 else if (WIFEXITED(i
))
327 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
333 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
342 * Make sure we aren't tying up any filesystems...
349 * Disable core dumps...
352 getrlimit(RLIMIT_CORE
, &limit
);
354 setrlimit(RLIMIT_CORE
, &limit
);
357 * Disconnect from the controlling terminal...
363 * Close all open files...
366 getrlimit(RLIMIT_NOFILE
, &limit
);
368 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
374 * Set the timezone info...
380 setlocale(LC_TIME
, "");
384 * Set the maximum number of files...
387 getrlimit(RLIMIT_NOFILE
, &limit
);
389 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
390 if (limit
.rlim_max
> FD_SETSIZE
)
393 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
395 if (limit
.rlim_max
== RLIM_INFINITY
)
398 #endif /* RLIM_INFINITY */
399 MaxFDs
= limit
.rlim_max
;
401 limit
.rlim_cur
= MaxFDs
;
403 setrlimit(RLIMIT_NOFILE
, &limit
);
408 * Read configuration...
411 if (!cupsdReadConfiguration())
413 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
418 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
421 * Clean out the temporary directory...
424 cups_dir_t
*dir
; /* Temporary directory */
425 cups_dentry_t
*dent
; /* Directory entry */
426 char tempfile
[1024]; /* Temporary filename */
429 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
431 cupsdLogMessage(CUPSD_LOG_INFO
,
432 "Cleaning out old temporary files in \"%s\"...", TempDir
);
434 while ((dent
= cupsDirRead(dir
)) != NULL
)
436 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
438 if (cupsdRemoveFile(tempfile
))
439 cupsdLogMessage(CUPSD_LOG_ERROR
,
440 "Unable to remove temporary file \"%s\" - %s",
441 tempfile
, strerror(errno
));
443 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
450 cupsdLogMessage(CUPSD_LOG_ERROR
,
451 "Unable to open temporary directory \"%s\" - %s",
452 TempDir
, strerror(errno
));
459 * If we were started by launchd get the listen sockets file descriptors...
464 #endif /* HAVE_LAUNCHD */
466 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
468 * Load Print Service quota enforcement library (X Server only)
471 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
474 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
475 #endif /* __APPLE__ && HAVE_DLFCN_H */
480 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
484 if (krb5_init_context
!= NULL
)
485 # endif /* __APPLE__ */
488 * Setup a Kerberos context for the scheduler to use...
491 if (krb5_init_context(&KerberosContext
))
492 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
493 #endif /* HAVE_GSSAPI */
496 * Startup the server...
502 * Catch hangup and child signals and ignore broken pipes...
505 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
506 sigset(SIGCHLD
, sigchld_handler
);
507 sigset(SIGHUP
, sighup_handler
);
508 sigset(SIGPIPE
, SIG_IGN
);
509 sigset(SIGTERM
, sigterm_handler
);
510 #elif defined(HAVE_SIGACTION)
511 memset(&action
, 0, sizeof(action
));
513 sigemptyset(&action
.sa_mask
);
514 sigaddset(&action
.sa_mask
, SIGTERM
);
515 sigaddset(&action
.sa_mask
, SIGCHLD
);
516 action
.sa_handler
= sigchld_handler
;
517 sigaction(SIGCHLD
, &action
, NULL
);
519 sigemptyset(&action
.sa_mask
);
520 sigaddset(&action
.sa_mask
, SIGHUP
);
521 action
.sa_handler
= sighup_handler
;
522 sigaction(SIGHUP
, &action
, NULL
);
524 sigemptyset(&action
.sa_mask
);
525 action
.sa_handler
= SIG_IGN
;
526 sigaction(SIGPIPE
, &action
, NULL
);
528 sigemptyset(&action
.sa_mask
);
529 sigaddset(&action
.sa_mask
, SIGTERM
);
530 sigaddset(&action
.sa_mask
, SIGCHLD
);
531 action
.sa_handler
= sigterm_handler
;
532 sigaction(SIGTERM
, &action
, NULL
);
534 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
535 signal(SIGHUP
, sighup_handler
);
536 signal(SIGPIPE
, SIG_IGN
);
537 signal(SIGTERM
, sigterm_handler
);
538 #endif /* HAVE_SIGSET */
542 * Try to create a fake lpsched lock file if one is not already there.
543 * Some Adobe applications need it under IRIX in order to enable
547 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
549 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
550 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
555 fchmod(cupsFileNumber(fp
), 0644);
556 fchown(cupsFileNumber(fp
), User
, Group
);
563 * Initialize authentication certificates...
569 * If we are running in the background, signal the parent process that
570 * we are up and running...
576 * Send a signal to the parent process, but only if the parent is
577 * not PID 1 (init). This avoids accidentally shutting down the
578 * system on OpenBSD if you CTRL-C the server before it is up...
581 i
= getppid(); /* Save parent PID to avoid race condition */
589 * Start power management framework...
592 cupsdStartSystemMonitor();
593 #endif /* __APPLE__ */
596 * Start any pending print jobs...
606 browse_time
= time(NULL
);
607 senddoc_time
= time(NULL
);
608 expire_time
= time(NULL
);
611 while (!stop_scheduler
)
614 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
615 "main: Top of loop, dead_children=%d, NeedReload=%d",
616 dead_children
, NeedReload
);
620 * Check if there are dead children to handle...
627 * Check if we need to load the server configuration file...
633 * Close any idle clients...
636 if (cupsArrayCount(Clients
) > 0)
638 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
640 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
641 if (con
->http
.state
== HTTP_WAITING
)
642 cupsdCloseClient(con
);
644 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
646 cupsdPauseListening();
650 * Check for any active jobs...
653 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
655 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
656 if (job
->state_value
== IPP_JOB_PROCESSING
)
660 * Restart if all clients are closed and all jobs finished, or
661 * if the reload timeout has elapsed...
664 if ((cupsArrayCount(Clients
) == 0 &&
665 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
666 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
669 * Shutdown the server...
675 * Read configuration...
678 if (!cupsdReadConfiguration())
680 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
689 * If we were started by launchd get the listen sockets file descriptors...
694 #endif /* HAVE_LAUNCHD */
697 * Startup the server...
705 * Check for available input or ready output. If cupsdDoSelect()
706 * returns 0 or -1, something bad happened and we should exit
709 * Note that we at least have one listening socket open at all
713 timeout
= select_timeout(fds
);
717 * If no other work is scheduled and we're being controlled by
718 * launchd then timeout after 'LaunchdTimeout' seconds of
722 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
723 !cupsArrayCount(ActiveJobs
) &&
725 (!BrowseRemoteProtocols
&&
726 (!NumBrowsers
|| !BrowseLocalProtocols
||
727 cupsArrayCount(Printers
) == 0))))
729 timeout
= LaunchdTimeout
;
730 launchd_idle_exit
= 1;
733 launchd_idle_exit
= 0;
734 #endif /* HAVE_LAUNCHD */
736 if ((fds
= cupsdDoSelect(timeout
)) < 0)
739 * Got an error from select!
743 cupsd_printer_t
*p
; /* Current printer */
744 #endif /* HAVE_DNSSD */
747 if (errno
== EINTR
) /* Just interrupted by a signal */
751 * Log all sorts of debug info to help track down the problem.
754 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
757 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
759 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
760 cupsdLogMessage(CUPSD_LOG_EMERG
,
761 "Clients[%d] = %d, file = %d, state = %d",
762 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
764 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
766 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
767 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
769 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
771 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
774 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
776 #endif /* __APPLE__ */
778 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
780 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
781 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
783 job
->status_buffer
? job
->status_buffer
->fd
: -1,
784 job
->print_pipes
[0], job
->print_pipes
[1],
785 job
->back_pipes
[0], job
->back_pipes
[1]);
788 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
790 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
791 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] %d", p
->name
,
793 #endif /* HAVE_DNSSD */
798 current_time
= time(NULL
);
802 * If no other work was scheduled and we're being controlled by launchd
803 * then timeout after 'LaunchdTimeout' seconds of inactivity...
806 if (!fds
&& launchd_idle_exit
)
808 cupsdLogMessage(CUPSD_LOG_INFO
,
809 "Printer sharing is off and there are no jobs pending, "
810 "will restart on demand.");
814 #endif /* HAVE_LAUNCHD */
817 * Resume listening for new connections as needed...
820 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
821 cupsArrayCount(Clients
) < MaxClients
)
822 cupsdResumeListening();
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...
845 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
846 BrowseSLPRefresh
<= current_time
)
847 cupsdUpdateSLPBrowse();
848 #endif /* HAVE_LIBSLP */
851 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
852 BrowseLDAPRefresh
<= current_time
)
853 cupsdUpdateLDAPBrowse();
854 #endif /* HAVE_LDAP */
857 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
859 cupsdSendBrowseList();
860 browse_time
= current_time
;
864 * Update the root certificate once every 5 minutes if we have client
868 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
869 !RunUser
&& cupsArrayCount(Clients
))
872 * Update the root certificate...
876 cupsdAddCert(0, "root");
880 * Check for new data on the client sockets...
883 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
885 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
888 * Process pending data in the input buffer...
893 cupsdReadClient(con
);
898 * Check the activity and close old clients...
901 activity
= current_time
- Timeout
;
902 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
904 cupsdLogMessage(CUPSD_LOG_DEBUG
,
905 "Closing client %d after %d seconds of inactivity...",
906 con
->http
.fd
, Timeout
);
908 cupsdCloseClient(con
);
914 * Update any pending multi-file documents...
917 if ((current_time
- senddoc_time
) >= 10)
920 senddoc_time
= current_time
;
924 * Log memory usage every minute...
927 if ((current_time
- mallinfo_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG2
)
930 struct mallinfo mem
; /* Malloc information */
934 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
935 "mallinfo: arena = %d, used = %d, free = %d\n",
936 mem
.arena
, mem
.usmblks
+ mem
.uordblks
,
937 mem
.fsmblks
+ mem
.fordblks
);
938 #endif /* HAVE_MALLINFO */
940 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
941 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
942 "stringpool: " CUPS_LLFMT
" strings, "
943 CUPS_LLFMT
" allocated, " CUPS_LLFMT
" total bytes",
944 CUPS_LLCAST string_count
, CUPS_LLCAST alloc_bytes
,
945 CUPS_LLCAST total_bytes
);
947 mallinfo_time
= current_time
;
951 * Handle OS-specific event notification for any events that have
952 * accumulated. Don't send these more than once a second...
957 #ifdef HAVE_NOTIFY_POST
958 if (LastEvent
& CUPSD_EVENT_PRINTER_CHANGED
)
960 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
961 "notify_post(\"com.apple.printerListChange\")");
962 notify_post("com.apple.printerListChange");
965 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
967 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
968 "notify_post(\"com.apple.printerHistoryChange\")");
969 notify_post("com.apple.printerHistoryChange");
972 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
973 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
974 CUPSD_EVENT_JOB_PROGRESS
))
976 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
977 "notify_post(\"com.apple.jobChange\")");
978 notify_post("com.apple.jobChange");
980 #endif /* HAVE_NOTIFY_POST */
983 * Reset the accumulated events...
986 LastEvent
= CUPSD_EVENT_NONE
;
991 * Log a message based on what happened...
995 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
997 cupsdLogMessage(CUPSD_LOG_ERROR
,
998 "Scheduler shutting down due to program error.");
1001 * Close all network clients...
1008 * Update the launchd KeepAlive file as needed...
1013 #endif /* HAVE_LAUNCHD */
1023 * Stop monitoring system event monitoring...
1026 cupsdStopSystemMonitor();
1027 #endif /* __APPLE__ */
1031 * Free the scheduler's Kerberos context...
1036 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1040 if (krb5_init_context
!= NULL
)
1041 # endif /* __APPLE__ */
1042 krb5_free_context(KerberosContext
);
1043 #endif /* HAVE_GSSAPI */
1048 * Unload Print Service quota enforcement library (X Server only)
1051 PSQUpdateQuotaProc
= NULL
;
1057 #endif /* HAVE_DLFCN_H */
1058 #endif /* __APPLE__ */
1062 * Remove the fake IRIX lpsched lock file, but only if the existing
1063 * file is not a FIFO which indicates that the real IRIX lpsched is
1067 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1068 if (!S_ISFIFO(statbuf
.st_mode
))
1069 unlink("/var/spool/lp/SCHEDLOCK");
1074 return (!stop_scheduler
);
1079 * 'cupsdClosePipe()' - Close a pipe as necessary.
1083 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1086 * Close file descriptors as needed...
1104 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1107 int /* O - 0 on success, -1 on error */
1108 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1111 * Create the pipe...
1123 * Set the "close on exec" flag on each end of the pipe...
1126 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1137 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1149 * Return 0 indicating success...
1157 * 'cupsdClearString()' - Clear a string.
1161 cupsdClearString(char **s
) /* O - String value */
1172 * 'cupsdHoldSignals()' - Hold child and termination signals.
1176 cupsdHoldSignals(void)
1178 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1179 sigset_t newmask
; /* New POSIX signal mask */
1180 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1190 #elif defined(HAVE_SIGACTION)
1191 sigemptyset(&newmask
);
1192 sigaddset(&newmask
, SIGTERM
);
1193 sigaddset(&newmask
, SIGCHLD
);
1194 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1195 #endif /* HAVE_SIGSET */
1200 * 'cupsdReleaseSignals()' - Release signals for delivery.
1204 cupsdReleaseSignals(void)
1213 #elif defined(HAVE_SIGACTION)
1214 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1215 #endif /* HAVE_SIGSET */
1220 * 'cupsdSetString()' - Set a string value.
1224 cupsdSetString(char **s
, /* O - New string */
1225 const char *v
) /* I - String value */
1234 *s
= _cupsStrAlloc(v
);
1241 * 'cupsdSetStringf()' - Set a formatted string value.
1245 cupsdSetStringf(char **s
, /* O - New string */
1246 const char *f
, /* I - Printf-style format string */
1247 ...) /* I - Additional args as needed */
1249 char v
[4096]; /* Formatting string value */
1250 va_list ap
; /* Argument pointer */
1251 char *olds
; /* Old string */
1262 vsnprintf(v
, sizeof(v
), f
, ap
);
1265 *s
= _cupsStrAlloc(v
);
1277 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1281 launchd_checkin(void)
1283 int i
, /* Looping var */
1284 count
, /* Numebr of listeners */
1285 portnum
; /* Port number */
1286 launch_data_t ld_msg
, /* Launch data message */
1287 ld_resp
, /* Launch data response */
1288 ld_array
, /* Launch data array */
1289 ld_sockets
, /* Launch data sockets dictionary */
1290 tmp
; /* Launch data */
1291 cupsd_listener_t
*lis
; /* Listeners array */
1292 http_addr_t addr
; /* Address variable */
1293 socklen_t addrlen
; /* Length of address */
1294 int fd
; /* File descriptor */
1295 char s
[256]; /* String addresss */
1298 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1301 * Check-in with launchd...
1304 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1305 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1307 cupsdLogMessage(CUPSD_LOG_ERROR
,
1308 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1313 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1315 errno
= launch_data_get_errno(ld_resp
);
1316 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1322 * Get the sockets dictionary...
1325 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1327 cupsdLogMessage(CUPSD_LOG_ERROR
,
1328 "launchd_checkin: No sockets found to answer requests on!");
1333 * Get the array of listener sockets...
1336 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1338 cupsdLogMessage(CUPSD_LOG_ERROR
,
1339 "launchd_checkin: No sockets found to answer requests on!");
1344 * Add listening fd(s) to the Listener array...
1347 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1349 count
= launch_data_array_get_count(ld_array
);
1351 for (i
= 0; i
< count
; i
++)
1354 * Get the launchd file descriptor and address...
1357 tmp
= launch_data_array_get_index(ld_array
, i
);
1358 fd
= launch_data_get_fd(tmp
);
1359 addrlen
= sizeof(addr
);
1361 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1363 cupsdLogMessage(CUPSD_LOG_ERROR
,
1364 "launchd_checkin: Unable to get local address - %s",
1370 * Try to match the launchd socket address to one of the listeners...
1373 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1375 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1376 if (httpAddrEqual(&lis
->address
, &addr
))
1380 * Add a new listener If there's no match...
1385 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1386 "launchd_checkin: Matched existing listener %s with fd %d...",
1387 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1391 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1392 "launchd_checkin: Adding new listener %s with fd %d...",
1393 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1395 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1397 cupsdLogMessage(CUPSD_LOG_ERROR
,
1398 "launchd_checkin: Unable to allocate listener - %s.",
1403 cupsArrayAdd(Listeners
, lis
);
1405 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1414 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1415 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1417 # endif /* AF_INET6 */
1418 if (lis
->address
.addr
.sa_family
== AF_INET
)
1419 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1422 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1423 # endif /* HAVE_SSL */
1427 launch_data_free(ld_msg
);
1428 launch_data_free(ld_resp
);
1433 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1437 launchd_checkout(void)
1439 int fd
; /* File descriptor */
1443 * Create or remove the launchd KeepAlive file based on whether
1444 * there are active jobs, polling, browsing for remote printers or
1445 * shared printers to advertise...
1448 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1450 (BrowseRemoteProtocols
||
1451 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1453 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1454 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1456 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1461 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1462 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1464 unlink(CUPS_KEEPALIVE
);
1467 #endif /* HAVE_LAUNCHD */
1471 * 'parent_handler()' - Catch USR1/CHLD signals...
1475 parent_handler(int sig
) /* I - Signal */
1478 * Store the signal we got from the OS and return...
1481 parent_signal
= sig
;
1486 * 'process_children()' - Process all dead children...
1490 process_children(void)
1492 int status
; /* Exit status of child */
1493 int pid
; /* Process ID of child */
1494 cupsd_job_t
*job
; /* Current job */
1495 int i
; /* Looping var */
1496 char name
[1024]; /* Process name */
1499 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1502 * Reset the dead_children flag...
1508 * Collect the exit status of some children...
1512 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1513 #elif defined(HAVE_WAIT3)
1514 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1516 if ((pid
= wait(&status
)) > 0)
1517 #endif /* HAVE_WAITPID */
1520 * Ignore SIGTERM errors - that comes when a job is canceled...
1523 cupsdFinishProcess(pid
, name
, sizeof(name
));
1525 if (status
== SIGTERM
)
1530 if (WIFEXITED(status
))
1531 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1532 pid
, name
, WEXITSTATUS(status
));
1534 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1535 pid
, name
, WTERMSIG(status
));
1537 if (LogLevel
< CUPSD_LOG_DEBUG
)
1538 cupsdLogMessage(CUPSD_LOG_INFO
,
1539 "Hint: Try setting the LogLevel to \"debug\" to find "
1543 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1547 * Delete certificates for CGI processes...
1551 cupsdDeleteCert(pid
);
1554 * Lookup the PID in the jobs list...
1557 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1559 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1560 if (job
->state_value
== IPP_JOB_PROCESSING
)
1562 for (i
= 0; job
->filters
[i
]; i
++)
1563 if (job
->filters
[i
] == pid
)
1566 if (job
->filters
[i
] || job
->backend
== pid
)
1569 * OK, this process has gone away; what's left?
1572 if (job
->filters
[i
])
1573 job
->filters
[i
] = -pid
;
1575 job
->backend
= -pid
;
1577 if (status
&& job
->status
>= 0)
1580 * An error occurred; save the exit status so we know to stop
1581 * the printer or cancel the job when all of the filters finish...
1583 * A negative status indicates that the backend failed and the
1584 * printer needs to be stopped.
1587 if (job
->filters
[i
])
1588 job
->status
= status
; /* Filter failed */
1590 job
->status
= -status
; /* Backend failed */
1592 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
))
1594 snprintf(job
->printer
->state_message
,
1595 sizeof(job
->printer
->state_message
), "%s failed", name
);
1596 cupsdAddPrinterHistory(job
->printer
);
1601 * If this is not the last file in a job, see if all of the
1602 * filters are done, and if so move to the next file.
1605 if (job
->current_file
< job
->num_files
)
1607 for (i
= 0; job
->filters
[i
] < 0; i
++);
1609 if (!job
->filters
[i
])
1612 * Process the next file...
1615 cupsdFinishJob(job
);
1626 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1630 sigchld_handler(int sig
) /* I - Signal number */
1635 * Flag that we have dead children...
1641 * Reset the signal handler as needed...
1644 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1645 signal(SIGCLD
, sigchld_handler
);
1646 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1651 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1655 sighup_handler(int sig
) /* I - Signal number */
1659 NeedReload
= RELOAD_ALL
;
1660 ReloadTime
= time(NULL
);
1662 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1663 signal(SIGHUP
, sighup_handler
);
1664 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1669 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1673 sigterm_handler(int sig
) /* I - Signal */
1675 (void)sig
; /* remove compiler warnings... */
1678 * Flag that we should stop and return...
1686 * 'select_timeout()' - Calculate the select timeout value.
1690 static long /* O - Number of seconds */
1691 select_timeout(int fds
) /* I - Number of descriptors returned */
1693 long timeout
; /* Timeout for select */
1694 time_t now
; /* Current time */
1695 cupsd_client_t
*con
; /* Client information */
1696 cupsd_printer_t
*p
; /* Printer information */
1697 cupsd_job_t
*job
; /* Job information */
1698 cupsd_subscription_t
*sub
; /* Subscription information */
1699 const char *why
; /* Debugging aid */
1703 * Check to see if any of the clients have pending data to be
1704 * processed; if so, the timeout should be 0...
1707 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1709 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1710 if (con
->http
.used
> 0)
1714 * If select has been active in the last second (fds > 0) or we have
1715 * many resources in use then don't bother trying to optimize the
1716 * timeout, just make it 1 second.
1719 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1723 * Otherwise, check all of the possible events that we need to wake for...
1727 timeout
= now
+ 86400; /* 86400 == 1 day */
1731 * Check whether we are accepting new connections...
1734 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1735 ListeningPaused
< timeout
)
1737 if (ListeningPaused
<= now
)
1740 timeout
= ListeningPaused
;
1742 why
= "resume listening";
1746 * Check the activity and close old clients...
1749 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1751 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1752 if ((con
->http
.activity
+ Timeout
) < timeout
)
1754 timeout
= con
->http
.activity
+ Timeout
;
1755 why
= "timeout a client connection";
1759 * Update the browse list as needed...
1762 if (Browsing
&& BrowseLocalProtocols
)
1765 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1767 timeout
= BrowseSLPRefresh
;
1768 why
= "update SLP browsing";
1770 #endif /* HAVE_LIBSLP */
1773 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1775 timeout
= BrowseLDAPRefresh
;
1776 why
= "update LDAP browsing";
1778 #endif /* HAVE_LDAP */
1780 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1782 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1784 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1786 if (p
->type
& CUPS_PRINTER_REMOTE
)
1788 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1790 timeout
= p
->browse_time
+ BrowseTimeout
;
1791 why
= "browse timeout a printer";
1794 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1796 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1798 timeout
= p
->browse_time
+ BrowseInterval
;
1799 why
= "send browse update";
1807 * Check for any active jobs...
1810 if (timeout
> (now
+ 10) && ActiveJobs
)
1812 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1814 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1815 if (job
->state_value
<= IPP_JOB_PROCESSING
)
1818 why
= "process active jobs";
1823 #ifdef HAVE_MALLINFO
1825 * Log memory usage every minute...
1828 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1830 timeout
= mallinfo_time
+ 60;
1831 why
= "display memory usage";
1833 #endif /* HAVE_MALLINFO */
1836 * Expire subscriptions as needed...
1839 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1841 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1842 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1844 timeout
= sub
->expire
;
1845 why
= "expire subscription";
1849 * Adjust from absolute to relative time. If p->browse_time above
1850 * was 0 then we can end up with a negative value here, so check.
1851 * We add 1 second to the timeout since events occur after the
1852 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1853 * to avoid select() timeout limits present on some operating
1857 timeout
= timeout
- now
+ 1;
1861 else if (timeout
> 86400)
1865 * Log and return the timeout value...
1868 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1876 * 'usage()' - Show scheduler usage.
1880 usage(int status
) /* O - Exit status */
1882 _cupsLangPuts(status
? stderr
: stdout
,
1883 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1885 "-c config-file Load alternate configuration file\n"
1886 "-f Run in the foreground\n"
1887 "-F Run in the foreground but detach\n"
1888 "-h Show this usage message\n"
1889 "-l Run cupsd from launchd(8)\n"));
1895 * End of "$Id: main.c 6915 2007-09-05 21:05:17Z mike $".