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 * cupsdFreeStrings() - Free an array of strings.
22 * cupsdHoldSignals() - Hold child and termination signals.
23 * cupsdReleaseSignals() - Release signals for delivery.
24 * cupsdSetString() - Set a string value.
25 * cupsdSetStringf() - Set a formatted string value.
26 * launchd_checkin() - Check-in with launchd and collect the listening
28 * launchd_checkout() - Update the launchd KeepAlive file as needed.
29 * parent_handler() - Catch USR1/CHLD signals...
30 * process_children() - Process all dead children...
31 * select_timeout() - Calculate the select timeout value.
32 * sigchld_handler() - Handle 'child' signals from old processes.
33 * sighup_handler() - Handle 'hangup' signals to reconfigure the
35 * sigterm_handler() - Handle 'terminate' signals that stop the scheduler.
36 * usage() - Show scheduler usage.
40 * Include necessary headers...
45 #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 */
78 static void launchd_checkin(void);
79 static void launchd_checkout(void);
80 #endif /* HAVE_LAUNCHD */
81 static void parent_handler(int sig
);
82 static void process_children(void);
83 static void sigchld_handler(int sig
);
84 static void sighup_handler(int sig
);
85 static void sigterm_handler(int sig
);
86 static long select_timeout(int fds
);
87 static void usage(int status
) __attribute__((noreturn
));
94 static int parent_signal
= 0;
95 /* Set to signal number from child */
96 static int holdcount
= 0; /* Number of times "hold" was called */
97 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
98 static sigset_t holdmask
; /* Old POSIX signal mask */
99 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
100 static int dead_children
= 0;
102 static int stop_scheduler
= 0;
103 /* Should the scheduler stop? */
107 * 'main()' - Main entry for the CUPS scheduler.
110 int /* O - Exit status */
111 main(int argc
, /* I - Number of command-line args */
112 char *argv
[]) /* I - Command-line arguments */
114 int i
; /* Looping var */
115 char *opt
; /* Option character */
116 int fg
; /* Run in the foreground */
117 int fds
; /* Number of ready descriptors */
118 cupsd_client_t
*con
; /* Current client */
119 cupsd_job_t
*job
; /* Current job */
120 cupsd_listener_t
*lis
; /* Current listener */
121 time_t current_time
, /* Current time */
122 activity
, /* Client activity timer */
123 browse_time
, /* Next browse send time */
124 senddoc_time
, /* Send-Document time */
125 expire_time
, /* Subscription expire time */
126 report_time
, /* Malloc/client/job report time */
127 event_time
; /* Last event notification time */
128 long timeout
; /* Timeout for cupsdDoSelect() */
129 struct rlimit limit
; /* Runtime limit */
130 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
131 struct sigaction action
; /* Actions for POSIX signals */
132 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
134 cups_file_t
*fp
; /* Fake lpsched lock file */
135 struct stat statbuf
; /* Needed for checking lpsched FIFO */
137 int run_as_child
= 0;
138 /* Needed for background fork/exec */
140 int use_sysman
= !getuid();
141 /* Use system management functions? */
143 time_t netif_time
= 0; /* Time since last network update */
144 #endif /* __APPLE__ */
146 int launchd_idle_exit
;
147 /* Idle exit on select timeout? */
148 #endif /* HAVE_LAUNCHD */
153 * Check for setuid invocation, which we do not support!
156 if (getuid() != geteuid())
158 fputs("cupsd: Cannot run as a setuid program\n", stderr
);
161 #endif /* HAVE_GETEUID */
164 * Check for command-line arguments...
170 if (getenv("CUPSD_LAUNCHD"))
175 #endif /* HAVE_LAUNCHD */
177 for (i
= 1; i
< argc
; i
++)
178 if (argv
[i
][0] == '-')
179 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
182 case 'C' : /* Run as child with config file */
186 case 'c' : /* Configuration file */
190 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
191 "after \"-c\" option."));
195 if (argv
[i
][0] == '/')
198 * Absolute directory...
201 cupsdSetString(&ConfigurationFile
, argv
[i
]);
206 * Relative directory...
209 char *current
; /* Current directory */
213 * Allocate a buffer for the current working directory to
214 * reduce run-time stack usage; this approximates the
215 * behavior of some implementations of getcwd() when they
216 * are passed a NULL pointer.
219 if ((current
= malloc(1024)) == NULL
)
221 _cupsLangPuts(stderr
,
222 _("cupsd: Unable to get current directory."));
226 if (!getcwd(current
, 1024))
228 _cupsLangPuts(stderr
,
229 _("cupsd: Unable to get current directory."));
234 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
239 case 'f' : /* Run in foreground... */
243 case 'F' : /* Run in foreground, but disconnect from terminal... */
247 case 'h' : /* Show usage/help */
251 case 'l' : /* Started by launchd... */
256 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
257 "in, running in normal mode."));
259 #endif /* HAVE_LAUNCHD */
262 case 'p' : /* Stop immediately for profiling */
263 fputs("cupsd: -p (startup profiling) is for internal testing "
264 "use only!\n", stderr
);
269 case 'P' : /* Disable security profiles */
270 fputs("cupsd: -P (disable security profiles) is for internal "
271 "testing use only!\n", stderr
);
276 case 'S' : /* Disable system management functions */
277 fputs("cupsd: -S (disable system management) for internal "
278 "testing use only!\n", stderr
);
281 #endif /* __APPLE__ */
283 case 't' : /* Test the cupsd.conf file... */
288 default : /* Unknown option */
289 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
296 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
301 if (!ConfigurationFile
)
302 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
305 * If the user hasn't specified "-f", run in the background...
311 * Setup signal handlers for the parent...
314 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
315 sigset(SIGUSR1
, parent_handler
);
316 sigset(SIGCHLD
, parent_handler
);
318 sigset(SIGHUP
, SIG_IGN
);
319 #elif defined(HAVE_SIGACTION)
320 memset(&action
, 0, sizeof(action
));
321 sigemptyset(&action
.sa_mask
);
322 sigaddset(&action
.sa_mask
, SIGUSR1
);
323 action
.sa_handler
= parent_handler
;
324 sigaction(SIGUSR1
, &action
, NULL
);
325 sigaction(SIGCHLD
, &action
, NULL
);
327 sigemptyset(&action
.sa_mask
);
328 action
.sa_handler
= SIG_IGN
;
329 sigaction(SIGHUP
, &action
, NULL
);
331 signal(SIGUSR1
, parent_handler
);
332 signal(SIGCLD
, parent_handler
);
334 signal(SIGHUP
, SIG_IGN
);
335 #endif /* HAVE_SIGSET */
340 * OK, wait for the child to startup and send us SIGUSR1 or to crash
341 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
342 * might be sent by the init script to restart the scheduler...
345 for (; parent_signal
== 0;)
348 if (parent_signal
== SIGUSR1
)
356 else if (WIFEXITED(i
))
358 fprintf(stderr
, "cupsd: Child exited with status %d\n",
364 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
371 * Call _thread_sys_closefrom() so the child process doesn't reset the
372 * parent's file descriptors to be blocking. This is a workaround for a
373 * limitation of userland libpthread on OpenBSD.
376 _thread_sys_closefrom(0);
377 #endif /* __OpenBSD__ */
380 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
381 * a program, and since this kind of really unfriendly behavior seems to be
382 * more common these days in system libraries, we need to re-execute the
383 * background cupsd with the "-C" option to avoid problems. Unfortunately,
384 * we also have to assume that argv[0] contains the name of the cupsd
385 * executable - there is no portable way to get the real pathname...
388 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
395 * Make sure we aren't tying up any filesystems...
402 * Disable core dumps...
405 getrlimit(RLIMIT_CORE
, &limit
);
407 setrlimit(RLIMIT_CORE
, &limit
);
410 * Disconnect from the controlling terminal...
416 * Close all open files...
419 getrlimit(RLIMIT_NOFILE
, &limit
);
421 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
425 * Redirect stdin/out/err to /dev/null...
428 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
434 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
440 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
449 * Set the timezone info...
455 setlocale(LC_TIME
, "");
459 * Set the maximum number of files...
462 getrlimit(RLIMIT_NOFILE
, &limit
);
464 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
465 if (limit
.rlim_max
> FD_SETSIZE
)
468 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
470 if (limit
.rlim_max
== RLIM_INFINITY
)
473 #endif /* RLIM_INFINITY */
474 MaxFDs
= limit
.rlim_max
;
476 limit
.rlim_cur
= MaxFDs
;
478 setrlimit(RLIMIT_NOFILE
, &limit
);
483 * Read configuration...
486 if (!cupsdReadConfiguration())
489 printf("%s contains errors\n", ConfigurationFile
);
491 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
495 else if (TestConfigFile
)
497 printf("%s is OK\n", ConfigurationFile
);
502 * Clean out old temp files and printer cache data.
505 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
506 cupsdCleanFiles(TempDir
, NULL
);
508 cupsdCleanFiles(CacheDir
, "*.ipp");
514 * If we were started by launchd get the listen sockets file descriptors...
520 #endif /* HAVE_LAUNCHD */
523 * Startup the server...
531 * Catch hangup and child signals and ignore broken pipes...
534 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
535 sigset(SIGCHLD
, sigchld_handler
);
536 sigset(SIGHUP
, sighup_handler
);
537 sigset(SIGPIPE
, SIG_IGN
);
538 sigset(SIGTERM
, sigterm_handler
);
539 #elif defined(HAVE_SIGACTION)
540 memset(&action
, 0, sizeof(action
));
542 sigemptyset(&action
.sa_mask
);
543 sigaddset(&action
.sa_mask
, SIGTERM
);
544 sigaddset(&action
.sa_mask
, SIGCHLD
);
545 action
.sa_handler
= sigchld_handler
;
546 sigaction(SIGCHLD
, &action
, NULL
);
548 sigemptyset(&action
.sa_mask
);
549 sigaddset(&action
.sa_mask
, SIGHUP
);
550 action
.sa_handler
= sighup_handler
;
551 sigaction(SIGHUP
, &action
, NULL
);
553 sigemptyset(&action
.sa_mask
);
554 action
.sa_handler
= SIG_IGN
;
555 sigaction(SIGPIPE
, &action
, NULL
);
557 sigemptyset(&action
.sa_mask
);
558 sigaddset(&action
.sa_mask
, SIGTERM
);
559 sigaddset(&action
.sa_mask
, SIGCHLD
);
560 action
.sa_handler
= sigterm_handler
;
561 sigaction(SIGTERM
, &action
, NULL
);
563 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
564 signal(SIGHUP
, sighup_handler
);
565 signal(SIGPIPE
, SIG_IGN
);
566 signal(SIGTERM
, sigterm_handler
);
567 #endif /* HAVE_SIGSET */
571 * Try to create a fake lpsched lock file if one is not already there.
572 * Some Adobe applications need it under IRIX in order to enable
576 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
578 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
579 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
584 fchmod(cupsFileNumber(fp
), 0644);
585 fchown(cupsFileNumber(fp
), User
, Group
);
592 * Initialize authentication certificates...
598 * If we are running in the background, signal the parent process that
599 * we are up and running...
602 if (!fg
|| run_as_child
)
605 * Send a signal to the parent process, but only if the parent is
606 * not PID 1 (init). This avoids accidentally shutting down the
607 * system on OpenBSD if you CTRL-C the server before it is up...
610 i
= getppid(); /* Save parent PID to avoid race condition */
618 * Start power management framework...
622 cupsdStartSystemMonitor();
623 #endif /* __APPLE__ */
626 * Send server-started event...
631 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
632 "Scheduler started via launchd.");
634 #endif /* HAVE_LAUNCHD */
636 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
637 "Scheduler started in foreground.");
639 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
640 "Scheduler started in background.");
643 * Start any pending print jobs...
652 current_time
= time(NULL
);
653 browse_time
= current_time
;
654 event_time
= current_time
;
655 expire_time
= current_time
;
658 senddoc_time
= current_time
;
660 while (!stop_scheduler
)
663 * Check if there are dead children to handle...
670 * Check if we need to load the server configuration file...
676 * Close any idle clients...
679 if (cupsArrayCount(Clients
) > 0)
681 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
683 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
684 if (con
->http
.state
== HTTP_WAITING
)
685 cupsdCloseClient(con
);
687 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
689 cupsdPauseListening();
693 * Restart if all clients are closed and all jobs finished, or
694 * if the reload timeout has elapsed...
697 if ((cupsArrayCount(Clients
) == 0 &&
698 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
699 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
702 * Shutdown the server...
710 * Read configuration...
713 if (!cupsdReadConfiguration())
715 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
724 * If we were started by launchd, get the listen socket file
731 #endif /* HAVE_LAUNCHD */
734 * Startup the server...
742 * Send a server-restarted event...
745 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
746 "Scheduler restarted.");
751 * Check for available input or ready output. If cupsdDoSelect()
752 * returns 0 or -1, something bad happened and we should exit
755 * Note that we at least have one listening socket open at all
759 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
764 * If no other work is scheduled and we're being controlled by
765 * launchd then timeout after 'LaunchdTimeout' seconds of
769 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&&
770 !cupsArrayCount(ActiveJobs
) &&
771 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
773 timeout
= LaunchdTimeout
;
774 launchd_idle_exit
= 1;
777 launchd_idle_exit
= 0;
778 #endif /* HAVE_LAUNCHD */
780 if ((fds
= cupsdDoSelect(timeout
)) < 0)
783 * Got an error from select!
787 cupsd_printer_t
*p
; /* Current printer */
788 #endif /* HAVE_DNSSD */
791 if (errno
== EINTR
) /* Just interrupted by a signal */
795 * Log all sorts of debug info to help track down the problem.
798 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
801 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
803 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
804 cupsdLogMessage(CUPSD_LOG_EMERG
,
805 "Clients[%d] = %d, file = %d, state = %d",
806 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
808 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
810 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
811 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
813 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
816 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
818 #endif /* __APPLE__ */
820 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
822 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
823 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
825 job
->status_buffer
? job
->status_buffer
->fd
: -1,
826 job
->print_pipes
[0], job
->print_pipes
[1],
827 job
->back_pipes
[0], job
->back_pipes
[1]);
830 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
832 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
833 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
834 p
->reg_name
? p
->reg_name
: "(null)");
835 #endif /* HAVE_DNSSD */
840 current_time
= time(NULL
);
843 * Write dirty config/state files...
846 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
851 * If we are going to sleep and still have pending jobs, stop them after
852 * a period of time...
855 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
856 cupsArrayCount(PrintingJobs
) > 0)
859 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
861 #endif /* __APPLE__ */
865 * Update the network interfaces once a minute...
868 if ((current_time
- netif_time
) >= 60)
870 netif_time
= current_time
;
873 #endif /* !__APPLE__ */
877 * If no other work was scheduled and we're being controlled by launchd
878 * then timeout after 'LaunchdTimeout' seconds of inactivity...
881 if (!fds
&& launchd_idle_exit
)
883 cupsdLogMessage(CUPSD_LOG_INFO
,
884 "Printer sharing is off and there are no jobs pending, "
885 "will restart on demand.");
889 #endif /* HAVE_LAUNCHD */
892 * Resume listening for new connections as needed...
895 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
896 cupsArrayCount(Clients
) < MaxClients
)
897 cupsdResumeListening();
900 * Expire subscriptions and unload completed jobs as needed...
903 if (current_time
> expire_time
)
905 if (cupsArrayCount(Subscriptions
) > 0)
906 cupsdExpireSubscriptions(NULL
, NULL
);
908 cupsdUnloadCompletedJobs();
910 expire_time
= current_time
;
913 #ifndef HAVE_AUTHORIZATION_H
915 * Update the root certificate once every 5 minutes if we have client
919 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
920 !RunUser
&& cupsArrayCount(Clients
))
923 * Update the root certificate...
927 cupsdAddCert(0, "root", NULL
);
929 #endif /* !HAVE_AUTHORIZATION_H */
932 * Check for new data on the client sockets...
935 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
937 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
940 * Process pending data in the input buffer...
945 cupsdReadClient(con
);
950 * Check the activity and close old clients...
953 activity
= current_time
- Timeout
;
954 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
956 cupsdLogMessage(CUPSD_LOG_DEBUG
,
957 "Closing client %d after %d seconds of inactivity...",
958 con
->http
.fd
, Timeout
);
960 cupsdCloseClient(con
);
966 * Update any pending multi-file documents...
969 if ((current_time
- senddoc_time
) >= 10)
973 senddoc_time
= current_time
;
977 * Log statistics at most once a minute when in debug mode...
980 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
982 size_t string_count
, /* String count */
983 alloc_bytes
, /* Allocated string bytes */
984 total_bytes
; /* Total string bytes */
986 struct mallinfo mem
; /* Malloc information */
990 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
991 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
992 mem
.usmblks
+ mem
.uordblks
);
993 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
994 mem
.fsmblks
+ mem
.fordblks
);
995 #endif /* HAVE_MALLINFO */
997 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
998 cupsArrayCount(Clients
));
999 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1000 cupsArrayCount(Jobs
));
1001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1002 cupsArrayCount(ActiveJobs
));
1003 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1004 cupsArrayCount(Printers
));
1006 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1007 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1008 "Report: stringpool-string-count=" CUPS_LLFMT
,
1009 CUPS_LLCAST string_count
);
1010 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1011 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1012 CUPS_LLCAST alloc_bytes
);
1013 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1014 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1015 CUPS_LLCAST total_bytes
);
1017 report_time
= current_time
;
1021 * Handle OS-specific event notification for any events that have
1022 * accumulated. Don't send these more than once a second...
1025 if (LastEvent
&& (current_time
- event_time
) >= 1)
1027 #ifdef HAVE_NOTIFY_POST
1028 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1029 CUPSD_EVENT_PRINTER_DELETED
|
1030 CUPSD_EVENT_PRINTER_MODIFIED
))
1032 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1033 "notify_post(\"com.apple.printerListChange\")");
1034 notify_post("com.apple.printerListChange");
1037 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1039 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1040 "notify_post(\"com.apple.printerHistoryChange\")");
1041 notify_post("com.apple.printerHistoryChange");
1044 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1045 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1046 CUPSD_EVENT_JOB_PROGRESS
))
1048 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1049 "notify_post(\"com.apple.jobChange\")");
1050 notify_post("com.apple.jobChange");
1052 #endif /* HAVE_NOTIFY_POST */
1055 * Reset the accumulated events...
1058 LastEvent
= CUPSD_EVENT_NONE
;
1059 event_time
= current_time
;
1064 * Log a message based on what happened...
1069 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1070 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1071 "Scheduler shutting down normally.");
1075 cupsdLogMessage(CUPSD_LOG_ERROR
,
1076 "Scheduler shutting down due to program error.");
1077 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1078 "Scheduler shutting down due to program error.");
1082 * Close all network clients...
1091 * Update the launchd KeepAlive file as needed...
1096 #endif /* HAVE_LAUNCHD */
1106 * Stop monitoring system event monitoring...
1110 cupsdStopSystemMonitor();
1111 #endif /* __APPLE__ */
1115 * Free the scheduler's Kerberos context...
1120 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1124 if (krb5_init_context
!= NULL
)
1125 # endif /* __APPLE__ */
1126 if (KerberosContext
)
1127 krb5_free_context(KerberosContext
);
1128 #endif /* HAVE_GSSAPI */
1132 * Remove the fake IRIX lpsched lock file, but only if the existing
1133 * file is not a FIFO which indicates that the real IRIX lpsched is
1137 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1138 if (!S_ISFIFO(statbuf
.st_mode
))
1139 unlink("/var/spool/lp/SCHEDLOCK");
1144 return (!stop_scheduler
);
1149 * 'cupsdAddString()' - Copy and add a string to an array.
1152 int /* O - 1 on success, 0 on failure */
1153 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1154 const char *s
) /* I - String to copy and add */
1157 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1158 (cups_ahash_func_t
)NULL
, 0,
1159 (cups_acopy_func_t
)_cupsStrAlloc
,
1160 (cups_afree_func_t
)_cupsStrFree
);
1162 return (cupsArrayAdd(*a
, (char *)s
));
1167 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1171 cupsdCheckProcess(void)
1174 * Flag that we have dead children...
1182 * 'cupsdClearString()' - Clear a string.
1186 cupsdClearString(char **s
) /* O - String value */
1197 * 'cupsdFreeStrings()' - Free an array of strings.
1201 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1205 cupsArrayDelete(*a
);
1212 * 'cupsdHoldSignals()' - Hold child and termination signals.
1216 cupsdHoldSignals(void)
1218 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1219 sigset_t newmask
; /* New POSIX signal mask */
1220 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1230 #elif defined(HAVE_SIGACTION)
1231 sigemptyset(&newmask
);
1232 sigaddset(&newmask
, SIGTERM
);
1233 sigaddset(&newmask
, SIGCHLD
);
1234 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1235 #endif /* HAVE_SIGSET */
1240 * 'cupsdReleaseSignals()' - Release signals for delivery.
1244 cupsdReleaseSignals(void)
1253 #elif defined(HAVE_SIGACTION)
1254 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1255 #endif /* HAVE_SIGSET */
1260 * 'cupsdSetString()' - Set a string value.
1264 cupsdSetString(char **s
, /* O - New string */
1265 const char *v
) /* I - String value */
1274 *s
= _cupsStrAlloc(v
);
1281 * 'cupsdSetStringf()' - Set a formatted string value.
1285 cupsdSetStringf(char **s
, /* O - New string */
1286 const char *f
, /* I - Printf-style format string */
1287 ...) /* I - Additional args as needed */
1289 char v
[4096]; /* Formatting string value */
1290 va_list ap
; /* Argument pointer */
1291 char *olds
; /* Old string */
1302 vsnprintf(v
, sizeof(v
), f
, ap
);
1305 *s
= _cupsStrAlloc(v
);
1317 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1321 launchd_checkin(void)
1323 size_t i
, /* Looping var */
1324 count
; /* Number of listeners */
1325 launch_data_t ld_msg
, /* Launch data message */
1326 ld_resp
, /* Launch data response */
1327 ld_array
, /* Launch data array */
1328 ld_sockets
, /* Launch data sockets dictionary */
1329 tmp
; /* Launch data */
1330 cupsd_listener_t
*lis
; /* Listeners array */
1331 http_addr_t addr
; /* Address variable */
1332 socklen_t addrlen
; /* Length of address */
1333 int fd
; /* File descriptor */
1334 char s
[256]; /* String addresss */
1337 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1340 * Check-in with launchd...
1343 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1344 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1346 cupsdLogMessage(CUPSD_LOG_ERROR
,
1347 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1350 return; /* anti-compiler-warning */
1353 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1355 errno
= launch_data_get_errno(ld_resp
);
1356 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1359 return; /* anti-compiler-warning */
1363 * Get the sockets dictionary...
1366 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1369 cupsdLogMessage(CUPSD_LOG_ERROR
,
1370 "launchd_checkin: No sockets found to answer requests on!");
1372 return; /* anti-compiler-warning */
1376 * Get the array of listener sockets...
1379 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1381 cupsdLogMessage(CUPSD_LOG_ERROR
,
1382 "launchd_checkin: No sockets found to answer requests on!");
1384 return; /* anti-compiler-warning */
1388 * Add listening fd(s) to the Listener array...
1391 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1393 count
= launch_data_array_get_count(ld_array
);
1395 for (i
= 0; i
< count
; i
++)
1398 * Get the launchd file descriptor and address...
1401 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1403 fd
= launch_data_get_fd(tmp
);
1404 addrlen
= sizeof(addr
);
1406 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1408 cupsdLogMessage(CUPSD_LOG_ERROR
,
1409 "launchd_checkin: Unable to get local address - %s",
1415 * Try to match the launchd socket address to one of the listeners...
1418 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1420 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1421 if (httpAddrEqual(&lis
->address
, &addr
))
1425 * Add a new listener If there's no match...
1430 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1431 "launchd_checkin: Matched existing listener %s with fd %d...",
1432 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1436 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1437 "launchd_checkin: Adding new listener %s with fd %d...",
1438 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1440 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1442 cupsdLogMessage(CUPSD_LOG_ERROR
,
1443 "launchd_checkin: Unable to allocate listener - "
1444 "%s.", strerror(errno
));
1448 cupsArrayAdd(Listeners
, lis
);
1450 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1456 if (_httpAddrPort(&(lis
->address
)) == 443)
1457 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1458 # endif /* HAVE_SSL */
1463 launch_data_free(ld_msg
);
1464 launch_data_free(ld_resp
);
1469 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1473 launchd_checkout(void)
1475 int fd
; /* File descriptor */
1479 * Create or remove the launchd KeepAlive file based on whether
1480 * there are active jobs, polling, browsing for remote printers or
1481 * shared printers to advertise...
1484 if (cupsArrayCount(ActiveJobs
) ||
1485 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
1487 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1488 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1491 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1496 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1497 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1500 unlink(CUPS_KEEPALIVE
);
1503 #endif /* HAVE_LAUNCHD */
1507 * 'parent_handler()' - Catch USR1/CHLD signals...
1511 parent_handler(int sig
) /* I - Signal */
1514 * Store the signal we got from the OS and return...
1517 parent_signal
= sig
;
1522 * 'process_children()' - Process all dead children...
1526 process_children(void)
1528 int status
; /* Exit status of child */
1529 int pid
, /* Process ID of child */
1530 job_id
; /* Job ID of child */
1531 cupsd_job_t
*job
; /* Current job */
1532 int i
; /* Looping var */
1533 char name
[1024]; /* Process name */
1536 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1539 * Reset the dead_children flag...
1545 * Collect the exit status of some children...
1549 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1550 #elif defined(HAVE_WAIT3)
1551 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1553 if ((pid
= wait(&status
)) > 0)
1554 #endif /* HAVE_WAITPID */
1557 * Collect the name of the process that finished...
1560 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1563 * Delete certificates for CGI processes...
1567 cupsdDeleteCert(pid
);
1570 * Handle completed job filters...
1573 if (job_id
> 0 && (job
= cupsdFindJob(job_id
)) != NULL
)
1575 for (i
= 0; job
->filters
[i
]; i
++)
1576 if (job
->filters
[i
] == pid
)
1579 if (job
->filters
[i
] || job
->backend
== pid
)
1582 * OK, this process has gone away; what's left?
1585 if (job
->filters
[i
])
1586 job
->filters
[i
] = -pid
;
1588 job
->backend
= -pid
;
1590 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1591 status
!= SIGPIPE
&& job
->status
>= 0)
1594 * An error occurred; save the exit status so we know to stop
1595 * the printer or cancel the job when all of the filters finish...
1597 * A negative status indicates that the backend failed and the
1598 * printer needs to be stopped.
1601 if (job
->filters
[i
])
1602 job
->status
= status
; /* Filter failed */
1604 job
->status
= -status
; /* Backend failed */
1606 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1607 job
->status_level
> CUPSD_LOG_ERROR
)
1609 char message
[1024]; /* New printer-state-message */
1612 job
->status_level
= CUPSD_LOG_ERROR
;
1614 snprintf(message
, sizeof(message
), "%s failed", name
);
1618 strlcpy(job
->printer
->state_message
, message
,
1619 sizeof(job
->printer
->state_message
));
1625 if (!job
->printer_message
&& job
->attrs
)
1627 if ((job
->printer_message
=
1628 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1629 IPP_TAG_TEXT
)) == NULL
)
1630 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1632 "job-printer-state-message",
1636 if (job
->printer_message
)
1637 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1643 * If this is not the last file in a job, see if all of the
1644 * filters are done, and if so move to the next file.
1647 if (job
->current_file
< job
->num_files
&& job
->printer
)
1649 for (i
= 0; job
->filters
[i
] < 0; i
++);
1651 if (!job
->filters
[i
] &&
1652 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1656 * Process the next file...
1659 cupsdContinueJob(job
);
1662 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1665 * Remove the job from the active list if there are no processes still
1669 for (i
= 0; job
->filters
[i
] < 0; i
++);
1671 if (!job
->filters
[i
] && job
->backend
<= 0)
1672 cupsArrayRemove(ActiveJobs
, job
);
1678 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1679 * since they come when we kill/end a process...
1682 if (status
== SIGTERM
|| status
== SIGKILL
)
1684 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1685 "PID %d (%s) was terminated normally with signal %d.",
1688 else if (status
== SIGPIPE
)
1690 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1691 "PID %d (%s) did not catch or ignore signal %d.",
1696 if (WIFEXITED(status
))
1698 int code
= WEXITSTATUS(status
); /* Exit code */
1701 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1702 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1703 code
, strerror(code
- 100));
1705 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1706 "PID %d (%s) stopped with status %d.", pid
, name
,
1710 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d.",
1711 pid
, name
, WTERMSIG(status
));
1713 if (LogLevel
< CUPSD_LOG_DEBUG
)
1714 cupsdLogMessage(CUPSD_LOG_INFO
,
1715 "Hint: Try setting the LogLevel to \"debug\" to find "
1719 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1724 * If wait*() is interrupted by a signal, tell main() to call us again...
1727 if (pid
< 0 && errno
== EINTR
)
1733 * 'select_timeout()' - Calculate the select timeout value.
1737 static long /* O - Number of seconds */
1738 select_timeout(int fds
) /* I - Number of descriptors returned */
1740 long timeout
; /* Timeout for select */
1741 time_t now
; /* Current time */
1742 cupsd_client_t
*con
; /* Client information */
1743 cupsd_job_t
*job
; /* Job information */
1744 cupsd_subscription_t
*sub
; /* Subscription information */
1745 const char *why
; /* Debugging aid */
1749 * Check to see if any of the clients have pending data to be
1750 * processed; if so, the timeout should be 0...
1753 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1755 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1756 if (con
->http
.used
> 0)
1760 * If select has been active in the last second (fds > 0) or we have
1761 * many resources in use then don't bother trying to optimize the
1762 * timeout, just make it 1 second.
1765 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1769 * Otherwise, check all of the possible events that we need to wake for...
1773 timeout
= now
+ 86400; /* 86400 == 1 day */
1778 * When going to sleep, wake up to cancel jobs that don't complete in time.
1781 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1783 timeout
= SleepJobs
;
1784 why
= "cancel jobs before sleeping";
1786 #endif /* __APPLE__ */
1789 * Check whether we are accepting new connections...
1792 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1793 ListeningPaused
< timeout
)
1795 if (ListeningPaused
<= now
)
1798 timeout
= ListeningPaused
;
1800 why
= "resume listening";
1804 * Check the activity and close old clients...
1807 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1809 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1810 if ((con
->http
.activity
+ Timeout
) < timeout
)
1812 timeout
= con
->http
.activity
+ Timeout
;
1813 why
= "timeout a client connection";
1817 * Write out changes to configuration and state files...
1820 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1822 timeout
= DirtyCleanTime
;
1823 why
= "write dirty config/state files";
1827 * Check for any active jobs...
1830 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1832 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1834 if (job
->kill_time
&& job
->kill_time
< timeout
)
1836 timeout
= job
->kill_time
;
1837 why
= "kill unresponsive jobs";
1840 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1842 timeout
= job
->hold_until
;
1843 why
= "release held jobs";
1845 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1848 why
= "start pending jobs";
1853 #ifdef HAVE_MALLINFO
1855 * Log memory usage every minute...
1858 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1860 timeout
= mallinfo_time
+ 60;
1861 why
= "display memory usage";
1863 #endif /* HAVE_MALLINFO */
1866 * Expire subscriptions as needed...
1869 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1871 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1872 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1874 timeout
= sub
->expire
;
1875 why
= "expire subscription";
1879 * Adjust from absolute to relative time. If p->browse_time above
1880 * was 0 then we can end up with a negative value here, so check.
1881 * We add 1 second to the timeout since events occur after the
1882 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1883 * to avoid select() timeout limits present on some operating
1887 timeout
= timeout
- now
+ 1;
1891 else if (timeout
> 86400)
1895 * Log and return the timeout value...
1898 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1906 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1910 sigchld_handler(int sig
) /* I - Signal number */
1915 * Flag that we have dead children...
1921 * Reset the signal handler as needed...
1924 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1925 signal(SIGCLD
, sigchld_handler
);
1926 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1931 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1935 sighup_handler(int sig
) /* I - Signal number */
1939 NeedReload
= RELOAD_ALL
;
1940 ReloadTime
= time(NULL
);
1942 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1943 signal(SIGHUP
, sighup_handler
);
1944 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1949 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1953 sigterm_handler(int sig
) /* I - Signal number */
1955 (void)sig
; /* remove compiler warnings... */
1958 * Flag that we should stop and return...
1966 * 'usage()' - Show scheduler usage.
1970 usage(int status
) /* O - Exit status */
1972 FILE *fp
= status
? stderr
: stdout
; /* Output file */
1975 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
1976 _cupsLangPuts(fp
, _("Options:"));
1977 _cupsLangPuts(fp
, _(" -c config-file Load alternate configuration "
1979 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
1980 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
1981 "detach from console."));
1982 _cupsLangPuts(fp
, _(" -h Show this usage message."));
1983 _cupsLangPuts(fp
, _(" -l Run cupsd from launchd(8)."));
1984 _cupsLangPuts(fp
, _(" -t Test the configuration "
1992 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".