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-2008 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 run_as_child
= 0;
151 /* Needed for Mac OS X fork/exec */
153 time_t netif_time
= 0; /* Time since last network update */
154 #endif /* __APPLE__ */
156 int launchd_idle_exit
;
157 /* Idle exit on select timeout? */
158 #endif /* HAVE_LAUNCHD */
163 * Check for setuid invocation, which we do not support!
166 if (getuid() != geteuid())
168 fputs("cupsd: Cannot run as a setuid program!\n", stderr
);
171 #endif /* HAVE_GETEUID */
174 * Check for command-line arguments...
180 if (getenv("CUPSD_LAUNCHD"))
185 #endif /* HAVE_LAUNCHD */
187 for (i
= 1; i
< argc
; i
++)
188 if (argv
[i
][0] == '-')
189 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
193 case 'C' : /* Run as child with config file */
196 #endif /* __APPLE__ */
198 case 'c' : /* Configuration file */
202 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
203 "after \"-c\" option!\n"));
207 if (argv
[i
][0] == '/')
210 * Absolute directory...
213 cupsdSetString(&ConfigurationFile
, argv
[i
]);
218 * Relative directory...
221 char *current
; /* Current directory */
225 * Allocate a buffer for the current working directory to
226 * reduce run-time stack usage; this approximates the
227 * behavior of some implementations of getcwd() when they
228 * are passed a NULL pointer.
231 if ((current
= malloc(1024)) == NULL
)
233 _cupsLangPuts(stderr
,
234 _("cupsd: Unable to get current directory!\n"));
238 if (!getcwd(current
, 1024))
240 _cupsLangPuts(stderr
,
241 _("cupsd: Unable to get current directory!\n"));
246 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
251 case 'f' : /* Run in foreground... */
255 case 'F' : /* Run in foreground, but disconnect from terminal... */
259 case 'h' : /* Show usage/help */
263 case 'l' : /* Started by launchd... */
268 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
269 "in, running in normal mode.\n"));
271 #endif /* HAVE_LAUNCHD */
274 case 'p' : /* Stop immediately for profiling */
275 puts("Warning: -p option is for internal testing use only!");
280 case 't' : /* Test the cupsd.conf file... */
285 default : /* Unknown option */
286 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
287 "aborting!\n"), *opt
);
293 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
298 if (!ConfigurationFile
)
299 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
302 * If the user hasn't specified "-f", run in the background...
308 * Setup signal handlers for the parent...
311 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
312 sigset(SIGUSR1
, parent_handler
);
313 sigset(SIGCHLD
, parent_handler
);
315 sigset(SIGHUP
, SIG_IGN
);
316 #elif defined(HAVE_SIGACTION)
317 memset(&action
, 0, sizeof(action
));
318 sigemptyset(&action
.sa_mask
);
319 sigaddset(&action
.sa_mask
, SIGUSR1
);
320 action
.sa_handler
= parent_handler
;
321 sigaction(SIGUSR1
, &action
, NULL
);
322 sigaction(SIGCHLD
, &action
, NULL
);
324 sigemptyset(&action
.sa_mask
);
325 action
.sa_handler
= SIG_IGN
;
326 sigaction(SIGHUP
, &action
, NULL
);
328 signal(SIGUSR1
, parent_handler
);
329 signal(SIGCLD
, parent_handler
);
331 signal(SIGHUP
, SIG_IGN
);
332 #endif /* HAVE_SIGSET */
337 * OK, wait for the child to startup and send us SIGUSR1 or to crash
338 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
339 * might be sent by the init script to restart the scheduler...
342 for (; parent_signal
== 0;)
345 if (parent_signal
== SIGUSR1
)
353 else if (WIFEXITED(i
))
355 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
361 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
368 * Since CoreFoundation has an overly-agressive check for whether a
369 * process has forked but not exec'd (whether CF has been called or
370 * not...), we now have to exec ourselves with the "-f" option to
371 * eliminate their bogus warning messages.
374 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
376 #endif /* __APPLE__ */
382 * Make sure we aren't tying up any filesystems...
389 * Disable core dumps...
392 getrlimit(RLIMIT_CORE
, &limit
);
394 setrlimit(RLIMIT_CORE
, &limit
);
397 * Disconnect from the controlling terminal...
403 * Close all open files...
406 getrlimit(RLIMIT_NOFILE
, &limit
);
408 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
412 * Redirect stdin/out/err to /dev/null...
415 open("/dev/null", O_RDONLY
);
416 open("/dev/null", O_WRONLY
);
417 open("/dev/null", O_WRONLY
);
422 * Set the timezone info...
428 setlocale(LC_TIME
, "");
432 * Set the maximum number of files...
435 getrlimit(RLIMIT_NOFILE
, &limit
);
437 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
438 if (limit
.rlim_max
> FD_SETSIZE
)
441 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
443 if (limit
.rlim_max
== RLIM_INFINITY
)
446 #endif /* RLIM_INFINITY */
447 MaxFDs
= limit
.rlim_max
;
449 limit
.rlim_cur
= MaxFDs
;
451 setrlimit(RLIMIT_NOFILE
, &limit
);
456 * Read configuration...
459 if (!cupsdReadConfiguration())
462 printf("%s contains errors\n", ConfigurationFile
);
464 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
468 else if (TestConfigFile
)
470 printf("%s is OK\n", ConfigurationFile
);
474 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
477 * Clean out the temporary directory...
480 cups_dir_t
*dir
; /* Temporary directory */
481 cups_dentry_t
*dent
; /* Directory entry */
482 char tempfile
[1024]; /* Temporary filename */
485 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
487 cupsdLogMessage(CUPSD_LOG_INFO
,
488 "Cleaning out old temporary files in \"%s\"...", TempDir
);
490 while ((dent
= cupsDirRead(dir
)) != NULL
)
492 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
494 if (cupsdRemoveFile(tempfile
))
495 cupsdLogMessage(CUPSD_LOG_ERROR
,
496 "Unable to remove temporary file \"%s\" - %s",
497 tempfile
, strerror(errno
));
499 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
506 cupsdLogMessage(CUPSD_LOG_ERROR
,
507 "Unable to open temporary directory \"%s\" - %s",
508 TempDir
, strerror(errno
));
515 * If we were started by launchd get the listen sockets file descriptors...
520 #endif /* HAVE_LAUNCHD */
522 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
524 * Load Print Service quota enforcement library (X Server only)
527 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
530 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
531 #endif /* __APPLE__ && HAVE_DLFCN_H */
536 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
540 if (krb5_init_context
!= NULL
)
541 # endif /* __APPLE__ */
544 * Setup a Kerberos context for the scheduler to use...
547 if (krb5_init_context(&KerberosContext
))
549 KerberosContext
= NULL
;
551 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
553 #endif /* HAVE_GSSAPI */
556 * Startup the server...
562 * Catch hangup and child signals and ignore broken pipes...
565 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
566 sigset(SIGCHLD
, sigchld_handler
);
567 sigset(SIGHUP
, sighup_handler
);
568 sigset(SIGPIPE
, SIG_IGN
);
569 sigset(SIGTERM
, sigterm_handler
);
570 #elif defined(HAVE_SIGACTION)
571 memset(&action
, 0, sizeof(action
));
573 sigemptyset(&action
.sa_mask
);
574 sigaddset(&action
.sa_mask
, SIGTERM
);
575 sigaddset(&action
.sa_mask
, SIGCHLD
);
576 action
.sa_handler
= sigchld_handler
;
577 sigaction(SIGCHLD
, &action
, NULL
);
579 sigemptyset(&action
.sa_mask
);
580 sigaddset(&action
.sa_mask
, SIGHUP
);
581 action
.sa_handler
= sighup_handler
;
582 sigaction(SIGHUP
, &action
, NULL
);
584 sigemptyset(&action
.sa_mask
);
585 action
.sa_handler
= SIG_IGN
;
586 sigaction(SIGPIPE
, &action
, NULL
);
588 sigemptyset(&action
.sa_mask
);
589 sigaddset(&action
.sa_mask
, SIGTERM
);
590 sigaddset(&action
.sa_mask
, SIGCHLD
);
591 action
.sa_handler
= sigterm_handler
;
592 sigaction(SIGTERM
, &action
, NULL
);
594 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
595 signal(SIGHUP
, sighup_handler
);
596 signal(SIGPIPE
, SIG_IGN
);
597 signal(SIGTERM
, sigterm_handler
);
598 #endif /* HAVE_SIGSET */
602 * Try to create a fake lpsched lock file if one is not already there.
603 * Some Adobe applications need it under IRIX in order to enable
607 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
609 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
610 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
615 fchmod(cupsFileNumber(fp
), 0644);
616 fchown(cupsFileNumber(fp
), User
, Group
);
623 * Initialize authentication certificates...
629 * If we are running in the background, signal the parent process that
630 * we are up and running...
634 if (!fg
|| run_as_child
)
637 #endif /* __APPLE__ */
640 * Send a signal to the parent process, but only if the parent is
641 * not PID 1 (init). This avoids accidentally shutting down the
642 * system on OpenBSD if you CTRL-C the server before it is up...
645 i
= getppid(); /* Save parent PID to avoid race condition */
653 * Start power management framework...
656 cupsdStartSystemMonitor();
657 #endif /* __APPLE__ */
660 * Start any pending print jobs...
670 browse_time
= time(NULL
);
671 senddoc_time
= time(NULL
);
672 expire_time
= time(NULL
);
675 while (!stop_scheduler
)
678 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
679 "main: Top of loop, dead_children=%d, NeedReload=%d",
680 dead_children
, NeedReload
);
684 * Check if there are dead children to handle...
691 * Check if we need to load the server configuration file...
697 * Close any idle clients...
700 if (cupsArrayCount(Clients
) > 0)
702 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
704 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
705 if (con
->http
.state
== HTTP_WAITING
)
706 cupsdCloseClient(con
);
708 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
710 cupsdPauseListening();
714 * Check for any active jobs...
717 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
719 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
720 if (job
->state_value
== IPP_JOB_PROCESSING
)
724 * Restart if all clients are closed and all jobs finished, or
725 * if the reload timeout has elapsed...
728 if ((cupsArrayCount(Clients
) == 0 &&
729 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
730 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
733 * Shutdown the server...
739 * Read configuration...
742 if (!cupsdReadConfiguration())
744 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
753 * If we were started by launchd get the listen sockets file descriptors...
758 #endif /* HAVE_LAUNCHD */
761 * Startup the server...
769 * Check for available input or ready output. If cupsdDoSelect()
770 * returns 0 or -1, something bad happened and we should exit
773 * Note that we at least have one listening socket open at all
777 timeout
= select_timeout(fds
);
781 * If no other work is scheduled and we're being controlled by
782 * launchd then timeout after 'LaunchdTimeout' seconds of
786 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
787 !cupsArrayCount(ActiveJobs
) &&
789 (!BrowseRemoteProtocols
&&
790 (!NumBrowsers
|| !BrowseLocalProtocols
||
791 cupsArrayCount(Printers
) == 0))))
793 timeout
= LaunchdTimeout
;
794 launchd_idle_exit
= 1;
797 launchd_idle_exit
= 0;
798 #endif /* HAVE_LAUNCHD */
800 if ((fds
= cupsdDoSelect(timeout
)) < 0)
803 * Got an error from select!
807 cupsd_printer_t
*p
; /* Current printer */
808 #endif /* HAVE_DNSSD */
811 if (errno
== EINTR
) /* Just interrupted by a signal */
815 * Log all sorts of debug info to help track down the problem.
818 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
821 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
823 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
824 cupsdLogMessage(CUPSD_LOG_EMERG
,
825 "Clients[%d] = %d, file = %d, state = %d",
826 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
828 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
830 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
831 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
833 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
835 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
838 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
840 #endif /* __APPLE__ */
842 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
844 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
845 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
847 job
->status_buffer
? job
->status_buffer
->fd
: -1,
848 job
->print_pipes
[0], job
->print_pipes
[1],
849 job
->back_pipes
[0], job
->back_pipes
[1]);
852 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
854 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
855 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] %d", p
->name
,
857 #endif /* HAVE_DNSSD */
862 current_time
= time(NULL
);
866 * Update the network interfaces once a minute...
869 if ((current_time
- netif_time
) >= 60)
871 netif_time
= current_time
;
874 #endif /* !__APPLE__ */
878 * If no other work was scheduled and we're being controlled by launchd
879 * then timeout after 'LaunchdTimeout' seconds of inactivity...
882 if (!fds
&& launchd_idle_exit
)
884 cupsdLogMessage(CUPSD_LOG_INFO
,
885 "Printer sharing is off and there are no jobs pending, "
886 "will restart on demand.");
890 #endif /* HAVE_LAUNCHD */
893 * Resume listening for new connections as needed...
896 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
897 cupsArrayCount(Clients
) < MaxClients
)
898 cupsdResumeListening();
901 * Expire subscriptions and unload completed jobs as needed...
904 if (current_time
> expire_time
)
906 if (cupsArrayCount(Subscriptions
) > 0)
907 cupsdExpireSubscriptions(NULL
, NULL
);
909 cupsdUnloadCompletedJobs();
911 expire_time
= current_time
;
915 * Update the browse list as needed...
921 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
922 BrowseSLPRefresh
<= current_time
)
923 cupsdUpdateSLPBrowse();
924 #endif /* HAVE_LIBSLP */
927 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
928 BrowseLDAPRefresh
<= current_time
)
929 cupsdUpdateLDAPBrowse();
930 #endif /* HAVE_LDAP */
933 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
935 cupsdSendBrowseList();
936 browse_time
= current_time
;
940 * Update the root certificate once every 5 minutes if we have client
944 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
945 !RunUser
&& cupsArrayCount(Clients
))
948 * Update the root certificate...
952 cupsdAddCert(0, "root");
956 * Check for new data on the client sockets...
959 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
961 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
964 * Process pending data in the input buffer...
969 cupsdReadClient(con
);
974 * Check the activity and close old clients...
977 activity
= current_time
- Timeout
;
978 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
980 cupsdLogMessage(CUPSD_LOG_DEBUG
,
981 "Closing client %d after %d seconds of inactivity...",
982 con
->http
.fd
, Timeout
);
984 cupsdCloseClient(con
);
990 * Update any pending multi-file documents...
993 if ((current_time
- senddoc_time
) >= 10)
996 senddoc_time
= current_time
;
1000 * Log memory usage every minute...
1003 if ((current_time
- mallinfo_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG2
)
1005 #ifdef HAVE_MALLINFO
1006 struct mallinfo mem
; /* Malloc information */
1010 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1011 "mallinfo: arena = %d, used = %d, free = %d\n",
1012 mem
.arena
, mem
.usmblks
+ mem
.uordblks
,
1013 mem
.fsmblks
+ mem
.fordblks
);
1014 #endif /* HAVE_MALLINFO */
1016 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1017 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1018 "stringpool: " CUPS_LLFMT
" strings, "
1019 CUPS_LLFMT
" allocated, " CUPS_LLFMT
" total bytes",
1020 CUPS_LLCAST string_count
, CUPS_LLCAST alloc_bytes
,
1021 CUPS_LLCAST total_bytes
);
1023 mallinfo_time
= current_time
;
1027 * Handle OS-specific event notification for any events that have
1028 * accumulated. Don't send these more than once a second...
1033 #ifdef HAVE_NOTIFY_POST
1034 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1035 CUPSD_EVENT_PRINTER_DELETED
|
1036 CUPSD_EVENT_PRINTER_MODIFIED
))
1038 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1039 "notify_post(\"com.apple.printerListChange\")");
1040 notify_post("com.apple.printerListChange");
1043 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1045 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1046 "notify_post(\"com.apple.printerHistoryChange\")");
1047 notify_post("com.apple.printerHistoryChange");
1050 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1051 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1052 CUPSD_EVENT_JOB_PROGRESS
))
1054 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1055 "notify_post(\"com.apple.jobChange\")");
1056 notify_post("com.apple.jobChange");
1058 #endif /* HAVE_NOTIFY_POST */
1061 * Reset the accumulated events...
1064 LastEvent
= CUPSD_EVENT_NONE
;
1069 * Log a message based on what happened...
1073 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1075 cupsdLogMessage(CUPSD_LOG_ERROR
,
1076 "Scheduler shutting down due to program error.");
1079 * Close all network clients...
1086 * Update the launchd KeepAlive file as needed...
1091 #endif /* HAVE_LAUNCHD */
1101 * Stop monitoring system event monitoring...
1104 cupsdStopSystemMonitor();
1105 #endif /* __APPLE__ */
1109 * Free the scheduler's Kerberos context...
1114 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1118 if (krb5_init_context
!= NULL
)
1119 # endif /* __APPLE__ */
1120 if (KerberosContext
)
1121 krb5_free_context(KerberosContext
);
1122 #endif /* HAVE_GSSAPI */
1127 * Unload Print Service quota enforcement library (X Server only)
1130 PSQUpdateQuotaProc
= NULL
;
1136 #endif /* HAVE_DLFCN_H */
1137 #endif /* __APPLE__ */
1141 * Remove the fake IRIX lpsched lock file, but only if the existing
1142 * file is not a FIFO which indicates that the real IRIX lpsched is
1146 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1147 if (!S_ISFIFO(statbuf
.st_mode
))
1148 unlink("/var/spool/lp/SCHEDLOCK");
1153 return (!stop_scheduler
);
1158 * 'cupsdClosePipe()' - Close a pipe as necessary.
1162 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1165 * Close file descriptors as needed...
1183 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1186 int /* O - 0 on success, -1 on error */
1187 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1190 * Create the pipe...
1202 * Set the "close on exec" flag on each end of the pipe...
1205 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1216 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1228 * Return 0 indicating success...
1236 * 'cupsdClearString()' - Clear a string.
1240 cupsdClearString(char **s
) /* O - String value */
1251 * 'cupsdHoldSignals()' - Hold child and termination signals.
1255 cupsdHoldSignals(void)
1257 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1258 sigset_t newmask
; /* New POSIX signal mask */
1259 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1269 #elif defined(HAVE_SIGACTION)
1270 sigemptyset(&newmask
);
1271 sigaddset(&newmask
, SIGTERM
);
1272 sigaddset(&newmask
, SIGCHLD
);
1273 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1274 #endif /* HAVE_SIGSET */
1279 * 'cupsdReleaseSignals()' - Release signals for delivery.
1283 cupsdReleaseSignals(void)
1292 #elif defined(HAVE_SIGACTION)
1293 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1294 #endif /* HAVE_SIGSET */
1299 * 'cupsdSetString()' - Set a string value.
1303 cupsdSetString(char **s
, /* O - New string */
1304 const char *v
) /* I - String value */
1313 *s
= _cupsStrAlloc(v
);
1320 * 'cupsdSetStringf()' - Set a formatted string value.
1324 cupsdSetStringf(char **s
, /* O - New string */
1325 const char *f
, /* I - Printf-style format string */
1326 ...) /* I - Additional args as needed */
1328 char v
[4096]; /* Formatting string value */
1329 va_list ap
; /* Argument pointer */
1330 char *olds
; /* Old string */
1341 vsnprintf(v
, sizeof(v
), f
, ap
);
1344 *s
= _cupsStrAlloc(v
);
1356 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1360 launchd_checkin(void)
1362 int i
, /* Looping var */
1363 count
, /* Numebr of listeners */
1364 portnum
; /* Port number */
1365 launch_data_t ld_msg
, /* Launch data message */
1366 ld_resp
, /* Launch data response */
1367 ld_array
, /* Launch data array */
1368 ld_sockets
, /* Launch data sockets dictionary */
1369 tmp
; /* Launch data */
1370 cupsd_listener_t
*lis
; /* Listeners array */
1371 http_addr_t addr
; /* Address variable */
1372 socklen_t addrlen
; /* Length of address */
1373 int fd
; /* File descriptor */
1374 char s
[256]; /* String addresss */
1377 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1380 * Check-in with launchd...
1383 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1384 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1386 cupsdLogMessage(CUPSD_LOG_ERROR
,
1387 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1392 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1394 errno
= launch_data_get_errno(ld_resp
);
1395 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1401 * Get the sockets dictionary...
1404 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1406 cupsdLogMessage(CUPSD_LOG_ERROR
,
1407 "launchd_checkin: No sockets found to answer requests on!");
1412 * Get the array of listener sockets...
1415 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1417 cupsdLogMessage(CUPSD_LOG_ERROR
,
1418 "launchd_checkin: No sockets found to answer requests on!");
1423 * Add listening fd(s) to the Listener array...
1426 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1428 count
= launch_data_array_get_count(ld_array
);
1430 for (i
= 0; i
< count
; i
++)
1433 * Get the launchd file descriptor and address...
1436 tmp
= launch_data_array_get_index(ld_array
, i
);
1437 fd
= launch_data_get_fd(tmp
);
1438 addrlen
= sizeof(addr
);
1440 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1442 cupsdLogMessage(CUPSD_LOG_ERROR
,
1443 "launchd_checkin: Unable to get local address - %s",
1449 * Try to match the launchd socket address to one of the listeners...
1452 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1454 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1455 if (httpAddrEqual(&lis
->address
, &addr
))
1459 * Add a new listener If there's no match...
1464 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1465 "launchd_checkin: Matched existing listener %s with fd %d...",
1466 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1470 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1471 "launchd_checkin: Adding new listener %s with fd %d...",
1472 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1474 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1476 cupsdLogMessage(CUPSD_LOG_ERROR
,
1477 "launchd_checkin: Unable to allocate listener - %s.",
1482 cupsArrayAdd(Listeners
, lis
);
1484 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1493 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1494 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1496 # endif /* AF_INET6 */
1497 if (lis
->address
.addr
.sa_family
== AF_INET
)
1498 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1501 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1502 # endif /* HAVE_SSL */
1506 launch_data_free(ld_msg
);
1507 launch_data_free(ld_resp
);
1512 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1516 launchd_checkout(void)
1518 int fd
; /* File descriptor */
1522 * Create or remove the launchd KeepAlive file based on whether
1523 * there are active jobs, polling, browsing for remote printers or
1524 * shared printers to advertise...
1527 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1529 (BrowseRemoteProtocols
||
1530 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1532 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1533 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1535 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1540 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1541 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1543 unlink(CUPS_KEEPALIVE
);
1546 #endif /* HAVE_LAUNCHD */
1550 * 'parent_handler()' - Catch USR1/CHLD signals...
1554 parent_handler(int sig
) /* I - Signal */
1557 * Store the signal we got from the OS and return...
1560 parent_signal
= sig
;
1565 * 'process_children()' - Process all dead children...
1569 process_children(void)
1571 int status
; /* Exit status of child */
1572 int pid
; /* Process ID of child */
1573 cupsd_job_t
*job
; /* Current job */
1574 int i
; /* Looping var */
1575 char name
[1024]; /* Process name */
1578 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1581 * Reset the dead_children flag...
1587 * Collect the exit status of some children...
1591 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1592 #elif defined(HAVE_WAIT3)
1593 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1595 if ((pid
= wait(&status
)) > 0)
1596 #endif /* HAVE_WAITPID */
1599 * Ignore SIGTERM errors - that comes when a job is canceled...
1602 cupsdFinishProcess(pid
, name
, sizeof(name
));
1604 if (status
== SIGTERM
)
1609 if (WIFEXITED(status
))
1610 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1611 pid
, name
, WEXITSTATUS(status
));
1613 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1614 pid
, name
, WTERMSIG(status
));
1616 if (LogLevel
< CUPSD_LOG_DEBUG
)
1617 cupsdLogMessage(CUPSD_LOG_INFO
,
1618 "Hint: Try setting the LogLevel to \"debug\" to find "
1622 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1626 * Delete certificates for CGI processes...
1630 cupsdDeleteCert(pid
);
1633 * Lookup the PID in the jobs list...
1636 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1638 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1639 if (job
->state_value
== IPP_JOB_PROCESSING
)
1641 for (i
= 0; job
->filters
[i
]; i
++)
1642 if (job
->filters
[i
] == pid
)
1645 if (job
->filters
[i
] || job
->backend
== pid
)
1648 * OK, this process has gone away; what's left?
1651 if (job
->filters
[i
])
1652 job
->filters
[i
] = -pid
;
1654 job
->backend
= -pid
;
1656 if (status
&& job
->status
>= 0)
1659 * An error occurred; save the exit status so we know to stop
1660 * the printer or cancel the job when all of the filters finish...
1662 * A negative status indicates that the backend failed and the
1663 * printer needs to be stopped.
1666 if (job
->filters
[i
])
1667 job
->status
= status
; /* Filter failed */
1669 job
->status
= -status
; /* Backend failed */
1671 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
))
1673 snprintf(job
->printer
->state_message
,
1674 sizeof(job
->printer
->state_message
), "%s failed", name
);
1675 cupsdAddPrinterHistory(job
->printer
);
1680 * If this is not the last file in a job, see if all of the
1681 * filters are done, and if so move to the next file.
1684 if (job
->current_file
< job
->num_files
)
1686 for (i
= 0; job
->filters
[i
] < 0; i
++);
1688 if (!job
->filters
[i
])
1691 * Process the next file...
1694 cupsdFinishJob(job
);
1705 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1709 sigchld_handler(int sig
) /* I - Signal number */
1714 * Flag that we have dead children...
1720 * Reset the signal handler as needed...
1723 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1724 signal(SIGCLD
, sigchld_handler
);
1725 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1730 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1734 sighup_handler(int sig
) /* I - Signal number */
1738 NeedReload
= RELOAD_ALL
;
1739 ReloadTime
= time(NULL
);
1741 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1742 signal(SIGHUP
, sighup_handler
);
1743 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1748 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1752 sigterm_handler(int sig
) /* I - Signal */
1754 (void)sig
; /* remove compiler warnings... */
1757 * Flag that we should stop and return...
1765 * 'select_timeout()' - Calculate the select timeout value.
1769 static long /* O - Number of seconds */
1770 select_timeout(int fds
) /* I - Number of descriptors returned */
1772 long timeout
; /* Timeout for select */
1773 time_t now
; /* Current time */
1774 cupsd_client_t
*con
; /* Client information */
1775 cupsd_printer_t
*p
; /* Printer information */
1776 cupsd_job_t
*job
; /* Job information */
1777 cupsd_subscription_t
*sub
; /* Subscription information */
1778 const char *why
; /* Debugging aid */
1782 * Check to see if any of the clients have pending data to be
1783 * processed; if so, the timeout should be 0...
1786 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1788 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1789 if (con
->http
.used
> 0)
1793 * If select has been active in the last second (fds > 0) or we have
1794 * many resources in use then don't bother trying to optimize the
1795 * timeout, just make it 1 second.
1798 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1802 * Otherwise, check all of the possible events that we need to wake for...
1806 timeout
= now
+ 86400; /* 86400 == 1 day */
1810 * Check whether we are accepting new connections...
1813 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1814 ListeningPaused
< timeout
)
1816 if (ListeningPaused
<= now
)
1819 timeout
= ListeningPaused
;
1821 why
= "resume listening";
1825 * Check the activity and close old clients...
1828 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1830 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1831 if ((con
->http
.activity
+ Timeout
) < timeout
)
1833 timeout
= con
->http
.activity
+ Timeout
;
1834 why
= "timeout a client connection";
1838 * Update the browse list as needed...
1841 if (Browsing
&& BrowseLocalProtocols
)
1844 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1846 timeout
= BrowseSLPRefresh
;
1847 why
= "update SLP browsing";
1849 #endif /* HAVE_LIBSLP */
1852 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1854 timeout
= BrowseLDAPRefresh
;
1855 why
= "update LDAP browsing";
1857 #endif /* HAVE_LDAP */
1859 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1861 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1863 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1865 if (p
->type
& CUPS_PRINTER_REMOTE
)
1867 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1869 timeout
= p
->browse_time
+ BrowseTimeout
;
1870 why
= "browse timeout a printer";
1873 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1875 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1877 timeout
= p
->browse_time
+ BrowseInterval
;
1878 why
= "send browse update";
1886 * Check for any active jobs...
1889 if (timeout
> (now
+ 10) && ActiveJobs
)
1891 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1893 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1894 if (job
->state_value
<= IPP_JOB_PROCESSING
)
1897 why
= "process active jobs";
1902 #ifdef HAVE_MALLINFO
1904 * Log memory usage every minute...
1907 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1909 timeout
= mallinfo_time
+ 60;
1910 why
= "display memory usage";
1912 #endif /* HAVE_MALLINFO */
1915 * Expire subscriptions as needed...
1918 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1920 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1921 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1923 timeout
= sub
->expire
;
1924 why
= "expire subscription";
1928 * Adjust from absolute to relative time. If p->browse_time above
1929 * was 0 then we can end up with a negative value here, so check.
1930 * We add 1 second to the timeout since events occur after the
1931 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1932 * to avoid select() timeout limits present on some operating
1936 timeout
= timeout
- now
+ 1;
1940 else if (timeout
> 86400)
1944 * Log and return the timeout value...
1947 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1955 * 'usage()' - Show scheduler usage.
1959 usage(int status
) /* O - Exit status */
1961 _cupsLangPuts(status
? stderr
: stdout
,
1962 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1964 "-c config-file Load alternate configuration file\n"
1965 "-f Run in the foreground\n"
1966 "-F Run in the foreground but detach\n"
1967 "-h Show this usage message\n"
1968 "-l Run cupsd from launchd(8)\n"));
1974 * End of "$Id: main.c 6914 2007-09-05 21:05:04Z mike $".