2 * "$Id: main.c 6755 2007-08-01 19:02:47Z mike $"
4 * Scheduler main loop for the Common UNIX Printing System (CUPS).
6 * Copyright 2007 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * "LICENSE" which should have been included with this file. If this
13 * file is missing or damaged, see the license at "http://www.cups.org/".
17 * main() - Main entry for the CUPS scheduler.
18 * cupsdClosePipe() - Close a pipe as necessary.
19 * cupsdOpenPipe() - Create a pipe which is closed on exec.
20 * cupsdHoldSignals() - Hold child and termination signals.
21 * cupsdReleaseSignals() - Release signals for delivery.
22 * cupsdSetString() - Set a string value.
23 * cupsdSetStringf() - Set a formatted string value.
24 * launchd_checkin() - Check-in with launchd and collect the
26 * launchd_checkout() - Check-out with launchd.
27 * parent_handler() - Catch USR1/CHLD signals...
28 * process_children() - Process all dead children...
29 * sigchld_handler() - Handle 'child' signals from old processes.
30 * sighup_handler() - Handle 'hangup' signals to reconfigure the
32 * sigterm_handler() - Handle 'terminate' signals that stop the
34 * select_timeout() - Calculate the select timeout value.
35 * usage() - Show scheduler usage.
39 * Include necessary headers...
44 #include <sys/resource.h>
52 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
53 /* Name of the launchd KeepAlive file */
54 # ifndef LAUNCH_JOBKEY_KEEPALIVE
55 # define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
56 # endif /* !LAUNCH_JOBKEY_KEEPALIVE */
57 # ifndef LAUNCH_JOBKEY_PATHSTATE
58 # define LAUNCH_JOBKEY_PATHSTATE "PathState"
59 # endif /* !LAUNCH_JOBKEY_PATHSTATE */
60 # ifndef LAUNCH_JOBKEY_SERVICEIPC
61 # define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
62 # endif /* !LAUNCH_JOBKEY_SERVICEIPC */
63 #endif /* HAVE_LAUNCH_H */
65 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
67 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
70 #endif /* HAVE_NOTIFY_H */
72 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
74 #endif /* __APPLE__ && HAVE_DLFCN_H */
82 static void launchd_checkin(void);
83 static void launchd_checkout(void);
84 #endif /* HAVE_LAUNCHD */
85 static void parent_handler(int sig
);
86 static void process_children(void);
87 static void sigchld_handler(int sig
);
88 static void sighup_handler(int sig
);
89 static void sigterm_handler(int sig
);
90 static long select_timeout(int fds
);
91 static void usage(int status
);
98 static int parent_signal
= 0;
99 /* Set to signal number from child */
100 static int holdcount
= 0; /* Number of times "hold" was called */
101 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
102 static sigset_t holdmask
; /* Old POSIX signal mask */
103 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
104 static int dead_children
= 0;
106 static int stop_scheduler
= 0;
107 /* Should the scheduler stop? */
109 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
110 static const char *PSQLibPath
= "/usr/lib/libPrintServiceQuota.dylib";
111 static const char *PSQLibFuncName
= "PSQUpdateQuota";
112 static void *PSQLibRef
; /* libPrintServiceQuota.dylib */
113 #endif /* HAVE_DLFCN_H */
117 * 'main()' - Main entry for the CUPS scheduler.
120 int /* O - Exit status */
121 main(int argc
, /* I - Number of command-line args */
122 char *argv
[]) /* I - Command-line arguments */
124 int i
; /* Looping var */
125 char *opt
; /* Option character */
126 int fg
; /* Run in the foreground */
127 int fds
; /* Number of ready descriptors */
128 cupsd_client_t
*con
; /* Current client */
129 cupsd_job_t
*job
; /* Current job */
130 cupsd_listener_t
*lis
; /* Current listener */
131 time_t current_time
, /* Current time */
132 activity
, /* Client activity timer */
133 browse_time
, /* Next browse send time */
134 senddoc_time
, /* Send-Document time */
135 expire_time
, /* Subscription expire time */
136 mallinfo_time
; /* Malloc information time */
137 size_t string_count
, /* String count */
138 alloc_bytes
, /* Allocated string bytes */
139 total_bytes
; /* Total string bytes */
140 long timeout
; /* Timeout for cupsdDoSelect() */
141 struct rlimit limit
; /* Runtime limit */
142 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
143 struct sigaction action
; /* Actions for POSIX signals */
144 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
146 cups_file_t
*fp
; /* Fake lpsched lock file */
147 struct stat statbuf
; /* Needed for checking lpsched FIFO */
150 int launchd_idle_exit
;
151 /* Idle exit on select timeout? */
152 #endif /* HAVE_LAUNCHD */
156 * Check for command-line arguments...
162 if (getenv("CUPSD_LAUNCHD"))
167 #endif /* HAVE_LAUNCHD */
169 for (i
= 1; i
< argc
; i
++)
170 if (argv
[i
][0] == '-')
171 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
174 case 'c' : /* Configuration file */
178 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
179 "after \"-c\" option!\n"));
183 if (argv
[i
][0] == '/')
186 * Absolute directory...
189 cupsdSetString(&ConfigurationFile
, argv
[i
]);
194 * Relative directory...
197 char *current
; /* Current directory */
201 * Allocate a buffer for the current working directory to
202 * reduce run-time stack usage; this approximates the
203 * behavior of some implementations of getcwd() when they
204 * are passed a NULL pointer.
207 current
= malloc(1024);
208 getcwd(current
, 1024);
210 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
216 case 'f' : /* Run in foreground... */
220 case 'F' : /* Run in foreground, but disconnect from terminal... */
224 case 'h' : /* Show usage/help */
228 case 'l' : /* Started by launchd... */
233 _cupsLangPuts(stderr
, _("cupsd: launchd(8) support not compiled "
234 "in, running in normal mode.\n"));
236 #endif /* HAVE_LAUNCHD */
239 case 'p' : /* Stop immediately for profiling */
240 puts("Warning: -p option is for internal testing use only!");
245 default : /* Unknown option */
246 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
247 "aborting!\n"), *opt
);
253 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
258 if (!ConfigurationFile
)
259 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
262 * If the user hasn't specified "-f", run in the background...
268 * Setup signal handlers for the parent...
271 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
272 sigset(SIGUSR1
, parent_handler
);
273 sigset(SIGCHLD
, parent_handler
);
275 sigset(SIGHUP
, SIG_IGN
);
276 #elif defined(HAVE_SIGACTION)
277 memset(&action
, 0, sizeof(action
));
278 sigemptyset(&action
.sa_mask
);
279 sigaddset(&action
.sa_mask
, SIGUSR1
);
280 action
.sa_handler
= parent_handler
;
281 sigaction(SIGUSR1
, &action
, NULL
);
282 sigaction(SIGCHLD
, &action
, NULL
);
284 sigemptyset(&action
.sa_mask
);
285 action
.sa_handler
= SIG_IGN
;
286 sigaction(SIGHUP
, &action
, NULL
);
288 signal(SIGUSR1
, parent_handler
);
289 signal(SIGCLD
, parent_handler
);
291 signal(SIGHUP
, SIG_IGN
);
292 #endif /* HAVE_SIGSET */
297 * OK, wait for the child to startup and send us SIGUSR1 or to crash
298 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
299 * might be sent by the init script to restart the scheduler...
302 for (; parent_signal
== 0;)
305 if (parent_signal
== SIGUSR1
)
313 else if (WIFEXITED(i
))
315 fprintf(stderr
, "cupsd: Child exited with status %d!\n",
321 fprintf(stderr
, "cupsd: Child exited on signal %d!\n", WTERMSIG(i
));
330 * Make sure we aren't tying up any filesystems...
337 * Disable core dumps...
340 getrlimit(RLIMIT_CORE
, &limit
);
342 setrlimit(RLIMIT_CORE
, &limit
);
345 * Disconnect from the controlling terminal...
351 * Close all open files...
354 getrlimit(RLIMIT_NOFILE
, &limit
);
356 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
362 * Set the timezone info...
368 setlocale(LC_TIME
, "");
372 * Set the maximum number of files...
375 getrlimit(RLIMIT_NOFILE
, &limit
);
377 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
378 if (limit
.rlim_max
> FD_SETSIZE
)
381 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
383 if (limit
.rlim_max
== RLIM_INFINITY
)
386 #endif /* RLIM_INFINITY */
387 MaxFDs
= limit
.rlim_max
;
389 limit
.rlim_cur
= MaxFDs
;
391 setrlimit(RLIMIT_NOFILE
, &limit
);
396 * Read configuration...
399 if (!cupsdReadConfiguration())
401 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
406 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
409 * Clean out the temporary directory...
412 cups_dir_t
*dir
; /* Temporary directory */
413 cups_dentry_t
*dent
; /* Directory entry */
414 char tempfile
[1024]; /* Temporary filename */
417 if ((dir
= cupsDirOpen(TempDir
)) != NULL
)
419 cupsdLogMessage(CUPSD_LOG_INFO
,
420 "Cleaning out old temporary files in \"%s\"...", TempDir
);
422 while ((dent
= cupsDirRead(dir
)) != NULL
)
424 snprintf(tempfile
, sizeof(tempfile
), "%s/%s", TempDir
, dent
->filename
);
426 if (cupsdRemoveFile(tempfile
))
427 cupsdLogMessage(CUPSD_LOG_ERROR
,
428 "Unable to remove temporary file \"%s\" - %s",
429 tempfile
, strerror(errno
));
431 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removed temporary file \"%s\"...",
438 cupsdLogMessage(CUPSD_LOG_ERROR
,
439 "Unable to open temporary directory \"%s\" - %s",
440 TempDir
, strerror(errno
));
447 * If we were started by launchd get the listen sockets file descriptors...
452 #endif /* HAVE_LAUNCHD */
454 #if defined(__APPLE__) && defined(HAVE_DLFCN_H)
456 * Load Print Service quota enforcement library (X Server only)
459 PSQLibRef
= dlopen(PSQLibPath
, RTLD_LAZY
);
462 PSQUpdateQuotaProc
= dlsym(PSQLibRef
, PSQLibFuncName
);
463 #endif /* __APPLE__ && HAVE_DLFCN_H */
468 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
472 if (krb5_init_context
!= NULL
)
473 # endif /* __APPLE__ */
476 * Setup a Kerberos context for the scheduler to use...
479 if (krb5_init_context(&KerberosContext
))
480 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to initialize Kerberos context");
481 #endif /* HAVE_GSSAPI */
484 * Startup the server...
490 * Catch hangup and child signals and ignore broken pipes...
493 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
494 sigset(SIGCHLD
, sigchld_handler
);
495 sigset(SIGHUP
, sighup_handler
);
496 sigset(SIGPIPE
, SIG_IGN
);
497 sigset(SIGTERM
, sigterm_handler
);
498 #elif defined(HAVE_SIGACTION)
499 memset(&action
, 0, sizeof(action
));
501 sigemptyset(&action
.sa_mask
);
502 sigaddset(&action
.sa_mask
, SIGTERM
);
503 sigaddset(&action
.sa_mask
, SIGCHLD
);
504 action
.sa_handler
= sigchld_handler
;
505 sigaction(SIGCHLD
, &action
, NULL
);
507 sigemptyset(&action
.sa_mask
);
508 sigaddset(&action
.sa_mask
, SIGHUP
);
509 action
.sa_handler
= sighup_handler
;
510 sigaction(SIGHUP
, &action
, NULL
);
512 sigemptyset(&action
.sa_mask
);
513 action
.sa_handler
= SIG_IGN
;
514 sigaction(SIGPIPE
, &action
, NULL
);
516 sigemptyset(&action
.sa_mask
);
517 sigaddset(&action
.sa_mask
, SIGTERM
);
518 sigaddset(&action
.sa_mask
, SIGCHLD
);
519 action
.sa_handler
= sigterm_handler
;
520 sigaction(SIGTERM
, &action
, NULL
);
522 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
523 signal(SIGHUP
, sighup_handler
);
524 signal(SIGPIPE
, SIG_IGN
);
525 signal(SIGTERM
, sigterm_handler
);
526 #endif /* HAVE_SIGSET */
530 * Try to create a fake lpsched lock file if one is not already there.
531 * Some Adobe applications need it under IRIX in order to enable
535 if ((fp
= cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL
)
537 syslog(LOG_LPR
, "Unable to create fake lpsched lock file "
538 "\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
543 fchmod(cupsFileNumber(fp
), 0644);
544 fchown(cupsFileNumber(fp
), User
, Group
);
551 * Initialize authentication certificates...
557 * If we are running in the background, signal the parent process that
558 * we are up and running...
564 * Send a signal to the parent process, but only if the parent is
565 * not PID 1 (init). This avoids accidentally shutting down the
566 * system on OpenBSD if you CTRL-C the server before it is up...
569 i
= getppid(); /* Save parent PID to avoid race condition */
577 * Start power management framework...
580 cupsdStartSystemMonitor();
581 #endif /* __APPLE__ */
584 * Start any pending print jobs...
594 browse_time
= time(NULL
);
595 senddoc_time
= time(NULL
);
596 expire_time
= time(NULL
);
599 while (!stop_scheduler
)
602 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
603 "main: Top of loop, dead_children=%d, NeedReload=%d",
604 dead_children
, NeedReload
);
608 * Check if there are dead children to handle...
615 * Check if we need to load the server configuration file...
621 * Close any idle clients...
624 if (cupsArrayCount(Clients
) > 0)
626 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
628 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
629 if (con
->http
.state
== HTTP_WAITING
)
630 cupsdCloseClient(con
);
632 con
->http
.keep_alive
= HTTP_KEEPALIVE_OFF
;
634 cupsdPauseListening();
638 * Check for any active jobs...
641 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
643 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
644 if (job
->state_value
== IPP_JOB_PROCESSING
)
648 * Restart if all clients are closed and all jobs finished, or
649 * if the reload timeout has elapsed...
652 if ((cupsArrayCount(Clients
) == 0 &&
653 (!job
|| NeedReload
!= RELOAD_ALL
)) ||
654 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
657 * Shutdown the server...
663 * Read configuration...
666 if (!cupsdReadConfiguration())
668 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
677 * If we were started by launchd get the listen sockets file descriptors...
682 #endif /* HAVE_LAUNCHD */
685 * Startup the server...
693 * Check for available input or ready output. If cupsdDoSelect()
694 * returns 0 or -1, something bad happened and we should exit
697 * Note that we at least have one listening socket open at all
701 timeout
= select_timeout(fds
);
705 * If no other work is scheduled and we're being controlled by
706 * launchd then timeout after 'LaunchdTimeout' seconds of
710 if (timeout
== 86400 && Launchd
&& LaunchdTimeout
&& !NumPolled
&&
711 !cupsArrayCount(ActiveJobs
) &&
713 (!BrowseRemoteProtocols
&&
714 (!NumBrowsers
|| !BrowseLocalProtocols
||
715 cupsArrayCount(Printers
) == 0))))
717 timeout
= LaunchdTimeout
;
718 launchd_idle_exit
= 1;
721 launchd_idle_exit
= 0;
722 #endif /* HAVE_LAUNCHD */
724 if ((fds
= cupsdDoSelect(timeout
)) < 0)
727 * Got an error from select!
731 cupsd_printer_t
*p
; /* Current printer */
732 #endif /* HAVE_DNSSD */
735 if (errno
== EINTR
) /* Just interrupted by a signal */
739 * Log all sorts of debug info to help track down the problem.
742 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
745 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
747 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
748 cupsdLogMessage(CUPSD_LOG_EMERG
,
749 "Clients[%d] = %d, file = %d, state = %d",
750 i
, con
->http
.fd
, con
->file
, con
->http
.state
);
752 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
754 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
755 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
757 cupsdLogMessage(CUPSD_LOG_EMERG
, "BrowseSocket = %d", BrowseSocket
);
759 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
762 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
764 #endif /* __APPLE__ */
766 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
768 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
769 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
771 job
->status_buffer
? job
->status_buffer
->fd
: -1,
772 job
->print_pipes
[0], job
->print_pipes
[1],
773 job
->back_pipes
[0], job
->back_pipes
[1]);
776 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
778 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
779 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] %d", p
->name
,
781 #endif /* HAVE_DNSSD */
786 current_time
= time(NULL
);
790 * If no other work was scheduled and we're being controlled by launchd
791 * then timeout after 'LaunchdTimeout' seconds of inactivity...
794 if (!fds
&& launchd_idle_exit
)
796 cupsdLogMessage(CUPSD_LOG_INFO
,
797 "Printer sharing is off and there are no jobs pending, "
798 "will restart on demand.");
802 #endif /* HAVE_LAUNCHD */
805 * Expire subscriptions and unload completed jobs as needed...
808 if (current_time
> expire_time
)
810 if (cupsArrayCount(Subscriptions
) > 0)
811 cupsdExpireSubscriptions(NULL
, NULL
);
813 cupsdUnloadCompletedJobs();
815 expire_time
= current_time
;
819 * Update the browse list as needed...
825 if ((BrowseRemoteProtocols
& BROWSE_SLP
) &&
826 BrowseSLPRefresh
<= current_time
)
827 cupsdUpdateSLPBrowse();
828 #endif /* HAVE_LIBSLP */
831 if ((BrowseRemoteProtocols
& BROWSE_LDAP
) &&
832 BrowseLDAPRefresh
<= current_time
)
833 cupsdUpdateLDAPBrowse();
834 #endif /* HAVE_LDAP */
837 if (Browsing
&& BrowseLocalProtocols
&& current_time
> browse_time
)
839 cupsdSendBrowseList();
840 browse_time
= current_time
;
844 * Update the root certificate once every 5 minutes if we have client
848 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
849 !RunUser
&& cupsArrayCount(Clients
))
852 * Update the root certificate...
856 cupsdAddCert(0, "root");
860 * Check for new data on the client sockets...
863 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
865 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
868 * Process pending data in the input buffer...
873 cupsdReadClient(con
);
878 * Check the activity and close old clients...
881 activity
= current_time
- Timeout
;
882 if (con
->http
.activity
< activity
&& !con
->pipe_pid
)
884 cupsdLogMessage(CUPSD_LOG_DEBUG
,
885 "Closing client %d after %d seconds of inactivity...",
886 con
->http
.fd
, Timeout
);
888 cupsdCloseClient(con
);
894 * Update any pending multi-file documents...
897 if ((current_time
- senddoc_time
) >= 10)
900 senddoc_time
= current_time
;
904 * Log memory usage every minute...
907 if ((current_time
- mallinfo_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG2
)
910 struct mallinfo mem
; /* Malloc information */
914 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
915 "mallinfo: arena = %d, used = %d, free = %d\n",
916 mem
.arena
, mem
.usmblks
+ mem
.uordblks
,
917 mem
.fsmblks
+ mem
.fordblks
);
918 #endif /* HAVE_MALLINFO */
920 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
921 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
922 "stringpool: " CUPS_LLFMT
" strings, "
923 CUPS_LLFMT
" allocated, " CUPS_LLFMT
" total bytes",
924 CUPS_LLCAST string_count
, CUPS_LLCAST alloc_bytes
,
925 CUPS_LLCAST total_bytes
);
927 mallinfo_time
= current_time
;
931 * Handle OS-specific event notification for any events that have
932 * accumulated. Don't send these more than once a second...
937 #ifdef HAVE_NOTIFY_POST
938 if (LastEvent
& CUPSD_EVENT_PRINTER_CHANGED
)
940 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
941 "notify_post(\"com.apple.printerListChange\")");
942 notify_post("com.apple.printerListChange");
945 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
947 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
948 "notify_post(\"com.apple.printerHistoryChange\")");
949 notify_post("com.apple.printerHistoryChange");
952 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
953 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
954 CUPSD_EVENT_JOB_PROGRESS
))
956 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
957 "notify_post(\"com.apple.jobChange\")");
958 notify_post("com.apple.jobChange");
960 #endif /* HAVE_NOTIFY_POST */
963 * Reset the accumulated events...
966 LastEvent
= CUPSD_EVENT_NONE
;
971 * Log a message based on what happened...
975 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
977 cupsdLogMessage(CUPSD_LOG_ERROR
,
978 "Scheduler shutting down due to program error.");
981 * Close all network clients and stop all jobs...
989 cupsdStopSystemMonitor();
990 #endif /* __APPLE__ */
995 * If the weak-linked GSSAPI/Kerberos library is not present, don't try
999 if (krb5_init_context
!= NULL
)
1000 # endif /* __APPLE__ */
1003 * Free the scheduler's Kerberos context...
1006 krb5_free_context(KerberosContext
);
1007 #endif /* HAVE_GSSAPI */
1011 * Update the launchd KeepAlive file as needed...
1016 #endif /* HAVE_LAUNCHD */
1021 * Unload Print Service quota enforcement library (X Server only)
1024 PSQUpdateQuotaProc
= NULL
;
1030 #endif /* HAVE_DLFCN_H */
1031 #endif /* __APPLE__ */
1035 * Remove the fake IRIX lpsched lock file, but only if the existing
1036 * file is not a FIFO which indicates that the real IRIX lpsched is
1040 if (!stat("/var/spool/lp/FIFO", &statbuf
))
1041 if (!S_ISFIFO(statbuf
.st_mode
))
1042 unlink("/var/spool/lp/SCHEDLOCK");
1047 return (!stop_scheduler
);
1052 * 'cupsdClosePipe()' - Close a pipe as necessary.
1056 cupsdClosePipe(int *fds
) /* I - Pipe file descriptors (2) */
1059 * Close file descriptors as needed...
1077 * 'cupsdOpenPipe()' - Create a pipe which is closed on exec.
1080 int /* O - 0 on success, -1 on error */
1081 cupsdOpenPipe(int *fds
) /* O - Pipe file descriptors (2) */
1084 * Create the pipe...
1096 * Set the "close on exec" flag on each end of the pipe...
1099 if (fcntl(fds
[0], F_SETFD
, fcntl(fds
[0], F_GETFD
) | FD_CLOEXEC
))
1110 if (fcntl(fds
[1], F_SETFD
, fcntl(fds
[1], F_GETFD
) | FD_CLOEXEC
))
1122 * Return 0 indicating success...
1130 * 'cupsdClearString()' - Clear a string.
1134 cupsdClearString(char **s
) /* O - String value */
1145 * 'cupsdHoldSignals()' - Hold child and termination signals.
1149 cupsdHoldSignals(void)
1151 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1152 sigset_t newmask
; /* New POSIX signal mask */
1153 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1163 #elif defined(HAVE_SIGACTION)
1164 sigemptyset(&newmask
);
1165 sigaddset(&newmask
, SIGTERM
);
1166 sigaddset(&newmask
, SIGCHLD
);
1167 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1168 #endif /* HAVE_SIGSET */
1173 * 'cupsdReleaseSignals()' - Release signals for delivery.
1177 cupsdReleaseSignals(void)
1186 #elif defined(HAVE_SIGACTION)
1187 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1188 #endif /* HAVE_SIGSET */
1193 * 'cupsdSetString()' - Set a string value.
1197 cupsdSetString(char **s
, /* O - New string */
1198 const char *v
) /* I - String value */
1207 *s
= _cupsStrAlloc(v
);
1214 * 'cupsdSetStringf()' - Set a formatted string value.
1218 cupsdSetStringf(char **s
, /* O - New string */
1219 const char *f
, /* I - Printf-style format string */
1220 ...) /* I - Additional args as needed */
1222 char v
[4096]; /* Formatting string value */
1223 va_list ap
; /* Argument pointer */
1224 char *olds
; /* Old string */
1235 vsnprintf(v
, sizeof(v
), f
, ap
);
1238 *s
= _cupsStrAlloc(v
);
1250 * 'launchd_checkin()' - Check-in with launchd and collect the listening fds.
1254 launchd_checkin(void)
1256 int i
, /* Looping var */
1257 count
, /* Numebr of listeners */
1258 portnum
; /* Port number */
1259 launch_data_t ld_msg
, /* Launch data message */
1260 ld_resp
, /* Launch data response */
1261 ld_array
, /* Launch data array */
1262 ld_sockets
, /* Launch data sockets dictionary */
1263 tmp
; /* Launch data */
1264 cupsd_listener_t
*lis
; /* Listeners array */
1265 http_addr_t addr
; /* Address variable */
1266 socklen_t addrlen
; /* Length of address */
1267 int fd
; /* File descriptor */
1268 char s
[256]; /* String addresss */
1271 cupsdLogMessage(CUPSD_LOG_DEBUG
, "launchd_checkin: pid=%d", (int)getpid());
1274 * Check-in with launchd...
1277 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1278 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1280 cupsdLogMessage(CUPSD_LOG_ERROR
,
1281 "launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1286 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1288 errno
= launch_data_get_errno(ld_resp
);
1289 cupsdLogMessage(CUPSD_LOG_ERROR
, "launchd_checkin: Check-in failed: %s",
1295 * Get the sockets dictionary...
1298 if (!(ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
)))
1300 cupsdLogMessage(CUPSD_LOG_ERROR
,
1301 "launchd_checkin: No sockets found to answer requests on!");
1306 * Get the array of listener sockets...
1309 if (!(ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")))
1311 cupsdLogMessage(CUPSD_LOG_ERROR
,
1312 "launchd_checkin: No sockets found to answer requests on!");
1317 * Add listening fd(s) to the Listener array...
1320 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1322 count
= launch_data_array_get_count(ld_array
);
1324 for (i
= 0; i
< count
; i
++)
1327 * Get the launchd file descriptor and address...
1330 tmp
= launch_data_array_get_index(ld_array
, i
);
1331 fd
= launch_data_get_fd(tmp
);
1332 addrlen
= sizeof(addr
);
1334 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1336 cupsdLogMessage(CUPSD_LOG_ERROR
,
1337 "launchd_checkin: Unable to get local address - %s",
1343 * Try to match the launchd socket address to one of the listeners...
1346 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1348 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1349 if (httpAddrEqual(&lis
->address
, &addr
))
1353 * Add a new listener If there's no match...
1358 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1359 "launchd_checkin: Matched existing listener %s with fd %d...",
1360 httpAddrString(&(lis
->address
), s
, sizeof(s
)), fd
);
1364 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1365 "launchd_checkin: Adding new listener %s with fd %d...",
1366 httpAddrString(&addr
, s
, sizeof(s
)), fd
);
1368 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1370 cupsdLogMessage(CUPSD_LOG_ERROR
,
1371 "launchd_checkin: Unable to allocate listener - %s.",
1376 cupsArrayAdd(Listeners
, lis
);
1378 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1387 if (lis
->address
.addr
.sa_family
== AF_INET6
)
1388 portnum
= ntohs(lis
->address
.ipv6
.sin6_port
);
1390 # endif /* AF_INET6 */
1391 if (lis
->address
.addr
.sa_family
== AF_INET
)
1392 portnum
= ntohs(lis
->address
.ipv4
.sin_port
);
1395 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1396 # endif /* HAVE_SSL */
1400 launch_data_free(ld_msg
);
1401 launch_data_free(ld_resp
);
1406 * 'launchd_checkout()' - Update the launchd KeepAlive file as needed.
1410 launchd_checkout(void)
1412 int fd
; /* File descriptor */
1416 * Create or remove the launchd KeepAlive file based on whether
1417 * there are active jobs, polling, browsing for remote printers or
1418 * shared printers to advertise...
1421 if ((cupsArrayCount(ActiveJobs
) || NumPolled
||
1423 (BrowseRemoteProtocols
||
1424 (BrowseLocalProtocols
&& NumBrowsers
&& cupsArrayCount(Printers
))))))
1426 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1427 "Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1429 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
1434 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1435 "Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
1437 unlink(CUPS_KEEPALIVE
);
1440 #endif /* HAVE_LAUNCHD */
1444 * 'parent_handler()' - Catch USR1/CHLD signals...
1448 parent_handler(int sig
) /* I - Signal */
1451 * Store the signal we got from the OS and return...
1454 parent_signal
= sig
;
1459 * 'process_children()' - Process all dead children...
1463 process_children(void)
1465 int status
; /* Exit status of child */
1466 int pid
; /* Process ID of child */
1467 cupsd_job_t
*job
; /* Current job */
1468 int i
; /* Looping var */
1469 char name
[1024]; /* Process name */
1472 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1475 * Reset the dead_children flag...
1481 * Collect the exit status of some children...
1485 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1486 #elif defined(HAVE_WAIT3)
1487 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1489 if ((pid
= wait(&status
)) > 0)
1490 #endif /* HAVE_WAITPID */
1493 * Ignore SIGTERM errors - that comes when a job is canceled...
1496 cupsdFinishProcess(pid
, name
, sizeof(name
));
1498 if (status
== SIGTERM
)
1503 if (WIFEXITED(status
))
1504 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) stopped with status %d!",
1505 pid
, name
, WEXITSTATUS(status
));
1507 cupsdLogMessage(CUPSD_LOG_ERROR
, "PID %d (%s) crashed on signal %d!",
1508 pid
, name
, WTERMSIG(status
));
1510 if (LogLevel
< CUPSD_LOG_DEBUG
)
1511 cupsdLogMessage(CUPSD_LOG_INFO
,
1512 "Hint: Try setting the LogLevel to \"debug\" to find "
1516 cupsdLogMessage(CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1520 * Delete certificates for CGI processes...
1524 cupsdDeleteCert(pid
);
1527 * Lookup the PID in the jobs list...
1530 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1532 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1533 if (job
->state_value
== IPP_JOB_PROCESSING
)
1535 for (i
= 0; job
->filters
[i
]; i
++)
1536 if (job
->filters
[i
] == pid
)
1539 if (job
->filters
[i
] || job
->backend
== pid
)
1542 * OK, this process has gone away; what's left?
1545 if (job
->filters
[i
])
1546 job
->filters
[i
] = -pid
;
1548 job
->backend
= -pid
;
1550 if (status
&& job
->status
>= 0)
1553 * An error occurred; save the exit status so we know to stop
1554 * the printer or cancel the job when all of the filters finish...
1556 * A negative status indicates that the backend failed and the
1557 * printer needs to be stopped.
1560 if (job
->filters
[i
])
1561 job
->status
= status
; /* Filter failed */
1563 job
->status
= -status
; /* Backend failed */
1565 if (job
->printer
&& !(job
->printer
->type
& CUPS_PRINTER_FAX
))
1567 snprintf(job
->printer
->state_message
,
1568 sizeof(job
->printer
->state_message
), "%s failed", name
);
1569 cupsdAddPrinterHistory(job
->printer
);
1574 * If this is not the last file in a job, see if all of the
1575 * filters are done, and if so move to the next file.
1578 if (job
->current_file
< job
->num_files
)
1580 for (i
= 0; job
->filters
[i
] < 0; i
++);
1582 if (!job
->filters
[i
])
1585 * Process the next file...
1588 cupsdFinishJob(job
);
1599 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1603 sigchld_handler(int sig
) /* I - Signal number */
1608 * Flag that we have dead children...
1614 * Reset the signal handler as needed...
1617 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1618 signal(SIGCLD
, sigchld_handler
);
1619 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1624 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1628 sighup_handler(int sig
) /* I - Signal number */
1632 NeedReload
= RELOAD_ALL
;
1633 ReloadTime
= time(NULL
);
1635 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1636 signal(SIGHUP
, sighup_handler
);
1637 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1642 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1646 sigterm_handler(int sig
) /* I - Signal */
1648 (void)sig
; /* remove compiler warnings... */
1651 * Flag that we should stop and return...
1659 * 'select_timeout()' - Calculate the select timeout value.
1663 static long /* O - Number of seconds */
1664 select_timeout(int fds
) /* I - Number of descriptors returned */
1666 long timeout
; /* Timeout for select */
1667 time_t now
; /* Current time */
1668 cupsd_client_t
*con
; /* Client information */
1669 cupsd_printer_t
*p
; /* Printer information */
1670 cupsd_job_t
*job
; /* Job information */
1671 cupsd_subscription_t
*sub
; /* Subscription information */
1672 const char *why
; /* Debugging aid */
1676 * Check to see if any of the clients have pending data to be
1677 * processed; if so, the timeout should be 0...
1680 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1682 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1683 if (con
->http
.used
> 0)
1687 * If select has been active in the last second (fds > 0) or we have
1688 * many resources in use then don't bother trying to optimize the
1689 * timeout, just make it 1 second.
1692 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1696 * Otherwise, check all of the possible events that we need to wake for...
1700 timeout
= now
+ 86400; /* 86400 == 1 day */
1704 * Check the activity and close old clients...
1707 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1709 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1710 if ((con
->http
.activity
+ Timeout
) < timeout
)
1712 timeout
= con
->http
.activity
+ Timeout
;
1713 why
= "timeout a client connection";
1717 * Update the browse list as needed...
1720 if (Browsing
&& BrowseLocalProtocols
)
1723 if ((BrowseLocalProtocols
& BROWSE_SLP
) && (BrowseSLPRefresh
< timeout
))
1725 timeout
= BrowseSLPRefresh
;
1726 why
= "update SLP browsing";
1728 #endif /* HAVE_LIBSLP */
1731 if ((BrowseLocalProtocols
& BROWSE_LDAP
) && (BrowseLDAPRefresh
< timeout
))
1733 timeout
= BrowseLDAPRefresh
;
1734 why
= "update LDAP browsing";
1736 #endif /* HAVE_LDAP */
1738 if ((BrowseLocalProtocols
& BROWSE_CUPS
) && NumBrowsers
)
1740 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
1742 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
1744 if (p
->type
& CUPS_PRINTER_REMOTE
)
1746 if ((p
->browse_time
+ BrowseTimeout
) < timeout
)
1748 timeout
= p
->browse_time
+ BrowseTimeout
;
1749 why
= "browse timeout a printer";
1752 else if (p
->shared
&& !(p
->type
& CUPS_PRINTER_IMPLICIT
))
1754 if (BrowseInterval
&& (p
->browse_time
+ BrowseInterval
) < timeout
)
1756 timeout
= p
->browse_time
+ BrowseInterval
;
1757 why
= "send browse update";
1765 * Check for any active jobs...
1768 if (timeout
> (now
+ 10) && ActiveJobs
)
1770 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1772 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1773 if (job
->state_value
<= IPP_JOB_PROCESSING
)
1776 why
= "process active jobs";
1781 #ifdef HAVE_MALLINFO
1783 * Log memory usage every minute...
1786 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1788 timeout
= mallinfo_time
+ 60;
1789 why
= "display memory usage";
1791 #endif /* HAVE_MALLINFO */
1794 * Expire subscriptions as needed...
1797 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1799 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1800 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1802 timeout
= sub
->expire
;
1803 why
= "expire subscription";
1807 * Adjust from absolute to relative time. If p->browse_time above
1808 * was 0 then we can end up with a negative value here, so check.
1809 * We add 1 second to the timeout since events occur after the
1810 * timeout expires, and limit the timeout to 86400 seconds (1 day)
1811 * to avoid select() timeout limits present on some operating
1815 timeout
= timeout
- now
+ 1;
1819 else if (timeout
> 86400)
1823 * Log and return the timeout value...
1826 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1834 * 'usage()' - Show scheduler usage.
1838 usage(int status
) /* O - Exit status */
1840 _cupsLangPuts(status
? stderr
: stdout
,
1841 _("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
1843 "-c config-file Load alternate configuration file\n"
1844 "-f Run in the foreground\n"
1845 "-F Run in the foreground but detach\n"
1846 "-h Show this usage message\n"
1847 "-l Run cupsd from launchd(8)\n"));
1853 * End of "$Id: main.c 6755 2007-08-01 19:02:47Z mike $".