2 * "$Id: main.c 7925 2008-09-10 17:47:26Z mike $"
4 * Main loop for the CUPS scheduler.
6 * Copyright 2007-2011 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 * cupsdAddString() - Copy and add a string to an array.
19 * cupsdCheckProcess() - Tell the main loop to check for dead children.
20 * cupsdClearString() - Clear a string.
21 * cupsdClosePipe() - Close a pipe as necessary.
22 * cupsdFreeStrings() - Free an array of strings.
23 * cupsdHoldSignals() - Hold child and termination signals.
24 * cupsdMakeUUID() - Make a UUID URI conforming to RFC 4122.
25 * cupsdOpenPipe() - Create a pipe which is closed on exec.
26 * cupsdReleaseSignals() - Release signals for delivery.
27 * cupsdSetString() - Set a string value.
28 * cupsdSetStringf() - Set a formatted string value.
29 * cupsd_clean_files() - Clean out old files.
30 * launchd_checkin() - Check-in with launchd and collect the listening
32 * launchd_checkout() - Update the launchd KeepAlive file as needed.
33 * parent_handler() - Catch USR1/CHLD signals...
34 * process_children() - Process all dead children...
35 * select_timeout() - Calculate the select timeout value.
36 * sigchld_handler() - Handle 'child' signals from old processes.
37 * sighup_handler() - Handle 'hangup' signals to reconfigure the
39 * sigterm_handler() - Handle 'terminate' signals that stop the scheduler.
40 * usage() - Show scheduler usage.
44 * Include necessary headers...
49 #include <sys/resource.h>
58 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
59 /* Name of the launchd KeepAlive file */
60 # ifndef LAUNCH_JOBKEY_KEEPALIVE
61 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
62 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
63 # ifndef LAUNCH_JOBKEY_PATHSTATE
64 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
65 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
66 # ifndef LAUNCH_JOBKEY_SERVICEIPC
67 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
68 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
69 #endif /* HAVE_LAUNCH_H */
71 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
73 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
76 #endif /* HAVE_NOTIFY_H */
83 static void cupsd_clean_files(const char *path
,
86 static void launchd_checkin(void);
87 static void launchd_checkout(void);
88 #endif /* HAVE_LAUNCHD */
89 static void parent_handler(int sig
);
90 static void process_children(void);
91 static void sigchld_handler(int sig
);
92 static void sighup_handler(int sig
);
93 static void sigterm_handler(int sig
);
94 static long select_timeout(int fds
);
95 static void usage(int status
);
102 static int parent_signal
= 0;
103 /* Set to signal number from child */
104 static int holdcount
= 0; /* Number of times "hold" was called */
105 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
106 static sigset_t holdmask
; /* Old POSIX signal mask */
107 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
108 static int dead_children
= 0;
110 static int stop_scheduler
= 0;
111 /* Should the scheduler stop? */
115 * 'main()' - Main entry for the CUPS scheduler.
118 int /* O - Exit status */
119 main(int argc
, /* I - Number of command-line args */
120 char *argv
[]) /* I - Command-line arguments */
122 int i
; /* Looping var */
123 char *opt
; /* Option character */
124 int fg
; /* Run in the foreground */
125 int fds
; /* Number of ready descriptors */
126 cupsd_client_t
*con
; /* Current client */
127 cupsd_job_t
*job
; /* Current job */
128 cupsd_listener_t
*lis
; /* Current listener */
129 time_t current_time
, /* Current time */
130 activity
, /* Client activity timer */
131 browse_time
, /* Next browse send time */
132 senddoc_time
, /* Send-Document time */
133 expire_time
, /* Subscription expire time */
134 report_time
, /* Malloc/client/job report time */
135 event_time
; /* Last event notification time */
136 long timeout
; /* Timeout for cupsdDoSelect() */
137 struct rlimit limit
; /* Runtime limit */
138 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
139 struct sigaction action
; /* Actions for POSIX signals */
140 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
142 cups_file_t
*fp
; /* Fake lpsched lock file */
143 struct stat statbuf
; /* Needed for checking lpsched FIFO */
145 int run_as_child
= 0;
146 /* Needed for background fork/exec */
148 int use_sysman
= !getuid();
149 /* Use system management functions? */
151 time_t netif_time
= 0; /* Time since last network update */
152 #endif /* __APPLE__ */
154 int launchd_idle_exit
;
155 /* Idle exit on select timeout? */
156 #endif /* HAVE_LAUNCHD */
161 * Check for setuid invocation, which we do not support!
164 if (getuid() != geteuid())
166 fputs("cupsd: Cannot run as a setuid program\n", stderr
);
169 #endif /* HAVE_GETEUID */
172 * Check for command-line arguments...
178 if (getenv("CUPSD_LAUNCHD"))
183 #endif /* HAVE_LAUNCHD */
185 for (i
= 1; i
< argc
; i
++)
186 if (argv
[i
][0] == '-')
187 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
190 case 'C' : /* Run as child with config file */
194 case 'c' : /* Configuration file */
198 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
199 "after \"-c\" option."));
203 if (argv
[i
][0] == '/')
206 * Absolute directory...
209 cupsdSetString(&ConfigurationFile
, argv
[i
]);
214 * Relative directory...
217 char *current
; /* Current directory */
221 * Allocate a buffer for the current working directory to
222 * reduce run-time stack usage; this approximates the
223 * behavior of some implementations of getcwd() when they
224 * are passed a NULL pointer.
227 if ((current
= malloc(1024)) == NULL
)
229 _cupsLangPuts(stderr
,
230 _("cupsd: Unable to get current directory."));
234 if (!getcwd(current
, 1024))
236 _cupsLangPuts(stderr
,
237 _("cupsd: Unable to get current directory."));
242 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
247 case 'f' : /* Run in foreground... */
251 case 'F' : /* Run in foreground, but disconnect from terminal... */
255 case 'h' : /* Show usage/help */
259 case 'l' : /* Started by launchd... */
264 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
265 "in, running in normal mode."));
267 #endif /* HAVE_LAUNCHD */
270 case 'p' : /* Stop immediately for profiling */
271 fputs("cupsd: -p (startup profiling) is for internal testing "
272 "use only!\n", stderr
);
277 case 'P' : /* Disable security profiles */
278 fputs("cupsd: -P (disable security profiles) is for internal "
279 "testing use only!\n", stderr
);
284 case 'S' : /* Disable system management functions */
285 fputs("cupsd: -S (disable system management) for internal "
286 "testing use only!\n", stderr
);
289 #endif /* __APPLE__ */
291 case 't' : /* Test the cupsd.conf file... */
296 default : /* Unknown option */
297 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
304 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
309 if (!ConfigurationFile
)
310 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
313 * If the user hasn't specified "-f", run in the background...
319 * Setup signal handlers for the parent...
322 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
323 sigset(SIGUSR1
, parent_handler
);
324 sigset(SIGCHLD
, parent_handler
);
326 sigset(SIGHUP
, SIG_IGN
);
327 #elif defined(HAVE_SIGACTION)
328 memset(&action
, 0, sizeof(action
));
329 sigemptyset(&action
.sa_mask
);
330 sigaddset(&action
.sa_mask
, SIGUSR1
);
331 action
.sa_handler
= parent_handler
;
332 sigaction(SIGUSR1
, &action
, NULL
);
333 sigaction(SIGCHLD
, &action
, NULL
);
335 sigemptyset(&action
.sa_mask
);
336 action
.sa_handler
= SIG_IGN
;
337 sigaction(SIGHUP
, &action
, NULL
);
339 signal(SIGUSR1
, parent_handler
);
340 signal(SIGCLD
, parent_handler
);
342 signal(SIGHUP
, SIG_IGN
);
343 #endif /* HAVE_SIGSET */
348 * OK, wait for the child to startup and send us SIGUSR1 or to crash
349 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
350 * might be sent by the init script to restart the scheduler...
353 for (; parent_signal
== 0;)
356 if (parent_signal
== SIGUSR1
)
364 else if (WIFEXITED(i
))
366 fprintf(stderr
, "cupsd: Child exited with status %d\n",
372 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
379 * Call _thread_sys_closefrom() so the child process doesn't reset the
380 * parent's file descriptors to be blocking. This is a workaround for a
381 * limitation of userland libpthread on OpenBSD.
384 _thread_sys_closefrom(0);
385 #endif /* __OpenBSD__ */
388 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
389 * a program, and since this kind of really unfriendly behavior seems to be
390 * more common these days in system libraries, we need to re-execute the
391 * background cupsd with the "-C" option to avoid problems. Unfortunately,
392 * we also have to assume that argv[0] contains the name of the cupsd
393 * executable - there is no portable way to get the real pathname...
396 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
403 * Make sure we aren't tying up any filesystems...
410 * Disable core dumps...
413 getrlimit(RLIMIT_CORE
, &limit
);
415 setrlimit(RLIMIT_CORE
, &limit
);
418 * Disconnect from the controlling terminal...
424 * Close all open files...
427 getrlimit(RLIMIT_NOFILE
, &limit
);
429 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
433 * Redirect stdin/out/err to /dev/null...
436 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
442 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
448 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
457 * Set the timezone info...
463 setlocale(LC_TIME
, "");
467 * Set the maximum number of files...
470 getrlimit(RLIMIT_NOFILE
, &limit
);
472 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
473 if (limit
.rlim_max
> FD_SETSIZE
)
476 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
478 if (limit
.rlim_max
== RLIM_INFINITY
)
481 #endif /* RLIM_INFINITY */
482 MaxFDs
= limit
.rlim_max
;
484 limit
.rlim_cur
= MaxFDs
;
486 setrlimit(RLIMIT_NOFILE
, &limit
);
491 * Read configuration...
494 if (!cupsdReadConfiguration())
497 printf("%s contains errors\n", ConfigurationFile
);
499 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
503 else if (TestConfigFile
)
505 printf("%s is OK\n", ConfigurationFile
);
510 * Clean out old temp files and printer cache data.
513 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
514 cupsd_clean_files(TempDir
, NULL
);
516 cupsd_clean_files(CacheDir
, "*.ipp");
522 * If we were started by launchd get the listen sockets file descriptors...
528 #endif /* HAVE_LAUNCHD */
531 * Startup the server...
539 * Catch hangup and child signals and ignore broken pipes...
542 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
543 sigset(SIGCHLD
, sigchld_handler
);
544 sigset(SIGHUP
, sighup_handler
);
545 sigset(SIGPIPE
, SIG_IGN
);
546 sigset(SIGTERM
, sigterm_handler
);
547 #elif defined(HAVE_SIGACTION)
548 memset(&action
, 0, sizeof(action
));
550 sigemptyset(&action
.sa_mask
);
551 sigaddset(&action
.sa_mask
, SIGTERM
);
552 sigaddset(&action
.sa_mask
, SIGCHLD
);
553 action
.sa_handler
= sigchld_handler
;
554 sigaction(SIGCHLD
, &action
, NULL
);
556 sigemptyset(&action
.sa_mask
);
557 sigaddset(&action
.sa_mask
, SIGHUP
);
558 action
.sa_handler
= sighup_handler
;
559 sigaction(SIGHUP
, &action
, NULL
);
561 sigemptyset(&action
.sa_mask
);
562 action
.sa_handler
= SIG_IGN
;
563 sigaction(SIGPIPE
, &action
, NULL
);
565 sigemptyset(&action
.sa_mask
);
566 sigaddset(&action
.sa_mask
, SIGTERM
);
567 sigaddset(&action
.sa_mask
, SIGCHLD
);
568 action
.sa_handler
= sigterm_handler
;
569 sigaction(SIGTERM
, &action
, NULL
);
571 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
572 signal(SIGHUP
, sighup_handler
);
573 signal(SIGPIPE
, SIG_IGN
);
574 signal(SIGTERM
, sigterm_handler
);
575 #endif /* HAVE_SIGSET */
579 * Try to create a fake lpsched lock file if one is not already there.
580 * Some Adobe applications need it under IRIX in order to enable
584 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
586 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
587 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
592 fchmod(cupsFileNumber(fp
), 0644);
593 fchown(cupsFileNumber(fp
), User
, Group
);
600 * Initialize authentication certificates...
606 * If we are running in the background, signal the parent process that
607 * we are up and running...
610 if (!fg
|| run_as_child
)
613 * Send a signal to the parent process, but only if the parent is
614 * not PID 1 (init). This avoids accidentally shutting down the
615 * system on OpenBSD if you CTRL-C the server before it is up...
618 i
= getppid(); /* Save parent PID to avoid race condition */
626 * Start power management framework...
630 cupsdStartSystemMonitor();
631 #endif /* __APPLE__ */
634 * Send server-started event...
639 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
640 "Scheduler started via launchd.");
642 #endif /* HAVE_LAUNCHD */
644 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
645 "Scheduler started in foreground.");
647 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
648 "Scheduler started in background.");
651 * Start any pending print jobs...
660 current_time
= time(NULL
);
661 browse_time
= current_time
;
662 event_time
= current_time
;
663 expire_time
= current_time
;
666 senddoc_time
= current_time
;
668 while (!stop_scheduler
)
671 * Check if there are dead children to handle...
678 * Check if we need to load the server configuration file...
684 * Close any idle clients...
687 if (cupsArrayCount(Clients
) > 0)
689 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
691 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
692 if (con
->http
.state
== HTTP_WAITING
)
693 cupsdCloseClient(con
);
695 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
697 cupsdPauseListening();
701 * Restart if all clients are closed and all jobs finished, or
702 * if the reload timeout has elapsed...
705 if ((cupsArrayCount(Clients
) == 0 &&
706 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
707 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
710 * Shutdown the server...
718 * Read configuration...
721 if (!cupsdReadConfiguration())
723 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
732 * If we were started by launchd, get the listen socket file
739 #endif /* HAVE_LAUNCHD */
742 * Startup the server...
750 * Send a server-restarted event...
753 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
754 "Scheduler restarted.");
759 * Check for available input or ready output. If cupsdDoSelect()
760 * returns 0 or -1, something bad happened and we should exit
763 * Note that we at least have one listening socket open at all
767 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
772 * If no other work is scheduled and we're being controlled by
773 * launchd then timeout after 'LaunchdTimeout' seconds of
777 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
778 !cupsArrayCount(ActiveJobs
) &&
780 (!BrowseRemoteProtocols
&&
781 (!BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))))
783 timeout
= LaunchdTimeout
;
784 launchd_idle_exit
= 1;
787 launchd_idle_exit
= 0;
788 #endif /* HAVE_LAUNCHD */
790 if ((fds
= cupsdDoSelect(timeout
)) < 0)
793 * Got an error from select!
797 cupsd_printer_t
*p
; /* Current printer */
798 #endif /* HAVE_DNSSD */
801 if (errno
== EINTR
) /* Just interrupted by a signal */
805 * Log all sorts of debug info to help track down the problem.
808 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
811 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
813 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
814 cupsdLogMessage(CUPSD_LOG_EMERG
,
815 "Clients[%d] = %d, file = %d, state = %d",
816 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
818 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
820 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
821 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
823 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
825 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
828 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
830 #endif /* __APPLE__ */
832 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
834 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
835 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
837 job
->status_buffer
? job
->status_buffer
->fd
: -1,
838 job
->print_pipes
[0], job
->print_pipes
[1],
839 job
->back_pipes
[0], job
->back_pipes
[1]);
842 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
844 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
845 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
846 p
->reg_name
? p
->reg_name
: "(null)");
847 #endif /* HAVE_DNSSD */
852 current_time
= time(NULL
);
855 * Write dirty config/state files...
858 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
863 * If we are going to sleep and still have pending jobs, stop them after
864 * a period of time...
867 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
868 cupsArrayCount(PrintingJobs
) > 0)
871 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
873 #endif /* __APPLE__ */
877 * Update the network interfaces once a minute...
880 if ((current_time
- netif_time
) >= 60)
882 netif_time
= current_time
;
885 #endif /* !__APPLE__ */
889 * If no other work was scheduled and we're being controlled by launchd
890 * then timeout after 'LaunchdTimeout' seconds of inactivity...
893 if (!fds
&& launchd_idle_exit
)
895 cupsdLogMessage(CUPSD_LOG_INFO
,
896 "Printer sharing is off and there are no jobs pending, "
897 "will restart on demand.");
901 #endif /* HAVE_LAUNCHD */
904 * Resume listening for new connections as needed...
907 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
908 cupsArrayCount(Clients
) < MaxClients
)
909 cupsdResumeListening();
912 * Expire subscriptions and unload completed jobs as needed...
915 if (current_time
> expire_time
)
917 if (cupsArrayCount(Subscriptions
) > 0)
918 cupsdExpireSubscriptions(NULL
, NULL
);
920 cupsdUnloadCompletedJobs();
922 expire_time
= current_time
;
926 * Update the browse list as needed...
932 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
933 BrowseSLPRefresh
<= current_time
)
934 cupsdUpdateSLPBrowse();
935 #endif /* HAVE_LIBSLP */
938 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
939 BrowseLDAPRefresh
<= current_time
)
940 cupsdUpdateLDAPBrowse();
941 #endif /* HAVE_LDAP */
944 if (Browsing
&& current_time
> browse_time
)
946 cupsdSendBrowseList();
947 browse_time
= current_time
;
951 * Update the root certificate once every 5 minutes if we have client
955 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
956 !RunUser
&& cupsArrayCount(Clients
))
959 * Update the root certificate...
963 cupsdAddCert(0, "root", NULL
);
967 * Check for new data on the client sockets...
970 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
972 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
975 * Process pending data in the input buffer...
980 cupsdReadClient(con
);
985 * Check the activity and close old clients...
988 activity
= current_time
- Timeout
;
989 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
991 cupsdLogMessage(CUPSD_LOG_DEBUG
,
992 "Closing client %d after %d seconds of inactivity...",
993 con
->http
.fd
, Timeout
);
995 cupsdCloseClient(con
);
1001 * Update any pending multi-file documents...
1004 if ((current_time
- senddoc_time
) >= 10)
1008 senddoc_time
= current_time
;
1012 * Log statistics at most once a minute when in debug mode...
1015 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1017 size_t string_count
, /* String count */
1018 alloc_bytes
, /* Allocated string bytes */
1019 total_bytes
; /* Total string bytes */
1020 #ifdef HAVE_MALLINFO
1021 struct mallinfo mem
; /* Malloc information */
1025 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1026 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1027 mem
.usmblks
+ mem
.uordblks
);
1028 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1029 mem
.fsmblks
+ mem
.fordblks
);
1030 #endif /* HAVE_MALLINFO */
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1033 cupsArrayCount(Clients
));
1034 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1035 cupsArrayCount(Jobs
));
1036 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1037 cupsArrayCount(ActiveJobs
));
1038 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1039 cupsArrayCount(Printers
));
1040 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1041 cupsArrayCount(ImplicitPrinters
));
1043 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1044 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1045 "Report: stringpool-string-count=" CUPS_LLFMT
,
1046 CUPS_LLCAST string_count
);
1047 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1048 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1049 CUPS_LLCAST alloc_bytes
);
1050 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1051 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1052 CUPS_LLCAST total_bytes
);
1054 report_time
= current_time
;
1058 * Handle OS-specific event notification for any events that have
1059 * accumulated. Don't send these more than once a second...
1062 if (LastEvent
&& (current_time
- event_time
) >= 1)
1064 #ifdef HAVE_NOTIFY_POST
1065 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1066 CUPSD_EVENT_PRINTER_DELETED
|
1067 CUPSD_EVENT_PRINTER_MODIFIED
))
1069 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1070 "notify_post(\"com.apple.printerListChange\")");
1071 notify_post("com.apple.printerListChange");
1074 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1076 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1077 "notify_post(\"com.apple.printerHistoryChange\")");
1078 notify_post("com.apple.printerHistoryChange");
1081 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1082 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1083 CUPSD_EVENT_JOB_PROGRESS
))
1085 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1086 "notify_post(\"com.apple.jobChange\")");
1087 notify_post("com.apple.jobChange");
1089 #endif /* HAVE_NOTIFY_POST */
1092 * Reset the accumulated events...
1095 LastEvent
= CUPSD_EVENT_NONE
;
1096 event_time
= current_time
;
1101 * Log a message based on what happened...
1106 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1107 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1108 "Scheduler shutting down normally.");
1112 cupsdLogMessage(CUPSD_LOG_ERROR
,
1113 "Scheduler shutting down due to program error.");
1114 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1115 "Scheduler shutting down due to program error.");
1119 * Close all network clients...
1128 * Update the launchd KeepAlive file as needed...
1133 #endif /* HAVE_LAUNCHD */
1143 * Stop monitoring system event monitoring...
1147 cupsdStopSystemMonitor();
1148 #endif /* __APPLE__ */
1152 * Free the scheduler's Kerberos context...
1157 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1161 if (krb5_init_context
!= NULL
)
1162 # endif /* __APPLE__ */
1163 if (KerberosContext
)
1164 krb5_free_context(KerberosContext
);
1165 #endif /* HAVE_GSSAPI */
1169 * Remove the fake IRIX lpsched lock file, but only if the existing
1170 * file is not a FIFO which indicates that the real IRIX lpsched is
1174 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1175 if (!S_ISFIFO(statbuf
.st_mode
))
1176 unlink("/var/spool/lp/SCHEDLOCK");
1181 return (!stop_scheduler
);
1186 * 'cupsdAddString()' - Copy and add a string to an array.
1189 int /* O - 1 on success, 0 on failure */
1190 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1191 const char *s
) /* I - String to copy and add */
1194 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1195 (cups_ahash_func_t
)NULL
, 0,
1196 (cups_acopy_func_t
)_cupsStrAlloc
,
1197 (cups_afree_func_t
)_cupsStrFree
);
1199 return (cupsArrayAdd(*a
, (char *)s
));
1204 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1208 cupsdCheckProcess(void)
1211 * Flag that we have dead children...
1219 * 'cupsdClearString()' - Clear a string.
1223 cupsdClearString(char **s
) /* O - String value */
1234 * 'cupsdClosePipe()' - Close a pipe as necessary.
1238 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1241 * Close file descriptors as needed...
1259 * 'cupsdFreeStrings()' - Free an array of strings.
1263 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1267 cupsArrayDelete(*a
);
1274 * 'cupsdHoldSignals()' - Hold child and termination signals.
1278 cupsdHoldSignals(void)
1280 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1281 sigset_t newmask
; /* New POSIX signal mask */
1282 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1292 #elif defined(HAVE_SIGACTION)
1293 sigemptyset(&newmask
);
1294 sigaddset(&newmask
, SIGTERM
);
1295 sigaddset(&newmask
, SIGCHLD
);
1296 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1297 #endif /* HAVE_SIGSET */
1302 * 'cupsdMakeUUID()' - Make a UUID URI conforming to RFC 4122.
1304 * The buffer needs to be at least 46 bytes in size.
1307 char * /* I - UUID string */
1308 cupsdMakeUUID(const char *name
, /* I - Object name */
1309 int number
, /* I - Object number */
1310 char *buffer
, /* I - String buffer */
1311 size_t bufsize
) /* I - Size of buffer */
1313 char data
[1024]; /* Source string for MD5 */
1314 _cups_md5_state_t md5state
; /* MD5 state */
1315 unsigned char md5sum
[16]; /* MD5 digest/sum */
1319 * Build a version 3 UUID conforming to RFC 4122.
1321 * Start with the MD5 sum of the ServerName, RemotePort, object name and
1322 * number, and some random data on the end.
1325 snprintf(data
, sizeof(data
), "%s:%d:%s:%d:%04x:%04x", ServerName
,
1326 RemotePort
, name
? name
: ServerName
, number
,
1327 CUPS_RAND() & 0xffff, CUPS_RAND() & 0xffff);
1329 _cupsMD5Init(&md5state
);
1330 _cupsMD5Append(&md5state
, (unsigned char *)data
, strlen(data
));
1331 _cupsMD5Finish(&md5state
, md5sum
);
1334 * Generate the UUID from the MD5...
1337 snprintf(buffer
, bufsize
,
1338 "urn:uuid:%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1339 "%02x%02x%02x%02x%02x%02x",
1340 md5sum
[0], md5sum
[1], md5sum
[2], md5sum
[3], md5sum
[4], md5sum
[5],
1341 (md5sum
[6] & 15) | 0x30, md5sum
[7], (md5sum
[8] & 0x3f) | 0x40,
1342 md5sum
[9], md5sum
[10], md5sum
[11], md5sum
[12], md5sum
[13],
1343 md5sum
[14], md5sum
[15]);
1350 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1353 int /* O - 0 on success, -1 on error */
1354 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1357 * Create the pipe...
1369 * Set the "close on exec" flag on each end of the pipe...
1372 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1383 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1395 * Return 0 indicating success...
1403 * 'cupsdReleaseSignals()' - Release signals for delivery.
1407 cupsdReleaseSignals(void)
1416 #elif defined(HAVE_SIGACTION)
1417 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1418 #endif /* HAVE_SIGSET */
1423 * 'cupsdSetString()' - Set a string value.
1427 cupsdSetString(char **s
, /* O - New string */
1428 const char *v
) /* I - String value */
1437 *s
= _cupsStrAlloc(v
);
1444 * 'cupsdSetStringf()' - Set a formatted string value.
1448 cupsdSetStringf(char **s
, /* O - New string */
1449 const char *f
, /* I - Printf-style format string */
1450 ...) /* I - Additional args as needed */
1452 char v
[4096]; /* Formatting string value */
1453 va_list ap
; /* Argument pointer */
1454 char *olds
; /* Old string */
1465 vsnprintf(v
, sizeof(v
), f
, ap
);
1468 *s
= _cupsStrAlloc(v
);
1479 * 'cupsd_clean_files()' - Clean out old files.
1483 cupsd_clean_files(const char *path
, /* I - Directory to clean */
1484 const char *pattern
) /* I - Filename pattern or NULL */
1486 cups_dir_t
*dir
; /* Directory */
1487 cups_dentry_t
*dent
; /* Directory entry */
1488 char filename
[1024]; /* Filename */
1489 int status
; /* Status from unlink/rmdir */
1492 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1493 "cupsd_clean_files(path=\"%s\", pattern=\"%s\")", path
,
1494 pattern
? pattern
: "(null)");
1496 if ((dir
= cupsDirOpen(path
)) == NULL
)
1498 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open directory \"%s\" - %s",
1499 path
, strerror(errno
));
1503 cupsdLogMessage(CUPSD_LOG_INFO
, "Cleaning out old files in \"%s\"...", path
);
1505 while ((dent
= cupsDirRead(dir
)) != NULL
)
1507 if (pattern
&& fnmatch(pattern
, dent
->filename
, 0))
1510 snprintf(filename
, sizeof(filename
), "%s/%s", path
, dent
->filename
);
1512 if (S_ISDIR(dent
->fileinfo
.st_mode
))
1514 cupsd_clean_files(filename
, pattern
);
1516 status
= rmdir(filename
);
1519 status
= unlink(filename
);
1522 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to remove \"%s\" - %s", filename
,
1525 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed \"%s\"...", filename
);
1534 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1538 launchd_checkin(void)
1540 size_t i
, /* Looping var */
1541 count
; /* Number of listeners */
1543 int portnum
; /* Port number */
1544 # endif /* HAVE_SSL */
1545 launch_data_t ld_msg
, /* Launch data message */
1546 ld_resp
, /* Launch data response */
1547 ld_array
, /* Launch data array */
1548 ld_sockets
, /* Launch data sockets dictionary */
1549 tmp
; /* Launch data */
1550 cupsd_listener_t
*lis
; /* Listeners array */
1551 http_addr_t addr
; /* Address variable */
1552 socklen_t addrlen
; /* Length of address */
1553 int fd
; /* File descriptor */
1554 char s
[256]; /* String addresss */
1557 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1560 * Check-in with launchd...
1563 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1564 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1566 cupsdLogMessage(CUPSD_LOG_ERROR
,
1567 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1570 return; /* anti-compiler-warning */
1573 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1575 errno
= launch_data_get_errno(ld_resp
);
1576 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1579 return; /* anti-compiler-warning */
1583 * Get the sockets dictionary...
1586 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1589 cupsdLogMessage(CUPSD_LOG_ERROR
,
1590 "launchd_checkin: No sockets found to answer requests on!");
1592 return; /* anti-compiler-warning */
1596 * Get the array of listener sockets...
1599 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1601 cupsdLogMessage(CUPSD_LOG_ERROR
,
1602 "launchd_checkin: No sockets found to answer requests on!");
1604 return; /* anti-compiler-warning */
1608 * Add listening fd(s) to the Listener array...
1611 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1613 count
= launch_data_array_get_count(ld_array
);
1615 for (i
= 0; i
< count
; i
++)
1618 * Get the launchd file descriptor and address...
1621 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1623 fd
= launch_data_get_fd(tmp
);
1624 addrlen
= sizeof(addr
);
1626 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1628 cupsdLogMessage(CUPSD_LOG_ERROR
,
1629 "launchd_checkin: Unable to get local address - %s",
1635 * Try to match the launchd socket address to one of the listeners...
1638 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1640 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1641 if (httpAddrEqual(&lis
->address
, &addr
))
1645 * Add a new listener If there's no match...
1650 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1651 "launchd_checkin: Matched existing listener %s with fd %d...",
1652 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1656 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1657 "launchd_checkin: Adding new listener %s with fd %d...",
1658 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1660 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1662 cupsdLogMessage(CUPSD_LOG_ERROR
,
1663 "launchd_checkin: Unable to allocate listener - "
1664 "%s.", strerror(errno
));
1668 cupsArrayAdd(Listeners
, lis
);
1670 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1679 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1680 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1682 # endif /* AF_INET6 */
1683 if (lis
->address
.addr
.sa_family
== AF_INET
)
1684 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1687 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1688 # endif /* HAVE_SSL */
1693 launch_data_free(ld_msg
);
1694 launch_data_free(ld_resp
);
1699 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1703 launchd_checkout(void)
1705 int fd
; /* File descriptor */
1709 * Create or remove the launchd KeepAlive file based on whether
1710 * there are active jobs, polling, browsing for remote printers or
1711 * shared printers to advertise...
1714 if (cupsArrayCount(ActiveJobs
) || NumPolled
||
1716 (BrowseRemoteProtocols
||
1717 (BrowseLocalProtocols
&& cupsArrayCount(Printers
)))))
1719 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1720 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1723 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1728 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1729 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1732 unlink(CUPS_KEEPALIVE
);
1735 #endif /* HAVE_LAUNCHD */
1739 * 'parent_handler()' - Catch USR1/CHLD signals...
1743 parent_handler(int sig
) /* I - Signal */
1746 * Store the signal we got from the OS and return...
1749 parent_signal
= sig
;
1754 * 'process_children()' - Process all dead children...
1758 process_children(void)
1760 int status
; /* Exit status of child */
1761 int pid
, /* Process ID of child */
1762 job_id
; /* Job ID of child */
1763 cupsd_job_t
*job
; /* Current job */
1764 int i
; /* Looping var */
1765 char name
[1024]; /* Process name */
1768 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1771 * Reset the dead_children flag...
1777 * Collect the exit status of some children...
1781 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1782 #elif defined(HAVE_WAIT3)
1783 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1785 if ((pid
= wait(&status
)) > 0)
1786 #endif /* HAVE_WAITPID */
1789 * Collect the name of the process that finished...
1792 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1795 * Delete certificates for CGI processes...
1799 cupsdDeleteCert(pid
);
1802 * Handle completed job filters...
1805 if (job_id
> 0 && (job
= cupsdFindJob(job_id
)) != NULL
)
1807 for (i
= 0; job
->filters
[i
]; i
++)
1808 if (job
->filters
[i
] == pid
)
1811 if (job
->filters
[i
] || job
->backend
== pid
)
1814 * OK, this process has gone away; what's left?
1817 if (job
->filters
[i
])
1818 job
->filters
[i
] = -pid
;
1820 job
->backend
= -pid
;
1822 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1823 status
!= SIGPIPE
&& job
->status
>= 0)
1826 * An error occurred; save the exit status so we know to stop
1827 * the printer or cancel the job when all of the filters finish...
1829 * A negative status indicates that the backend failed and the
1830 * printer needs to be stopped.
1833 if (job
->filters
[i
])
1834 job
->status
= status
; /* Filter failed */
1836 job
->status
= -status
; /* Backend failed */
1838 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1839 job
->status_level
> CUPSD_LOG_ERROR
)
1841 char message
[1024]; /* New printer-state-message */
1844 job
->status_level
= CUPSD_LOG_ERROR
;
1846 snprintf(message
, sizeof(message
), "%s failed", name
);
1850 strlcpy(job
->printer
->state_message
, message
,
1851 sizeof(job
->printer
->state_message
));
1857 if (!job
->printer_message
&& job
->attrs
)
1859 if ((job
->printer_message
=
1860 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1861 IPP_TAG_TEXT
)) == NULL
)
1862 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1864 "job-printer-state-message",
1868 if (job
->printer_message
)
1869 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1875 * If this is not the last file in a job, see if all of the
1876 * filters are done, and if so move to the next file.
1879 if (job
->current_file
< job
->num_files
&& job
->printer
)
1881 for (i
= 0; job
->filters
[i
] < 0; i
++);
1883 if (!job
->filters
[i
] &&
1884 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1888 * Process the next file...
1891 cupsdContinueJob(job
);
1894 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1897 * Remove the job from the active list if there are no processes still
1901 for (i
= 0; job
->filters
[i
] < 0; i
++);
1903 if (!job
->filters
[i
] && job
->backend
<= 0)
1904 cupsArrayRemove(ActiveJobs
, job
);
1910 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1911 * since they come when we kill/end a process...
1914 if (status
== SIGTERM
|| status
== SIGKILL
)
1916 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1917 "PID %d (%s) was terminated normally with signal %d.",
1920 else if (status
== SIGPIPE
)
1922 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1923 "PID %d (%s) did not catch or ignore signal %d.",
1928 if (WIFEXITED(status
))
1929 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) stopped with status %d!",
1930 pid
, name
, WEXITSTATUS(status
));
1932 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1933 pid
, name
, WTERMSIG(status
));
1935 if (LogLevel
< CUPSD_LOG_DEBUG
)
1936 cupsdLogMessage(CUPSD_LOG_INFO
,
1937 "Hint: Try setting the LogLevel to \"debug\" to find "
1941 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1946 * If wait*() is interrupted by a signal, tell main() to call us again...
1949 if (pid
< 0 && errno
== EINTR
)
1955 * 'select_timeout()' - Calculate the select timeout value.
1959 static long /* O - Number of seconds */
1960 select_timeout(int fds
) /* I - Number of descriptors returned */
1962 long timeout
; /* Timeout for select */
1963 time_t now
; /* Current time */
1964 cupsd_client_t
*con
; /* Client information */
1965 cupsd_printer_t
*p
; /* Printer information */
1966 cupsd_job_t
*job
; /* Job information */
1967 cupsd_subscription_t
*sub
; /* Subscription information */
1968 const char *why
; /* Debugging aid */
1972 * Check to see if any of the clients have pending data to be
1973 * processed; if so, the timeout should be 0...
1976 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1978 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1979 if (con
->http
.used
> 0)
1983 * If select has been active in the last second (fds > 0) or we have
1984 * many resources in use then don't bother trying to optimize the
1985 * timeout, just make it 1 second.
1988 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1992 * Otherwise, check all of the possible events that we need to wake for...
1996 timeout
= now
+ 86400; /* 86400 == 1 day */
2001 * When going to sleep, wake up to cancel jobs that don't complete in time.
2004 if (SleepJobs
> 0 && SleepJobs
< timeout
)
2006 timeout
= SleepJobs
;
2007 why
= "cancel jobs before sleeping";
2009 #endif /* __APPLE__ */
2012 * Check whether we are accepting new connections...
2015 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
2016 ListeningPaused
< timeout
)
2018 if (ListeningPaused
<= now
)
2021 timeout
= ListeningPaused
;
2023 why
= "resume listening";
2027 * Check the activity and close old clients...
2030 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
2032 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
2033 if ((con
->http
.activity
+ Timeout
) < timeout
)
2035 timeout
= con
->http
.activity
+ Timeout
;
2036 why
= "timeout a client connection";
2040 * Update the browse list as needed...
2043 if (Browsing
&& BrowseLocalProtocols
)
2046 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
2048 timeout
= BrowseSLPRefresh
;
2049 why
= "update SLP browsing";
2051 #endif /* HAVE_LIBSLP */
2054 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
2056 timeout
= BrowseLDAPRefresh
;
2057 why
= "update LDAP browsing";
2059 #endif /* HAVE_LDAP */
2061 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
2063 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
2065 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
2067 if (p
->type
& CUPS_PRINTER_REMOTE
)
2069 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
2071 timeout
= p
->browse_time
+ BrowseTimeout
;
2072 why
= "browse timeout a printer";
2075 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
2077 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
2079 timeout
= p
->browse_time
+ BrowseInterval
;
2080 why
= "send browse update";
2088 * Write out changes to configuration and state files...
2091 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
2093 timeout
= DirtyCleanTime
;
2094 why
= "write dirty config/state files";
2098 * Check for any active jobs...
2101 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
2103 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2105 if (job
->kill_time
&& job
->kill_time
< timeout
)
2107 timeout
= job
->kill_time
;
2108 why
= "kill unresponsive jobs";
2111 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
2113 timeout
= job
->hold_until
;
2114 why
= "release held jobs";
2116 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
2119 why
= "start pending jobs";
2124 #ifdef HAVE_MALLINFO
2126 * Log memory usage every minute...
2129 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2131 timeout
= mallinfo_time
+ 60;
2132 why
= "display memory usage";
2134 #endif /* HAVE_MALLINFO */
2137 * Expire subscriptions as needed...
2140 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2142 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2143 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2145 timeout
= sub
->expire
;
2146 why
= "expire subscription";
2150 * Adjust from absolute to relative time. If p->browse_time above
2151 * was 0 then we can end up with a negative value here, so check.
2152 * We add 1 second to the timeout since events occur after the
2153 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2154 * to avoid select() timeout limits present on some operating
2158 timeout
= timeout
- now
+ 1;
2162 else if (timeout
> 86400)
2166 * Log and return the timeout value...
2169 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
2177 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2181 sigchld_handler(int sig
) /* I - Signal number */
2186 * Flag that we have dead children...
2192 * Reset the signal handler as needed...
2195 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2196 signal(SIGCLD
, sigchld_handler
);
2197 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2202 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2206 sighup_handler(int sig
) /* I - Signal number */
2210 NeedReload
= RELOAD_ALL
;
2211 ReloadTime
= time(NULL
);
2213 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2214 signal(SIGHUP
, sighup_handler
);
2215 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2220 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2224 sigterm_handler(int sig
) /* I - Signal number */
2226 (void)sig
; /* remove compiler warnings... */
2229 * Flag that we should stop and return...
2237 * 'usage()' - Show scheduler usage.
2241 usage(int status
) /* O - Exit status */
2243 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2246 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2247 _cupsLangPuts(fp
, _("Options:"));
2248 _cupsLangPuts(fp
, _(" -c config-file Load alternate configuration "
2250 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2251 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
2252 "detach from console."));
2253 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2254 _cupsLangPuts(fp
, _(" -l Run cupsd from launchd(8)."));
2255 _cupsLangPuts(fp
, _(" -t Test the configuration "
2263 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".