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 senddoc_time
, /* Send-Document time */
124 expire_time
, /* Subscription expire time */
125 report_time
, /* Malloc/client/job report time */
126 event_time
; /* Last event notification time */
127 long timeout
; /* Timeout for cupsdDoSelect() */
128 struct rlimit limit
; /* Runtime limit */
129 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
130 struct sigaction action
; /* Actions for POSIX signals */
131 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
133 cups_file_t
*fp
; /* Fake lpsched lock file */
134 struct stat statbuf
; /* Needed for checking lpsched FIFO */
136 int run_as_child
= 0;
137 /* Needed for background fork/exec */
139 int use_sysman
= !getuid();
140 /* Use system management functions? */
142 time_t netif_time
= 0; /* Time since last network update */
143 #endif /* __APPLE__ */
145 int launchd_idle_exit
;
146 /* Idle exit on select timeout? */
147 #endif /* HAVE_LAUNCHD */
152 * Check for setuid invocation, which we do not support!
155 if (getuid() != geteuid())
157 fputs("cupsd: Cannot run as a setuid program\n", stderr
);
160 #endif /* HAVE_GETEUID */
163 * Check for command-line arguments...
169 if (getenv("CUPSD_LAUNCHD"))
174 #endif /* HAVE_LAUNCHD */
176 for (i
= 1; i
< argc
; i
++)
177 if (argv
[i
][0] == '-')
178 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
181 case 'C' : /* Run as child with config file */
185 case 'c' : /* Configuration file */
189 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
190 "after \"-c\" option."));
194 if (argv
[i
][0] == '/')
197 * Absolute directory...
200 cupsdSetString(&ConfigurationFile
, argv
[i
]);
205 * Relative directory...
208 char *current
; /* Current directory */
212 * Allocate a buffer for the current working directory to
213 * reduce run-time stack usage; this approximates the
214 * behavior of some implementations of getcwd() when they
215 * are passed a NULL pointer.
218 if ((current
= malloc(1024)) == NULL
)
220 _cupsLangPuts(stderr
,
221 _("cupsd: Unable to get current directory."));
225 if (!getcwd(current
, 1024))
227 _cupsLangPuts(stderr
,
228 _("cupsd: Unable to get current directory."));
233 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
238 case 'f' : /* Run in foreground... */
242 case 'F' : /* Run in foreground, but disconnect from terminal... */
246 case 'h' : /* Show usage/help */
250 case 'l' : /* Started by launchd... */
255 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
256 "in, running in normal mode."));
258 #endif /* HAVE_LAUNCHD */
261 case 'p' : /* Stop immediately for profiling */
262 fputs("cupsd: -p (startup profiling) is for internal testing "
263 "use only!\n", stderr
);
268 case 'P' : /* Disable security profiles */
269 fputs("cupsd: -P (disable security profiles) is for internal "
270 "testing use only!\n", stderr
);
275 case 'S' : /* Disable system management functions */
276 fputs("cupsd: -S (disable system management) for internal "
277 "testing use only!\n", stderr
);
280 #endif /* __APPLE__ */
282 case 't' : /* Test the cupsd.conf file... */
287 default : /* Unknown option */
288 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
295 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
300 if (!ConfigurationFile
)
301 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
304 * If the user hasn't specified "-f", run in the background...
310 * Setup signal handlers for the parent...
313 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
314 sigset(SIGUSR1
, parent_handler
);
315 sigset(SIGCHLD
, parent_handler
);
317 sigset(SIGHUP
, SIG_IGN
);
318 #elif defined(HAVE_SIGACTION)
319 memset(&action
, 0, sizeof(action
));
320 sigemptyset(&action
.sa_mask
);
321 sigaddset(&action
.sa_mask
, SIGUSR1
);
322 action
.sa_handler
= parent_handler
;
323 sigaction(SIGUSR1
, &action
, NULL
);
324 sigaction(SIGCHLD
, &action
, NULL
);
326 sigemptyset(&action
.sa_mask
);
327 action
.sa_handler
= SIG_IGN
;
328 sigaction(SIGHUP
, &action
, NULL
);
330 signal(SIGUSR1
, parent_handler
);
331 signal(SIGCLD
, parent_handler
);
333 signal(SIGHUP
, SIG_IGN
);
334 #endif /* HAVE_SIGSET */
339 * OK, wait for the child to startup and send us SIGUSR1 or to crash
340 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
341 * might be sent by the init script to restart the scheduler...
344 for (; parent_signal
== 0;)
347 if (parent_signal
== SIGUSR1
)
355 else if (WIFEXITED(i
))
357 fprintf(stderr
, "cupsd: Child exited with status %d\n",
363 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
370 * Call _thread_sys_closefrom() so the child process doesn't reset the
371 * parent's file descriptors to be blocking. This is a workaround for a
372 * limitation of userland libpthread on OpenBSD.
375 _thread_sys_closefrom(0);
376 #endif /* __OpenBSD__ */
379 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
380 * a program, and since this kind of really unfriendly behavior seems to be
381 * more common these days in system libraries, we need to re-execute the
382 * background cupsd with the "-C" option to avoid problems. Unfortunately,
383 * we also have to assume that argv[0] contains the name of the cupsd
384 * executable - there is no portable way to get the real pathname...
387 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
394 * Make sure we aren't tying up any filesystems...
401 * Disable core dumps...
404 getrlimit(RLIMIT_CORE
, &limit
);
406 setrlimit(RLIMIT_CORE
, &limit
);
409 * Disconnect from the controlling terminal...
415 * Close all open files...
418 getrlimit(RLIMIT_NOFILE
, &limit
);
420 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
424 * Redirect stdin/out/err to /dev/null...
427 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
433 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
439 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
448 * Set the timezone info...
454 setlocale(LC_TIME
, "");
458 * Set the maximum number of files...
461 getrlimit(RLIMIT_NOFILE
, &limit
);
463 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
464 if (limit
.rlim_max
> FD_SETSIZE
)
467 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
469 if (limit
.rlim_max
== RLIM_INFINITY
)
472 #endif /* RLIM_INFINITY */
473 MaxFDs
= limit
.rlim_max
;
475 limit
.rlim_cur
= MaxFDs
;
477 setrlimit(RLIMIT_NOFILE
, &limit
);
482 * Read configuration...
485 if (!cupsdReadConfiguration())
488 printf("%s contains errors\n", ConfigurationFile
);
490 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
494 else if (TestConfigFile
)
496 printf("%s is OK\n", ConfigurationFile
);
501 * Clean out old temp files and printer cache data.
504 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
505 cupsdCleanFiles(TempDir
, NULL
);
507 cupsdCleanFiles(CacheDir
, "*.ipp");
513 * If we were started by launchd get the listen sockets file descriptors...
519 #endif /* HAVE_LAUNCHD */
522 * Startup the server...
530 * Catch hangup and child signals and ignore broken pipes...
533 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
534 sigset(SIGCHLD
, sigchld_handler
);
535 sigset(SIGHUP
, sighup_handler
);
536 sigset(SIGPIPE
, SIG_IGN
);
537 sigset(SIGTERM
, sigterm_handler
);
538 #elif defined(HAVE_SIGACTION)
539 memset(&action
, 0, sizeof(action
));
541 sigemptyset(&action
.sa_mask
);
542 sigaddset(&action
.sa_mask
, SIGTERM
);
543 sigaddset(&action
.sa_mask
, SIGCHLD
);
544 action
.sa_handler
= sigchld_handler
;
545 sigaction(SIGCHLD
, &action
, NULL
);
547 sigemptyset(&action
.sa_mask
);
548 sigaddset(&action
.sa_mask
, SIGHUP
);
549 action
.sa_handler
= sighup_handler
;
550 sigaction(SIGHUP
, &action
, NULL
);
552 sigemptyset(&action
.sa_mask
);
553 action
.sa_handler
= SIG_IGN
;
554 sigaction(SIGPIPE
, &action
, NULL
);
556 sigemptyset(&action
.sa_mask
);
557 sigaddset(&action
.sa_mask
, SIGTERM
);
558 sigaddset(&action
.sa_mask
, SIGCHLD
);
559 action
.sa_handler
= sigterm_handler
;
560 sigaction(SIGTERM
, &action
, NULL
);
562 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
563 signal(SIGHUP
, sighup_handler
);
564 signal(SIGPIPE
, SIG_IGN
);
565 signal(SIGTERM
, sigterm_handler
);
566 #endif /* HAVE_SIGSET */
570 * Try to create a fake lpsched lock file if one is not already there.
571 * Some Adobe applications need it under IRIX in order to enable
575 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
577 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
578 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
583 fchmod(cupsFileNumber(fp
), 0644);
584 fchown(cupsFileNumber(fp
), User
, Group
);
591 * Initialize authentication certificates...
597 * If we are running in the background, signal the parent process that
598 * we are up and running...
601 if (!fg
|| run_as_child
)
604 * Send a signal to the parent process, but only if the parent is
605 * not PID 1 (init). This avoids accidentally shutting down the
606 * system on OpenBSD if you CTRL-C the server before it is up...
609 i
= getppid(); /* Save parent PID to avoid race condition */
617 * Start power management framework...
621 cupsdStartSystemMonitor();
622 #endif /* __APPLE__ */
625 * Send server-started event...
630 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
631 "Scheduler started via launchd.");
633 #endif /* HAVE_LAUNCHD */
635 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
636 "Scheduler started in foreground.");
638 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
,
639 "Scheduler started in background.");
642 * Start any pending print jobs...
651 current_time
= time(NULL
);
652 event_time
= current_time
;
653 expire_time
= current_time
;
656 senddoc_time
= current_time
;
658 while (!stop_scheduler
)
661 * Check if there are dead children to handle...
668 * Check if we need to load the server configuration file...
674 * Close any idle clients...
677 if (cupsArrayCount(Clients
) > 0)
679 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
681 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
682 if (con
->http
.state
== HTTP_WAITING
)
683 cupsdCloseClient(con
);
685 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
687 cupsdPauseListening();
691 * Restart if all clients are closed and all jobs finished, or
692 * if the reload timeout has elapsed...
695 if ((cupsArrayCount(Clients
) == 0 &&
696 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
697 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
700 * Shutdown the server...
708 * Read configuration...
711 if (!cupsdReadConfiguration())
713 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
722 * If we were started by launchd, get the listen socket file
729 #endif /* HAVE_LAUNCHD */
732 * Startup the server...
740 * Send a server-restarted event...
743 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
744 "Scheduler restarted.");
749 * Check for available input or ready output. If cupsdDoSelect()
750 * returns 0 or -1, something bad happened and we should exit
753 * Note that we at least have one listening socket open at all
757 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
762 * If no other work is scheduled and we're being controlled by
763 * launchd then timeout after 'LaunchdTimeout' seconds of
767 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&&
768 !cupsArrayCount(ActiveJobs
) &&
769 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
771 timeout
= LaunchdTimeout
;
772 launchd_idle_exit
= 1;
775 launchd_idle_exit
= 0;
776 #endif /* HAVE_LAUNCHD */
778 if ((fds
= cupsdDoSelect(timeout
)) < 0)
781 * Got an error from select!
785 cupsd_printer_t
*p
; /* Current printer */
786 #endif /* HAVE_DNSSD */
789 if (errno
== EINTR
) /* Just interrupted by a signal */
793 * Log all sorts of debug info to help track down the problem.
796 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
799 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
801 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
802 cupsdLogMessage(CUPSD_LOG_EMERG
,
803 "Clients[%d] = %d, file = %d, state = %d",
804 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
806 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
808 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
809 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
811 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
814 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
816 #endif /* __APPLE__ */
818 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
820 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
821 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
823 job
->status_buffer
? job
->status_buffer
->fd
: -1,
824 job
->print_pipes
[0], job
->print_pipes
[1],
825 job
->back_pipes
[0], job
->back_pipes
[1]);
828 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
830 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
831 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
832 p
->reg_name
? p
->reg_name
: "(null)");
833 #endif /* HAVE_DNSSD */
838 current_time
= time(NULL
);
841 * Write dirty config/state files...
844 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
849 * If we are going to sleep and still have pending jobs, stop them after
850 * a period of time...
853 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
854 cupsArrayCount(PrintingJobs
) > 0)
857 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
859 #endif /* __APPLE__ */
863 * Update the network interfaces once a minute...
866 if ((current_time
- netif_time
) >= 60)
868 netif_time
= current_time
;
871 #endif /* !__APPLE__ */
875 * If no other work was scheduled and we're being controlled by launchd
876 * then timeout after 'LaunchdTimeout' seconds of inactivity...
879 if (!fds
&& launchd_idle_exit
)
881 cupsdLogMessage(CUPSD_LOG_INFO
,
882 "Printer sharing is off and there are no jobs pending, "
883 "will restart on demand.");
887 #endif /* HAVE_LAUNCHD */
890 * Resume listening for new connections as needed...
893 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
894 cupsArrayCount(Clients
) < MaxClients
)
895 cupsdResumeListening();
898 * Expire subscriptions and unload completed jobs as needed...
901 if (current_time
> expire_time
)
903 if (cupsArrayCount(Subscriptions
) > 0)
904 cupsdExpireSubscriptions(NULL
, NULL
);
906 cupsdUnloadCompletedJobs();
908 expire_time
= current_time
;
911 #ifndef HAVE_AUTHORIZATION_H
913 * Update the root certificate once every 5 minutes if we have client
917 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
918 !RunUser
&& cupsArrayCount(Clients
))
921 * Update the root certificate...
925 cupsdAddCert(0, "root", NULL
);
927 #endif /* !HAVE_AUTHORIZATION_H */
930 * Check for new data on the client sockets...
933 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
935 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
938 * Process pending data in the input buffer...
943 cupsdReadClient(con
);
948 * Check the activity and close old clients...
951 activity
= current_time
- Timeout
;
952 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
954 cupsdLogMessage(CUPSD_LOG_DEBUG
,
955 "Closing client %d after %d seconds of inactivity...",
956 con
->http
.fd
, Timeout
);
958 cupsdCloseClient(con
);
964 * Update any pending multi-file documents...
967 if ((current_time
- senddoc_time
) >= 10)
971 senddoc_time
= current_time
;
975 * Log statistics at most once a minute when in debug mode...
978 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
980 size_t string_count
, /* String count */
981 alloc_bytes
, /* Allocated string bytes */
982 total_bytes
; /* Total string bytes */
984 struct mallinfo mem
; /* Malloc information */
988 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
989 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
990 mem
.usmblks
+ mem
.uordblks
);
991 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
992 mem
.fsmblks
+ mem
.fordblks
);
993 #endif /* HAVE_MALLINFO */
995 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
996 cupsArrayCount(Clients
));
997 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
998 cupsArrayCount(Jobs
));
999 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1000 cupsArrayCount(ActiveJobs
));
1001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1002 cupsArrayCount(Printers
));
1004 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1005 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1006 "Report: stringpool-string-count=" CUPS_LLFMT
,
1007 CUPS_LLCAST string_count
);
1008 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1009 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1010 CUPS_LLCAST alloc_bytes
);
1011 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1012 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1013 CUPS_LLCAST total_bytes
);
1015 report_time
= current_time
;
1019 * Handle OS-specific event notification for any events that have
1020 * accumulated. Don't send these more than once a second...
1023 if (LastEvent
&& (current_time
- event_time
) >= 1)
1025 #ifdef HAVE_NOTIFY_POST
1026 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1027 CUPSD_EVENT_PRINTER_DELETED
|
1028 CUPSD_EVENT_PRINTER_MODIFIED
))
1030 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1031 "notify_post(\"com.apple.printerListChange\")");
1032 notify_post("com.apple.printerListChange");
1035 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1037 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1038 "notify_post(\"com.apple.printerHistoryChange\")");
1039 notify_post("com.apple.printerHistoryChange");
1042 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1043 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1044 CUPSD_EVENT_JOB_PROGRESS
))
1046 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1047 "notify_post(\"com.apple.jobChange\")");
1048 notify_post("com.apple.jobChange");
1050 #endif /* HAVE_NOTIFY_POST */
1053 * Reset the accumulated events...
1056 LastEvent
= CUPSD_EVENT_NONE
;
1057 event_time
= current_time
;
1062 * Log a message based on what happened...
1067 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1068 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1069 "Scheduler shutting down normally.");
1073 cupsdLogMessage(CUPSD_LOG_ERROR
,
1074 "Scheduler shutting down due to program error.");
1075 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1076 "Scheduler shutting down due to program error.");
1080 * Close all network clients...
1089 * Update the launchd KeepAlive file as needed...
1094 #endif /* HAVE_LAUNCHD */
1104 * Stop monitoring system event monitoring...
1108 cupsdStopSystemMonitor();
1109 #endif /* __APPLE__ */
1113 * Free the scheduler's Kerberos context...
1118 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
1122 if (krb5_init_context
!= NULL
)
1123 # endif /* __APPLE__ */
1124 if (KerberosContext
)
1125 krb5_free_context(KerberosContext
);
1126 #endif /* HAVE_GSSAPI */
1130 * Remove the fake IRIX lpsched lock file, but only if the existing
1131 * file is not a FIFO which indicates that the real IRIX lpsched is
1135 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1136 if (!S_ISFIFO(statbuf
.st_mode
))
1137 unlink("/var/spool/lp/SCHEDLOCK");
1142 return (!stop_scheduler
);
1147 * 'cupsdAddString()' - Copy and add a string to an array.
1150 int /* O - 1 on success, 0 on failure */
1151 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1152 const char *s
) /* I - String to copy and add */
1155 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1156 (cups_ahash_func_t
)NULL
, 0,
1157 (cups_acopy_func_t
)_cupsStrAlloc
,
1158 (cups_afree_func_t
)_cupsStrFree
);
1160 return (cupsArrayAdd(*a
, (char *)s
));
1165 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1169 cupsdCheckProcess(void)
1172 * Flag that we have dead children...
1180 * 'cupsdClearString()' - Clear a string.
1184 cupsdClearString(char **s
) /* O - String value */
1195 * 'cupsdFreeStrings()' - Free an array of strings.
1199 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1203 cupsArrayDelete(*a
);
1210 * 'cupsdHoldSignals()' - Hold child and termination signals.
1214 cupsdHoldSignals(void)
1216 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1217 sigset_t newmask
; /* New POSIX signal mask */
1218 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1228 #elif defined(HAVE_SIGACTION)
1229 sigemptyset(&newmask
);
1230 sigaddset(&newmask
, SIGTERM
);
1231 sigaddset(&newmask
, SIGCHLD
);
1232 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1233 #endif /* HAVE_SIGSET */
1238 * 'cupsdReleaseSignals()' - Release signals for delivery.
1242 cupsdReleaseSignals(void)
1251 #elif defined(HAVE_SIGACTION)
1252 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1253 #endif /* HAVE_SIGSET */
1258 * 'cupsdSetString()' - Set a string value.
1262 cupsdSetString(char **s
, /* O - New string */
1263 const char *v
) /* I - String value */
1272 *s
= _cupsStrAlloc(v
);
1279 * 'cupsdSetStringf()' - Set a formatted string value.
1283 cupsdSetStringf(char **s
, /* O - New string */
1284 const char *f
, /* I - Printf-style format string */
1285 ...) /* I - Additional args as needed */
1287 char v
[4096]; /* Formatting string value */
1288 va_list ap
; /* Argument pointer */
1289 char *olds
; /* Old string */
1300 vsnprintf(v
, sizeof(v
), f
, ap
);
1303 *s
= _cupsStrAlloc(v
);
1315 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1319 launchd_checkin(void)
1321 size_t i
, /* Looping var */
1322 count
; /* Number of listeners */
1323 launch_data_t ld_msg
, /* Launch data message */
1324 ld_resp
, /* Launch data response */
1325 ld_array
, /* Launch data array */
1326 ld_sockets
, /* Launch data sockets dictionary */
1327 tmp
; /* Launch data */
1328 cupsd_listener_t
*lis
; /* Listeners array */
1329 http_addr_t addr
; /* Address variable */
1330 socklen_t addrlen
; /* Length of address */
1331 int fd
; /* File descriptor */
1332 char s
[256]; /* String addresss */
1335 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1338 * Check-in with launchd...
1341 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1342 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1344 cupsdLogMessage(CUPSD_LOG_ERROR
,
1345 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1348 return; /* anti-compiler-warning */
1351 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1353 errno
= launch_data_get_errno(ld_resp
);
1354 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1357 return; /* anti-compiler-warning */
1361 * Get the sockets dictionary...
1364 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1367 cupsdLogMessage(CUPSD_LOG_ERROR
,
1368 "launchd_checkin: No sockets found to answer requests on!");
1370 return; /* anti-compiler-warning */
1374 * Get the array of listener sockets...
1377 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1379 cupsdLogMessage(CUPSD_LOG_ERROR
,
1380 "launchd_checkin: No sockets found to answer requests on!");
1382 return; /* anti-compiler-warning */
1386 * Add listening fd(s) to the Listener array...
1389 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1391 count
= launch_data_array_get_count(ld_array
);
1393 for (i
= 0; i
< count
; i
++)
1396 * Get the launchd file descriptor and address...
1399 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1401 fd
= launch_data_get_fd(tmp
);
1402 addrlen
= sizeof(addr
);
1404 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1406 cupsdLogMessage(CUPSD_LOG_ERROR
,
1407 "launchd_checkin: Unable to get local address - %s",
1413 * Try to match the launchd socket address to one of the listeners...
1416 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1418 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1419 if (httpAddrEqual(&lis
->address
, &addr
))
1423 * Add a new listener If there's no match...
1428 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1429 "launchd_checkin: Matched existing listener %s with fd %d...",
1430 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1434 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1435 "launchd_checkin: Adding new listener %s with fd %d...",
1436 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1438 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1440 cupsdLogMessage(CUPSD_LOG_ERROR
,
1441 "launchd_checkin: Unable to allocate listener - "
1442 "%s.", strerror(errno
));
1446 cupsArrayAdd(Listeners
, lis
);
1448 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1454 if (_httpAddrPort(&(lis
->address
)) == 443)
1455 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1456 # endif /* HAVE_SSL */
1461 launch_data_free(ld_msg
);
1462 launch_data_free(ld_resp
);
1467 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1471 launchd_checkout(void)
1473 int fd
; /* File descriptor */
1477 * Create or remove the launchd KeepAlive file based on whether
1478 * there are active jobs, polling, browsing for remote printers or
1479 * shared printers to advertise...
1482 if (cupsArrayCount(ActiveJobs
) ||
1483 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
1485 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1486 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
1489 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1494 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1495 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
1498 unlink(CUPS_KEEPALIVE
);
1501 #endif /* HAVE_LAUNCHD */
1505 * 'parent_handler()' - Catch USR1/CHLD signals...
1509 parent_handler(int sig
) /* I - Signal */
1512 * Store the signal we got from the OS and return...
1515 parent_signal
= sig
;
1520 * 'process_children()' - Process all dead children...
1524 process_children(void)
1526 int status
; /* Exit status of child */
1527 int pid
, /* Process ID of child */
1528 job_id
; /* Job ID of child */
1529 cupsd_job_t
*job
; /* Current job */
1530 int i
; /* Looping var */
1531 char name
[1024]; /* Process name */
1532 const char *type
; /* Type of program */
1535 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1538 * Reset the dead_children flag...
1544 * Collect the exit status of some children...
1548 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1549 #elif defined(HAVE_WAIT3)
1550 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1552 if ((pid
= wait(&status
)) > 0)
1553 #endif /* HAVE_WAITPID */
1556 * Collect the name of the process that finished...
1559 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1562 * Delete certificates for CGI processes...
1566 cupsdDeleteCert(pid
);
1569 * Handle completed job filters...
1573 job
= cupsdFindJob(job_id
);
1579 for (i
= 0; job
->filters
[i
]; i
++)
1580 if (job
->filters
[i
] == pid
)
1583 if (job
->filters
[i
] || job
->backend
== pid
)
1586 * OK, this process has gone away; what's left?
1589 if (job
->filters
[i
])
1591 job
->filters
[i
] = -pid
;
1596 job
->backend
= -pid
;
1600 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1601 status
!= SIGPIPE
&& job
->status
>= 0)
1604 * An error occurred; save the exit status so we know to stop
1605 * the printer or cancel the job when all of the filters finish...
1607 * A negative status indicates that the backend failed and the
1608 * printer needs to be stopped.
1611 if (job
->filters
[i
])
1612 job
->status
= status
; /* Filter failed */
1614 job
->status
= -status
; /* Backend failed */
1616 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1617 job
->status_level
> CUPSD_LOG_ERROR
&&
1618 (job
->filters
[i
] || !WIFEXITED(status
)))
1620 char message
[1024]; /* New printer-state-message */
1623 job
->status_level
= CUPSD_LOG_ERROR
;
1625 snprintf(message
, sizeof(message
), "%s failed", type
);
1629 strlcpy(job
->printer
->state_message
, message
,
1630 sizeof(job
->printer
->state_message
));
1636 if (!job
->printer_message
&& job
->attrs
)
1638 if ((job
->printer_message
=
1639 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1640 IPP_TAG_TEXT
)) == NULL
)
1641 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1643 "job-printer-state-message",
1647 if (job
->printer_message
)
1648 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1654 * If this is not the last file in a job, see if all of the
1655 * filters are done, and if so move to the next file.
1658 if (job
->current_file
< job
->num_files
&& job
->printer
)
1660 for (i
= 0; job
->filters
[i
] < 0; i
++);
1662 if (!job
->filters
[i
] &&
1663 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1667 * Process the next file...
1670 cupsdContinueJob(job
);
1673 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1676 * Remove the job from the active list if there are no processes still
1680 for (i
= 0; job
->filters
[i
] < 0; i
++);
1682 if (!job
->filters
[i
] && job
->backend
<= 0)
1683 cupsArrayRemove(ActiveJobs
, job
);
1689 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1690 * since they come when we kill/end a process...
1693 if (status
== SIGTERM
|| status
== SIGKILL
)
1695 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1696 "PID %d (%s) was terminated normally with signal %d.", pid
,
1699 else if (status
== SIGPIPE
)
1701 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1702 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1707 if (WIFEXITED(status
))
1709 int code
= WEXITSTATUS(status
); /* Exit code */
1712 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1713 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1714 code
, strerror(code
- 100));
1716 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1717 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1720 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1721 pid
, name
, WTERMSIG(status
));
1723 if (LogLevel
< CUPSD_LOG_DEBUG
)
1724 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1725 "Hint: Try setting the LogLevel to \"debug\" to find out "
1729 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1734 * If wait*() is interrupted by a signal, tell main() to call us again...
1737 if (pid
< 0 && errno
== EINTR
)
1743 * 'select_timeout()' - Calculate the select timeout value.
1747 static long /* O - Number of seconds */
1748 select_timeout(int fds
) /* I - Number of descriptors returned */
1750 long timeout
; /* Timeout for select */
1751 time_t now
; /* Current time */
1752 cupsd_client_t
*con
; /* Client information */
1753 cupsd_job_t
*job
; /* Job information */
1754 cupsd_subscription_t
*sub
; /* Subscription information */
1755 const char *why
; /* Debugging aid */
1759 * Check to see if any of the clients have pending data to be
1760 * processed; if so, the timeout should be 0...
1763 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1765 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1766 if (con
->http
.used
> 0)
1770 * If select has been active in the last second (fds > 0) or we have
1771 * many resources in use then don't bother trying to optimize the
1772 * timeout, just make it 1 second.
1775 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1779 * Otherwise, check all of the possible events that we need to wake for...
1783 timeout
= now
+ 86400; /* 86400 == 1 day */
1788 * When going to sleep, wake up to cancel jobs that don't complete in time.
1791 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1793 timeout
= SleepJobs
;
1794 why
= "cancel jobs before sleeping";
1796 #endif /* __APPLE__ */
1799 * Check whether we are accepting new connections...
1802 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1803 ListeningPaused
< timeout
)
1805 if (ListeningPaused
<= now
)
1808 timeout
= ListeningPaused
;
1810 why
= "resume listening";
1814 * Check the activity and close old clients...
1817 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1819 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1820 if ((con
->http
.activity
+ Timeout
) < timeout
)
1822 timeout
= con
->http
.activity
+ Timeout
;
1823 why
= "timeout a client connection";
1827 * Write out changes to configuration and state files...
1830 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1832 timeout
= DirtyCleanTime
;
1833 why
= "write dirty config/state files";
1837 * Check for any active jobs...
1840 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1842 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1844 if (job
->kill_time
&& job
->kill_time
< timeout
)
1846 timeout
= job
->kill_time
;
1847 why
= "kill unresponsive jobs";
1849 else if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1851 timeout
= job
->cancel_time
;
1852 why
= "cancel stuck jobs";
1854 else if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1856 timeout
= job
->hold_until
;
1857 why
= "release held jobs";
1859 else if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1862 why
= "start pending jobs";
1867 #ifdef HAVE_MALLINFO
1869 * Log memory usage every minute...
1872 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1874 timeout
= mallinfo_time
+ 60;
1875 why
= "display memory usage";
1877 #endif /* HAVE_MALLINFO */
1880 * Expire subscriptions as needed...
1883 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1885 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1886 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1888 timeout
= sub
->expire
;
1889 why
= "expire subscription";
1893 * Adjust from absolute to relative time. We add 1 second to the timeout since
1894 * events occur after the timeout expires, and limit the timeout to 86400
1895 * seconds (1 day) to avoid select() timeout limits present on some operating
1899 timeout
= timeout
- now
+ 1;
1903 else if (timeout
> 86400)
1907 * Log and return the timeout value...
1910 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1918 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1922 sigchld_handler(int sig
) /* I - Signal number */
1927 * Flag that we have dead children...
1933 * Reset the signal handler as needed...
1936 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1937 signal(SIGCLD
, sigchld_handler
);
1938 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1943 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1947 sighup_handler(int sig
) /* I - Signal number */
1951 NeedReload
= RELOAD_ALL
;
1952 ReloadTime
= time(NULL
);
1954 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1955 signal(SIGHUP
, sighup_handler
);
1956 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1961 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1965 sigterm_handler(int sig
) /* I - Signal number */
1967 (void)sig
; /* remove compiler warnings... */
1970 * Flag that we should stop and return...
1978 * 'usage()' - Show scheduler usage.
1982 usage(int status
) /* O - Exit status */
1984 FILE *fp
= status
? stderr
: stdout
; /* Output file */
1987 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
1988 _cupsLangPuts(fp
, _("Options:"));
1989 _cupsLangPuts(fp
, _(" -c config-file Load alternate configuration "
1991 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
1992 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
1993 "detach from console."));
1994 _cupsLangPuts(fp
, _(" -h Show this usage message."));
1995 _cupsLangPuts(fp
, _(" -l Run cupsd from launchd(8)."));
1996 _cupsLangPuts(fp
, _(" -t Test the configuration "
2004 * End of "$Id: main.c 7925 2008-09-10 17:47:26Z mike $".