2 * Main loop for the CUPS scheduler.
4 * Copyright 2007-2016 by Apple Inc.
5 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * "LICENSE" which should have been included with this file. If this
11 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * Include necessary headers...
20 #include <sys/resource.h>
23 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
24 # define SD_JOURNAL_SUPPRESS_LOCATION
25 # include <systemd/sd-journal.h>
26 #endif /* HAVE_ASL_H */
33 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
34 /* Update when we have a public header we can include */
35 extern int launch_activate_socket(const char *name
, int **fds
, size_t *cnt
);
36 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
37 #endif /* HAVE_LAUNCH_H */
40 # include <systemd/sd-daemon.h>
41 #endif /* HAVE_SYSTEMD */
44 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
45 /* Name of the KeepAlive file */
48 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
50 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
54 #endif /* HAVE_NOTIFY_H */
57 # include <dbus/dbus.h>
58 #endif /* HAVE_DBUS */
60 #ifdef HAVE_SYS_PARAM_H
61 # include <sys/param.h>
62 #endif /* HAVE_SYS_PARAM_H */
69 static void parent_handler(int sig
);
70 static void process_children(void);
71 static void sigchld_handler(int sig
);
72 static void sighup_handler(int sig
);
73 static void sigterm_handler(int sig
);
74 static long select_timeout(int fds
);
75 #if defined(HAVE_ONDEMAND)
76 static void service_checkin(void);
77 static void service_checkout(void);
78 #endif /* HAVE_ONDEMAND */
79 static void usage(int status
) __attribute__((noreturn
));
86 static int parent_signal
= 0;
87 /* Set to signal number from child */
88 static int holdcount
= 0; /* Number of times "hold" was called */
89 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
90 static sigset_t holdmask
; /* Old POSIX signal mask */
91 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
92 static int dead_children
= 0;
94 static int stop_scheduler
= 0;
95 /* Should the scheduler stop? */
99 * 'main()' - Main entry for the CUPS scheduler.
102 int /* O - Exit status */
103 main(int argc
, /* I - Number of command-line args */
104 char *argv
[]) /* I - Command-line arguments */
106 int i
; /* Looping var */
107 char *opt
; /* Option character */
108 int close_all
= 1, /* Close all file descriptors? */
109 disconnect
= 1, /* Disconnect from controlling terminal? */
110 fg
= 0, /* Run in foreground? */
112 /* Running as child process? */
114 /* Print the sandbox profile to stdout? */
115 int fds
; /* Number of ready descriptors */
116 cupsd_client_t
*con
; /* Current client */
117 cupsd_job_t
*job
; /* Current job */
118 cupsd_listener_t
*lis
; /* Current listener */
119 time_t current_time
, /* Current time */
120 activity
, /* Client activity timer */
121 senddoc_time
, /* Send-Document time */
122 expire_time
, /* Subscription expire time */
123 report_time
, /* Malloc/client/job report time */
124 event_time
; /* Last event notification time */
125 long timeout
; /* Timeout for cupsdDoSelect() */
126 struct rlimit limit
; /* Runtime limit */
127 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
128 struct sigaction action
; /* Actions for POSIX signals */
129 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
131 int use_sysman
= 1; /* Use system management functions? */
133 time_t netif_time
= 0; /* Time since last network update */
134 #endif /* __APPLE__ */
135 #if defined(HAVE_ONDEMAND)
136 int service_idle_exit
;
137 /* Idle exit on select timeout? */
138 #endif /* HAVE_ONDEMAND */
143 * Check for setuid invocation, which we do not support!
146 if (getuid() != geteuid())
148 fputs("cupsd: Cannot run as a setuid program.\n", stderr
);
151 #endif /* HAVE_GETEUID */
154 * Check for command-line arguments...
160 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' : /* Run as child with config file */
179 case 'c' : /* Configuration file */
183 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
184 "after \"-c\" option."));
188 if (argv
[i
][0] == '/')
191 * Absolute directory...
194 cupsdSetString(&ConfigurationFile
, argv
[i
]);
199 * Relative directory...
202 char *current
; /* Current directory */
205 * Allocate a buffer for the current working directory to
206 * reduce run-time stack usage; this approximates the
207 * behavior of some implementations of getcwd() when they
208 * are passed a NULL pointer.
211 if ((current
= malloc(1024)) == NULL
)
213 _cupsLangPuts(stderr
,
214 _("cupsd: Unable to get current directory."));
218 if (!getcwd(current
, 1024))
220 _cupsLangPuts(stderr
,
221 _("cupsd: Unable to get current directory."));
226 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
231 case 'f' : /* Run in foreground... */
237 case 'F' : /* Run in foreground, but disconnect from terminal... */
242 case 'h' : /* Show usage/help */
246 case 'l' : /* Started by launchd/systemd/upstart... */
247 #if defined(HAVE_ONDEMAND)
253 _cupsLangPuts(stderr
, _("cupsd: On-demand support not compiled "
254 "in, running in normal mode."));
258 #endif /* HAVE_ONDEMAND */
261 case 'p' : /* Stop immediately for profiling */
262 fputs("cupsd: -p (startup profiling) is for internal testing "
263 "use only!\n", stderr
);
270 case 'P' : /* Disable security profiles */
271 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr
);
275 case 's' : /* Set cups-files.conf location */
279 _cupsLangPuts(stderr
, _("cupsd: Expected cups-files.conf "
280 "filename after \"-s\" option."));
284 if (argv
[i
][0] != '/')
287 * Relative filename not allowed...
290 _cupsLangPuts(stderr
, _("cupsd: Relative cups-files.conf "
291 "filename not allowed."));
295 cupsdSetString(&CupsFilesFile
, argv
[i
]);
299 case 'S' : /* Disable system management functions */
300 fputs("cupsd: -S (disable system management) for internal "
301 "testing use only!\n", stderr
);
304 #endif /* __APPLE__ */
306 case 't' : /* Test the cupsd.conf file... */
313 case 'T' : /* Print security profile */
320 default : /* Unknown option */
321 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
328 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
333 if (!ConfigurationFile
)
334 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
338 char *filename
, /* Copy of cupsd.conf filename */
339 *slash
; /* Final slash in cupsd.conf filename */
340 size_t len
; /* Size of buffer */
342 len
= strlen(ConfigurationFile
) + 15;
343 if ((filename
= malloc(len
)) == NULL
)
345 _cupsLangPrintf(stderr
,
346 _("cupsd: Unable to get path to "
347 "cups-files.conf file."));
351 strlcpy(filename
, ConfigurationFile
, len
);
352 if ((slash
= strrchr(filename
, '/')) == NULL
)
354 _cupsLangPrintf(stderr
,
355 _("cupsd: Unable to get path to "
356 "cups-files.conf file."));
360 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
361 cupsdSetString(&CupsFilesFile
, filename
);
368 * Make sure we aren't tying up any filesystems...
374 * Disconnect from the controlling terminal...
383 * Close all open files...
386 getrlimit(RLIMIT_NOFILE
, &limit
);
388 for (i
= 0; i
< (int)limit
.rlim_cur
&& i
< 1024; i
++)
392 * Redirect stdin/out/err to /dev/null...
395 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
401 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
407 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
414 LogStderr
= cupsFileStderr();
417 * Run in the background as needed...
423 * Setup signal handlers for the parent...
426 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
427 sigset(SIGUSR1
, parent_handler
);
428 sigset(SIGCHLD
, parent_handler
);
430 sigset(SIGHUP
, SIG_IGN
);
431 #elif defined(HAVE_SIGACTION)
432 memset(&action
, 0, sizeof(action
));
433 sigemptyset(&action
.sa_mask
);
434 sigaddset(&action
.sa_mask
, SIGUSR1
);
435 action
.sa_handler
= parent_handler
;
436 sigaction(SIGUSR1
, &action
, NULL
);
437 sigaction(SIGCHLD
, &action
, NULL
);
439 sigemptyset(&action
.sa_mask
);
440 action
.sa_handler
= SIG_IGN
;
441 sigaction(SIGHUP
, &action
, NULL
);
443 signal(SIGUSR1
, parent_handler
);
444 signal(SIGCLD
, parent_handler
);
446 signal(SIGHUP
, SIG_IGN
);
447 #endif /* HAVE_SIGSET */
452 * OK, wait for the child to startup and send us SIGUSR1 or to crash
453 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
454 * might be sent by the init script to restart the scheduler...
457 for (; parent_signal
== 0;)
460 if (parent_signal
== SIGUSR1
)
468 else if (WIFEXITED(i
))
470 fprintf(stderr
, "cupsd: Child exited with status %d\n",
476 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
481 #if defined(__OpenBSD__) && OpenBSD < 201211
483 * Call _thread_sys_closefrom() so the child process doesn't reset the
484 * parent's file descriptors to be blocking. This is a workaround for a
485 * limitation of userland libpthread on older versions of OpenBSD.
488 _thread_sys_closefrom(0);
489 #endif /* __OpenBSD__ && OpenBSD < 201211 */
492 * Since many system libraries create fork-unsafe data on execution of a
493 * program, we need to re-execute the background cupsd with the "-C" and "-s"
494 * options to avoid problems. Unfortunately, we also have to assume that
495 * argv[0] contains the name of the cupsd executable - there is no portable
496 * way to get the real pathname...
499 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, "-s", CupsFilesFile
, (char *)0);
504 * Set the timezone info...
510 setlocale(LC_TIME
, "");
513 #ifdef HAVE_DBUS_THREADS_INIT
515 * Enable threading support for D-BUS...
518 dbus_threads_init_default();
519 #endif /* HAVE_DBUS_THREADS_INIT */
522 * Set the maximum number of files...
525 getrlimit(RLIMIT_NOFILE
, &limit
);
527 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
528 if (limit
.rlim_max
> FD_SETSIZE
)
531 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
533 if (limit
.rlim_max
== RLIM_INFINITY
)
536 #endif /* RLIM_INFINITY */
537 MaxFDs
= limit
.rlim_max
;
539 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
541 setrlimit(RLIMIT_NOFILE
, &limit
);
546 * Read configuration...
549 if (!cupsdReadConfiguration())
551 else if (TestConfigFile
)
553 printf("\"%s\" is OK.\n", CupsFilesFile
);
554 printf("\"%s\" is OK.\n", ConfigurationFile
);
557 else if (print_profile
)
559 cups_file_t
*fp
; /* File pointer */
560 const char *profile
= cupsdCreateProfile(42, 0);
562 char line
[1024]; /* Line from file */
565 if ((fp
= cupsFileOpen(profile
, "r")) == NULL
)
567 printf("Unable to open profile file \"%s\": %s\n", profile
? profile
: "(null)", strerror(errno
));
571 while (cupsFileGets(fp
, line
, sizeof(line
)))
580 * Clean out old temp files and printer cache data.
583 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
584 cupsdCleanFiles(TempDir
, NULL
);
586 cupsdCleanFiles(CacheDir
, "*.ipp");
588 #if defined(HAVE_ONDEMAND)
592 * If we were started on demand by launchd or systemd get the listen sockets
593 * file descriptors...
599 #endif /* HAVE_ONDEMAND */
602 * Startup the server...
610 * Catch hangup and child signals and ignore broken pipes...
613 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
614 sigset(SIGCHLD
, sigchld_handler
);
615 sigset(SIGHUP
, sighup_handler
);
616 sigset(SIGPIPE
, SIG_IGN
);
617 sigset(SIGTERM
, sigterm_handler
);
618 #elif defined(HAVE_SIGACTION)
619 memset(&action
, 0, sizeof(action
));
621 sigemptyset(&action
.sa_mask
);
622 sigaddset(&action
.sa_mask
, SIGTERM
);
623 sigaddset(&action
.sa_mask
, SIGCHLD
);
624 action
.sa_handler
= sigchld_handler
;
625 sigaction(SIGCHLD
, &action
, NULL
);
627 sigemptyset(&action
.sa_mask
);
628 sigaddset(&action
.sa_mask
, SIGHUP
);
629 action
.sa_handler
= sighup_handler
;
630 sigaction(SIGHUP
, &action
, NULL
);
632 sigemptyset(&action
.sa_mask
);
633 action
.sa_handler
= SIG_IGN
;
634 sigaction(SIGPIPE
, &action
, NULL
);
636 sigemptyset(&action
.sa_mask
);
637 sigaddset(&action
.sa_mask
, SIGTERM
);
638 sigaddset(&action
.sa_mask
, SIGCHLD
);
639 action
.sa_handler
= sigterm_handler
;
640 sigaction(SIGTERM
, &action
, NULL
);
642 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
643 signal(SIGHUP
, sighup_handler
);
644 signal(SIGPIPE
, SIG_IGN
);
645 signal(SIGTERM
, sigterm_handler
);
646 #endif /* HAVE_SIGSET */
649 * Initialize authentication certificates...
655 * If we are running in the background, signal the parent process that
656 * we are up and running...
659 if (!fg
|| run_as_child
)
662 * Send a signal to the parent process, but only if the parent is
663 * not PID 1 (init). This avoids accidentally shutting down the
664 * system on OpenBSD if you CTRL-C the server before it is up...
667 i
= getppid(); /* Save parent PID to avoid race condition */
675 * Start power management framework...
679 cupsdStartSystemMonitor();
680 #endif /* __APPLE__ */
683 * Send server-started event...
686 #if defined(HAVE_ONDEMAND)
688 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
690 #endif /* HAVE_ONDEMAND */
692 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
694 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
697 * Start any pending print jobs...
706 current_time
= time(NULL
);
707 event_time
= current_time
;
708 expire_time
= current_time
;
711 senddoc_time
= current_time
;
713 while (!stop_scheduler
)
716 * Check if there are dead children to handle...
723 * Check if we need to load the server configuration file...
729 * Close any idle clients...
732 if (cupsArrayCount(Clients
) > 0)
734 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
736 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
737 if (httpGetState(con
->http
) == HTTP_WAITING
)
738 cupsdCloseClient(con
);
740 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
742 cupsdPauseListening();
746 * Restart if all clients are closed and all jobs finished, or
747 * if the reload timeout has elapsed...
750 if ((cupsArrayCount(Clients
) == 0 &&
751 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
752 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
755 * Shutdown the server...
758 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
761 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
768 * Read configuration...
771 if (!cupsdReadConfiguration())
774 asl_object_t m
; /* Log message */
776 m
= asl_new(ASL_TYPE_MSG
);
777 asl_set(m
, ASL_KEY_FACILITY
, "org.cups.cupsd");
778 asl_log(NULL
, m
, ASL_LEVEL_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
780 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
781 sd_journal_print(LOG_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
783 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting.", ConfigurationFile
);
784 #endif /* HAVE_ASL_H */
790 * Startup the server...
798 * Send a server-restarted event...
801 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
802 "Scheduler restarted.");
807 * Check for available input or ready output. If cupsdDoSelect()
808 * returns 0 or -1, something bad happened and we should exit
811 * Note that we at least have one listening socket open at all
815 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
818 #if defined(HAVE_ONDEMAND)
820 * If no other work is scheduled and we're being controlled by
821 * launchd then timeout after 'LaunchdTimeout' seconds of
825 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
826 !cupsArrayCount(ActiveJobs
) &&
829 # endif /* HAVE_SYSTEMD */
830 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
832 timeout
= IdleExitTimeout
;
833 service_idle_exit
= 1;
836 service_idle_exit
= 0;
837 #endif /* HAVE_ONDEMAND */
839 if ((fds
= cupsdDoSelect(timeout
)) < 0)
842 * Got an error from select!
845 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
846 cupsd_printer_t
*p
; /* Current printer */
847 #endif /* HAVE_DNSSD || HAVE_AVAHI */
850 if (errno
== EINTR
) /* Just interrupted by a signal */
854 * Log all sorts of debug info to help track down the problem.
857 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
860 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
862 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
863 cupsdLogMessage(CUPSD_LOG_EMERG
,
864 "Clients[%d] = %d, file = %d, state = %d",
865 i
, con
->number
, con
->file
, httpGetState(con
->http
));
867 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
869 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
870 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
872 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
875 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
877 #endif /* __APPLE__ */
879 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
881 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
882 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
884 job
->status_buffer
? job
->status_buffer
->fd
: -1,
885 job
->print_pipes
[0], job
->print_pipes
[1],
886 job
->back_pipes
[0], job
->back_pipes
[1]);
888 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
889 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
891 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
892 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
893 p
->reg_name
? p
->reg_name
: "(null)");
894 #endif /* HAVE_DNSSD || HAVE_AVAHI */
899 current_time
= time(NULL
);
902 * Write dirty config/state files...
905 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
910 * If we are going to sleep and still have pending jobs, stop them after
911 * a period of time...
914 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
915 cupsArrayCount(PrintingJobs
) > 0)
918 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
920 #endif /* __APPLE__ */
924 * Update the network interfaces once a minute...
927 if ((current_time
- netif_time
) >= 60)
929 netif_time
= current_time
;
932 #endif /* !__APPLE__ */
934 #if defined(HAVE_ONDEMAND)
936 * If no other work was scheduled and we're being controlled by launchd
937 * then timeout after 'LaunchdTimeout' seconds of inactivity...
940 if (!fds
&& service_idle_exit
)
942 cupsdLogMessage(CUPSD_LOG_INFO
,
943 "Printer sharing is off and there are no jobs pending, "
944 "will restart on demand.");
948 #endif /* HAVE_ONDEMAND */
951 * Resume listening for new connections as needed...
954 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
955 cupsArrayCount(Clients
) < MaxClients
)
956 cupsdResumeListening();
959 * Expire subscriptions and unload completed jobs as needed...
962 if (current_time
> expire_time
)
964 if (cupsArrayCount(Subscriptions
) > 0)
965 cupsdExpireSubscriptions(NULL
, NULL
);
967 cupsdUnloadCompletedJobs();
969 expire_time
= current_time
;
972 #ifndef HAVE_AUTHORIZATION_H
974 * Update the root certificate once every 5 minutes if we have client
978 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
979 !RunUser
&& cupsArrayCount(Clients
))
982 * Update the root certificate...
986 cupsdAddCert(0, "root", cupsdDefaultAuthType());
988 #endif /* !HAVE_AUTHORIZATION_H */
991 * Check for new data on the client sockets...
994 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
996 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
999 * Process pending data in the input buffer...
1002 if (httpGetReady(con
->http
))
1004 cupsdReadClient(con
);
1009 * Check the activity and close old clients...
1012 activity
= current_time
- Timeout
;
1013 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
1015 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
1017 cupsdCloseClient(con
);
1023 * Update any pending multi-file documents...
1026 if ((current_time
- senddoc_time
) >= 10)
1029 senddoc_time
= current_time
;
1033 * Clean job history...
1036 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
1040 * Log statistics at most once a minute when in debug mode...
1043 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1045 size_t string_count
, /* String count */
1046 alloc_bytes
, /* Allocated string bytes */
1047 total_bytes
; /* Total string bytes */
1048 #ifdef HAVE_MALLINFO
1049 struct mallinfo mem
; /* Malloc information */
1053 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1054 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1055 mem
.usmblks
+ mem
.uordblks
);
1056 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1057 mem
.fsmblks
+ mem
.fordblks
);
1058 #endif /* HAVE_MALLINFO */
1060 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1061 cupsArrayCount(Clients
));
1062 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1063 cupsArrayCount(Jobs
));
1064 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1065 cupsArrayCount(ActiveJobs
));
1066 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1067 cupsArrayCount(Printers
));
1069 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1070 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1071 "Report: stringpool-string-count=" CUPS_LLFMT
,
1072 CUPS_LLCAST string_count
);
1073 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1074 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1075 CUPS_LLCAST alloc_bytes
);
1076 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1077 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1078 CUPS_LLCAST total_bytes
);
1080 report_time
= current_time
;
1084 * Handle OS-specific event notification for any events that have
1085 * accumulated. Don't send these more than once a second...
1088 if (LastEvent
&& (current_time
- event_time
) >= 1)
1090 #ifdef HAVE_NOTIFY_POST
1091 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1092 CUPSD_EVENT_PRINTER_DELETED
|
1093 CUPSD_EVENT_PRINTER_MODIFIED
))
1095 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1096 "notify_post(\"com.apple.printerListChange\")");
1097 notify_post("com.apple.printerListChange");
1100 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1102 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1103 "notify_post(\"com.apple.printerHistoryChange\")");
1104 notify_post("com.apple.printerHistoryChange");
1107 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1108 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1109 CUPSD_EVENT_JOB_PROGRESS
))
1111 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1112 "notify_post(\"com.apple.jobChange\")");
1113 notify_post("com.apple.jobChange");
1115 #endif /* HAVE_NOTIFY_POST */
1118 * Reset the accumulated events...
1121 LastEvent
= CUPSD_EVENT_NONE
;
1122 event_time
= current_time
;
1127 * Log a message based on what happened...
1132 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1133 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1134 "Scheduler shutting down normally.");
1138 cupsdLogMessage(CUPSD_LOG_ERROR
,
1139 "Scheduler shutting down due to program error.");
1140 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1141 "Scheduler shutting down due to program error.");
1145 * Close all network clients...
1152 #if defined(HAVE_ONDEMAND)
1154 * Update the keep-alive file as needed...
1159 #endif /* HAVE_ONDEMAND */
1169 * Stop monitoring system event monitoring...
1173 cupsdStopSystemMonitor();
1174 #endif /* __APPLE__ */
1178 return (!stop_scheduler
);
1183 * 'cupsdAddString()' - Copy and add a string to an array.
1186 int /* O - 1 on success, 0 on failure */
1187 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1188 const char *s
) /* I - String to copy and add */
1191 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1192 (cups_ahash_func_t
)NULL
, 0,
1193 (cups_acopy_func_t
)strdup
,
1194 (cups_afree_func_t
)free
);
1196 return (cupsArrayAdd(*a
, (char *)s
));
1201 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1205 cupsdCheckProcess(void)
1208 * Flag that we have dead children...
1216 * 'cupsdClearString()' - Clear a string.
1220 cupsdClearString(char **s
) /* O - String value */
1231 * 'cupsdFreeStrings()' - Free an array of strings.
1235 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1239 cupsArrayDelete(*a
);
1246 * 'cupsdHoldSignals()' - Hold child and termination signals.
1250 cupsdHoldSignals(void)
1252 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1253 sigset_t newmask
; /* New POSIX signal mask */
1254 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1264 #elif defined(HAVE_SIGACTION)
1265 sigemptyset(&newmask
);
1266 sigaddset(&newmask
, SIGTERM
);
1267 sigaddset(&newmask
, SIGCHLD
);
1268 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1269 #endif /* HAVE_SIGSET */
1274 * 'cupsdReleaseSignals()' - Release signals for delivery.
1278 cupsdReleaseSignals(void)
1287 #elif defined(HAVE_SIGACTION)
1288 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1289 #endif /* HAVE_SIGSET */
1294 * 'cupsdSetString()' - Set a string value.
1298 cupsdSetString(char **s
, /* O - New string */
1299 const char *v
) /* I - String value */
1315 * 'cupsdSetStringf()' - Set a formatted string value.
1319 cupsdSetStringf(char **s
, /* O - New string */
1320 const char *f
, /* I - Printf-style format string */
1321 ...) /* I - Additional args as needed */
1323 char v
[65536 + 64]; /* Formatting string value */
1324 va_list ap
; /* Argument pointer */
1325 char *olds
; /* Old string */
1336 vsnprintf(v
, sizeof(v
), f
, ap
);
1350 * 'parent_handler()' - Catch USR1/CHLD signals...
1354 parent_handler(int sig
) /* I - Signal */
1357 * Store the signal we got from the OS and return...
1360 parent_signal
= sig
;
1365 * 'process_children()' - Process all dead children...
1369 process_children(void)
1371 int status
; /* Exit status of child */
1372 int pid
, /* Process ID of child */
1373 job_id
; /* Job ID of child */
1374 cupsd_job_t
*job
; /* Current job */
1375 int i
; /* Looping var */
1376 char name
[1024]; /* Process name */
1377 const char *type
; /* Type of program */
1380 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1383 * Reset the dead_children flag...
1389 * Collect the exit status of some children...
1393 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1394 #elif defined(HAVE_WAIT3)
1395 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1397 if ((pid
= wait(&status
)) > 0)
1398 #endif /* HAVE_WAITPID */
1401 * Collect the name of the process that finished...
1404 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1407 * Delete certificates for CGI processes...
1411 cupsdDeleteCert(pid
);
1414 * Handle completed job filters...
1418 job
= cupsdFindJob(job_id
);
1424 for (i
= 0; job
->filters
[i
]; i
++)
1425 if (job
->filters
[i
] == pid
)
1428 if (job
->filters
[i
] || job
->backend
== pid
)
1431 * OK, this process has gone away; what's left?
1434 if (job
->filters
[i
])
1436 job
->filters
[i
] = -pid
;
1441 job
->backend
= -pid
;
1445 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1449 * An error occurred; save the exit status so we know to stop
1450 * the printer or cancel the job when all of the filters finish...
1452 * A negative status indicates that the backend failed and the
1453 * printer needs to be stopped.
1455 * In order to preserve the most serious status, we always log
1456 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1457 * and SIGBUS) and prefer to log the backend exit status over a
1461 int old_status
= abs(job
->status
);
1463 if (WIFSIGNALED(status
) || /* This process crashed, or */
1464 !job
->status
|| /* No process had a status, or */
1465 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1466 { /* Backend and filter didn't crash */
1467 if (job
->filters
[i
])
1468 job
->status
= status
; /* Filter failed */
1470 job
->status
= -status
; /* Backend failed */
1473 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1474 job
->status_level
> CUPSD_LOG_ERROR
&&
1475 (job
->filters
[i
] || !WIFEXITED(status
)))
1477 char message
[1024]; /* New printer-state-message */
1480 job
->status_level
= CUPSD_LOG_ERROR
;
1482 snprintf(message
, sizeof(message
), "%s failed", type
);
1486 strlcpy(job
->printer
->state_message
, message
,
1487 sizeof(job
->printer
->state_message
));
1493 if (!job
->printer_message
&& job
->attrs
)
1495 if ((job
->printer_message
=
1496 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1497 IPP_TAG_TEXT
)) == NULL
)
1498 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1500 "job-printer-state-message",
1504 if (job
->printer_message
)
1505 ippSetString(job
->attrs
, &job
->printer_message
, 0, message
);
1510 * If this is not the last file in a job, see if all of the
1511 * filters are done, and if so move to the next file.
1514 if (job
->state_value
>= IPP_JOB_CANCELED
)
1517 * Remove the job from the active list if there are no processes still
1521 for (i
= 0; job
->filters
[i
] < 0; i
++);
1523 if (!job
->filters
[i
] && job
->backend
<= 0)
1524 cupsArrayRemove(ActiveJobs
, job
);
1526 else if (job
->current_file
< job
->num_files
&& job
->printer
)
1528 for (i
= 0; job
->filters
[i
] < 0; i
++);
1530 if (!job
->filters
[i
] &&
1531 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1535 * Process the next file...
1538 cupsdContinueJob(job
);
1545 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1546 * since they come when we kill/end a process...
1549 if (status
== SIGTERM
|| status
== SIGKILL
)
1551 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1552 "PID %d (%s) was terminated normally with signal %d.", pid
,
1555 else if (status
== SIGPIPE
)
1557 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1558 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1563 if (WIFEXITED(status
))
1565 int code
= WEXITSTATUS(status
); /* Exit code */
1568 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1569 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1570 code
, strerror(code
- 100));
1572 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1573 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1576 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1577 pid
, name
, WTERMSIG(status
));
1579 if (LogLevel
< CUPSD_LOG_DEBUG
)
1580 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1581 "Hint: Try setting the LogLevel to \"debug\" to find out "
1585 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1590 * If wait*() is interrupted by a signal, tell main() to call us again...
1593 if (pid
< 0 && errno
== EINTR
)
1599 * 'select_timeout()' - Calculate the select timeout value.
1603 static long /* O - Number of seconds */
1604 select_timeout(int fds
) /* I - Number of descriptors returned */
1606 long timeout
; /* Timeout for select */
1607 time_t now
; /* Current time */
1608 cupsd_client_t
*con
; /* Client information */
1609 cupsd_job_t
*job
; /* Job information */
1610 const char *why
; /* Debugging aid */
1613 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1614 (long)JobHistoryUpdate
);
1617 * Check to see if any of the clients have pending data to be
1618 * processed; if so, the timeout should be 0...
1621 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1623 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1624 if (httpGetReady(con
->http
))
1628 * If select has been active in the last second (fds > 0) or we have
1629 * many resources in use then don't bother trying to optimize the
1630 * timeout, just make it 1 second.
1633 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1637 * Otherwise, check all of the possible events that we need to wake for...
1641 timeout
= now
+ 86400; /* 86400 == 1 day */
1646 * When going to sleep, wake up to cancel jobs that don't complete in time.
1649 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1651 timeout
= SleepJobs
;
1652 why
= "cancel jobs before sleeping";
1654 #endif /* __APPLE__ */
1657 * Check whether we are accepting new connections...
1660 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1661 ListeningPaused
< timeout
)
1663 if (ListeningPaused
<= now
)
1666 timeout
= ListeningPaused
;
1668 why
= "resume listening";
1672 * Check the activity and close old clients...
1675 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1677 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1678 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1680 timeout
= httpGetActivity(con
->http
) + Timeout
;
1681 why
= "timeout a client connection";
1685 * Write out changes to configuration and state files...
1688 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1690 timeout
= DirtyCleanTime
;
1691 why
= "write dirty config/state files";
1695 * Check for any job activity...
1698 if (JobHistoryUpdate
&& timeout
> JobHistoryUpdate
)
1700 timeout
= JobHistoryUpdate
;
1701 why
= "update job history";
1704 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1706 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1708 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1710 timeout
= job
->cancel_time
;
1711 why
= "cancel stuck jobs";
1714 if (job
->kill_time
&& job
->kill_time
< timeout
)
1716 timeout
= job
->kill_time
;
1717 why
= "kill unresponsive jobs";
1720 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1722 timeout
= job
->hold_until
;
1723 why
= "release held jobs";
1726 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1729 why
= "start pending jobs";
1734 #ifdef HAVE_MALLINFO
1736 * Log memory usage every minute...
1739 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1741 timeout
= mallinfo_time
+ 60;
1742 why
= "display memory usage";
1744 #endif /* HAVE_MALLINFO */
1747 * Adjust from absolute to relative time. We add 1 second to the timeout since
1748 * events occur after the timeout expires, and limit the timeout to 86400
1749 * seconds (1 day) to avoid select() timeout limits present on some operating
1753 timeout
= timeout
- now
+ 1;
1757 else if (timeout
> 86400)
1761 * Log and return the timeout value...
1764 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1772 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1776 sigchld_handler(int sig
) /* I - Signal number */
1781 * Flag that we have dead children...
1787 * Reset the signal handler as needed...
1790 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1791 signal(SIGCLD
, sigchld_handler
);
1792 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1797 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1801 sighup_handler(int sig
) /* I - Signal number */
1805 NeedReload
= RELOAD_ALL
;
1806 ReloadTime
= time(NULL
);
1808 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1809 signal(SIGHUP
, sighup_handler
);
1810 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1815 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1819 sigterm_handler(int sig
) /* I - Signal number */
1821 (void)sig
; /* remove compiler warnings... */
1824 * Flag that we should stop and return...
1831 #if defined(HAVE_ONDEMAND)
1834 * 'add_ondemand_listener()' - Bind an open fd as a Listener.
1838 add_ondemand_listener(int fd
, /* I - Socket file descriptor */
1839 int idx
) /* I - Listener number, for logging */
1841 cupsd_listener_t
*lis
; /* Listeners array */
1842 http_addr_t addr
; /* Address variable */
1843 socklen_t addrlen
; /* Length of address */
1844 char s
[256]; /* String addresss */
1846 addrlen
= sizeof(addr
);
1848 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1850 cupsdLogMessage(CUPSD_LOG_ERROR
,
1851 "service_checkin: Unable to get local address for listener #%d: %s",
1852 idx
+ 1, strerror(errno
));
1856 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1857 "service_checkin: Listener #%d at fd %d, \"%s\".",
1858 idx
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
1861 * Try to match the on-demand socket address to one of the listeners...
1864 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1866 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1867 if (httpAddrEqual(&lis
->address
, &addr
))
1871 * Add a new listener If there's no match...
1876 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1877 "service_checkin: Matched existing listener #%d to %s.",
1878 idx
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1882 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1883 "service_checkin: Adding new listener #%d for %s.",
1884 idx
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1886 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1888 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s.", strerror(errno
));
1893 cupsArrayAdd(Listeners
, lis
);
1895 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1902 if (httpAddrPort(&(lis
->address
)) == 443)
1903 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1904 # endif /* HAVE_SSL */
1908 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1912 service_checkin(void)
1914 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
1915 int error
; /* Check-in error, if any */
1916 size_t i
, /* Looping var */
1917 count
; /* Number of listeners */
1918 int *ld_sockets
; /* Listener sockets */
1921 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1924 * Check-in with launchd...
1927 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1929 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1931 return; /* anti-compiler-warning */
1935 * Try to match the launchd sockets to the cupsd listeners...
1938 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1940 for (i
= 0; i
< count
; i
++)
1942 add_ondemand_listener(ld_sockets
[i
], i
);
1947 # elif defined(HAVE_LAUNCHD)
1948 size_t i
, /* Looping var */
1949 count
; /* Number of listeners */
1950 launch_data_t ld_msg
, /* Launch data message */
1951 ld_resp
, /* Launch data response */
1952 ld_array
, /* Launch data array */
1953 ld_sockets
, /* Launch data sockets dictionary */
1954 tmp
; /* Launch data */
1955 int fd
; /* File descriptor */
1958 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1961 * Check-in with launchd...
1964 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1965 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1967 cupsdLogMessage(CUPSD_LOG_ERROR
,
1968 "service_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1971 return; /* anti-compiler-warning */
1974 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1976 errno
= launch_data_get_errno(ld_resp
);
1977 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Check-in failed: %s",
1980 return; /* anti-compiler-warning */
1984 * Get the sockets dictionary...
1987 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1990 cupsdLogMessage(CUPSD_LOG_ERROR
,
1991 "service_checkin: No sockets found to answer requests on.");
1993 return; /* anti-compiler-warning */
1997 * Get the array of listener sockets...
2000 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
2002 cupsdLogMessage(CUPSD_LOG_ERROR
,
2003 "service_checkin: No sockets found to answer requests on.");
2005 return; /* anti-compiler-warning */
2009 * Add listening fd(s) to the Listener array...
2012 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
2014 count
= launch_data_array_get_count(ld_array
);
2016 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
2018 for (i
= 0; i
< count
; i
++)
2021 * Get the launchd file descriptor and address...
2024 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
2026 fd
= launch_data_get_fd(tmp
);
2027 add_ondemand_listener(fd
, i
);
2032 launch_data_free(ld_msg
);
2033 launch_data_free(ld_resp
);
2035 # elif defined(HAVE_SYSTEMD)
2036 int i
, /* Looping var */
2037 count
; /* Number of listeners */
2040 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
2043 * Check-in with systemd...
2046 if ((count
= sd_listen_fds(0)) < 0)
2048 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
2050 return; /* anti-compiler-warning */
2054 * Try to match the systemd sockets to the cupsd listeners...
2057 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
2059 for (i
= 0; i
< count
; i
++)
2061 add_ondemand_listener(SD_LISTEN_FDS_START
+ i
, i
);
2063 # elif defined(HAVE_UPSTART)
2064 const char *e
; /* Environment var */
2065 int fd
; /* File descriptor */
2067 if (!(e
= getenv("UPSTART_EVENTS")))
2069 cupsdLogMessage(CUPSD_LOG_ERROR
,
2070 "service_checkin: We did not get started via Upstart.");
2075 if (strcasecmp(e
, "socket"))
2077 cupsdLogMessage(CUPSD_LOG_ERROR
,
2078 "service_checkin: We did not get triggered via an Upstart socket event.");
2083 if (!(e
= getenv("UPSTART_FDS")))
2085 cupsdLogMessage(CUPSD_LOG_ERROR
,
2086 "service_checkin: Unable to get listener sockets from UPSTART_FDS.");
2091 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: UPSTART_FDS=%s", e
);
2093 fd
= strtol(e
, NULL
, 10);
2095 cupsdLogMessage(CUPSD_LOG_ERROR
,
2096 "service_checkin: Could not parse UPSTART_FDS: %s", strerror(errno
));
2101 /* Upstart only supportst a single on-demand socket fd */
2102 add_ondemand_listener(fd
, 0);
2105 # error "Error: defined HAVE_ONDEMAND but no launchd/systemd/upstart selection"
2106 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
2111 * 'service_checkout()' - Update the CUPS_KEEPALIVE file as needed.
2115 service_checkout(void)
2117 int fd
; /* File descriptor */
2121 * Create or remove the "keep-alive" file based on whether there are active
2122 * jobs or shared printers to advertise...
2125 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2126 WebInterface
|| /* Web interface enabled */
2127 NeedReload
|| /* Doing a reload */
2128 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
2129 /* Printers being shared */
2131 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating keep-alive file \"" CUPS_KEEPALIVE
"\".");
2133 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
2138 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing keep-alive file \"" CUPS_KEEPALIVE
"\".");
2140 unlink(CUPS_KEEPALIVE
);
2143 #endif /* HAVE_ONDEMAND */
2147 * 'usage()' - Show scheduler usage.
2151 usage(int status
) /* O - Exit status */
2153 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2156 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2157 _cupsLangPuts(fp
, _("Options:"));
2158 _cupsLangPuts(fp
, _(" -c cupsd.conf Set cupsd.conf file to use."));
2159 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2160 _cupsLangPuts(fp
, _(" -F Run in the foreground but detach from console."));
2161 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2162 _cupsLangPuts(fp
, _(" -l Run cupsd on demand."));
2163 _cupsLangPuts(fp
, _(" -s cups-files.conf Set cups-files.conf file to use."));
2164 _cupsLangPuts(fp
, _(" -t Test the configuration file."));