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 * cupsdOpenPipe() - Create a pipe which is closed on exec.
25 * cupsdReleaseSignals() - Release signals for delivery.
26 * cupsdSetString() - Set a string value.
27 * cupsdSetStringf() - Set a formatted string value.
28 * cupsd_clean_files() - Clean out old files.
29 * launchd_checkin() - Check-in with launchd and collect the listening
31 * launchd_checkout() - Update the launchd KeepAlive file as needed.
32 * parent_handler() - Catch USR1/CHLD signals...
33 * process_children() - Process all dead children...
34 * select_timeout() - Calculate the select timeout value.
35 * sigchld_handler() - Handle 'child' signals from old processes.
36 * sighup_handler() - Handle 'hangup' signals to reconfigure the
38 * sigterm_handler() - Handle 'terminate' signals that stop the scheduler.
39 * usage() - Show scheduler usage.
43 * Include necessary headers...
48 #include <sys/resource.h>
57 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
58 /* Name of the launchd KeepAlive file */
59 # ifndef LAUNCH_JOBKEY_KEEPALIVE
60 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
61 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
62 # ifndef LAUNCH_JOBKEY_PATHSTATE
63 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
64 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
65 # ifndef LAUNCH_JOBKEY_SERVICEIPC
66 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
67 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
68 #endif /* HAVE_LAUNCH_H */
70 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
72 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
75 #endif /* HAVE_NOTIFY_H */
82 static void cupsd_clean_files(const char *path
,
85 static void launchd_checkin(void);
86 static void launchd_checkout(void);
87 #endif /* HAVE_LAUNCHD */
88 static void parent_handler(int sig
);
89 static void process_children(void);
90 static void sigchld_handler(int sig
);
91 static void sighup_handler(int sig
);
92 static void sigterm_handler(int sig
);
93 static long select_timeout(int fds
);
94 static void usage(int status
);
101 static int parent_signal
= 0;
102 /* Set to signal number from child */
103 static int holdcount
= 0; /* Number of times "hold" was called */
104 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
105 static sigset_t holdmask
; /* Old POSIX signal mask */
106 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
107 static int dead_children
= 0;
109 static int stop_scheduler
= 0;
110 /* Should the scheduler stop? */
114 * 'main()' - Main entry for the CUPS scheduler.
117 int /* O - Exit status */
118 main(int argc
, /* I - Number of command-line args */
119 char *argv
[]) /* I - Command-line arguments */
121 int i
; /* Looping var */
122 char *opt
; /* Option character */
123 int fg
; /* Run in the foreground */
124 int fds
; /* Number of ready descriptors */
125 cupsd_client_t
*con
; /* Current client */
126 cupsd_job_t
*job
; /* Current job */
127 cupsd_listener_t
*lis
; /* Current listener */
128 time_t current_time
, /* Current time */
129 activity
, /* Client activity timer */
130 browse_time
, /* Next browse send time */
131 senddoc_time
, /* Send-Document time */
132 expire_time
, /* Subscription expire time */
133 report_time
, /* Malloc/client/job report time */
134 event_time
; /* Last event notification time */
135 long timeout
; /* Timeout for cupsdDoSelect() */
136 struct rlimit limit
; /* Runtime limit */
137 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
138 struct sigaction action
; /* Actions for POSIX signals */
139 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
141 cups_file_t
*fp
; /* Fake lpsched lock file */
142 struct stat statbuf
; /* Needed for checking lpsched FIFO */
144 int run_as_child
= 0;
145 /* Needed for background fork/exec */
147 int use_sysman
= !getuid();
148 /* Use system management functions? */
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
++)
189 case 'C' : /* Run as child with config file */
193 case 'c' : /* Configuration file */
197 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
198 "after \"-c\" option."));
202 if (argv
[i
][0] == '/')
205 * Absolute directory...
208 cupsdSetString(&ConfigurationFile
, argv
[i
]);
213 * Relative directory...
216 char *current
; /* Current directory */
220 * Allocate a buffer for the current working directory to
221 * reduce run-time stack usage; this approximates the
222 * behavior of some implementations of getcwd() when they
223 * are passed a NULL pointer.
226 if ((current
= malloc(1024)) == NULL
)
228 _cupsLangPuts(stderr
,
229 _("cupsd: Unable to get current directory."));
233 if (!getcwd(current
, 1024))
235 _cupsLangPuts(stderr
,
236 _("cupsd: Unable to get current directory."));
241 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
246 case 'f' : /* Run in foreground... */
250 case 'F' : /* Run in foreground, but disconnect from terminal... */
254 case 'h' : /* Show usage/help */
258 case 'l' : /* Started by launchd... */
263 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
264 "in, running in normal mode."));
266 #endif /* HAVE_LAUNCHD */
269 case 'p' : /* Stop immediately for profiling */
270 fputs("cupsd: -p (startup profiling) is for internal testing "
271 "use only!\n", stderr
);
276 case 'P' : /* Disable security profiles */
277 fputs("cupsd: -P (disable security profiles) is for internal "
278 "testing use only!\n", stderr
);
283 case 'S' : /* Disable system management functions */
284 fputs("cupsd: -S (disable system management) for internal "
285 "testing use only!\n", stderr
);
288 #endif /* __APPLE__ */
290 case 't' : /* Test the cupsd.conf file... */
295 default : /* Unknown option */
296 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
303 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
308 if (!ConfigurationFile
)
309 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
312 * If the user hasn't specified "-f", run in the background...
318 * Setup signal handlers for the parent...
321 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
322 sigset(SIGUSR1
, parent_handler
);
323 sigset(SIGCHLD
, parent_handler
);
325 sigset(SIGHUP
, SIG_IGN
);
326 #elif defined(HAVE_SIGACTION)
327 memset(&action
, 0, sizeof(action
));
328 sigemptyset(&action
.sa_mask
);
329 sigaddset(&action
.sa_mask
, SIGUSR1
);
330 action
.sa_handler
= parent_handler
;
331 sigaction(SIGUSR1
, &action
, NULL
);
332 sigaction(SIGCHLD
, &action
, NULL
);
334 sigemptyset(&action
.sa_mask
);
335 action
.sa_handler
= SIG_IGN
;
336 sigaction(SIGHUP
, &action
, NULL
);
338 signal(SIGUSR1
, parent_handler
);
339 signal(SIGCLD
, parent_handler
);
341 signal(SIGHUP
, SIG_IGN
);
342 #endif /* HAVE_SIGSET */
347 * OK, wait for the child to startup and send us SIGUSR1 or to crash
348 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
349 * might be sent by the init script to restart the scheduler...
352 for (; parent_signal
== 0;)
355 if (parent_signal
== SIGUSR1
)
363 else if (WIFEXITED(i
))
365 fprintf(stderr
, "cupsd: Child exited with status %d\n",
371 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
378 * Call _thread_sys_closefrom() so the child process doesn't reset the
379 * parent's file descriptors to be blocking. This is a workaround for a
380 * limitation of userland libpthread on OpenBSD.
383 _thread_sys_closefrom(0);
384 #endif /* __OpenBSD__ */
387 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
388 * a program, and since this kind of really unfriendly behavior seems to be
389 * more common these days in system libraries, we need to re-execute the
390 * background cupsd with the "-C" option to avoid problems. Unfortunately,
391 * we also have to assume that argv[0] contains the name of the cupsd
392 * executable - there is no portable way to get the real pathname...
395 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
402 * Make sure we aren't tying up any filesystems...
409 * Disable core dumps...
412 getrlimit(RLIMIT_CORE
, &limit
);
414 setrlimit(RLIMIT_CORE
, &limit
);
417 * Disconnect from the controlling terminal...
423 * Close all open files...
426 getrlimit(RLIMIT_NOFILE
, &limit
);
428 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
432 * Redirect stdin/out/err to /dev/null...
435 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
441 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
447 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
456 * Set the timezone info...
462 setlocale(LC_TIME
, "");
466 * Set the maximum number of files...
469 getrlimit(RLIMIT_NOFILE
, &limit
);
471 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
472 if (limit
.rlim_max
> FD_SETSIZE
)
475 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
477 if (limit
.rlim_max
== RLIM_INFINITY
)
480 #endif /* RLIM_INFINITY */
481 MaxFDs
= limit
.rlim_max
;
483 limit
.rlim_cur
= MaxFDs
;
485 setrlimit(RLIMIT_NOFILE
, &limit
);
490 * Read configuration...
493 if (!cupsdReadConfiguration())
496 printf("%s contains errors\n", ConfigurationFile
);
498 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
502 else if (TestConfigFile
)
504 printf("%s is OK\n", ConfigurationFile
);
509 * Clean out old temp files and printer cache data.
512 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
513 cupsd_clean_files(TempDir
, NULL
);
515 cupsd_clean_files(CacheDir
, "*.ipp");
521 * If we were started by launchd get the listen sockets file descriptors...
527 #endif /* HAVE_LAUNCHD */
530 * Startup the server...
538 * Catch hangup and child signals and ignore broken pipes...
541 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
542 sigset(SIGCHLD
, sigchld_handler
);
543 sigset(SIGHUP
, sighup_handler
);
544 sigset(SIGPIPE
, SIG_IGN
);
545 sigset(SIGTERM
, sigterm_handler
);
546 #elif defined(HAVE_SIGACTION)
547 memset(&action
, 0, sizeof(action
));
549 sigemptyset(&action
.sa_mask
);
550 sigaddset(&action
.sa_mask
, SIGTERM
);
551 sigaddset(&action
.sa_mask
, SIGCHLD
);
552 action
.sa_handler
= sigchld_handler
;
553 sigaction(SIGCHLD
, &action
, NULL
);
555 sigemptyset(&action
.sa_mask
);
556 sigaddset(&action
.sa_mask
, SIGHUP
);
557 action
.sa_handler
= sighup_handler
;
558 sigaction(SIGHUP
, &action
, NULL
);
560 sigemptyset(&action
.sa_mask
);
561 action
.sa_handler
= SIG_IGN
;
562 sigaction(SIGPIPE
, &action
, NULL
);
564 sigemptyset(&action
.sa_mask
);
565 sigaddset(&action
.sa_mask
, SIGTERM
);
566 sigaddset(&action
.sa_mask
, SIGCHLD
);
567 action
.sa_handler
= sigterm_handler
;
568 sigaction(SIGTERM
, &action
, NULL
);
570 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
571 signal(SIGHUP
, sighup_handler
);
572 signal(SIGPIPE
, SIG_IGN
);
573 signal(SIGTERM
, sigterm_handler
);
574 #endif /* HAVE_SIGSET */
578 * Try to create a fake lpsched lock file if one is not already there.
579 * Some Adobe applications need it under IRIX in order to enable
583 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
585 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
586 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
591 fchmod(cupsFileNumber(fp
), 0644);
592 fchown(cupsFileNumber(fp
), User
, Group
);
599 * Initialize authentication certificates...
605 * If we are running in the background, signal the parent process that
606 * we are up and running...
609 if (!fg
|| run_as_child
)
612 * Send a signal to the parent process, but only if the parent is
613 * not PID 1 (init). This avoids accidentally shutting down the
614 * system on OpenBSD if you CTRL-C the server before it is up...
617 i
= getppid(); /* Save parent PID to avoid race condition */
625 * Start power management framework...
629 cupsdStartSystemMonitor();
630 #endif /* __APPLE__ */
633 * Send server-started event...
638 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
639 "Scheduler started via launchd.");
641 #endif /* HAVE_LAUNCHD */
643 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
644 "Scheduler started in foreground.");
646 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
647 "Scheduler started in background.");
650 * Start any pending print jobs...
659 current_time
= time(NULL
);
660 browse_time
= current_time
;
661 event_time
= current_time
;
662 expire_time
= current_time
;
665 senddoc_time
= current_time
;
667 while (!stop_scheduler
)
670 * Check if there are dead children to handle...
677 * Check if we need to load the server configuration file...
683 * Close any idle clients...
686 if (cupsArrayCount(Clients
) > 0)
688 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
690 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
691 if (con
->http
.state
== HTTP_WAITING
)
692 cupsdCloseClient(con
);
694 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
696 cupsdPauseListening();
700 * Restart if all clients are closed and all jobs finished, or
701 * if the reload timeout has elapsed...
704 if ((cupsArrayCount(Clients
) == 0 &&
705 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
706 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
709 * Shutdown the server...
717 * Read configuration...
720 if (!cupsdReadConfiguration())
722 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
731 * If we were started by launchd, get the listen socket file
738 #endif /* HAVE_LAUNCHD */
741 * Startup the server...
749 * Send a server-restarted event...
752 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
753 "Scheduler restarted.");
758 * Check for available input or ready output. If cupsdDoSelect()
759 * returns 0 or -1, something bad happened and we should exit
762 * Note that we at least have one listening socket open at all
766 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
771 * If no other work is scheduled and we're being controlled by
772 * launchd then timeout after 'LaunchdTimeout' seconds of
776 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
777 !cupsArrayCount(ActiveJobs
) &&
779 (!BrowseRemoteProtocols
&&
780 (!BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))))
782 timeout
= LaunchdTimeout
;
783 launchd_idle_exit
= 1;
786 launchd_idle_exit
= 0;
787 #endif /* HAVE_LAUNCHD */
789 if ((fds
= cupsdDoSelect(timeout
)) < 0)
792 * Got an error from select!
796 cupsd_printer_t
*p
; /* Current printer */
797 #endif /* HAVE_DNSSD */
800 if (errno
== EINTR
) /* Just interrupted by a signal */
804 * Log all sorts of debug info to help track down the problem.
807 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
810 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
812 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
813 cupsdLogMessage(CUPSD_LOG_EMERG
,
814 "Clients[%d] = %d, file = %d, state = %d",
815 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
817 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
819 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
820 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
822 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
824 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
827 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
829 #endif /* __APPLE__ */
831 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
833 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
834 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
836 job
->status_buffer
? job
->status_buffer
->fd
: -1,
837 job
->print_pipes
[0], job
->print_pipes
[1],
838 job
->back_pipes
[0], job
->back_pipes
[1]);
841 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
843 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
844 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
845 p
->reg_name
? p
->reg_name
: "(null)");
846 #endif /* HAVE_DNSSD */
851 current_time
= time(NULL
);
854 * Write dirty config/state files...
857 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
862 * If we are going to sleep and still have pending jobs, stop them after
863 * a period of time...
866 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
867 cupsArrayCount(PrintingJobs
) > 0)
870 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
872 #endif /* __APPLE__ */
876 * Update the network interfaces once a minute...
879 if ((current_time
- netif_time
) >= 60)
881 netif_time
= current_time
;
884 #endif /* !__APPLE__ */
888 * If no other work was scheduled and we're being controlled by launchd
889 * then timeout after 'LaunchdTimeout' seconds of inactivity...
892 if (!fds
&& launchd_idle_exit
)
894 cupsdLogMessage(CUPSD_LOG_INFO
,
895 "Printer sharing is off and there are no jobs pending, "
896 "will restart on demand.");
900 #endif /* HAVE_LAUNCHD */
903 * Resume listening for new connections as needed...
906 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
907 cupsArrayCount(Clients
) < MaxClients
)
908 cupsdResumeListening();
911 * Expire subscriptions and unload completed jobs as needed...
914 if (current_time
> expire_time
)
916 if (cupsArrayCount(Subscriptions
) > 0)
917 cupsdExpireSubscriptions(NULL
, NULL
);
919 cupsdUnloadCompletedJobs();
921 expire_time
= current_time
;
925 * Update the browse list as needed...
931 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
932 BrowseSLPRefresh
<= current_time
)
933 cupsdUpdateSLPBrowse();
934 #endif /* HAVE_LIBSLP */
937 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
938 BrowseLDAPRefresh
<= current_time
)
939 cupsdUpdateLDAPBrowse();
940 #endif /* HAVE_LDAP */
943 if (Browsing
&& current_time
> browse_time
)
945 cupsdSendBrowseList();
946 browse_time
= current_time
;
950 * Update the root certificate once every 5 minutes if we have client
954 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
955 !RunUser
&& cupsArrayCount(Clients
))
958 * Update the root certificate...
962 cupsdAddCert(0, "root", NULL
);
966 * Check for new data on the client sockets...
969 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
971 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
974 * Process pending data in the input buffer...
979 cupsdReadClient(con
);
984 * Check the activity and close old clients...
987 activity
= current_time
- Timeout
;
988 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
990 cupsdLogMessage(CUPSD_LOG_DEBUG
,
991 "Closing client %d after %d seconds of inactivity...",
992 con
->http
.fd
, Timeout
);
994 cupsdCloseClient(con
);
1000 * Update any pending multi-file documents...
1003 if ((current_time
- senddoc_time
) >= 10)
1007 senddoc_time
= current_time
;
1011 * Log statistics at most once a minute when in debug mode...
1014 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1016 size_t string_count
, /* String count */
1017 alloc_bytes
, /* Allocated string bytes */
1018 total_bytes
; /* Total string bytes */
1019 #ifdef HAVE_MALLINFO
1020 struct mallinfo mem
; /* Malloc information */
1024 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1025 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1026 mem
.usmblks
+ mem
.uordblks
);
1027 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1028 mem
.fsmblks
+ mem
.fordblks
);
1029 #endif /* HAVE_MALLINFO */
1031 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1032 cupsArrayCount(Clients
));
1033 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1034 cupsArrayCount(Jobs
));
1035 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1036 cupsArrayCount(ActiveJobs
));
1037 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1038 cupsArrayCount(Printers
));
1039 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers-implicit=%d",
1040 cupsArrayCount(ImplicitPrinters
));
1042 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1043 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1044 "Report: stringpool-string-count=" CUPS_LLFMT
,
1045 CUPS_LLCAST string_count
);
1046 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1047 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1048 CUPS_LLCAST alloc_bytes
);
1049 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1050 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1051 CUPS_LLCAST total_bytes
);
1053 report_time
= current_time
;
1057 * Handle OS-specific event notification for any events that have
1058 * accumulated. Don't send these more than once a second...
1061 if (LastEvent
&& (current_time
- event_time
) >= 1)
1063 #ifdef HAVE_NOTIFY_POST
1064 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1065 CUPSD_EVENT_PRINTER_DELETED
|
1066 CUPSD_EVENT_PRINTER_MODIFIED
))
1068 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1069 "notify_post(\"com.apple.printerListChange\")");
1070 notify_post("com.apple.printerListChange");
1073 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1075 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1076 "notify_post(\"com.apple.printerHistoryChange\")");
1077 notify_post("com.apple.printerHistoryChange");
1080 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1081 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1082 CUPSD_EVENT_JOB_PROGRESS
))
1084 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1085 "notify_post(\"com.apple.jobChange\")");
1086 notify_post("com.apple.jobChange");
1088 #endif /* HAVE_NOTIFY_POST */
1091 * Reset the accumulated events...
1094 LastEvent
= CUPSD_EVENT_NONE
;
1095 event_time
= current_time
;
1100 * Log a message based on what happened...
1105 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1106 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1107 "Scheduler shutting down normally.");
1111 cupsdLogMessage(CUPSD_LOG_ERROR
,
1112 "Scheduler shutting down due to program error.");
1113 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1114 "Scheduler shutting down due to program error.");
1118 * Close all network clients...
1127 * Update the launchd KeepAlive file as needed...
1132 #endif /* HAVE_LAUNCHD */
1142 * Stop monitoring system event monitoring...
1146 cupsdStopSystemMonitor();
1147 #endif /* __APPLE__ */
1151 * Free the scheduler's Kerberos context...
1156 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1160 if (krb5_init_context
!= NULL
)
1161 # endif /* __APPLE__ */
1162 if (KerberosContext
)
1163 krb5_free_context(KerberosContext
);
1164 #endif /* HAVE_GSSAPI */
1168 * Remove the fake IRIX lpsched lock file, but only if the existing
1169 * file is not a FIFO which indicates that the real IRIX lpsched is
1173 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1174 if (!S_ISFIFO(statbuf
.st_mode
))
1175 unlink("/var/spool/lp/SCHEDLOCK");
1180 return (!stop_scheduler
);
1185 * 'cupsdAddString()' - Copy and add a string to an array.
1188 int /* O - 1 on success, 0 on failure */
1189 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1190 const char *s
) /* I - String to copy and add */
1193 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1194 (cups_ahash_func_t
)NULL
, 0,
1195 (cups_acopy_func_t
)_cupsStrAlloc
,
1196 (cups_afree_func_t
)_cupsStrFree
);
1198 return (cupsArrayAdd(*a
, (char *)s
));
1203 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1207 cupsdCheckProcess(void)
1210 * Flag that we have dead children...
1218 * 'cupsdClearString()' - Clear a string.
1222 cupsdClearString(char **s
) /* O - String value */
1233 * 'cupsdClosePipe()' - Close a pipe as necessary.
1237 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1240 * Close file descriptors as needed...
1258 * 'cupsdFreeStrings()' - Free an array of strings.
1262 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1266 cupsArrayDelete(*a
);
1273 * 'cupsdHoldSignals()' - Hold child and termination signals.
1277 cupsdHoldSignals(void)
1279 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1280 sigset_t newmask
; /* New POSIX signal mask */
1281 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1291 #elif defined(HAVE_SIGACTION)
1292 sigemptyset(&newmask
);
1293 sigaddset(&newmask
, SIGTERM
);
1294 sigaddset(&newmask
, SIGCHLD
);
1295 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1296 #endif /* HAVE_SIGSET */
1301 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1304 int /* O - 0 on success, -1 on error */
1305 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1308 * Create the pipe...
1320 * Set the "close on exec" flag on each end of the pipe...
1323 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1334 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1346 * Return 0 indicating success...
1354 * 'cupsdReleaseSignals()' - Release signals for delivery.
1358 cupsdReleaseSignals(void)
1367 #elif defined(HAVE_SIGACTION)
1368 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1369 #endif /* HAVE_SIGSET */
1374 * 'cupsdSetString()' - Set a string value.
1378 cupsdSetString(char **s
, /* O - New string */
1379 const char *v
) /* I - String value */
1388 *s
= _cupsStrAlloc(v
);
1395 * 'cupsdSetStringf()' - Set a formatted string value.
1399 cupsdSetStringf(char **s
, /* O - New string */
1400 const char *f
, /* I - Printf-style format string */
1401 ...) /* I - Additional args as needed */
1403 char v
[4096]; /* Formatting string value */
1404 va_list ap
; /* Argument pointer */
1405 char *olds
; /* Old string */
1416 vsnprintf(v
, sizeof(v
), f
, ap
);
1419 *s
= _cupsStrAlloc(v
);
1430 * 'cupsd_clean_files()' - Clean out old files.
1434 cupsd_clean_files(const char *path
, /* I - Directory to clean */
1435 const char *pattern
) /* I - Filename pattern or NULL */
1437 cups_dir_t
*dir
; /* Directory */
1438 cups_dentry_t
*dent
; /* Directory entry */
1439 char filename
[1024]; /* Filename */
1440 int status
; /* Status from unlink/rmdir */
1443 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1444 "cupsd_clean_files(path=\"%s\", pattern=\"%s\")", path
,
1445 pattern
? pattern
: "(null)");
1447 if ((dir
= cupsDirOpen(path
)) == NULL
)
1449 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to open directory \"%s\" - %s",
1450 path
, strerror(errno
));
1454 cupsdLogMessage(CUPSD_LOG_INFO
, "Cleaning out old files in \"%s\"...", path
);
1456 while ((dent
= cupsDirRead(dir
)) != NULL
)
1458 if (pattern
&& fnmatch(pattern
, dent
->filename
, 0))
1461 snprintf(filename
, sizeof(filename
), "%s/%s", path
, dent
->filename
);
1463 if (S_ISDIR(dent
->fileinfo
.st_mode
))
1465 cupsd_clean_files(filename
, pattern
);
1467 status
= rmdir(filename
);
1470 status
= unlink(filename
);
1473 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to remove \"%s\" - %s", filename
,
1476 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed \"%s\"...", filename
);
1485 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1489 launchd_checkin(void)
1491 size_t i
, /* Looping var */
1492 count
; /* Number of listeners */
1494 int portnum
; /* Port number */
1495 # endif /* HAVE_SSL */
1496 launch_data_t ld_msg
, /* Launch data message */
1497 ld_resp
, /* Launch data response */
1498 ld_array
, /* Launch data array */
1499 ld_sockets
, /* Launch data sockets dictionary */
1500 tmp
; /* Launch data */
1501 cupsd_listener_t
*lis
; /* Listeners array */
1502 http_addr_t addr
; /* Address variable */
1503 socklen_t addrlen
; /* Length of address */
1504 int fd
; /* File descriptor */
1505 char s
[256]; /* String addresss */
1508 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1511 * Check-in with launchd...
1514 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1515 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1517 cupsdLogMessage(CUPSD_LOG_ERROR
,
1518 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1521 return; /* anti-compiler-warning */
1524 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1526 errno
= launch_data_get_errno(ld_resp
);
1527 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1530 return; /* anti-compiler-warning */
1534 * Get the sockets dictionary...
1537 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1540 cupsdLogMessage(CUPSD_LOG_ERROR
,
1541 "launchd_checkin: No sockets found to answer requests on!");
1543 return; /* anti-compiler-warning */
1547 * Get the array of listener sockets...
1550 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1552 cupsdLogMessage(CUPSD_LOG_ERROR
,
1553 "launchd_checkin: No sockets found to answer requests on!");
1555 return; /* anti-compiler-warning */
1559 * Add listening fd(s) to the Listener array...
1562 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1564 count
= launch_data_array_get_count(ld_array
);
1566 for (i
= 0; i
< count
; i
++)
1569 * Get the launchd file descriptor and address...
1572 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1574 fd
= launch_data_get_fd(tmp
);
1575 addrlen
= sizeof(addr
);
1577 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1579 cupsdLogMessage(CUPSD_LOG_ERROR
,
1580 "launchd_checkin: Unable to get local address - %s",
1586 * Try to match the launchd socket address to one of the listeners...
1589 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1591 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1592 if (httpAddrEqual(&lis
->address
, &addr
))
1596 * Add a new listener If there's no match...
1601 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1602 "launchd_checkin: Matched existing listener %s with fd %d...",
1603 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1607 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1608 "launchd_checkin: Adding new listener %s with fd %d...",
1609 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1611 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1613 cupsdLogMessage(CUPSD_LOG_ERROR
,
1614 "launchd_checkin: Unable to allocate listener - "
1615 "%s.", strerror(errno
));
1619 cupsArrayAdd(Listeners
, lis
);
1621 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1630 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1631 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1633 # endif /* AF_INET6 */
1634 if (lis
->address
.addr
.sa_family
== AF_INET
)
1635 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1638 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1639 # endif /* HAVE_SSL */
1644 launch_data_free(ld_msg
);
1645 launch_data_free(ld_resp
);
1650 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1654 launchd_checkout(void)
1656 int fd
; /* File descriptor */
1660 * Create or remove the launchd KeepAlive file based on whether
1661 * there are active jobs, polling, browsing for remote printers or
1662 * shared printers to advertise...
1665 if (cupsArrayCount(ActiveJobs
) || NumPolled
||
1667 (BrowseRemoteProtocols
||
1668 (BrowseLocalProtocols
&& cupsArrayCount(Printers
)))))
1670 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1671 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1674 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1679 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1680 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1683 unlink(CUPS_KEEPALIVE
);
1686 #endif /* HAVE_LAUNCHD */
1690 * 'parent_handler()' - Catch USR1/CHLD signals...
1694 parent_handler(int sig
) /* I - Signal */
1697 * Store the signal we got from the OS and return...
1700 parent_signal
= sig
;
1705 * 'process_children()' - Process all dead children...
1709 process_children(void)
1711 int status
; /* Exit status of child */
1712 int pid
, /* Process ID of child */
1713 job_id
; /* Job ID of child */
1714 cupsd_job_t
*job
; /* Current job */
1715 int i
; /* Looping var */
1716 char name
[1024]; /* Process name */
1719 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1722 * Reset the dead_children flag...
1728 * Collect the exit status of some children...
1732 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1733 #elif defined(HAVE_WAIT3)
1734 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1736 if ((pid
= wait(&status
)) > 0)
1737 #endif /* HAVE_WAITPID */
1740 * Collect the name of the process that finished...
1743 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1746 * Delete certificates for CGI processes...
1750 cupsdDeleteCert(pid
);
1753 * Handle completed job filters...
1756 if (job_id
> 0 && (job
= cupsdFindJob(job_id
)) != NULL
)
1758 for (i
= 0; job
->filters
[i
]; i
++)
1759 if (job
->filters
[i
] == pid
)
1762 if (job
->filters
[i
] || job
->backend
== pid
)
1765 * OK, this process has gone away; what's left?
1768 if (job
->filters
[i
])
1769 job
->filters
[i
] = -pid
;
1771 job
->backend
= -pid
;
1773 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1774 status
!= SIGPIPE
&& job
->status
>= 0)
1777 * An error occurred; save the exit status so we know to stop
1778 * the printer or cancel the job when all of the filters finish...
1780 * A negative status indicates that the backend failed and the
1781 * printer needs to be stopped.
1784 if (job
->filters
[i
])
1785 job
->status
= status
; /* Filter failed */
1787 job
->status
= -status
; /* Backend failed */
1789 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1790 job
->status_level
> CUPSD_LOG_ERROR
)
1792 char message
[1024]; /* New printer-state-message */
1795 job
->status_level
= CUPSD_LOG_ERROR
;
1797 snprintf(message
, sizeof(message
), "%s failed", name
);
1801 strlcpy(job
->printer
->state_message
, message
,
1802 sizeof(job
->printer
->state_message
));
1808 if (!job
->printer_message
&& job
->attrs
)
1810 if ((job
->printer_message
=
1811 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1812 IPP_TAG_TEXT
)) == NULL
)
1813 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1815 "job-printer-state-message",
1819 if (job
->printer_message
)
1820 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1826 * If this is not the last file in a job, see if all of the
1827 * filters are done, and if so move to the next file.
1830 if (job
->current_file
< job
->num_files
&& job
->printer
)
1832 for (i
= 0; job
->filters
[i
] < 0; i
++);
1834 if (!job
->filters
[i
])
1837 * Process the next file...
1840 cupsdContinueJob(job
);
1843 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1846 * Remove the job from the active list if there are no processes still
1850 for (i
= 0; job
->filters
[i
] < 0; i
++);
1852 if (!job
->filters
[i
] && job
->backend
<= 0)
1853 cupsArrayRemove(ActiveJobs
, job
);
1859 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1860 * since they come when we kill/end a process...
1863 if (status
== SIGTERM
|| status
== SIGKILL
)
1865 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1866 "PID %d (%s) was terminated normally with signal %d.",
1869 else if (status
== SIGPIPE
)
1871 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1872 "PID %d (%s) did not catch or ignore signal %d.",
1877 if (WIFEXITED(status
))
1878 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) stopped with status %d!",
1879 pid
, name
, WEXITSTATUS(status
));
1881 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1882 pid
, name
, WTERMSIG(status
));
1884 if (LogLevel
< CUPSD_LOG_DEBUG
)
1885 cupsdLogMessage(CUPSD_LOG_INFO
,
1886 "Hint: Try setting the LogLevel to \"debug\" to find "
1890 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1895 * If wait*() is interrupted by a signal, tell main() to call us again...
1898 if (pid
< 0 && errno
== EINTR
)
1904 * 'select_timeout()' - Calculate the select timeout value.
1908 static long /* O - Number of seconds */
1909 select_timeout(int fds
) /* I - Number of descriptors returned */
1911 long timeout
; /* Timeout for select */
1912 time_t now
; /* Current time */
1913 cupsd_client_t
*con
; /* Client information */
1914 cupsd_printer_t
*p
; /* Printer information */
1915 cupsd_job_t
*job
; /* Job information */
1916 cupsd_subscription_t
*sub
; /* Subscription information */
1917 const char *why
; /* Debugging aid */
1921 * Check to see if any of the clients have pending data to be
1922 * processed; if so, the timeout should be 0...
1925 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1927 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1928 if (con
->http
.used
> 0)
1932 * If select has been active in the last second (fds > 0) or we have
1933 * many resources in use then don't bother trying to optimize the
1934 * timeout, just make it 1 second.
1937 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1941 * Otherwise, check all of the possible events that we need to wake for...
1945 timeout
= now
+ 86400; /* 86400 == 1 day */
1950 * When going to sleep, wake up to cancel jobs that don't complete in time.
1953 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1955 timeout
= SleepJobs
;
1956 why
= "cancel jobs before sleeping";
1958 #endif /* __APPLE__ */
1961 * Check whether we are accepting new connections...
1964 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1965 ListeningPaused
< timeout
)
1967 if (ListeningPaused
<= now
)
1970 timeout
= ListeningPaused
;
1972 why
= "resume listening";
1976 * Check the activity and close old clients...
1979 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1981 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1982 if ((con
->http
.activity
+ Timeout
) < timeout
)
1984 timeout
= con
->http
.activity
+ Timeout
;
1985 why
= "timeout a client connection";
1989 * Update the browse list as needed...
1992 if (Browsing
&& BrowseLocalProtocols
)
1995 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1997 timeout
= BrowseSLPRefresh
;
1998 why
= "update SLP browsing";
2000 #endif /* HAVE_LIBSLP */
2003 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
2005 timeout
= BrowseLDAPRefresh
;
2006 why
= "update LDAP browsing";
2008 #endif /* HAVE_LDAP */
2010 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
2012 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
2014 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
2016 if (p
->type
& CUPS_PRINTER_REMOTE
)
2018 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
2020 timeout
= p
->browse_time
+ BrowseTimeout
;
2021 why
= "browse timeout a printer";
2024 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
2026 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
2028 timeout
= p
->browse_time
+ BrowseInterval
;
2029 why
= "send browse update";
2037 * Write out changes to configuration and state files...
2040 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
2042 timeout
= DirtyCleanTime
;
2043 why
= "write dirty config/state files";
2047 * Check for any active jobs...
2050 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
2052 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
2054 if (job
->kill_time
&& job
->kill_time
< timeout
)
2056 timeout
= job
->kill_time
;
2057 why
= "kill unresponsive jobs";
2060 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
2062 timeout
= job
->hold_until
;
2063 why
= "release held jobs";
2065 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
2068 why
= "start pending jobs";
2073 #ifdef HAVE_MALLINFO
2075 * Log memory usage every minute...
2078 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
2080 timeout
= mallinfo_time
+ 60;
2081 why
= "display memory usage";
2083 #endif /* HAVE_MALLINFO */
2086 * Expire subscriptions as needed...
2089 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
2091 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
2092 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
2094 timeout
= sub
->expire
;
2095 why
= "expire subscription";
2099 * Adjust from absolute to relative time. If p->browse_time above
2100 * was 0 then we can end up with a negative value here, so check.
2101 * We add 1 second to the timeout since events occur after the
2102 * timeout expires, and limit the timeout to 86400 seconds (1 day)
2103 * to avoid select() timeout limits present on some operating
2107 timeout
= timeout
- now
+ 1;
2111 else if (timeout
> 86400)
2115 * Log and return the timeout value...
2118 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
2126 * 'sigchld_handler()' - Handle 'child' signals from old processes.
2130 sigchld_handler(int sig
) /* I - Signal number */
2135 * Flag that we have dead children...
2141 * Reset the signal handler as needed...
2144 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2145 signal(SIGCLD
, sigchld_handler
);
2146 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2151 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
2155 sighup_handler(int sig
) /* I - Signal number */
2159 NeedReload
= RELOAD_ALL
;
2160 ReloadTime
= time(NULL
);
2162 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
2163 signal(SIGHUP
, sighup_handler
);
2164 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
2169 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
2173 sigterm_handler(int sig
) /* I - Signal number */
2175 (void)sig
; /* remove compiler warnings... */
2178 * Flag that we should stop and return...
2186 * 'usage()' - Show scheduler usage.
2190 usage(int status
) /* O - Exit status */
2192 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2195 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2196 _cupsLangPuts(fp
, _("Options:"));
2197 _cupsLangPuts(fp
, _("-c config-file Load alternate configuration "
2199 _cupsLangPuts(fp
, _("-f Run in the foreground."));
2200 _cupsLangPuts(fp
, _("-F Run in the foreground but detach "
2202 _cupsLangPuts(fp
, _("-h Show this usage message."));
2203 _cupsLangPuts(fp
, _("-l Run cupsd from launchd(8)."));
2204 _cupsLangPuts(fp
, _("-t Test the configuration file."));
2211 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".