4 * Main loop for the CUPS scheduler.
6 * Copyright 2007-2016 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 * Include necessary headers...
22 #include <sys/resource.h>
25 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
26 # define SD_JOURNAL_SUPPRESS_LOCATION
27 # include <systemd/sd-journal.h>
28 #endif /* HAVE_ASL_H */
35 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
36 /* Name of the launchd KeepAlive file */
37 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
38 /* Update when we have a public header we can include */
39 extern int launch_activate_socket(const char *name
, int **fds
, size_t *cnt
);
40 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
41 #endif /* HAVE_LAUNCH_H */
44 # include <systemd/sd-daemon.h>
45 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
46 /* Name of the systemd path file */
47 #endif /* HAVE_SYSTEMD */
49 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
51 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
55 #endif /* HAVE_NOTIFY_H */
58 # include <dbus/dbus.h>
59 #endif /* HAVE_DBUS */
61 #ifdef HAVE_SYS_PARAM_H
62 # include <sys/param.h>
63 #endif /* HAVE_SYS_PARAM_H */
70 static void parent_handler(int sig
);
71 static void process_children(void);
72 static void sigchld_handler(int sig
);
73 static void sighup_handler(int sig
);
74 static void sigterm_handler(int sig
);
75 static long select_timeout(int fds
);
76 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
77 static void service_checkin(void);
78 static void service_checkout(void);
79 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
80 static void usage(int status
) __attribute__((noreturn
));
87 static int parent_signal
= 0;
88 /* Set to signal number from child */
89 static int holdcount
= 0; /* Number of times "hold" was called */
90 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
91 static sigset_t holdmask
; /* Old POSIX signal mask */
92 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
93 static int dead_children
= 0;
95 static int stop_scheduler
= 0;
96 /* Should the scheduler stop? */
100 * 'main()' - Main entry for the CUPS scheduler.
103 int /* O - Exit status */
104 main(int argc
, /* I - Number of command-line args */
105 char *argv
[]) /* I - Command-line arguments */
107 int i
; /* Looping var */
108 char *opt
; /* Option character */
109 int close_all
= 1, /* Close all file descriptors? */
110 disconnect
= 1, /* Disconnect from controlling terminal? */
111 fg
= 0, /* Run in foreground? */
113 /* Running as child process? */
114 int fds
; /* Number of ready descriptors */
115 cupsd_client_t
*con
; /* Current client */
116 cupsd_job_t
*job
; /* Current job */
117 cupsd_listener_t
*lis
; /* Current listener */
118 time_t current_time
, /* Current time */
119 activity
, /* Client activity timer */
120 senddoc_time
, /* Send-Document time */
121 expire_time
, /* Subscription expire time */
122 report_time
, /* Malloc/client/job report time */
123 event_time
; /* Last event notification time */
124 long timeout
; /* Timeout for cupsdDoSelect() */
125 struct rlimit limit
; /* Runtime limit */
126 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
127 struct sigaction action
; /* Actions for POSIX signals */
128 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
130 int use_sysman
= 1; /* Use system management functions? */
132 time_t netif_time
= 0; /* Time since last network update */
133 #endif /* __APPLE__ */
134 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
135 int service_idle_exit
;
136 /* Idle exit on select timeout? */
137 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
142 * Check for setuid invocation, which we do not support!
145 if (getuid() != geteuid())
147 fputs("cupsd: Cannot run as a setuid program.\n", stderr
);
150 #endif /* HAVE_GETEUID */
153 * Check for command-line arguments...
159 if (getenv("CUPSD_LAUNCHD"))
166 #endif /* HAVE_LAUNCHD */
168 for (i
= 1; i
< argc
; i
++)
169 if (argv
[i
][0] == '-')
170 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
173 case 'C' : /* Run as child with config file */
178 case 'c' : /* Configuration file */
182 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
183 "after \"-c\" option."));
187 if (argv
[i
][0] == '/')
190 * Absolute directory...
193 cupsdSetString(&ConfigurationFile
, argv
[i
]);
198 * Relative directory...
201 char *current
; /* Current directory */
204 * Allocate a buffer for the current working directory to
205 * reduce run-time stack usage; this approximates the
206 * behavior of some implementations of getcwd() when they
207 * are passed a NULL pointer.
210 if ((current
= malloc(1024)) == NULL
)
212 _cupsLangPuts(stderr
,
213 _("cupsd: Unable to get current directory."));
217 if (!getcwd(current
, 1024))
219 _cupsLangPuts(stderr
,
220 _("cupsd: Unable to get current directory."));
225 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
230 case 'f' : /* Run in foreground... */
236 case 'F' : /* Run in foreground, but disconnect from terminal... */
241 case 'h' : /* Show usage/help */
245 case 'l' : /* Started by launchd/systemd... */
246 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
252 _cupsLangPuts(stderr
, _("cupsd: On-demand support not compiled "
253 "in, running in normal mode."));
257 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
260 case 'p' : /* Stop immediately for profiling */
261 fputs("cupsd: -p (startup profiling) is for internal testing "
262 "use only!\n", stderr
);
269 case 'P' : /* Disable security profiles */
270 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr
);
274 case 's' : /* Set cups-files.conf location */
278 _cupsLangPuts(stderr
, _("cupsd: Expected cups-files.conf "
279 "filename after \"-s\" option."));
283 if (argv
[i
][0] != '/')
286 * Relative filename not allowed...
289 _cupsLangPuts(stderr
, _("cupsd: Relative cups-files.conf "
290 "filename not allowed."));
294 cupsdSetString(&CupsFilesFile
, argv
[i
]);
298 case 'S' : /* Disable system management functions */
299 fputs("cupsd: -S (disable system management) for internal "
300 "testing use only!\n", stderr
);
303 #endif /* __APPLE__ */
305 case 't' : /* Test the cupsd.conf file... */
312 default : /* Unknown option */
313 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
320 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
325 if (!ConfigurationFile
)
326 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
330 char *filename
, /* Copy of cupsd.conf filename */
331 *slash
; /* Final slash in cupsd.conf filename */
332 size_t len
; /* Size of buffer */
334 len
= strlen(ConfigurationFile
) + 15;
335 if ((filename
= malloc(len
)) == NULL
)
337 _cupsLangPrintf(stderr
,
338 _("cupsd: Unable to get path to "
339 "cups-files.conf file."));
343 strlcpy(filename
, ConfigurationFile
, len
);
344 if ((slash
= strrchr(filename
, '/')) == NULL
)
346 _cupsLangPrintf(stderr
,
347 _("cupsd: Unable to get path to "
348 "cups-files.conf file."));
352 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
353 cupsdSetString(&CupsFilesFile
, filename
);
360 * Make sure we aren't tying up any filesystems...
366 * Disconnect from the controlling terminal...
375 * Close all open files...
378 getrlimit(RLIMIT_NOFILE
, &limit
);
380 for (i
= 0; i
< (int)limit
.rlim_cur
&& i
< 1024; i
++)
384 * Redirect stdin/out/err to /dev/null...
387 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
393 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
399 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
406 LogStderr
= cupsFileStderr();
409 * Run in the background as needed...
415 * Setup signal handlers for the parent...
418 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
419 sigset(SIGUSR1
, parent_handler
);
420 sigset(SIGCHLD
, parent_handler
);
422 sigset(SIGHUP
, SIG_IGN
);
423 #elif defined(HAVE_SIGACTION)
424 memset(&action
, 0, sizeof(action
));
425 sigemptyset(&action
.sa_mask
);
426 sigaddset(&action
.sa_mask
, SIGUSR1
);
427 action
.sa_handler
= parent_handler
;
428 sigaction(SIGUSR1
, &action
, NULL
);
429 sigaction(SIGCHLD
, &action
, NULL
);
431 sigemptyset(&action
.sa_mask
);
432 action
.sa_handler
= SIG_IGN
;
433 sigaction(SIGHUP
, &action
, NULL
);
435 signal(SIGUSR1
, parent_handler
);
436 signal(SIGCLD
, parent_handler
);
438 signal(SIGHUP
, SIG_IGN
);
439 #endif /* HAVE_SIGSET */
444 * OK, wait for the child to startup and send us SIGUSR1 or to crash
445 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
446 * might be sent by the init script to restart the scheduler...
449 for (; parent_signal
== 0;)
452 if (parent_signal
== SIGUSR1
)
460 else if (WIFEXITED(i
))
462 fprintf(stderr
, "cupsd: Child exited with status %d\n",
468 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
473 #if defined(__OpenBSD__) && OpenBSD < 201211
475 * Call _thread_sys_closefrom() so the child process doesn't reset the
476 * parent's file descriptors to be blocking. This is a workaround for a
477 * limitation of userland libpthread on older versions of OpenBSD.
480 _thread_sys_closefrom(0);
481 #endif /* __OpenBSD__ && OpenBSD < 201211 */
484 * Since many system libraries create fork-unsafe data on execution of a
485 * program, we need to re-execute the background cupsd with the "-C" and "-s"
486 * options to avoid problems. Unfortunately, we also have to assume that
487 * argv[0] contains the name of the cupsd executable - there is no portable
488 * way to get the real pathname...
491 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, "-s", CupsFilesFile
, (char *)0);
496 * Set the timezone info...
502 setlocale(LC_TIME
, "");
505 #ifdef HAVE_DBUS_THREADS_INIT
507 * Enable threading support for D-BUS...
510 dbus_threads_init_default();
511 #endif /* HAVE_DBUS_THREADS_INIT */
514 * Set the maximum number of files...
517 getrlimit(RLIMIT_NOFILE
, &limit
);
519 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
520 if (limit
.rlim_max
> FD_SETSIZE
)
523 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
525 if (limit
.rlim_max
== RLIM_INFINITY
)
528 #endif /* RLIM_INFINITY */
529 MaxFDs
= limit
.rlim_max
;
531 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
533 setrlimit(RLIMIT_NOFILE
, &limit
);
538 * Read configuration...
541 if (!cupsdReadConfiguration())
543 else if (TestConfigFile
)
545 printf("\"%s\" is OK.\n", CupsFilesFile
);
546 printf("\"%s\" is OK.\n", ConfigurationFile
);
551 * Clean out old temp files and printer cache data.
554 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
555 cupsdCleanFiles(TempDir
, NULL
);
557 cupsdCleanFiles(CacheDir
, "*.ipp");
559 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
563 * If we were started on demand by launchd or systemd get the listen sockets
564 * file descriptors...
570 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
573 * Startup the server...
581 * Catch hangup and child signals and ignore broken pipes...
584 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
585 sigset(SIGCHLD
, sigchld_handler
);
586 sigset(SIGHUP
, sighup_handler
);
587 sigset(SIGPIPE
, SIG_IGN
);
588 sigset(SIGTERM
, sigterm_handler
);
589 #elif defined(HAVE_SIGACTION)
590 memset(&action
, 0, sizeof(action
));
592 sigemptyset(&action
.sa_mask
);
593 sigaddset(&action
.sa_mask
, SIGTERM
);
594 sigaddset(&action
.sa_mask
, SIGCHLD
);
595 action
.sa_handler
= sigchld_handler
;
596 sigaction(SIGCHLD
, &action
, NULL
);
598 sigemptyset(&action
.sa_mask
);
599 sigaddset(&action
.sa_mask
, SIGHUP
);
600 action
.sa_handler
= sighup_handler
;
601 sigaction(SIGHUP
, &action
, NULL
);
603 sigemptyset(&action
.sa_mask
);
604 action
.sa_handler
= SIG_IGN
;
605 sigaction(SIGPIPE
, &action
, NULL
);
607 sigemptyset(&action
.sa_mask
);
608 sigaddset(&action
.sa_mask
, SIGTERM
);
609 sigaddset(&action
.sa_mask
, SIGCHLD
);
610 action
.sa_handler
= sigterm_handler
;
611 sigaction(SIGTERM
, &action
, NULL
);
613 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
614 signal(SIGHUP
, sighup_handler
);
615 signal(SIGPIPE
, SIG_IGN
);
616 signal(SIGTERM
, sigterm_handler
);
617 #endif /* HAVE_SIGSET */
620 * Initialize authentication certificates...
626 * If we are running in the background, signal the parent process that
627 * we are up and running...
630 if (!fg
|| run_as_child
)
633 * Send a signal to the parent process, but only if the parent is
634 * not PID 1 (init). This avoids accidentally shutting down the
635 * system on OpenBSD if you CTRL-C the server before it is up...
638 i
= getppid(); /* Save parent PID to avoid race condition */
646 * Start power management framework...
650 cupsdStartSystemMonitor();
651 #endif /* __APPLE__ */
654 * Send server-started event...
657 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
659 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
661 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
663 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
665 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
668 * Start any pending print jobs...
677 current_time
= time(NULL
);
678 event_time
= current_time
;
679 expire_time
= current_time
;
682 senddoc_time
= current_time
;
684 while (!stop_scheduler
)
687 * Check if there are dead children to handle...
694 * Check if we need to load the server configuration file...
700 * Close any idle clients...
703 if (cupsArrayCount(Clients
) > 0)
705 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
707 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
708 if (httpGetState(con
->http
) == HTTP_WAITING
)
709 cupsdCloseClient(con
);
711 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
713 cupsdPauseListening();
717 * Restart if all clients are closed and all jobs finished, or
718 * if the reload timeout has elapsed...
721 if ((cupsArrayCount(Clients
) == 0 &&
722 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
723 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
726 * Shutdown the server...
734 * Read configuration...
737 if (!cupsdReadConfiguration())
740 asl_object_t m
; /* Log message */
742 m
= asl_new(ASL_TYPE_MSG
);
743 asl_set(m
, ASL_KEY_FACILITY
, "org.cups.cupsd");
744 asl_log(NULL
, m
, ASL_LEVEL_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
746 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
747 sd_journal_print(LOG_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
749 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting.", ConfigurationFile
);
750 #endif /* HAVE_ASL_H */
756 * Startup the server...
764 * Send a server-restarted event...
767 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
768 "Scheduler restarted.");
773 * Check for available input or ready output. If cupsdDoSelect()
774 * returns 0 or -1, something bad happened and we should exit
777 * Note that we at least have one listening socket open at all
781 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
784 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
786 * If no other work is scheduled and we're being controlled by
787 * launchd then timeout after 'LaunchdTimeout' seconds of
791 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
792 !cupsArrayCount(ActiveJobs
) &&
795 # endif /* HAVE_SYSTEMD */
796 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
798 timeout
= IdleExitTimeout
;
799 service_idle_exit
= 1;
802 service_idle_exit
= 0;
803 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
805 if ((fds
= cupsdDoSelect(timeout
)) < 0)
808 * Got an error from select!
811 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
812 cupsd_printer_t
*p
; /* Current printer */
813 #endif /* HAVE_DNSSD || HAVE_AVAHI */
816 if (errno
== EINTR
) /* Just interrupted by a signal */
820 * Log all sorts of debug info to help track down the problem.
823 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
826 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
828 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
829 cupsdLogMessage(CUPSD_LOG_EMERG
,
830 "Clients[%d] = %d, file = %d, state = %d",
831 i
, con
->number
, con
->file
, httpGetState(con
->http
));
833 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
835 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
836 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
838 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
841 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
843 #endif /* __APPLE__ */
845 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
847 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
848 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
850 job
->status_buffer
? job
->status_buffer
->fd
: -1,
851 job
->print_pipes
[0], job
->print_pipes
[1],
852 job
->back_pipes
[0], job
->back_pipes
[1]);
854 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
855 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
857 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
858 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
859 p
->reg_name
? p
->reg_name
: "(null)");
860 #endif /* HAVE_DNSSD || HAVE_AVAHI */
865 current_time
= time(NULL
);
868 * Write dirty config/state files...
871 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
876 * If we are going to sleep and still have pending jobs, stop them after
877 * a period of time...
880 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
881 cupsArrayCount(PrintingJobs
) > 0)
884 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
886 #endif /* __APPLE__ */
890 * Update the network interfaces once a minute...
893 if ((current_time
- netif_time
) >= 60)
895 netif_time
= current_time
;
898 #endif /* !__APPLE__ */
900 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
902 * If no other work was scheduled and we're being controlled by launchd
903 * then timeout after 'LaunchdTimeout' seconds of inactivity...
906 if (!fds
&& service_idle_exit
)
908 cupsdLogMessage(CUPSD_LOG_INFO
,
909 "Printer sharing is off and there are no jobs pending, "
910 "will restart on demand.");
914 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
917 * Resume listening for new connections as needed...
920 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
921 cupsArrayCount(Clients
) < MaxClients
)
922 cupsdResumeListening();
925 * Expire subscriptions and unload completed jobs as needed...
928 if (current_time
> expire_time
)
930 if (cupsArrayCount(Subscriptions
) > 0)
931 cupsdExpireSubscriptions(NULL
, NULL
);
933 cupsdUnloadCompletedJobs();
935 expire_time
= current_time
;
938 #ifndef HAVE_AUTHORIZATION_H
940 * Update the root certificate once every 5 minutes if we have client
944 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
945 !RunUser
&& cupsArrayCount(Clients
))
948 * Update the root certificate...
952 cupsdAddCert(0, "root", cupsdDefaultAuthType());
954 #endif /* !HAVE_AUTHORIZATION_H */
957 * Check for new data on the client sockets...
960 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
962 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
965 * Process pending data in the input buffer...
968 if (httpGetReady(con
->http
))
970 cupsdReadClient(con
);
975 * Check the activity and close old clients...
978 activity
= current_time
- Timeout
;
979 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
981 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
983 cupsdCloseClient(con
);
989 * Update any pending multi-file documents...
992 if ((current_time
- senddoc_time
) >= 10)
995 senddoc_time
= current_time
;
999 * Clean job history...
1002 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
1006 * Log statistics at most once a minute when in debug mode...
1009 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1011 size_t string_count
, /* String count */
1012 alloc_bytes
, /* Allocated string bytes */
1013 total_bytes
; /* Total string bytes */
1014 #ifdef HAVE_MALLINFO
1015 struct mallinfo mem
; /* Malloc information */
1019 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1020 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1021 mem
.usmblks
+ mem
.uordblks
);
1022 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1023 mem
.fsmblks
+ mem
.fordblks
);
1024 #endif /* HAVE_MALLINFO */
1026 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1027 cupsArrayCount(Clients
));
1028 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1029 cupsArrayCount(Jobs
));
1030 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1031 cupsArrayCount(ActiveJobs
));
1032 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1033 cupsArrayCount(Printers
));
1035 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1036 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1037 "Report: stringpool-string-count=" CUPS_LLFMT
,
1038 CUPS_LLCAST string_count
);
1039 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1040 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1041 CUPS_LLCAST alloc_bytes
);
1042 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1043 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1044 CUPS_LLCAST total_bytes
);
1046 report_time
= current_time
;
1050 * Handle OS-specific event notification for any events that have
1051 * accumulated. Don't send these more than once a second...
1054 if (LastEvent
&& (current_time
- event_time
) >= 1)
1056 #ifdef HAVE_NOTIFY_POST
1057 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1058 CUPSD_EVENT_PRINTER_DELETED
|
1059 CUPSD_EVENT_PRINTER_MODIFIED
))
1061 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1062 "notify_post(\"com.apple.printerListChange\")");
1063 notify_post("com.apple.printerListChange");
1066 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1068 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1069 "notify_post(\"com.apple.printerHistoryChange\")");
1070 notify_post("com.apple.printerHistoryChange");
1073 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1074 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1075 CUPSD_EVENT_JOB_PROGRESS
))
1077 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1078 "notify_post(\"com.apple.jobChange\")");
1079 notify_post("com.apple.jobChange");
1081 #endif /* HAVE_NOTIFY_POST */
1084 * Reset the accumulated events...
1087 LastEvent
= CUPSD_EVENT_NONE
;
1088 event_time
= current_time
;
1093 * Log a message based on what happened...
1098 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1099 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1100 "Scheduler shutting down normally.");
1104 cupsdLogMessage(CUPSD_LOG_ERROR
,
1105 "Scheduler shutting down due to program error.");
1106 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1107 "Scheduler shutting down due to program error.");
1111 * Close all network clients...
1118 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1120 * Update the keep-alive file as needed...
1125 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
1135 * Stop monitoring system event monitoring...
1139 cupsdStopSystemMonitor();
1140 #endif /* __APPLE__ */
1144 return (!stop_scheduler
);
1149 * 'cupsdAddString()' - Copy and add a string to an array.
1152 int /* O - 1 on success, 0 on failure */
1153 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1154 const char *s
) /* I - String to copy and add */
1157 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1158 (cups_ahash_func_t
)NULL
, 0,
1159 (cups_acopy_func_t
)strdup
,
1160 (cups_afree_func_t
)free
);
1162 return (cupsArrayAdd(*a
, (char *)s
));
1167 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1171 cupsdCheckProcess(void)
1174 * Flag that we have dead children...
1182 * 'cupsdClearString()' - Clear a string.
1186 cupsdClearString(char **s
) /* O - String value */
1197 * 'cupsdFreeStrings()' - Free an array of strings.
1201 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1205 cupsArrayDelete(*a
);
1212 * 'cupsdHoldSignals()' - Hold child and termination signals.
1216 cupsdHoldSignals(void)
1218 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1219 sigset_t newmask
; /* New POSIX signal mask */
1220 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1230 #elif defined(HAVE_SIGACTION)
1231 sigemptyset(&newmask
);
1232 sigaddset(&newmask
, SIGTERM
);
1233 sigaddset(&newmask
, SIGCHLD
);
1234 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1235 #endif /* HAVE_SIGSET */
1240 * 'cupsdReleaseSignals()' - Release signals for delivery.
1244 cupsdReleaseSignals(void)
1253 #elif defined(HAVE_SIGACTION)
1254 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1255 #endif /* HAVE_SIGSET */
1260 * 'cupsdSetString()' - Set a string value.
1264 cupsdSetString(char **s
, /* O - New string */
1265 const char *v
) /* I - String value */
1281 * 'cupsdSetStringf()' - Set a formatted string value.
1285 cupsdSetStringf(char **s
, /* O - New string */
1286 const char *f
, /* I - Printf-style format string */
1287 ...) /* I - Additional args as needed */
1289 char v
[65536 + 64]; /* Formatting string value */
1290 va_list ap
; /* Argument pointer */
1291 char *olds
; /* Old string */
1302 vsnprintf(v
, sizeof(v
), f
, ap
);
1316 * 'parent_handler()' - Catch USR1/CHLD signals...
1320 parent_handler(int sig
) /* I - Signal */
1323 * Store the signal we got from the OS and return...
1326 parent_signal
= sig
;
1331 * 'process_children()' - Process all dead children...
1335 process_children(void)
1337 int status
; /* Exit status of child */
1338 int pid
, /* Process ID of child */
1339 job_id
; /* Job ID of child */
1340 cupsd_job_t
*job
; /* Current job */
1341 int i
; /* Looping var */
1342 char name
[1024]; /* Process name */
1343 const char *type
; /* Type of program */
1346 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1349 * Reset the dead_children flag...
1355 * Collect the exit status of some children...
1359 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1360 #elif defined(HAVE_WAIT3)
1361 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1363 if ((pid
= wait(&status
)) > 0)
1364 #endif /* HAVE_WAITPID */
1367 * Collect the name of the process that finished...
1370 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1373 * Delete certificates for CGI processes...
1377 cupsdDeleteCert(pid
);
1380 * Handle completed job filters...
1384 job
= cupsdFindJob(job_id
);
1390 for (i
= 0; job
->filters
[i
]; i
++)
1391 if (job
->filters
[i
] == pid
)
1394 if (job
->filters
[i
] || job
->backend
== pid
)
1397 * OK, this process has gone away; what's left?
1400 if (job
->filters
[i
])
1402 job
->filters
[i
] = -pid
;
1407 job
->backend
= -pid
;
1411 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1415 * An error occurred; save the exit status so we know to stop
1416 * the printer or cancel the job when all of the filters finish...
1418 * A negative status indicates that the backend failed and the
1419 * printer needs to be stopped.
1421 * In order to preserve the most serious status, we always log
1422 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1423 * and SIGBUS) and prefer to log the backend exit status over a
1427 int old_status
= abs(job
->status
);
1429 if (WIFSIGNALED(status
) || /* This process crashed, or */
1430 !job
->status
|| /* No process had a status, or */
1431 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1432 { /* Backend and filter didn't crash */
1433 if (job
->filters
[i
])
1434 job
->status
= status
; /* Filter failed */
1436 job
->status
= -status
; /* Backend failed */
1439 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1440 job
->status_level
> CUPSD_LOG_ERROR
&&
1441 (job
->filters
[i
] || !WIFEXITED(status
)))
1443 char message
[1024]; /* New printer-state-message */
1446 job
->status_level
= CUPSD_LOG_ERROR
;
1448 snprintf(message
, sizeof(message
), "%s failed", type
);
1452 strlcpy(job
->printer
->state_message
, message
,
1453 sizeof(job
->printer
->state_message
));
1459 if (!job
->printer_message
&& job
->attrs
)
1461 if ((job
->printer_message
=
1462 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1463 IPP_TAG_TEXT
)) == NULL
)
1464 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1466 "job-printer-state-message",
1470 if (job
->printer_message
)
1471 ippSetString(job
->attrs
, &job
->printer_message
, 0, message
);
1476 * If this is not the last file in a job, see if all of the
1477 * filters are done, and if so move to the next file.
1480 if (job
->current_file
< job
->num_files
&& job
->printer
)
1482 for (i
= 0; job
->filters
[i
] < 0; i
++);
1484 if (!job
->filters
[i
] &&
1485 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1489 * Process the next file...
1492 cupsdContinueJob(job
);
1495 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1498 * Remove the job from the active list if there are no processes still
1502 for (i
= 0; job
->filters
[i
] < 0; i
++);
1504 if (!job
->filters
[i
] && job
->backend
<= 0)
1505 cupsArrayRemove(ActiveJobs
, job
);
1511 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1512 * since they come when we kill/end a process...
1515 if (status
== SIGTERM
|| status
== SIGKILL
)
1517 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1518 "PID %d (%s) was terminated normally with signal %d.", pid
,
1521 else if (status
== SIGPIPE
)
1523 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1524 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1529 if (WIFEXITED(status
))
1531 int code
= WEXITSTATUS(status
); /* Exit code */
1534 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1535 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1536 code
, strerror(code
- 100));
1538 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1539 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1542 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1543 pid
, name
, WTERMSIG(status
));
1545 if (LogLevel
< CUPSD_LOG_DEBUG
)
1546 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1547 "Hint: Try setting the LogLevel to \"debug\" to find out "
1551 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1556 * If wait*() is interrupted by a signal, tell main() to call us again...
1559 if (pid
< 0 && errno
== EINTR
)
1565 * 'select_timeout()' - Calculate the select timeout value.
1569 static long /* O - Number of seconds */
1570 select_timeout(int fds
) /* I - Number of descriptors returned */
1572 long timeout
; /* Timeout for select */
1573 time_t now
; /* Current time */
1574 cupsd_client_t
*con
; /* Client information */
1575 cupsd_job_t
*job
; /* Job information */
1576 const char *why
; /* Debugging aid */
1579 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1580 (long)JobHistoryUpdate
);
1583 * Check to see if any of the clients have pending data to be
1584 * processed; if so, the timeout should be 0...
1587 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1589 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1590 if (httpGetReady(con
->http
))
1594 * If select has been active in the last second (fds > 0) or we have
1595 * many resources in use then don't bother trying to optimize the
1596 * timeout, just make it 1 second.
1599 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1603 * Otherwise, check all of the possible events that we need to wake for...
1607 timeout
= now
+ 86400; /* 86400 == 1 day */
1612 * When going to sleep, wake up to cancel jobs that don't complete in time.
1615 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1617 timeout
= SleepJobs
;
1618 why
= "cancel jobs before sleeping";
1620 #endif /* __APPLE__ */
1623 * Check whether we are accepting new connections...
1626 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1627 ListeningPaused
< timeout
)
1629 if (ListeningPaused
<= now
)
1632 timeout
= ListeningPaused
;
1634 why
= "resume listening";
1638 * Check the activity and close old clients...
1641 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1643 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1644 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1646 timeout
= httpGetActivity(con
->http
) + Timeout
;
1647 why
= "timeout a client connection";
1651 * Write out changes to configuration and state files...
1654 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1656 timeout
= DirtyCleanTime
;
1657 why
= "write dirty config/state files";
1661 * Check for any job activity...
1664 if (JobHistoryUpdate
&& timeout
> JobHistoryUpdate
)
1666 timeout
= JobHistoryUpdate
;
1667 why
= "update job history";
1670 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1672 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1674 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1676 timeout
= job
->cancel_time
;
1677 why
= "cancel stuck jobs";
1680 if (job
->kill_time
&& job
->kill_time
< timeout
)
1682 timeout
= job
->kill_time
;
1683 why
= "kill unresponsive jobs";
1686 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1688 timeout
= job
->hold_until
;
1689 why
= "release held jobs";
1692 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1695 why
= "start pending jobs";
1700 #ifdef HAVE_MALLINFO
1702 * Log memory usage every minute...
1705 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1707 timeout
= mallinfo_time
+ 60;
1708 why
= "display memory usage";
1710 #endif /* HAVE_MALLINFO */
1713 * Adjust from absolute to relative time. We add 1 second to the timeout since
1714 * events occur after the timeout expires, and limit the timeout to 86400
1715 * seconds (1 day) to avoid select() timeout limits present on some operating
1719 timeout
= timeout
- now
+ 1;
1723 else if (timeout
> 86400)
1727 * Log and return the timeout value...
1730 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1738 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1742 sigchld_handler(int sig
) /* I - Signal number */
1747 * Flag that we have dead children...
1753 * Reset the signal handler as needed...
1756 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1757 signal(SIGCLD
, sigchld_handler
);
1758 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1763 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1767 sighup_handler(int sig
) /* I - Signal number */
1771 NeedReload
= RELOAD_ALL
;
1772 ReloadTime
= time(NULL
);
1774 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1775 signal(SIGHUP
, sighup_handler
);
1776 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1781 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1785 sigterm_handler(int sig
) /* I - Signal number */
1787 (void)sig
; /* remove compiler warnings... */
1790 * Flag that we should stop and return...
1797 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1799 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1803 service_checkin(void)
1805 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
1806 int error
; /* Check-in error, if any */
1807 size_t i
, /* Looping var */
1808 count
; /* Number of listeners */
1809 int *ld_sockets
; /* Listener sockets */
1810 cupsd_listener_t
*lis
; /* Listeners array */
1811 http_addr_t addr
; /* Address variable */
1812 socklen_t addrlen
; /* Length of address */
1813 char s
[256]; /* String addresss */
1816 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1819 * Check-in with launchd...
1822 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1824 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1826 return; /* anti-compiler-warning */
1830 * Try to match the launchd sockets to the cupsd listeners...
1833 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1835 for (i
= 0; i
< count
; i
++)
1838 * Get the launchd socket address...
1841 addrlen
= sizeof(addr
);
1843 if (getsockname(ld_sockets
[i
], (struct sockaddr
*)&addr
, &addrlen
))
1845 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1849 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, ld_sockets
[i
], httpAddrString(&addr
, s
, sizeof(s
)));
1851 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1853 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1854 if (httpAddrEqual(&lis
->address
, &addr
))
1858 * Add a new listener if there's no match...
1863 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1867 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1869 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1871 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
1875 cupsArrayAdd(Listeners
, lis
);
1877 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1880 lis
->fd
= ld_sockets
[i
];
1884 if (httpAddrPort(&(lis
->address
)) == 443)
1885 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1886 # endif /* HAVE_SSL */
1891 # elif defined(HAVE_LAUNCHD)
1892 size_t i
, /* Looping var */
1893 count
; /* Number of listeners */
1894 launch_data_t ld_msg
, /* Launch data message */
1895 ld_resp
, /* Launch data response */
1896 ld_array
, /* Launch data array */
1897 ld_sockets
, /* Launch data sockets dictionary */
1898 tmp
; /* Launch data */
1899 cupsd_listener_t
*lis
; /* Listeners array */
1900 http_addr_t addr
; /* Address variable */
1901 socklen_t addrlen
; /* Length of address */
1902 int fd
; /* File descriptor */
1903 char s
[256]; /* String addresss */
1906 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1909 * Check-in with launchd...
1912 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1913 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1915 cupsdLogMessage(CUPSD_LOG_ERROR
,
1916 "service_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1919 return; /* anti-compiler-warning */
1922 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1924 errno
= launch_data_get_errno(ld_resp
);
1925 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Check-in failed: %s",
1928 return; /* anti-compiler-warning */
1932 * Get the sockets dictionary...
1935 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1938 cupsdLogMessage(CUPSD_LOG_ERROR
,
1939 "service_checkin: No sockets found to answer requests on.");
1941 return; /* anti-compiler-warning */
1945 * Get the array of listener sockets...
1948 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1950 cupsdLogMessage(CUPSD_LOG_ERROR
,
1951 "service_checkin: No sockets found to answer requests on.");
1953 return; /* anti-compiler-warning */
1957 * Add listening fd(s) to the Listener array...
1960 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1962 count
= launch_data_array_get_count(ld_array
);
1964 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1966 for (i
= 0; i
< count
; i
++)
1969 * Get the launchd file descriptor and address...
1972 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1974 fd
= launch_data_get_fd(tmp
);
1975 addrlen
= sizeof(addr
);
1977 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1979 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1983 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
1986 * Try to match the launchd socket address to one of the listeners...
1989 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1991 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1992 if (httpAddrEqual(&lis
->address
, &addr
))
1996 * Add a new listener If there's no match...
2001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2005 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2007 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2009 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s.", strerror(errno
));
2013 cupsArrayAdd(Listeners
, lis
);
2015 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2022 if (httpAddrPort(&(lis
->address
)) == 443)
2023 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2024 # endif /* HAVE_SSL */
2029 launch_data_free(ld_msg
);
2030 launch_data_free(ld_resp
);
2032 # else /* HAVE_SYSTEMD */
2033 int i
, /* Looping var */
2034 count
; /* Number of listeners */
2035 cupsd_listener_t
*lis
; /* Listeners array */
2036 http_addr_t addr
; /* Address variable */
2037 socklen_t addrlen
; /* Length of address */
2038 char s
[256]; /* String addresss */
2041 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
2044 * Check-in with systemd...
2047 if ((count
= sd_listen_fds(0)) < 0)
2049 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
2051 return; /* anti-compiler-warning */
2055 * Try to match the systemd sockets to the cupsd listeners...
2058 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
2060 for (i
= 0; i
< count
; i
++)
2063 * Get the launchd socket address...
2066 addrlen
= sizeof(addr
);
2068 if (getsockname(SD_LISTEN_FDS_START
+ i
, (struct sockaddr
*)&addr
, &addrlen
))
2070 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2074 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, SD_LISTEN_FDS_START
+ i
, httpAddrString(&addr
, s
, sizeof(s
)));
2076 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2078 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2079 if (httpAddrEqual(&lis
->address
, &addr
))
2083 * Add a new listener if there's no match...
2088 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2092 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2094 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2096 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
2100 cupsArrayAdd(Listeners
, lis
);
2102 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2105 lis
->fd
= SD_LISTEN_FDS_START
+ i
;
2109 if (httpAddrPort(&(lis
->address
)) == 443)
2110 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2111 # endif /* HAVE_SSL */
2113 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
2118 * 'service_checkout()' - Update the CUPS_KEEPALIVE file as needed.
2122 service_checkout(void)
2124 int fd
; /* File descriptor */
2128 * Create or remove the "keep-alive" file based on whether there are active
2129 * jobs or shared printers to advertise...
2132 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2133 WebInterface
|| /* Web interface enabled */
2134 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
2135 /* Printers being shared */
2137 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating keep-alive file \"" CUPS_KEEPALIVE
"\".");
2139 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
2144 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing keep-alive file \"" CUPS_KEEPALIVE
"\".");
2146 unlink(CUPS_KEEPALIVE
);
2149 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
2153 * 'usage()' - Show scheduler usage.
2157 usage(int status
) /* O - Exit status */
2159 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2162 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2163 _cupsLangPuts(fp
, _("Options:"));
2164 _cupsLangPuts(fp
, _(" -c cupsd.conf Set cupsd.conf file to use."));
2165 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2166 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
2167 "detach from console."));
2168 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2169 _cupsLangPuts(fp
, _(" -l Run cupsd on demand."));
2170 _cupsLangPuts(fp
, _(" -t Test the configuration "