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 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
34 /* Name of the launchd KeepAlive file */
35 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
36 /* Update when we have a public header we can include */
37 extern int launch_activate_socket(const char *name
, int **fds
, size_t *cnt
);
38 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
39 #endif /* HAVE_LAUNCH_H */
42 # include <systemd/sd-daemon.h>
43 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
44 /* Name of the systemd path file */
45 #endif /* HAVE_SYSTEMD */
47 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
49 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
53 #endif /* HAVE_NOTIFY_H */
56 # include <dbus/dbus.h>
57 #endif /* HAVE_DBUS */
59 #ifdef HAVE_SYS_PARAM_H
60 # include <sys/param.h>
61 #endif /* HAVE_SYS_PARAM_H */
68 static void parent_handler(int sig
);
69 static void process_children(void);
70 static void sigchld_handler(int sig
);
71 static void sighup_handler(int sig
);
72 static void sigterm_handler(int sig
);
73 static long select_timeout(int fds
);
74 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
75 static void service_checkin(void);
76 static void service_checkout(void);
77 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
78 static void usage(int status
) __attribute__((noreturn
));
85 static int parent_signal
= 0;
86 /* Set to signal number from child */
87 static int holdcount
= 0; /* Number of times "hold" was called */
88 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
89 static sigset_t holdmask
; /* Old POSIX signal mask */
90 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
91 static int dead_children
= 0;
93 static int stop_scheduler
= 0;
94 /* Should the scheduler stop? */
98 * 'main()' - Main entry for the CUPS scheduler.
101 int /* O - Exit status */
102 main(int argc
, /* I - Number of command-line args */
103 char *argv
[]) /* I - Command-line arguments */
105 int i
; /* Looping var */
106 char *opt
; /* Option character */
107 int close_all
= 1, /* Close all file descriptors? */
108 disconnect
= 1, /* Disconnect from controlling terminal? */
109 fg
= 0, /* Run in foreground? */
111 /* Running as child process? */
113 /* Print the sandbox profile to stdout? */
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 case 'T' : /* Print security profile */
319 default : /* Unknown option */
320 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
327 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
332 if (!ConfigurationFile
)
333 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
337 char *filename
, /* Copy of cupsd.conf filename */
338 *slash
; /* Final slash in cupsd.conf filename */
339 size_t len
; /* Size of buffer */
341 len
= strlen(ConfigurationFile
) + 15;
342 if ((filename
= malloc(len
)) == NULL
)
344 _cupsLangPrintf(stderr
,
345 _("cupsd: Unable to get path to "
346 "cups-files.conf file."));
350 strlcpy(filename
, ConfigurationFile
, len
);
351 if ((slash
= strrchr(filename
, '/')) == NULL
)
353 _cupsLangPrintf(stderr
,
354 _("cupsd: Unable to get path to "
355 "cups-files.conf file."));
359 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
360 cupsdSetString(&CupsFilesFile
, filename
);
367 * Make sure we aren't tying up any filesystems...
373 * Disconnect from the controlling terminal...
382 * Close all open files...
385 getrlimit(RLIMIT_NOFILE
, &limit
);
387 for (i
= 0; i
< (int)limit
.rlim_cur
&& i
< 1024; i
++)
391 * Redirect stdin/out/err to /dev/null...
394 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
400 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
406 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
413 LogStderr
= cupsFileStderr();
416 * Run in the background as needed...
422 * Setup signal handlers for the parent...
425 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
426 sigset(SIGUSR1
, parent_handler
);
427 sigset(SIGCHLD
, parent_handler
);
429 sigset(SIGHUP
, SIG_IGN
);
430 #elif defined(HAVE_SIGACTION)
431 memset(&action
, 0, sizeof(action
));
432 sigemptyset(&action
.sa_mask
);
433 sigaddset(&action
.sa_mask
, SIGUSR1
);
434 action
.sa_handler
= parent_handler
;
435 sigaction(SIGUSR1
, &action
, NULL
);
436 sigaction(SIGCHLD
, &action
, NULL
);
438 sigemptyset(&action
.sa_mask
);
439 action
.sa_handler
= SIG_IGN
;
440 sigaction(SIGHUP
, &action
, NULL
);
442 signal(SIGUSR1
, parent_handler
);
443 signal(SIGCLD
, parent_handler
);
445 signal(SIGHUP
, SIG_IGN
);
446 #endif /* HAVE_SIGSET */
451 * OK, wait for the child to startup and send us SIGUSR1 or to crash
452 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
453 * might be sent by the init script to restart the scheduler...
456 for (; parent_signal
== 0;)
459 if (parent_signal
== SIGUSR1
)
467 else if (WIFEXITED(i
))
469 fprintf(stderr
, "cupsd: Child exited with status %d\n",
475 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
480 #if defined(__OpenBSD__) && OpenBSD < 201211
482 * Call _thread_sys_closefrom() so the child process doesn't reset the
483 * parent's file descriptors to be blocking. This is a workaround for a
484 * limitation of userland libpthread on older versions of OpenBSD.
487 _thread_sys_closefrom(0);
488 #endif /* __OpenBSD__ && OpenBSD < 201211 */
491 * Since many system libraries create fork-unsafe data on execution of a
492 * program, we need to re-execute the background cupsd with the "-C" and "-s"
493 * options to avoid problems. Unfortunately, we also have to assume that
494 * argv[0] contains the name of the cupsd executable - there is no portable
495 * way to get the real pathname...
498 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, "-s", CupsFilesFile
, (char *)0);
503 * Set the timezone info...
509 setlocale(LC_TIME
, "");
512 #ifdef HAVE_DBUS_THREADS_INIT
514 * Enable threading support for D-BUS...
517 dbus_threads_init_default();
518 #endif /* HAVE_DBUS_THREADS_INIT */
521 * Set the maximum number of files...
524 getrlimit(RLIMIT_NOFILE
, &limit
);
526 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
527 if (limit
.rlim_max
> FD_SETSIZE
)
530 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
532 if (limit
.rlim_max
== RLIM_INFINITY
)
535 #endif /* RLIM_INFINITY */
536 MaxFDs
= limit
.rlim_max
;
538 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
540 setrlimit(RLIMIT_NOFILE
, &limit
);
545 * Read configuration...
548 if (!cupsdReadConfiguration())
550 else if (TestConfigFile
)
552 printf("\"%s\" is OK.\n", CupsFilesFile
);
553 printf("\"%s\" is OK.\n", ConfigurationFile
);
556 else if (print_profile
)
558 cups_file_t
*fp
; /* File pointer */
559 const char *profile
= cupsdCreateProfile(42, 0);
561 char line
[1024]; /* Line from file */
564 if ((fp
= cupsFileOpen(profile
, "r")) == NULL
)
566 printf("Unable to open profile file \"%s\": %s\n", profile
? profile
: "(null)", strerror(errno
));
570 while (cupsFileGets(fp
, line
, sizeof(line
)))
579 * Clean out old temp files and printer cache data.
582 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
583 cupsdCleanFiles(TempDir
, NULL
);
585 cupsdCleanFiles(CacheDir
, "*.ipp");
587 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
591 * If we were started on demand by launchd or systemd get the listen sockets
592 * file descriptors...
598 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
601 * Startup the server...
609 * Catch hangup and child signals and ignore broken pipes...
612 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
613 sigset(SIGCHLD
, sigchld_handler
);
614 sigset(SIGHUP
, sighup_handler
);
615 sigset(SIGPIPE
, SIG_IGN
);
616 sigset(SIGTERM
, sigterm_handler
);
617 #elif defined(HAVE_SIGACTION)
618 memset(&action
, 0, sizeof(action
));
620 sigemptyset(&action
.sa_mask
);
621 sigaddset(&action
.sa_mask
, SIGTERM
);
622 sigaddset(&action
.sa_mask
, SIGCHLD
);
623 action
.sa_handler
= sigchld_handler
;
624 sigaction(SIGCHLD
, &action
, NULL
);
626 sigemptyset(&action
.sa_mask
);
627 sigaddset(&action
.sa_mask
, SIGHUP
);
628 action
.sa_handler
= sighup_handler
;
629 sigaction(SIGHUP
, &action
, NULL
);
631 sigemptyset(&action
.sa_mask
);
632 action
.sa_handler
= SIG_IGN
;
633 sigaction(SIGPIPE
, &action
, NULL
);
635 sigemptyset(&action
.sa_mask
);
636 sigaddset(&action
.sa_mask
, SIGTERM
);
637 sigaddset(&action
.sa_mask
, SIGCHLD
);
638 action
.sa_handler
= sigterm_handler
;
639 sigaction(SIGTERM
, &action
, NULL
);
641 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
642 signal(SIGHUP
, sighup_handler
);
643 signal(SIGPIPE
, SIG_IGN
);
644 signal(SIGTERM
, sigterm_handler
);
645 #endif /* HAVE_SIGSET */
648 * Initialize authentication certificates...
654 * If we are running in the background, signal the parent process that
655 * we are up and running...
658 if (!fg
|| run_as_child
)
661 * Send a signal to the parent process, but only if the parent is
662 * not PID 1 (init). This avoids accidentally shutting down the
663 * system on OpenBSD if you CTRL-C the server before it is up...
666 i
= getppid(); /* Save parent PID to avoid race condition */
674 * Start power management framework...
678 cupsdStartSystemMonitor();
679 #endif /* __APPLE__ */
682 * Send server-started event...
685 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
687 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
689 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
691 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
693 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
696 * Start any pending print jobs...
705 current_time
= time(NULL
);
706 event_time
= current_time
;
707 expire_time
= current_time
;
710 senddoc_time
= current_time
;
712 while (!stop_scheduler
)
715 * Check if there are dead children to handle...
722 * Check if we need to load the server configuration file...
728 * Close any idle clients...
731 if (cupsArrayCount(Clients
) > 0)
733 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
735 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
736 if (httpGetState(con
->http
) == HTTP_WAITING
)
737 cupsdCloseClient(con
);
739 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
741 cupsdPauseListening();
745 * Restart if all clients are closed and all jobs finished, or
746 * if the reload timeout has elapsed...
749 if ((cupsArrayCount(Clients
) == 0 &&
750 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
751 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
754 * Shutdown the server...
762 * Read configuration...
765 if (!cupsdReadConfiguration())
768 asl_object_t m
; /* Log message */
770 m
= asl_new(ASL_TYPE_MSG
);
771 asl_set(m
, ASL_KEY_FACILITY
, "org.cups.cupsd");
772 asl_log(NULL
, m
, ASL_LEVEL_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
774 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
775 sd_journal_print(LOG_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
777 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting.", ConfigurationFile
);
778 #endif /* HAVE_ASL_H */
784 * Startup the server...
792 * Send a server-restarted event...
795 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
796 "Scheduler restarted.");
801 * Check for available input or ready output. If cupsdDoSelect()
802 * returns 0 or -1, something bad happened and we should exit
805 * Note that we at least have one listening socket open at all
809 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
812 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
814 * If no other work is scheduled and we're being controlled by
815 * launchd then timeout after 'LaunchdTimeout' seconds of
819 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
820 !cupsArrayCount(ActiveJobs
) &&
823 # endif /* HAVE_SYSTEMD */
824 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
826 timeout
= IdleExitTimeout
;
827 service_idle_exit
= 1;
830 service_idle_exit
= 0;
831 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
833 if ((fds
= cupsdDoSelect(timeout
)) < 0)
836 * Got an error from select!
839 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
840 cupsd_printer_t
*p
; /* Current printer */
841 #endif /* HAVE_DNSSD || HAVE_AVAHI */
844 if (errno
== EINTR
) /* Just interrupted by a signal */
848 * Log all sorts of debug info to help track down the problem.
851 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
854 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
856 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
857 cupsdLogMessage(CUPSD_LOG_EMERG
,
858 "Clients[%d] = %d, file = %d, state = %d",
859 i
, con
->number
, con
->file
, httpGetState(con
->http
));
861 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
863 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
864 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
866 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
869 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
871 #endif /* __APPLE__ */
873 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
875 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
876 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
878 job
->status_buffer
? job
->status_buffer
->fd
: -1,
879 job
->print_pipes
[0], job
->print_pipes
[1],
880 job
->back_pipes
[0], job
->back_pipes
[1]);
882 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
883 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
885 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
886 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
887 p
->reg_name
? p
->reg_name
: "(null)");
888 #endif /* HAVE_DNSSD || HAVE_AVAHI */
893 current_time
= time(NULL
);
896 * Write dirty config/state files...
899 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
904 * If we are going to sleep and still have pending jobs, stop them after
905 * a period of time...
908 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
909 cupsArrayCount(PrintingJobs
) > 0)
912 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
914 #endif /* __APPLE__ */
918 * Update the network interfaces once a minute...
921 if ((current_time
- netif_time
) >= 60)
923 netif_time
= current_time
;
926 #endif /* !__APPLE__ */
928 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
930 * If no other work was scheduled and we're being controlled by launchd
931 * then timeout after 'LaunchdTimeout' seconds of inactivity...
934 if (!fds
&& service_idle_exit
)
936 cupsdLogMessage(CUPSD_LOG_INFO
,
937 "Printer sharing is off and there are no jobs pending, "
938 "will restart on demand.");
942 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
945 * Resume listening for new connections as needed...
948 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
949 cupsArrayCount(Clients
) < MaxClients
)
950 cupsdResumeListening();
953 * Expire subscriptions and unload completed jobs as needed...
956 if (current_time
> expire_time
)
958 if (cupsArrayCount(Subscriptions
) > 0)
959 cupsdExpireSubscriptions(NULL
, NULL
);
961 cupsdUnloadCompletedJobs();
963 expire_time
= current_time
;
966 #ifndef HAVE_AUTHORIZATION_H
968 * Update the root certificate once every 5 minutes if we have client
972 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
973 !RunUser
&& cupsArrayCount(Clients
))
976 * Update the root certificate...
980 cupsdAddCert(0, "root", cupsdDefaultAuthType());
982 #endif /* !HAVE_AUTHORIZATION_H */
985 * Check for new data on the client sockets...
988 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
990 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
993 * Process pending data in the input buffer...
996 if (httpGetReady(con
->http
))
998 cupsdReadClient(con
);
1003 * Check the activity and close old clients...
1006 activity
= current_time
- Timeout
;
1007 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
1009 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
1011 cupsdCloseClient(con
);
1017 * Update any pending multi-file documents...
1020 if ((current_time
- senddoc_time
) >= 10)
1023 senddoc_time
= current_time
;
1027 * Clean job history...
1030 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
1034 * Log statistics at most once a minute when in debug mode...
1037 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1039 size_t string_count
, /* String count */
1040 alloc_bytes
, /* Allocated string bytes */
1041 total_bytes
; /* Total string bytes */
1042 #ifdef HAVE_MALLINFO
1043 struct mallinfo mem
; /* Malloc information */
1047 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1048 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1049 mem
.usmblks
+ mem
.uordblks
);
1050 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1051 mem
.fsmblks
+ mem
.fordblks
);
1052 #endif /* HAVE_MALLINFO */
1054 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1055 cupsArrayCount(Clients
));
1056 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1057 cupsArrayCount(Jobs
));
1058 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1059 cupsArrayCount(ActiveJobs
));
1060 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1061 cupsArrayCount(Printers
));
1063 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1064 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1065 "Report: stringpool-string-count=" CUPS_LLFMT
,
1066 CUPS_LLCAST string_count
);
1067 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1068 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1069 CUPS_LLCAST alloc_bytes
);
1070 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1071 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1072 CUPS_LLCAST total_bytes
);
1074 report_time
= current_time
;
1078 * Handle OS-specific event notification for any events that have
1079 * accumulated. Don't send these more than once a second...
1082 if (LastEvent
&& (current_time
- event_time
) >= 1)
1084 #ifdef HAVE_NOTIFY_POST
1085 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1086 CUPSD_EVENT_PRINTER_DELETED
|
1087 CUPSD_EVENT_PRINTER_MODIFIED
))
1089 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1090 "notify_post(\"com.apple.printerListChange\")");
1091 notify_post("com.apple.printerListChange");
1094 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1096 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1097 "notify_post(\"com.apple.printerHistoryChange\")");
1098 notify_post("com.apple.printerHistoryChange");
1101 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1102 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1103 CUPSD_EVENT_JOB_PROGRESS
))
1105 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1106 "notify_post(\"com.apple.jobChange\")");
1107 notify_post("com.apple.jobChange");
1109 #endif /* HAVE_NOTIFY_POST */
1112 * Reset the accumulated events...
1115 LastEvent
= CUPSD_EVENT_NONE
;
1116 event_time
= current_time
;
1121 * Log a message based on what happened...
1126 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1127 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1128 "Scheduler shutting down normally.");
1132 cupsdLogMessage(CUPSD_LOG_ERROR
,
1133 "Scheduler shutting down due to program error.");
1134 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1135 "Scheduler shutting down due to program error.");
1139 * Close all network clients...
1146 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1148 * Update the keep-alive file as needed...
1153 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
1163 * Stop monitoring system event monitoring...
1167 cupsdStopSystemMonitor();
1168 #endif /* __APPLE__ */
1172 return (!stop_scheduler
);
1177 * 'cupsdAddString()' - Copy and add a string to an array.
1180 int /* O - 1 on success, 0 on failure */
1181 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1182 const char *s
) /* I - String to copy and add */
1185 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1186 (cups_ahash_func_t
)NULL
, 0,
1187 (cups_acopy_func_t
)strdup
,
1188 (cups_afree_func_t
)free
);
1190 return (cupsArrayAdd(*a
, (char *)s
));
1195 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1199 cupsdCheckProcess(void)
1202 * Flag that we have dead children...
1210 * 'cupsdClearString()' - Clear a string.
1214 cupsdClearString(char **s
) /* O - String value */
1225 * 'cupsdFreeStrings()' - Free an array of strings.
1229 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1233 cupsArrayDelete(*a
);
1240 * 'cupsdHoldSignals()' - Hold child and termination signals.
1244 cupsdHoldSignals(void)
1246 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1247 sigset_t newmask
; /* New POSIX signal mask */
1248 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1258 #elif defined(HAVE_SIGACTION)
1259 sigemptyset(&newmask
);
1260 sigaddset(&newmask
, SIGTERM
);
1261 sigaddset(&newmask
, SIGCHLD
);
1262 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1263 #endif /* HAVE_SIGSET */
1268 * 'cupsdReleaseSignals()' - Release signals for delivery.
1272 cupsdReleaseSignals(void)
1281 #elif defined(HAVE_SIGACTION)
1282 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1283 #endif /* HAVE_SIGSET */
1288 * 'cupsdSetString()' - Set a string value.
1292 cupsdSetString(char **s
, /* O - New string */
1293 const char *v
) /* I - String value */
1309 * 'cupsdSetStringf()' - Set a formatted string value.
1313 cupsdSetStringf(char **s
, /* O - New string */
1314 const char *f
, /* I - Printf-style format string */
1315 ...) /* I - Additional args as needed */
1317 char v
[65536 + 64]; /* Formatting string value */
1318 va_list ap
; /* Argument pointer */
1319 char *olds
; /* Old string */
1330 vsnprintf(v
, sizeof(v
), f
, ap
);
1344 * 'parent_handler()' - Catch USR1/CHLD signals...
1348 parent_handler(int sig
) /* I - Signal */
1351 * Store the signal we got from the OS and return...
1354 parent_signal
= sig
;
1359 * 'process_children()' - Process all dead children...
1363 process_children(void)
1365 int status
; /* Exit status of child */
1366 int pid
, /* Process ID of child */
1367 job_id
; /* Job ID of child */
1368 cupsd_job_t
*job
; /* Current job */
1369 int i
; /* Looping var */
1370 char name
[1024]; /* Process name */
1371 const char *type
; /* Type of program */
1374 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1377 * Reset the dead_children flag...
1383 * Collect the exit status of some children...
1387 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1388 #elif defined(HAVE_WAIT3)
1389 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1391 if ((pid
= wait(&status
)) > 0)
1392 #endif /* HAVE_WAITPID */
1395 * Collect the name of the process that finished...
1398 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1401 * Delete certificates for CGI processes...
1405 cupsdDeleteCert(pid
);
1408 * Handle completed job filters...
1412 job
= cupsdFindJob(job_id
);
1418 for (i
= 0; job
->filters
[i
]; i
++)
1419 if (job
->filters
[i
] == pid
)
1422 if (job
->filters
[i
] || job
->backend
== pid
)
1425 * OK, this process has gone away; what's left?
1428 if (job
->filters
[i
])
1430 job
->filters
[i
] = -pid
;
1435 job
->backend
= -pid
;
1439 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1443 * An error occurred; save the exit status so we know to stop
1444 * the printer or cancel the job when all of the filters finish...
1446 * A negative status indicates that the backend failed and the
1447 * printer needs to be stopped.
1449 * In order to preserve the most serious status, we always log
1450 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1451 * and SIGBUS) and prefer to log the backend exit status over a
1455 int old_status
= abs(job
->status
);
1457 if (WIFSIGNALED(status
) || /* This process crashed, or */
1458 !job
->status
|| /* No process had a status, or */
1459 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1460 { /* Backend and filter didn't crash */
1461 if (job
->filters
[i
])
1462 job
->status
= status
; /* Filter failed */
1464 job
->status
= -status
; /* Backend failed */
1467 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1468 job
->status_level
> CUPSD_LOG_ERROR
&&
1469 (job
->filters
[i
] || !WIFEXITED(status
)))
1471 char message
[1024]; /* New printer-state-message */
1474 job
->status_level
= CUPSD_LOG_ERROR
;
1476 snprintf(message
, sizeof(message
), "%s failed", type
);
1480 strlcpy(job
->printer
->state_message
, message
,
1481 sizeof(job
->printer
->state_message
));
1487 if (!job
->printer_message
&& job
->attrs
)
1489 if ((job
->printer_message
=
1490 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1491 IPP_TAG_TEXT
)) == NULL
)
1492 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1494 "job-printer-state-message",
1498 if (job
->printer_message
)
1499 ippSetString(job
->attrs
, &job
->printer_message
, 0, message
);
1504 * If this is not the last file in a job, see if all of the
1505 * filters are done, and if so move to the next file.
1508 if (job
->state_value
>= IPP_JOB_CANCELED
)
1511 * Remove the job from the active list if there are no processes still
1515 for (i
= 0; job
->filters
[i
] < 0; i
++);
1517 if (!job
->filters
[i
] && job
->backend
<= 0)
1518 cupsArrayRemove(ActiveJobs
, job
);
1520 else if (job
->current_file
< job
->num_files
&& job
->printer
)
1522 for (i
= 0; job
->filters
[i
] < 0; i
++);
1524 if (!job
->filters
[i
] &&
1525 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1529 * Process the next file...
1532 cupsdContinueJob(job
);
1539 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1540 * since they come when we kill/end a process...
1543 if (status
== SIGTERM
|| status
== SIGKILL
)
1545 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1546 "PID %d (%s) was terminated normally with signal %d.", pid
,
1549 else if (status
== SIGPIPE
)
1551 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1552 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1557 if (WIFEXITED(status
))
1559 int code
= WEXITSTATUS(status
); /* Exit code */
1562 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1563 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1564 code
, strerror(code
- 100));
1566 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1567 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1570 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1571 pid
, name
, WTERMSIG(status
));
1573 if (LogLevel
< CUPSD_LOG_DEBUG
)
1574 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1575 "Hint: Try setting the LogLevel to \"debug\" to find out "
1579 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1584 * If wait*() is interrupted by a signal, tell main() to call us again...
1587 if (pid
< 0 && errno
== EINTR
)
1593 * 'select_timeout()' - Calculate the select timeout value.
1597 static long /* O - Number of seconds */
1598 select_timeout(int fds
) /* I - Number of descriptors returned */
1600 long timeout
; /* Timeout for select */
1601 time_t now
; /* Current time */
1602 cupsd_client_t
*con
; /* Client information */
1603 cupsd_job_t
*job
; /* Job information */
1604 const char *why
; /* Debugging aid */
1607 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1608 (long)JobHistoryUpdate
);
1611 * Check to see if any of the clients have pending data to be
1612 * processed; if so, the timeout should be 0...
1615 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1617 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1618 if (httpGetReady(con
->http
))
1622 * If select has been active in the last second (fds > 0) or we have
1623 * many resources in use then don't bother trying to optimize the
1624 * timeout, just make it 1 second.
1627 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1631 * Otherwise, check all of the possible events that we need to wake for...
1635 timeout
= now
+ 86400; /* 86400 == 1 day */
1640 * When going to sleep, wake up to cancel jobs that don't complete in time.
1643 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1645 timeout
= SleepJobs
;
1646 why
= "cancel jobs before sleeping";
1648 #endif /* __APPLE__ */
1651 * Check whether we are accepting new connections...
1654 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1655 ListeningPaused
< timeout
)
1657 if (ListeningPaused
<= now
)
1660 timeout
= ListeningPaused
;
1662 why
= "resume listening";
1666 * Check the activity and close old clients...
1669 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1671 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1672 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1674 timeout
= httpGetActivity(con
->http
) + Timeout
;
1675 why
= "timeout a client connection";
1679 * Write out changes to configuration and state files...
1682 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1684 timeout
= DirtyCleanTime
;
1685 why
= "write dirty config/state files";
1689 * Check for any job activity...
1692 if (JobHistoryUpdate
&& timeout
> JobHistoryUpdate
)
1694 timeout
= JobHistoryUpdate
;
1695 why
= "update job history";
1698 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1700 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1702 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1704 timeout
= job
->cancel_time
;
1705 why
= "cancel stuck jobs";
1708 if (job
->kill_time
&& job
->kill_time
< timeout
)
1710 timeout
= job
->kill_time
;
1711 why
= "kill unresponsive jobs";
1714 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1716 timeout
= job
->hold_until
;
1717 why
= "release held jobs";
1720 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1723 why
= "start pending jobs";
1728 #ifdef HAVE_MALLINFO
1730 * Log memory usage every minute...
1733 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1735 timeout
= mallinfo_time
+ 60;
1736 why
= "display memory usage";
1738 #endif /* HAVE_MALLINFO */
1741 * Adjust from absolute to relative time. We add 1 second to the timeout since
1742 * events occur after the timeout expires, and limit the timeout to 86400
1743 * seconds (1 day) to avoid select() timeout limits present on some operating
1747 timeout
= timeout
- now
+ 1;
1751 else if (timeout
> 86400)
1755 * Log and return the timeout value...
1758 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1766 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1770 sigchld_handler(int sig
) /* I - Signal number */
1775 * Flag that we have dead children...
1781 * Reset the signal handler as needed...
1784 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1785 signal(SIGCLD
, sigchld_handler
);
1786 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1791 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1795 sighup_handler(int sig
) /* I - Signal number */
1799 NeedReload
= RELOAD_ALL
;
1800 ReloadTime
= time(NULL
);
1802 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1803 signal(SIGHUP
, sighup_handler
);
1804 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1809 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1813 sigterm_handler(int sig
) /* I - Signal number */
1815 (void)sig
; /* remove compiler warnings... */
1818 * Flag that we should stop and return...
1825 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1827 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1831 service_checkin(void)
1833 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
1834 int error
; /* Check-in error, if any */
1835 size_t i
, /* Looping var */
1836 count
; /* Number of listeners */
1837 int *ld_sockets
; /* Listener sockets */
1838 cupsd_listener_t
*lis
; /* Listeners array */
1839 http_addr_t addr
; /* Address variable */
1840 socklen_t addrlen
; /* Length of address */
1841 char s
[256]; /* String addresss */
1844 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1847 * Check-in with launchd...
1850 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1852 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1854 return; /* anti-compiler-warning */
1858 * Try to match the launchd sockets to the cupsd listeners...
1861 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1863 for (i
= 0; i
< count
; i
++)
1866 * Get the launchd socket address...
1869 addrlen
= sizeof(addr
);
1871 if (getsockname(ld_sockets
[i
], (struct sockaddr
*)&addr
, &addrlen
))
1873 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1877 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, ld_sockets
[i
], httpAddrString(&addr
, s
, sizeof(s
)));
1879 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1881 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1882 if (httpAddrEqual(&lis
->address
, &addr
))
1886 * Add a new listener if there's no match...
1891 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1895 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1897 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1899 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
1903 cupsArrayAdd(Listeners
, lis
);
1905 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1908 lis
->fd
= ld_sockets
[i
];
1912 if (httpAddrPort(&(lis
->address
)) == 443)
1913 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1914 # endif /* HAVE_SSL */
1919 # elif defined(HAVE_LAUNCHD)
1920 size_t i
, /* Looping var */
1921 count
; /* Number of listeners */
1922 launch_data_t ld_msg
, /* Launch data message */
1923 ld_resp
, /* Launch data response */
1924 ld_array
, /* Launch data array */
1925 ld_sockets
, /* Launch data sockets dictionary */
1926 tmp
; /* Launch data */
1927 cupsd_listener_t
*lis
; /* Listeners array */
1928 http_addr_t addr
; /* Address variable */
1929 socklen_t addrlen
; /* Length of address */
1930 int fd
; /* File descriptor */
1931 char s
[256]; /* String addresss */
1934 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1937 * Check-in with launchd...
1940 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1941 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1943 cupsdLogMessage(CUPSD_LOG_ERROR
,
1944 "service_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1947 return; /* anti-compiler-warning */
1950 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1952 errno
= launch_data_get_errno(ld_resp
);
1953 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Check-in failed: %s",
1956 return; /* anti-compiler-warning */
1960 * Get the sockets dictionary...
1963 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1966 cupsdLogMessage(CUPSD_LOG_ERROR
,
1967 "service_checkin: No sockets found to answer requests on.");
1969 return; /* anti-compiler-warning */
1973 * Get the array of listener sockets...
1976 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1978 cupsdLogMessage(CUPSD_LOG_ERROR
,
1979 "service_checkin: No sockets found to answer requests on.");
1981 return; /* anti-compiler-warning */
1985 * Add listening fd(s) to the Listener array...
1988 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1990 count
= launch_data_array_get_count(ld_array
);
1992 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1994 for (i
= 0; i
< count
; i
++)
1997 * Get the launchd file descriptor and address...
2000 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
2002 fd
= launch_data_get_fd(tmp
);
2003 addrlen
= sizeof(addr
);
2005 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
2007 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2011 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
2014 * Try to match the launchd socket address to one of the listeners...
2017 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2019 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2020 if (httpAddrEqual(&lis
->address
, &addr
))
2024 * Add a new listener If there's no match...
2029 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2033 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2035 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2037 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s.", strerror(errno
));
2041 cupsArrayAdd(Listeners
, lis
);
2043 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2050 if (httpAddrPort(&(lis
->address
)) == 443)
2051 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2052 # endif /* HAVE_SSL */
2057 launch_data_free(ld_msg
);
2058 launch_data_free(ld_resp
);
2060 # else /* HAVE_SYSTEMD */
2061 int i
, /* Looping var */
2062 count
; /* Number of listeners */
2063 cupsd_listener_t
*lis
; /* Listeners array */
2064 http_addr_t addr
; /* Address variable */
2065 socklen_t addrlen
; /* Length of address */
2066 char s
[256]; /* String addresss */
2069 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
2072 * Check-in with systemd...
2075 if ((count
= sd_listen_fds(0)) < 0)
2077 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
2079 return; /* anti-compiler-warning */
2083 * Try to match the systemd sockets to the cupsd listeners...
2086 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
2088 for (i
= 0; i
< count
; i
++)
2091 * Get the launchd socket address...
2094 addrlen
= sizeof(addr
);
2096 if (getsockname(SD_LISTEN_FDS_START
+ i
, (struct sockaddr
*)&addr
, &addrlen
))
2098 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2102 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
)));
2104 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2106 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2107 if (httpAddrEqual(&lis
->address
, &addr
))
2111 * Add a new listener if there's no match...
2116 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2120 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2122 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2124 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
2128 cupsArrayAdd(Listeners
, lis
);
2130 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2133 lis
->fd
= SD_LISTEN_FDS_START
+ i
;
2137 if (httpAddrPort(&(lis
->address
)) == 443)
2138 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2139 # endif /* HAVE_SSL */
2141 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
2146 * 'service_checkout()' - Update the CUPS_KEEPALIVE file as needed.
2150 service_checkout(void)
2152 int fd
; /* File descriptor */
2156 * Create or remove the "keep-alive" file based on whether there are active
2157 * jobs or shared printers to advertise...
2160 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2161 WebInterface
|| /* Web interface enabled */
2162 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
2163 /* Printers being shared */
2165 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating keep-alive file \"" CUPS_KEEPALIVE
"\".");
2167 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
2172 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing keep-alive file \"" CUPS_KEEPALIVE
"\".");
2174 unlink(CUPS_KEEPALIVE
);
2177 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
2181 * 'usage()' - Show scheduler usage.
2185 usage(int status
) /* O - Exit status */
2187 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2190 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2191 _cupsLangPuts(fp
, _("Options:"));
2192 _cupsLangPuts(fp
, _(" -c cupsd.conf Set cupsd.conf file to use."));
2193 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2194 _cupsLangPuts(fp
, _(" -F Run in the foreground but detach from console."));
2195 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2196 _cupsLangPuts(fp
, _(" -l Run cupsd on demand."));
2197 _cupsLangPuts(fp
, _(" -s cups-files.conf Set cups-files.conf file to use."));
2198 _cupsLangPuts(fp
, _(" -t Test the configuration file."));