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 report_time
; /* Malloc/client/job report time */
137 long timeout
; /* Timeout for cupsdDoSelect() */
138 struct rlimit limit
; /* Runtime limit */
139 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
140 struct sigaction action
; /* Actions for POSIX signals */
141 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
143 cups_file_t
*fp
; /* Fake lpsched lock file */
144 struct stat statbuf
; /* Needed for checking lpsched FIFO */
147 int run_as_child
= 0;
148 /* Needed for Mac OS X fork/exec */
150 time_t netif_time
= 0; /* Time since last network update */
151 #endif /* __APPLE__ */
153 int launchd_idle_exit
;
154 /* Idle exit on select timeout? */
155 #endif /* HAVE_LAUNCHD */
160 * Check for setuid invocation, which we do not support!
163 if (getuid() != geteuid())
165 fputs("cupsd: Cannot run as a setuid program!\n", stderr
);
168 #endif /* HAVE_GETEUID */
171 * Check for command-line arguments...
177 if (getenv("CUPSD_LAUNCHD"))
182 #endif /* HAVE_LAUNCHD */
184 for (i
= 1; i
< argc
; i
++)
185 if (argv
[i
][0] == '-')
186 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
190 case 'C' : /* Run as child with config file */
193 #endif /* __APPLE__ */
195 case 'c' : /* Configuration file */
199 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
200 "after \"-c\" option!\n"));
204 if (argv
[i
][0] == '/')
207 * Absolute directory...
210 cupsdSetString(&ConfigurationFile
, argv
[i
]);
215 * Relative directory...
218 char *current
; /* Current directory */
222 * Allocate a buffer for the current working directory to
223 * reduce run-time stack usage; this approximates the
224 * behavior of some implementations of getcwd() when they
225 * are passed a NULL pointer.
228 if ((current
= malloc(1024)) == NULL
)
230 _cupsLangPuts(stderr
,
231 _("cupsd: Unable to get current directory!\n"));
235 if (!getcwd(current
, 1024))
237 _cupsLangPuts(stderr
,
238 _("cupsd: Unable to get current directory!\n"));
243 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
248 case 'f' : /* Run in foreground... */
252 case 'F' : /* Run in foreground, but disconnect from terminal... */
256 case 'h' : /* Show usage/help */
260 case 'l' : /* Started by launchd... */
265 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
266 "in, running in normal mode.\n"));
268 #endif /* HAVE_LAUNCHD */
271 case 'p' : /* Stop immediately for profiling */
272 puts("Warning: -p option is for internal testing use only!");
277 case 't' : /* Test the cupsd.conf file... */
282 default : /* Unknown option */
283 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
284 "aborting!\n"), *opt
);
290 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
295 if (!ConfigurationFile
)
296 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
299 * If the user hasn't specified "-f", run in the background...
305 * Setup signal handlers for the parent...
308 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
309 sigset(SIGUSR1
, parent_handler
);
310 sigset(SIGCHLD
, parent_handler
);
312 sigset(SIGHUP
, SIG_IGN
);
313 #elif defined(HAVE_SIGACTION)
314 memset(&action
, 0, sizeof(action
));
315 sigemptyset(&action
.sa_mask
);
316 sigaddset(&action
.sa_mask
, SIGUSR1
);
317 action
.sa_handler
= parent_handler
;
318 sigaction(SIGUSR1
, &action
, NULL
);
319 sigaction(SIGCHLD
, &action
, NULL
);
321 sigemptyset(&action
.sa_mask
);
322 action
.sa_handler
= SIG_IGN
;
323 sigaction(SIGHUP
, &action
, NULL
);
325 signal(SIGUSR1
, parent_handler
);
326 signal(SIGCLD
, parent_handler
);
328 signal(SIGHUP
, SIG_IGN
);
329 #endif /* HAVE_SIGSET */
334 * OK, wait for the child to startup and send us SIGUSR1 or to crash
335 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
336 * might be sent by the init script to restart the scheduler...
339 for (; parent_signal
== 0;)
342 if (parent_signal
== SIGUSR1
)
350 else if (WIFEXITED(i
))
352 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
358 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
365 * Since CoreFoundation has an overly-agressive check for whether a
366 * process has forked but not exec'd (whether CF has been called or
367 * not...), we now have to exec ourselves with the "-f" option to
368 * eliminate their bogus warning messages.
371 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
373 #endif /* __APPLE__ */
379 * Make sure we aren't tying up any filesystems...
386 * Disable core dumps...
389 getrlimit(RLIMIT_CORE
, &limit
);
391 setrlimit(RLIMIT_CORE
, &limit
);
394 * Disconnect from the controlling terminal...
400 * Close all open files...
403 getrlimit(RLIMIT_NOFILE
, &limit
);
405 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
409 * Redirect stdin/out/err to /dev/null...
412 open("/dev/null", O_RDONLY
);
413 open("/dev/null", O_WRONLY
);
414 open("/dev/null", O_WRONLY
);
419 * Set the timezone info...
425 setlocale(LC_TIME
, "");
429 * Set the maximum number of files...
432 getrlimit(RLIMIT_NOFILE
, &limit
);
434 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
435 if (limit
.rlim_max
> FD_SETSIZE
)
438 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
440 if (limit
.rlim_max
== RLIM_INFINITY
)
443 #endif /* RLIM_INFINITY */
444 MaxFDs
= limit
.rlim_max
;
446 limit
.rlim_cur
= MaxFDs
;
448 setrlimit(RLIMIT_NOFILE
, &limit
);
453 * Read configuration...
456 if (!cupsdReadConfiguration())
459 printf("%s contains errors\n", ConfigurationFile
);
461 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
465 else if (TestConfigFile
)
467 printf("%s is OK\n", ConfigurationFile
);
471 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
474 * Clean out the temporary directory...
477 cups_dir_t
*dir
; /* Temporary directory */
478 cups_dentry_t
*dent
; /* Directory entry */
479 char tempfile
[1024]; /* Temporary filename */
482 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
484 cupsdLogMessage(CUPSD_LOG_INFO
,
485 "Cleaning out old temporary files in \"%s\"...", TempDir
);
487 while ((dent
= cupsDirRead(dir
)) != NULL
)
489 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
491 if (cupsdRemoveFile(tempfile
))
492 cupsdLogMessage(CUPSD_LOG_ERROR
,
493 "Unable to remove temporary file \"%s\" - %s",
494 tempfile
, strerror(errno
));
496 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
503 cupsdLogMessage(CUPSD_LOG_ERROR
,
504 "Unable to open temporary directory \"%s\" - %s",
505 TempDir
, strerror(errno
));
512 * If we were started by launchd get the listen sockets file descriptors...
517 #endif /* HAVE_LAUNCHD */
519 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
521 * Load Print Service quota enforcement library (X Server only)
524 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
527 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
528 #endif /* __APPLE__ && HAVE_DLFCN_H */
533 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
537 if (krb5_init_context
!= NULL
)
538 # endif /* __APPLE__ */
541 * Setup a Kerberos context for the scheduler to use...
544 if (krb5_init_context(&KerberosContext
))
546 KerberosContext
= NULL
;
548 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
550 #endif /* HAVE_GSSAPI */
553 * Startup the server...
559 * Catch hangup and child signals and ignore broken pipes...
562 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
563 sigset(SIGCHLD
, sigchld_handler
);
564 sigset(SIGHUP
, sighup_handler
);
565 sigset(SIGPIPE
, SIG_IGN
);
566 sigset(SIGTERM
, sigterm_handler
);
567 #elif defined(HAVE_SIGACTION)
568 memset(&action
, 0, sizeof(action
));
570 sigemptyset(&action
.sa_mask
);
571 sigaddset(&action
.sa_mask
, SIGTERM
);
572 sigaddset(&action
.sa_mask
, SIGCHLD
);
573 action
.sa_handler
= sigchld_handler
;
574 sigaction(SIGCHLD
, &action
, NULL
);
576 sigemptyset(&action
.sa_mask
);
577 sigaddset(&action
.sa_mask
, SIGHUP
);
578 action
.sa_handler
= sighup_handler
;
579 sigaction(SIGHUP
, &action
, NULL
);
581 sigemptyset(&action
.sa_mask
);
582 action
.sa_handler
= SIG_IGN
;
583 sigaction(SIGPIPE
, &action
, NULL
);
585 sigemptyset(&action
.sa_mask
);
586 sigaddset(&action
.sa_mask
, SIGTERM
);
587 sigaddset(&action
.sa_mask
, SIGCHLD
);
588 action
.sa_handler
= sigterm_handler
;
589 sigaction(SIGTERM
, &action
, NULL
);
591 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
592 signal(SIGHUP
, sighup_handler
);
593 signal(SIGPIPE
, SIG_IGN
);
594 signal(SIGTERM
, sigterm_handler
);
595 #endif /* HAVE_SIGSET */
599 * Try to create a fake lpsched lock file if one is not already there.
600 * Some Adobe applications need it under IRIX in order to enable
604 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
606 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
607 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
612 fchmod(cupsFileNumber(fp
), 0644);
613 fchown(cupsFileNumber(fp
), User
, Group
);
620 * Initialize authentication certificates...
626 * If we are running in the background, signal the parent process that
627 * we are up and running...
631 if (!fg
|| run_as_child
)
634 #endif /* __APPLE__ */
637 * Send a signal to the parent process, but only if the parent is
638 * not PID 1 (init). This avoids accidentally shutting down the
639 * system on OpenBSD if you CTRL-C the server before it is up...
642 i
= getppid(); /* Save parent PID to avoid race condition */
650 * Start power management framework...
653 cupsdStartSystemMonitor();
654 #endif /* __APPLE__ */
657 * Start any pending print jobs...
666 browse_time
= time(NULL
);
667 expire_time
= time(NULL
);
670 senddoc_time
= time(NULL
);
672 while (!stop_scheduler
)
675 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
676 "main: Top of loop, dead_children=%d, NeedReload=%d",
677 dead_children
, NeedReload
);
681 * Check if there are dead children to handle...
688 * Check if we need to load the server configuration file...
694 * Close any idle clients...
697 if (cupsArrayCount(Clients
) > 0)
699 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
701 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
702 if (con
->http
.state
== HTTP_WAITING
)
703 cupsdCloseClient(con
);
705 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
707 cupsdPauseListening();
711 * Check for any active jobs...
714 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
716 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
717 if (job
->state_value
== IPP_JOB_PROCESSING
)
721 * Restart if all clients are closed and all jobs finished, or
722 * if the reload timeout has elapsed...
725 if ((cupsArrayCount(Clients
) == 0 &&
726 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
727 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
730 * Shutdown the server...
736 * Read configuration...
739 if (!cupsdReadConfiguration())
741 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
750 * If we were started by launchd get the listen sockets file descriptors...
755 #endif /* HAVE_LAUNCHD */
758 * Startup the server...
766 * Check for available input or ready output. If cupsdDoSelect()
767 * returns 0 or -1, something bad happened and we should exit
770 * Note that we at least have one listening socket open at all
774 timeout
= select_timeout(fds
);
778 * If no other work is scheduled and we're being controlled by
779 * launchd then timeout after 'LaunchdTimeout' seconds of
783 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
784 !cupsArrayCount(ActiveJobs
) &&
786 (!BrowseRemoteProtocols
&&
787 (!NumBrowsers
|| !BrowseLocalProtocols
||
788 cupsArrayCount(Printers
) == 0))))
790 timeout
= LaunchdTimeout
;
791 launchd_idle_exit
= 1;
794 launchd_idle_exit
= 0;
795 #endif /* HAVE_LAUNCHD */
797 if ((fds
= cupsdDoSelect(timeout
)) < 0)
800 * Got an error from select!
804 cupsd_printer_t
*p
; /* Current printer */
805 #endif /* HAVE_DNSSD */
808 if (errno
== EINTR
) /* Just interrupted by a signal */
812 * Log all sorts of debug info to help track down the problem.
815 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
818 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
820 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
821 cupsdLogMessage(CUPSD_LOG_EMERG
,
822 "Clients[%d] = %d, file = %d, state = %d",
823 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
825 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
827 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
828 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
830 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
832 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
835 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
837 #endif /* __APPLE__ */
839 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
841 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
842 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
844 job
->status_buffer
? job
->status_buffer
->fd
: -1,
845 job
->print_pipes
[0], job
->print_pipes
[1],
846 job
->back_pipes
[0], job
->back_pipes
[1]);
849 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
851 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
852 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] %d", p
->name
,
854 #endif /* HAVE_DNSSD */
859 current_time
= time(NULL
);
863 * Update the network interfaces once a minute...
866 if ((current_time
- netif_time
) >= 60)
868 netif_time
= current_time
;
871 #endif /* !__APPLE__ */
875 * If no other work was scheduled and we're being controlled by launchd
876 * then timeout after 'LaunchdTimeout' seconds of inactivity...
879 if (!fds
&& launchd_idle_exit
)
881 cupsdLogMessage(CUPSD_LOG_INFO
,
882 "Printer sharing is off and there are no jobs pending, "
883 "will restart on demand.");
887 #endif /* HAVE_LAUNCHD */
890 * Resume listening for new connections as needed...
893 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
894 cupsArrayCount(Clients
) < MaxClients
)
895 cupsdResumeListening();
898 * Expire subscriptions and unload completed jobs as needed...
901 if (current_time
> expire_time
)
903 if (cupsArrayCount(Subscriptions
) > 0)
904 cupsdExpireSubscriptions(NULL
, NULL
);
906 cupsdUnloadCompletedJobs();
908 expire_time
= current_time
;
912 * Update the browse list as needed...
918 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
919 BrowseSLPRefresh
<= current_time
)
920 cupsdUpdateSLPBrowse();
921 #endif /* HAVE_LIBSLP */
924 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
925 BrowseLDAPRefresh
<= current_time
)
926 cupsdUpdateLDAPBrowse();
927 #endif /* HAVE_LDAP */
930 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
932 cupsdSendBrowseList();
933 browse_time
= current_time
;
937 * Update the root certificate once every 5 minutes if we have client
941 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
942 !RunUser
&& cupsArrayCount(Clients
))
945 * Update the root certificate...
949 cupsdAddCert(0, "root", NULL
);
953 * Check for new data on the client sockets...
956 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
958 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
961 * Process pending data in the input buffer...
966 cupsdReadClient(con
);
971 * Check the activity and close old clients...
974 activity
= current_time
- Timeout
;
975 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
977 cupsdLogMessage(CUPSD_LOG_DEBUG
,
978 "Closing client %d after %d seconds of inactivity...",
979 con
->http
.fd
, Timeout
);
981 cupsdCloseClient(con
);
987 * Update any pending multi-file documents...
990 if ((current_time
- senddoc_time
) >= 10)
993 senddoc_time
= current_time
;
997 * Log statistics at most once a minute when in debug mode...
1000 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1002 size_t string_count
, /* String count */
1003 alloc_bytes
, /* Allocated string bytes */
1004 total_bytes
; /* Total string bytes */
1005 #ifdef HAVE_MALLINFO
1006 struct mallinfo mem
; /* Malloc information */
1010 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1011 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1012 mem
.usmblks
+ mem
.uordblks
);
1013 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1014 mem
.fsmblks
+ mem
.fordblks
);
1015 #endif /* HAVE_MALLINFO */
1017 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1018 cupsArrayCount(Clients
));
1019 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1020 cupsArrayCount(Jobs
));
1021 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1022 cupsArrayCount(ActiveJobs
));
1023 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1024 cupsArrayCount(Printers
));
1025 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1026 cupsArrayCount(ImplicitPrinters
));
1028 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1029 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1030 "Report: stringpool-string-count=" CUPS_LLFMT
,
1031 CUPS_LLCAST string_count
);
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1033 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1034 CUPS_LLCAST alloc_bytes
);
1035 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1036 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1037 CUPS_LLCAST total_bytes
);
1039 report_time
= current_time
;
1043 * Handle OS-specific event notification for any events that have
1044 * accumulated. Don't send these more than once a second...
1049 #ifdef HAVE_NOTIFY_POST
1050 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1051 CUPSD_EVENT_PRINTER_DELETED
|
1052 CUPSD_EVENT_PRINTER_MODIFIED
))
1054 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1055 "notify_post(\"com.apple.printerListChange\")");
1056 notify_post("com.apple.printerListChange");
1059 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1061 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1062 "notify_post(\"com.apple.printerHistoryChange\")");
1063 notify_post("com.apple.printerHistoryChange");
1066 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1067 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1068 CUPSD_EVENT_JOB_PROGRESS
))
1070 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1071 "notify_post(\"com.apple.jobChange\")");
1072 notify_post("com.apple.jobChange");
1074 #endif /* HAVE_NOTIFY_POST */
1077 * Reset the accumulated events...
1080 LastEvent
= CUPSD_EVENT_NONE
;
1085 * Log a message based on what happened...
1089 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1091 cupsdLogMessage(CUPSD_LOG_ERROR
,
1092 "Scheduler shutting down due to program error.");
1095 * Close all network clients...
1102 * Update the launchd KeepAlive file as needed...
1107 #endif /* HAVE_LAUNCHD */
1117 * Stop monitoring system event monitoring...
1120 cupsdStopSystemMonitor();
1121 #endif /* __APPLE__ */
1125 * Free the scheduler's Kerberos context...
1130 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1134 if (krb5_init_context
!= NULL
)
1135 # endif /* __APPLE__ */
1136 if (KerberosContext
)
1137 krb5_free_context(KerberosContext
);
1138 #endif /* HAVE_GSSAPI */
1143 * Unload Print Service quota enforcement library (X Server only)
1146 PSQUpdateQuotaProc
= NULL
;
1152 #endif /* HAVE_DLFCN_H */
1153 #endif /* __APPLE__ */
1157 * Remove the fake IRIX lpsched lock file, but only if the existing
1158 * file is not a FIFO which indicates that the real IRIX lpsched is
1162 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1163 if (!S_ISFIFO(statbuf
.st_mode
))
1164 unlink("/var/spool/lp/SCHEDLOCK");
1169 return (!stop_scheduler
);
1174 * 'cupsdClosePipe()' - Close a pipe as necessary.
1178 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1181 * Close file descriptors as needed...
1199 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1202 int /* O - 0 on success, -1 on error */
1203 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1206 * Create the pipe...
1218 * Set the "close on exec" flag on each end of the pipe...
1221 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1232 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1244 * Return 0 indicating success...
1252 * 'cupsdClearString()' - Clear a string.
1256 cupsdClearString(char **s
) /* O - String value */
1267 * 'cupsdHoldSignals()' - Hold child and termination signals.
1271 cupsdHoldSignals(void)
1273 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1274 sigset_t newmask
; /* New POSIX signal mask */
1275 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1285 #elif defined(HAVE_SIGACTION)
1286 sigemptyset(&newmask
);
1287 sigaddset(&newmask
, SIGTERM
);
1288 sigaddset(&newmask
, SIGCHLD
);
1289 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1290 #endif /* HAVE_SIGSET */
1295 * 'cupsdReleaseSignals()' - Release signals for delivery.
1299 cupsdReleaseSignals(void)
1308 #elif defined(HAVE_SIGACTION)
1309 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1310 #endif /* HAVE_SIGSET */
1315 * 'cupsdSetString()' - Set a string value.
1319 cupsdSetString(char **s
, /* O - New string */
1320 const char *v
) /* I - String value */
1329 *s
= _cupsStrAlloc(v
);
1336 * 'cupsdSetStringf()' - Set a formatted string value.
1340 cupsdSetStringf(char **s
, /* O - New string */
1341 const char *f
, /* I - Printf-style format string */
1342 ...) /* I - Additional args as needed */
1344 char v
[4096]; /* Formatting string value */
1345 va_list ap
; /* Argument pointer */
1346 char *olds
; /* Old string */
1357 vsnprintf(v
, sizeof(v
), f
, ap
);
1360 *s
= _cupsStrAlloc(v
);
1372 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1376 launchd_checkin(void)
1378 int i
, /* Looping var */
1379 count
, /* Numebr of listeners */
1380 portnum
; /* Port number */
1381 launch_data_t ld_msg
, /* Launch data message */
1382 ld_resp
, /* Launch data response */
1383 ld_array
, /* Launch data array */
1384 ld_sockets
, /* Launch data sockets dictionary */
1385 tmp
; /* Launch data */
1386 cupsd_listener_t
*lis
; /* Listeners array */
1387 http_addr_t addr
; /* Address variable */
1388 socklen_t addrlen
; /* Length of address */
1389 int fd
; /* File descriptor */
1390 char s
[256]; /* String addresss */
1393 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1396 * Check-in with launchd...
1399 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1400 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1402 cupsdLogMessage(CUPSD_LOG_ERROR
,
1403 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1408 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1410 errno
= launch_data_get_errno(ld_resp
);
1411 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1417 * Get the sockets dictionary...
1420 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1422 cupsdLogMessage(CUPSD_LOG_ERROR
,
1423 "launchd_checkin: No sockets found to answer requests on!");
1428 * Get the array of listener sockets...
1431 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1433 cupsdLogMessage(CUPSD_LOG_ERROR
,
1434 "launchd_checkin: No sockets found to answer requests on!");
1439 * Add listening fd(s) to the Listener array...
1442 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1444 count
= launch_data_array_get_count(ld_array
);
1446 for (i
= 0; i
< count
; i
++)
1449 * Get the launchd file descriptor and address...
1452 tmp
= launch_data_array_get_index(ld_array
, i
);
1453 fd
= launch_data_get_fd(tmp
);
1454 addrlen
= sizeof(addr
);
1456 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1458 cupsdLogMessage(CUPSD_LOG_ERROR
,
1459 "launchd_checkin: Unable to get local address - %s",
1465 * Try to match the launchd socket address to one of the listeners...
1468 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1470 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1471 if (httpAddrEqual(&lis
->address
, &addr
))
1475 * Add a new listener If there's no match...
1480 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1481 "launchd_checkin: Matched existing listener %s with fd %d...",
1482 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1486 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1487 "launchd_checkin: Adding new listener %s with fd %d...",
1488 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1490 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1492 cupsdLogMessage(CUPSD_LOG_ERROR
,
1493 "launchd_checkin: Unable to allocate listener - %s.",
1498 cupsArrayAdd(Listeners
, lis
);
1500 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1509 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1510 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1512 # endif /* AF_INET6 */
1513 if (lis
->address
.addr
.sa_family
== AF_INET
)
1514 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1517 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1518 # endif /* HAVE_SSL */
1522 launch_data_free(ld_msg
);
1523 launch_data_free(ld_resp
);
1528 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1532 launchd_checkout(void)
1534 int fd
; /* File descriptor */
1538 * Create or remove the launchd KeepAlive file based on whether
1539 * there are active jobs, polling, browsing for remote printers or
1540 * shared printers to advertise...
1543 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1545 (BrowseRemoteProtocols
||
1546 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1548 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1549 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1551 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1556 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1557 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1559 unlink(CUPS_KEEPALIVE
);
1562 #endif /* HAVE_LAUNCHD */
1566 * 'parent_handler()' - Catch USR1/CHLD signals...
1570 parent_handler(int sig
) /* I - Signal */
1573 * Store the signal we got from the OS and return...
1576 parent_signal
= sig
;
1581 * 'process_children()' - Process all dead children...
1585 process_children(void)
1587 int status
; /* Exit status of child */
1588 int pid
; /* Process ID of child */
1589 cupsd_job_t
*job
; /* Current job */
1590 int i
; /* Looping var */
1591 char name
[1024]; /* Process name */
1594 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1597 * Reset the dead_children flag...
1603 * Collect the exit status of some children...
1607 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1608 #elif defined(HAVE_WAIT3)
1609 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1611 if ((pid
= wait(&status
)) > 0)
1612 #endif /* HAVE_WAITPID */
1615 * Ignore SIGTERM errors - that comes when a job is canceled...
1618 cupsdFinishProcess(pid
, name
, sizeof(name
));
1620 if (status
== SIGTERM
)
1625 if (WIFEXITED(status
))
1626 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1627 pid
, name
, WEXITSTATUS(status
));
1629 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1630 pid
, name
, WTERMSIG(status
));
1632 if (LogLevel
< CUPSD_LOG_DEBUG
)
1633 cupsdLogMessage(CUPSD_LOG_INFO
,
1634 "Hint: Try setting the LogLevel to \"debug\" to find "
1638 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1642 * Delete certificates for CGI processes...
1646 cupsdDeleteCert(pid
);
1649 * Lookup the PID in the jobs list...
1652 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1654 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1655 if (job
->state_value
== IPP_JOB_PROCESSING
)
1657 for (i
= 0; job
->filters
[i
]; i
++)
1658 if (job
->filters
[i
] == pid
)
1661 if (job
->filters
[i
] || job
->backend
== pid
)
1664 * OK, this process has gone away; what's left?
1667 if (job
->filters
[i
])
1668 job
->filters
[i
] = -pid
;
1670 job
->backend
= -pid
;
1672 if (status
&& job
->status
>= 0)
1675 * An error occurred; save the exit status so we know to stop
1676 * the printer or cancel the job when all of the filters finish...
1678 * A negative status indicates that the backend failed and the
1679 * printer needs to be stopped.
1682 if (job
->filters
[i
])
1683 job
->status
= status
; /* Filter failed */
1685 job
->status
= -status
; /* Backend failed */
1687 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
) &&
1688 job
->status_level
> CUPSD_LOG_ERROR
)
1690 job
->status_level
= CUPSD_LOG_ERROR
;
1692 snprintf(job
->printer
->state_message
,
1693 sizeof(job
->printer
->state_message
), "%s failed", name
);
1694 cupsdAddPrinterHistory(job
->printer
);
1699 * If this is not the last file in a job, see if all of the
1700 * filters are done, and if so move to the next file.
1703 if (job
->current_file
< job
->num_files
)
1705 for (i
= 0; job
->filters
[i
] < 0; i
++);
1707 if (!job
->filters
[i
])
1710 * Process the next file...
1713 cupsdFinishJob(job
);
1724 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1728 sigchld_handler(int sig
) /* I - Signal number */
1733 * Flag that we have dead children...
1739 * Reset the signal handler as needed...
1742 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1743 signal(SIGCLD
, sigchld_handler
);
1744 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1749 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1753 sighup_handler(int sig
) /* I - Signal number */
1757 NeedReload
= RELOAD_ALL
;
1758 ReloadTime
= time(NULL
);
1760 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1761 signal(SIGHUP
, sighup_handler
);
1762 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1767 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1771 sigterm_handler(int sig
) /* I - Signal */
1773 (void)sig
; /* remove compiler warnings... */
1776 * Flag that we should stop and return...
1784 * 'select_timeout()' - Calculate the select timeout value.
1788 static long /* O - Number of seconds */
1789 select_timeout(int fds
) /* I - Number of descriptors returned */
1791 long timeout
; /* Timeout for select */
1792 time_t now
; /* Current time */
1793 cupsd_client_t
*con
; /* Client information */
1794 cupsd_printer_t
*p
; /* Printer information */
1795 cupsd_job_t
*job
; /* Job information */
1796 cupsd_subscription_t
*sub
; /* Subscription information */
1797 const char *why
; /* Debugging aid */
1801 * Check to see if any of the clients have pending data to be
1802 * processed; if so, the timeout should be 0...
1805 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1807 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1808 if (con
->http
.used
> 0)
1812 * If select has been active in the last second (fds > 0) or we have
1813 * many resources in use then don't bother trying to optimize the
1814 * timeout, just make it 1 second.
1817 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1821 * Otherwise, check all of the possible events that we need to wake for...
1825 timeout
= now
+ 86400; /* 86400 == 1 day */
1829 * Check whether we are accepting new connections...
1832 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1833 ListeningPaused
< timeout
)
1835 if (ListeningPaused
<= now
)
1838 timeout
= ListeningPaused
;
1840 why
= "resume listening";
1844 * Check the activity and close old clients...
1847 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1849 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1850 if ((con
->http
.activity
+ Timeout
) < timeout
)
1852 timeout
= con
->http
.activity
+ Timeout
;
1853 why
= "timeout a client connection";
1857 * Update the browse list as needed...
1860 if (Browsing
&& BrowseLocalProtocols
)
1863 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1865 timeout
= BrowseSLPRefresh
;
1866 why
= "update SLP browsing";
1868 #endif /* HAVE_LIBSLP */
1871 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1873 timeout
= BrowseLDAPRefresh
;
1874 why
= "update LDAP browsing";
1876 #endif /* HAVE_LDAP */
1878 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1880 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1882 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1884 if (p
->type
& CUPS_PRINTER_REMOTE
)
1886 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1888 timeout
= p
->browse_time
+ BrowseTimeout
;
1889 why
= "browse timeout a printer";
1892 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1894 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1896 timeout
= p
->browse_time
+ BrowseInterval
;
1897 why
= "send browse update";
1905 * Check for any active jobs...
1908 if (timeout
> (now
+ 10) && ActiveJobs
)
1910 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1912 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1913 if (job
->state_value
<= IPP_JOB_PROCESSING
)
1916 why
= "process active jobs";
1921 #ifdef HAVE_MALLINFO
1923 * Log memory usage every minute...
1926 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1928 timeout
= mallinfo_time
+ 60;
1929 why
= "display memory usage";
1931 #endif /* HAVE_MALLINFO */
1934 * Expire subscriptions as needed...
1937 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1939 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1940 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1942 timeout
= sub
->expire
;
1943 why
= "expire subscription";
1947 * Adjust from absolute to relative time. If p->browse_time above
1948 * was 0 then we can end up with a negative value here, so check.
1949 * We add 1 second to the timeout since events occur after the
1950 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1951 * to avoid select() timeout limits present on some operating
1955 timeout
= timeout
- now
+ 1;
1959 else if (timeout
> 86400)
1963 * Log and return the timeout value...
1966 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1974 * 'usage()' - Show scheduler usage.
1978 usage(int status
) /* O - Exit status */
1980 _cupsLangPuts(status
? stderr
: stdout
,
1981 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1983 "-c config-file Load alternate configuration file\n"
1984 "-f Run in the foreground\n"
1985 "-F Run in the foreground but detach\n"
1986 "-h Show this usage message\n"
1987 "-l Run cupsd from launchd(8)\n"));
1993 * End of "$Id: main.c 6914 2007-09-05 21:05:04Z mike $".