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? */
115 /* Print the sandbox profile to stdout? */
116 int fds
; /* Number of ready descriptors */
117 cupsd_client_t
*con
; /* Current client */
118 cupsd_job_t
*job
; /* Current job */
119 cupsd_listener_t
*lis
; /* Current listener */
120 time_t current_time
, /* Current time */
121 activity
, /* Client activity timer */
122 senddoc_time
, /* Send-Document time */
123 expire_time
, /* Subscription expire time */
124 report_time
, /* Malloc/client/job report time */
125 event_time
; /* Last event notification time */
126 long timeout
; /* Timeout for cupsdDoSelect() */
127 struct rlimit limit
; /* Runtime limit */
128 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
129 struct sigaction action
; /* Actions for POSIX signals */
130 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
132 int use_sysman
= 1; /* Use system management functions? */
134 time_t netif_time
= 0; /* Time since last network update */
135 #endif /* __APPLE__ */
136 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
137 int service_idle_exit
;
138 /* Idle exit on select timeout? */
139 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
144 * Check for setuid invocation, which we do not support!
147 if (getuid() != geteuid())
149 fputs("cupsd: Cannot run as a setuid program.\n", stderr
);
152 #endif /* HAVE_GETEUID */
155 * Check for command-line arguments...
161 if (getenv("CUPSD_LAUNCHD"))
168 #endif /* HAVE_LAUNCHD */
170 for (i
= 1; i
< argc
; i
++)
171 if (argv
[i
][0] == '-')
172 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
175 case 'C' : /* Run as child with config file */
180 case 'c' : /* Configuration file */
184 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
185 "after \"-c\" option."));
189 if (argv
[i
][0] == '/')
192 * Absolute directory...
195 cupsdSetString(&ConfigurationFile
, argv
[i
]);
200 * Relative directory...
203 char *current
; /* Current directory */
206 * Allocate a buffer for the current working directory to
207 * reduce run-time stack usage; this approximates the
208 * behavior of some implementations of getcwd() when they
209 * are passed a NULL pointer.
212 if ((current
= malloc(1024)) == NULL
)
214 _cupsLangPuts(stderr
,
215 _("cupsd: Unable to get current directory."));
219 if (!getcwd(current
, 1024))
221 _cupsLangPuts(stderr
,
222 _("cupsd: Unable to get current directory."));
227 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
232 case 'f' : /* Run in foreground... */
238 case 'F' : /* Run in foreground, but disconnect from terminal... */
243 case 'h' : /* Show usage/help */
247 case 'l' : /* Started by launchd/systemd... */
248 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
254 _cupsLangPuts(stderr
, _("cupsd: On-demand support not compiled "
255 "in, running in normal mode."));
259 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
262 case 'p' : /* Stop immediately for profiling */
263 fputs("cupsd: -p (startup profiling) is for internal testing "
264 "use only!\n", stderr
);
271 case 'P' : /* Disable security profiles */
272 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr
);
276 case 's' : /* Set cups-files.conf location */
280 _cupsLangPuts(stderr
, _("cupsd: Expected cups-files.conf "
281 "filename after \"-s\" option."));
285 if (argv
[i
][0] != '/')
288 * Relative filename not allowed...
291 _cupsLangPuts(stderr
, _("cupsd: Relative cups-files.conf "
292 "filename not allowed."));
296 cupsdSetString(&CupsFilesFile
, argv
[i
]);
300 case 'S' : /* Disable system management functions */
301 fputs("cupsd: -S (disable system management) for internal "
302 "testing use only!\n", stderr
);
305 #endif /* __APPLE__ */
307 case 't' : /* Test the cupsd.conf file... */
314 case 'T' : /* Print security profile */
321 default : /* Unknown option */
322 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
329 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
334 if (!ConfigurationFile
)
335 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
339 char *filename
, /* Copy of cupsd.conf filename */
340 *slash
; /* Final slash in cupsd.conf filename */
341 size_t len
; /* Size of buffer */
343 len
= strlen(ConfigurationFile
) + 15;
344 if ((filename
= malloc(len
)) == NULL
)
346 _cupsLangPrintf(stderr
,
347 _("cupsd: Unable to get path to "
348 "cups-files.conf file."));
352 strlcpy(filename
, ConfigurationFile
, len
);
353 if ((slash
= strrchr(filename
, '/')) == NULL
)
355 _cupsLangPrintf(stderr
,
356 _("cupsd: Unable to get path to "
357 "cups-files.conf file."));
361 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
362 cupsdSetString(&CupsFilesFile
, filename
);
369 * Make sure we aren't tying up any filesystems...
375 * Disconnect from the controlling terminal...
384 * Close all open files...
387 getrlimit(RLIMIT_NOFILE
, &limit
);
389 for (i
= 0; i
< (int)limit
.rlim_cur
&& i
< 1024; i
++)
393 * Redirect stdin/out/err to /dev/null...
396 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
402 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
408 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
415 LogStderr
= cupsFileStderr();
418 * Run in the background as needed...
424 * Setup signal handlers for the parent...
427 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
428 sigset(SIGUSR1
, parent_handler
);
429 sigset(SIGCHLD
, parent_handler
);
431 sigset(SIGHUP
, SIG_IGN
);
432 #elif defined(HAVE_SIGACTION)
433 memset(&action
, 0, sizeof(action
));
434 sigemptyset(&action
.sa_mask
);
435 sigaddset(&action
.sa_mask
, SIGUSR1
);
436 action
.sa_handler
= parent_handler
;
437 sigaction(SIGUSR1
, &action
, NULL
);
438 sigaction(SIGCHLD
, &action
, NULL
);
440 sigemptyset(&action
.sa_mask
);
441 action
.sa_handler
= SIG_IGN
;
442 sigaction(SIGHUP
, &action
, NULL
);
444 signal(SIGUSR1
, parent_handler
);
445 signal(SIGCLD
, parent_handler
);
447 signal(SIGHUP
, SIG_IGN
);
448 #endif /* HAVE_SIGSET */
453 * OK, wait for the child to startup and send us SIGUSR1 or to crash
454 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
455 * might be sent by the init script to restart the scheduler...
458 for (; parent_signal
== 0;)
461 if (parent_signal
== SIGUSR1
)
469 else if (WIFEXITED(i
))
471 fprintf(stderr
, "cupsd: Child exited with status %d\n",
477 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
482 #if defined(__OpenBSD__) && OpenBSD < 201211
484 * Call _thread_sys_closefrom() so the child process doesn't reset the
485 * parent's file descriptors to be blocking. This is a workaround for a
486 * limitation of userland libpthread on older versions of OpenBSD.
489 _thread_sys_closefrom(0);
490 #endif /* __OpenBSD__ && OpenBSD < 201211 */
493 * Since many system libraries create fork-unsafe data on execution of a
494 * program, we need to re-execute the background cupsd with the "-C" and "-s"
495 * options to avoid problems. Unfortunately, we also have to assume that
496 * argv[0] contains the name of the cupsd executable - there is no portable
497 * way to get the real pathname...
500 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, "-s", CupsFilesFile
, (char *)0);
505 * Set the timezone info...
511 setlocale(LC_TIME
, "");
514 #ifdef HAVE_DBUS_THREADS_INIT
516 * Enable threading support for D-BUS...
519 dbus_threads_init_default();
520 #endif /* HAVE_DBUS_THREADS_INIT */
523 * Set the maximum number of files...
526 getrlimit(RLIMIT_NOFILE
, &limit
);
528 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
529 if (limit
.rlim_max
> FD_SETSIZE
)
532 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
534 if (limit
.rlim_max
== RLIM_INFINITY
)
537 #endif /* RLIM_INFINITY */
538 MaxFDs
= limit
.rlim_max
;
540 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
542 setrlimit(RLIMIT_NOFILE
, &limit
);
547 * Read configuration...
550 if (!cupsdReadConfiguration())
552 else if (TestConfigFile
)
554 printf("\"%s\" is OK.\n", CupsFilesFile
);
555 printf("\"%s\" is OK.\n", ConfigurationFile
);
558 else if (print_profile
)
560 cups_file_t
*fp
; /* File pointer */
561 const char *profile
= cupsdCreateProfile(42, 0);
563 char line
[1024]; /* Line from file */
566 if ((fp
= cupsFileOpen(profile
, "r")) == NULL
)
568 printf("Unable to open profile file \"%s\": %s\n", profile
? profile
: "(null)", strerror(errno
));
572 while (cupsFileGets(fp
, line
, sizeof(line
)))
581 * Clean out old temp files and printer cache data.
584 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
585 cupsdCleanFiles(TempDir
, NULL
);
587 cupsdCleanFiles(CacheDir
, "*.ipp");
589 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
593 * If we were started on demand by launchd or systemd get the listen sockets
594 * file descriptors...
600 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
603 * Startup the server...
611 * Catch hangup and child signals and ignore broken pipes...
614 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
615 sigset(SIGCHLD
, sigchld_handler
);
616 sigset(SIGHUP
, sighup_handler
);
617 sigset(SIGPIPE
, SIG_IGN
);
618 sigset(SIGTERM
, sigterm_handler
);
619 #elif defined(HAVE_SIGACTION)
620 memset(&action
, 0, sizeof(action
));
622 sigemptyset(&action
.sa_mask
);
623 sigaddset(&action
.sa_mask
, SIGTERM
);
624 sigaddset(&action
.sa_mask
, SIGCHLD
);
625 action
.sa_handler
= sigchld_handler
;
626 sigaction(SIGCHLD
, &action
, NULL
);
628 sigemptyset(&action
.sa_mask
);
629 sigaddset(&action
.sa_mask
, SIGHUP
);
630 action
.sa_handler
= sighup_handler
;
631 sigaction(SIGHUP
, &action
, NULL
);
633 sigemptyset(&action
.sa_mask
);
634 action
.sa_handler
= SIG_IGN
;
635 sigaction(SIGPIPE
, &action
, NULL
);
637 sigemptyset(&action
.sa_mask
);
638 sigaddset(&action
.sa_mask
, SIGTERM
);
639 sigaddset(&action
.sa_mask
, SIGCHLD
);
640 action
.sa_handler
= sigterm_handler
;
641 sigaction(SIGTERM
, &action
, NULL
);
643 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
644 signal(SIGHUP
, sighup_handler
);
645 signal(SIGPIPE
, SIG_IGN
);
646 signal(SIGTERM
, sigterm_handler
);
647 #endif /* HAVE_SIGSET */
650 * Initialize authentication certificates...
656 * If we are running in the background, signal the parent process that
657 * we are up and running...
660 if (!fg
|| run_as_child
)
663 * Send a signal to the parent process, but only if the parent is
664 * not PID 1 (init). This avoids accidentally shutting down the
665 * system on OpenBSD if you CTRL-C the server before it is up...
668 i
= getppid(); /* Save parent PID to avoid race condition */
676 * Start power management framework...
680 cupsdStartSystemMonitor();
681 #endif /* __APPLE__ */
684 * Send server-started event...
687 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
689 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
691 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
693 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
695 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
698 * Start any pending print jobs...
707 current_time
= time(NULL
);
708 event_time
= current_time
;
709 expire_time
= current_time
;
712 senddoc_time
= current_time
;
714 while (!stop_scheduler
)
717 * Check if there are dead children to handle...
724 * Check if we need to load the server configuration file...
730 * Close any idle clients...
733 if (cupsArrayCount(Clients
) > 0)
735 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
737 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
738 if (httpGetState(con
->http
) == HTTP_WAITING
)
739 cupsdCloseClient(con
);
741 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
743 cupsdPauseListening();
747 * Restart if all clients are closed and all jobs finished, or
748 * if the reload timeout has elapsed...
751 if ((cupsArrayCount(Clients
) == 0 &&
752 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
753 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
756 * Shutdown the server...
764 * Read configuration...
767 if (!cupsdReadConfiguration())
770 asl_object_t m
; /* Log message */
772 m
= asl_new(ASL_TYPE_MSG
);
773 asl_set(m
, ASL_KEY_FACILITY
, "org.cups.cupsd");
774 asl_log(NULL
, m
, ASL_LEVEL_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
776 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
777 sd_journal_print(LOG_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
779 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting.", ConfigurationFile
);
780 #endif /* HAVE_ASL_H */
786 * Startup the server...
794 * Send a server-restarted event...
797 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
798 "Scheduler restarted.");
803 * Check for available input or ready output. If cupsdDoSelect()
804 * returns 0 or -1, something bad happened and we should exit
807 * Note that we at least have one listening socket open at all
811 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
814 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
816 * If no other work is scheduled and we're being controlled by
817 * launchd then timeout after 'LaunchdTimeout' seconds of
821 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
822 !cupsArrayCount(ActiveJobs
) &&
825 # endif /* HAVE_SYSTEMD */
826 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
828 timeout
= IdleExitTimeout
;
829 service_idle_exit
= 1;
832 service_idle_exit
= 0;
833 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
835 if ((fds
= cupsdDoSelect(timeout
)) < 0)
838 * Got an error from select!
841 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
842 cupsd_printer_t
*p
; /* Current printer */
843 #endif /* HAVE_DNSSD || HAVE_AVAHI */
846 if (errno
== EINTR
) /* Just interrupted by a signal */
850 * Log all sorts of debug info to help track down the problem.
853 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
856 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
858 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
859 cupsdLogMessage(CUPSD_LOG_EMERG
,
860 "Clients[%d] = %d, file = %d, state = %d",
861 i
, con
->number
, con
->file
, httpGetState(con
->http
));
863 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
865 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
866 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
868 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
871 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
873 #endif /* __APPLE__ */
875 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
877 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
878 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
880 job
->status_buffer
? job
->status_buffer
->fd
: -1,
881 job
->print_pipes
[0], job
->print_pipes
[1],
882 job
->back_pipes
[0], job
->back_pipes
[1]);
884 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
885 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
887 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
888 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
889 p
->reg_name
? p
->reg_name
: "(null)");
890 #endif /* HAVE_DNSSD || HAVE_AVAHI */
895 current_time
= time(NULL
);
898 * Write dirty config/state files...
901 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
906 * If we are going to sleep and still have pending jobs, stop them after
907 * a period of time...
910 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
911 cupsArrayCount(PrintingJobs
) > 0)
914 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
916 #endif /* __APPLE__ */
920 * Update the network interfaces once a minute...
923 if ((current_time
- netif_time
) >= 60)
925 netif_time
= current_time
;
928 #endif /* !__APPLE__ */
930 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
932 * If no other work was scheduled and we're being controlled by launchd
933 * then timeout after 'LaunchdTimeout' seconds of inactivity...
936 if (!fds
&& service_idle_exit
)
938 cupsdLogMessage(CUPSD_LOG_INFO
,
939 "Printer sharing is off and there are no jobs pending, "
940 "will restart on demand.");
944 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
947 * Resume listening for new connections as needed...
950 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
951 cupsArrayCount(Clients
) < MaxClients
)
952 cupsdResumeListening();
955 * Expire subscriptions and unload completed jobs as needed...
958 if (current_time
> expire_time
)
960 if (cupsArrayCount(Subscriptions
) > 0)
961 cupsdExpireSubscriptions(NULL
, NULL
);
963 cupsdUnloadCompletedJobs();
965 expire_time
= current_time
;
968 #ifndef HAVE_AUTHORIZATION_H
970 * Update the root certificate once every 5 minutes if we have client
974 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
975 !RunUser
&& cupsArrayCount(Clients
))
978 * Update the root certificate...
982 cupsdAddCert(0, "root", cupsdDefaultAuthType());
984 #endif /* !HAVE_AUTHORIZATION_H */
987 * Check for new data on the client sockets...
990 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
992 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
995 * Process pending data in the input buffer...
998 if (httpGetReady(con
->http
))
1000 cupsdReadClient(con
);
1005 * Check the activity and close old clients...
1008 activity
= current_time
- Timeout
;
1009 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
1011 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
1013 cupsdCloseClient(con
);
1019 * Update any pending multi-file documents...
1022 if ((current_time
- senddoc_time
) >= 10)
1025 senddoc_time
= current_time
;
1029 * Clean job history...
1032 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
1036 * Log statistics at most once a minute when in debug mode...
1039 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1041 size_t string_count
, /* String count */
1042 alloc_bytes
, /* Allocated string bytes */
1043 total_bytes
; /* Total string bytes */
1044 #ifdef HAVE_MALLINFO
1045 struct mallinfo mem
; /* Malloc information */
1049 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1050 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1051 mem
.usmblks
+ mem
.uordblks
);
1052 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1053 mem
.fsmblks
+ mem
.fordblks
);
1054 #endif /* HAVE_MALLINFO */
1056 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1057 cupsArrayCount(Clients
));
1058 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1059 cupsArrayCount(Jobs
));
1060 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1061 cupsArrayCount(ActiveJobs
));
1062 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1063 cupsArrayCount(Printers
));
1065 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1066 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1067 "Report: stringpool-string-count=" CUPS_LLFMT
,
1068 CUPS_LLCAST string_count
);
1069 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1070 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1071 CUPS_LLCAST alloc_bytes
);
1072 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1073 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1074 CUPS_LLCAST total_bytes
);
1076 report_time
= current_time
;
1080 * Handle OS-specific event notification for any events that have
1081 * accumulated. Don't send these more than once a second...
1084 if (LastEvent
&& (current_time
- event_time
) >= 1)
1086 #ifdef HAVE_NOTIFY_POST
1087 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1088 CUPSD_EVENT_PRINTER_DELETED
|
1089 CUPSD_EVENT_PRINTER_MODIFIED
))
1091 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1092 "notify_post(\"com.apple.printerListChange\")");
1093 notify_post("com.apple.printerListChange");
1096 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1098 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1099 "notify_post(\"com.apple.printerHistoryChange\")");
1100 notify_post("com.apple.printerHistoryChange");
1103 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1104 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1105 CUPSD_EVENT_JOB_PROGRESS
))
1107 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1108 "notify_post(\"com.apple.jobChange\")");
1109 notify_post("com.apple.jobChange");
1111 #endif /* HAVE_NOTIFY_POST */
1114 * Reset the accumulated events...
1117 LastEvent
= CUPSD_EVENT_NONE
;
1118 event_time
= current_time
;
1123 * Log a message based on what happened...
1128 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1129 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1130 "Scheduler shutting down normally.");
1134 cupsdLogMessage(CUPSD_LOG_ERROR
,
1135 "Scheduler shutting down due to program error.");
1136 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1137 "Scheduler shutting down due to program error.");
1141 * Close all network clients...
1148 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1150 * Update the keep-alive file as needed...
1155 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
1165 * Stop monitoring system event monitoring...
1169 cupsdStopSystemMonitor();
1170 #endif /* __APPLE__ */
1174 return (!stop_scheduler
);
1179 * 'cupsdAddString()' - Copy and add a string to an array.
1182 int /* O - 1 on success, 0 on failure */
1183 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1184 const char *s
) /* I - String to copy and add */
1187 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1188 (cups_ahash_func_t
)NULL
, 0,
1189 (cups_acopy_func_t
)strdup
,
1190 (cups_afree_func_t
)free
);
1192 return (cupsArrayAdd(*a
, (char *)s
));
1197 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1201 cupsdCheckProcess(void)
1204 * Flag that we have dead children...
1212 * 'cupsdClearString()' - Clear a string.
1216 cupsdClearString(char **s
) /* O - String value */
1227 * 'cupsdFreeStrings()' - Free an array of strings.
1231 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1235 cupsArrayDelete(*a
);
1242 * 'cupsdHoldSignals()' - Hold child and termination signals.
1246 cupsdHoldSignals(void)
1248 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1249 sigset_t newmask
; /* New POSIX signal mask */
1250 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1260 #elif defined(HAVE_SIGACTION)
1261 sigemptyset(&newmask
);
1262 sigaddset(&newmask
, SIGTERM
);
1263 sigaddset(&newmask
, SIGCHLD
);
1264 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1265 #endif /* HAVE_SIGSET */
1270 * 'cupsdReleaseSignals()' - Release signals for delivery.
1274 cupsdReleaseSignals(void)
1283 #elif defined(HAVE_SIGACTION)
1284 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1285 #endif /* HAVE_SIGSET */
1290 * 'cupsdSetString()' - Set a string value.
1294 cupsdSetString(char **s
, /* O - New string */
1295 const char *v
) /* I - String value */
1311 * 'cupsdSetStringf()' - Set a formatted string value.
1315 cupsdSetStringf(char **s
, /* O - New string */
1316 const char *f
, /* I - Printf-style format string */
1317 ...) /* I - Additional args as needed */
1319 char v
[65536 + 64]; /* Formatting string value */
1320 va_list ap
; /* Argument pointer */
1321 char *olds
; /* Old string */
1332 vsnprintf(v
, sizeof(v
), f
, ap
);
1346 * 'parent_handler()' - Catch USR1/CHLD signals...
1350 parent_handler(int sig
) /* I - Signal */
1353 * Store the signal we got from the OS and return...
1356 parent_signal
= sig
;
1361 * 'process_children()' - Process all dead children...
1365 process_children(void)
1367 int status
; /* Exit status of child */
1368 int pid
, /* Process ID of child */
1369 job_id
; /* Job ID of child */
1370 cupsd_job_t
*job
; /* Current job */
1371 int i
; /* Looping var */
1372 char name
[1024]; /* Process name */
1373 const char *type
; /* Type of program */
1376 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1379 * Reset the dead_children flag...
1385 * Collect the exit status of some children...
1389 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1390 #elif defined(HAVE_WAIT3)
1391 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1393 if ((pid
= wait(&status
)) > 0)
1394 #endif /* HAVE_WAITPID */
1397 * Collect the name of the process that finished...
1400 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1403 * Delete certificates for CGI processes...
1407 cupsdDeleteCert(pid
);
1410 * Handle completed job filters...
1414 job
= cupsdFindJob(job_id
);
1420 for (i
= 0; job
->filters
[i
]; i
++)
1421 if (job
->filters
[i
] == pid
)
1424 if (job
->filters
[i
] || job
->backend
== pid
)
1427 * OK, this process has gone away; what's left?
1430 if (job
->filters
[i
])
1432 job
->filters
[i
] = -pid
;
1437 job
->backend
= -pid
;
1441 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1445 * An error occurred; save the exit status so we know to stop
1446 * the printer or cancel the job when all of the filters finish...
1448 * A negative status indicates that the backend failed and the
1449 * printer needs to be stopped.
1451 * In order to preserve the most serious status, we always log
1452 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1453 * and SIGBUS) and prefer to log the backend exit status over a
1457 int old_status
= abs(job
->status
);
1459 if (WIFSIGNALED(status
) || /* This process crashed, or */
1460 !job
->status
|| /* No process had a status, or */
1461 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1462 { /* Backend and filter didn't crash */
1463 if (job
->filters
[i
])
1464 job
->status
= status
; /* Filter failed */
1466 job
->status
= -status
; /* Backend failed */
1469 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1470 job
->status_level
> CUPSD_LOG_ERROR
&&
1471 (job
->filters
[i
] || !WIFEXITED(status
)))
1473 char message
[1024]; /* New printer-state-message */
1476 job
->status_level
= CUPSD_LOG_ERROR
;
1478 snprintf(message
, sizeof(message
), "%s failed", type
);
1482 strlcpy(job
->printer
->state_message
, message
,
1483 sizeof(job
->printer
->state_message
));
1489 if (!job
->printer_message
&& job
->attrs
)
1491 if ((job
->printer_message
=
1492 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1493 IPP_TAG_TEXT
)) == NULL
)
1494 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1496 "job-printer-state-message",
1500 if (job
->printer_message
)
1501 ippSetString(job
->attrs
, &job
->printer_message
, 0, message
);
1506 * If this is not the last file in a job, see if all of the
1507 * filters are done, and if so move to the next file.
1510 if (job
->current_file
< job
->num_files
&& job
->printer
)
1512 for (i
= 0; job
->filters
[i
] < 0; i
++);
1514 if (!job
->filters
[i
] &&
1515 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1519 * Process the next file...
1522 cupsdContinueJob(job
);
1525 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1528 * Remove the job from the active list if there are no processes still
1532 for (i
= 0; job
->filters
[i
] < 0; i
++);
1534 if (!job
->filters
[i
] && job
->backend
<= 0)
1535 cupsArrayRemove(ActiveJobs
, job
);
1541 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1542 * since they come when we kill/end a process...
1545 if (status
== SIGTERM
|| status
== SIGKILL
)
1547 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1548 "PID %d (%s) was terminated normally with signal %d.", pid
,
1551 else if (status
== SIGPIPE
)
1553 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1554 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1559 if (WIFEXITED(status
))
1561 int code
= WEXITSTATUS(status
); /* Exit code */
1564 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1565 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1566 code
, strerror(code
- 100));
1568 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1569 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1572 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1573 pid
, name
, WTERMSIG(status
));
1575 if (LogLevel
< CUPSD_LOG_DEBUG
)
1576 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1577 "Hint: Try setting the LogLevel to \"debug\" to find out "
1581 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1586 * If wait*() is interrupted by a signal, tell main() to call us again...
1589 if (pid
< 0 && errno
== EINTR
)
1595 * 'select_timeout()' - Calculate the select timeout value.
1599 static long /* O - Number of seconds */
1600 select_timeout(int fds
) /* I - Number of descriptors returned */
1602 long timeout
; /* Timeout for select */
1603 time_t now
; /* Current time */
1604 cupsd_client_t
*con
; /* Client information */
1605 cupsd_job_t
*job
; /* Job information */
1606 const char *why
; /* Debugging aid */
1609 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1610 (long)JobHistoryUpdate
);
1613 * Check to see if any of the clients have pending data to be
1614 * processed; if so, the timeout should be 0...
1617 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1619 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1620 if (httpGetReady(con
->http
))
1624 * If select has been active in the last second (fds > 0) or we have
1625 * many resources in use then don't bother trying to optimize the
1626 * timeout, just make it 1 second.
1629 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1633 * Otherwise, check all of the possible events that we need to wake for...
1637 timeout
= now
+ 86400; /* 86400 == 1 day */
1642 * When going to sleep, wake up to cancel jobs that don't complete in time.
1645 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1647 timeout
= SleepJobs
;
1648 why
= "cancel jobs before sleeping";
1650 #endif /* __APPLE__ */
1653 * Check whether we are accepting new connections...
1656 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1657 ListeningPaused
< timeout
)
1659 if (ListeningPaused
<= now
)
1662 timeout
= ListeningPaused
;
1664 why
= "resume listening";
1668 * Check the activity and close old clients...
1671 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1673 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1674 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1676 timeout
= httpGetActivity(con
->http
) + Timeout
;
1677 why
= "timeout a client connection";
1681 * Write out changes to configuration and state files...
1684 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1686 timeout
= DirtyCleanTime
;
1687 why
= "write dirty config/state files";
1691 * Check for any job activity...
1694 if (JobHistoryUpdate
&& timeout
> JobHistoryUpdate
)
1696 timeout
= JobHistoryUpdate
;
1697 why
= "update job history";
1700 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1702 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1704 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1706 timeout
= job
->cancel_time
;
1707 why
= "cancel stuck jobs";
1710 if (job
->kill_time
&& job
->kill_time
< timeout
)
1712 timeout
= job
->kill_time
;
1713 why
= "kill unresponsive jobs";
1716 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1718 timeout
= job
->hold_until
;
1719 why
= "release held jobs";
1722 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1725 why
= "start pending jobs";
1730 #ifdef HAVE_MALLINFO
1732 * Log memory usage every minute...
1735 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1737 timeout
= mallinfo_time
+ 60;
1738 why
= "display memory usage";
1740 #endif /* HAVE_MALLINFO */
1743 * Adjust from absolute to relative time. We add 1 second to the timeout since
1744 * events occur after the timeout expires, and limit the timeout to 86400
1745 * seconds (1 day) to avoid select() timeout limits present on some operating
1749 timeout
= timeout
- now
+ 1;
1753 else if (timeout
> 86400)
1757 * Log and return the timeout value...
1760 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1768 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1772 sigchld_handler(int sig
) /* I - Signal number */
1777 * Flag that we have dead children...
1783 * Reset the signal handler as needed...
1786 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1787 signal(SIGCLD
, sigchld_handler
);
1788 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1793 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1797 sighup_handler(int sig
) /* I - Signal number */
1801 NeedReload
= RELOAD_ALL
;
1802 ReloadTime
= time(NULL
);
1804 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1805 signal(SIGHUP
, sighup_handler
);
1806 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1811 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1815 sigterm_handler(int sig
) /* I - Signal number */
1817 (void)sig
; /* remove compiler warnings... */
1820 * Flag that we should stop and return...
1827 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1829 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1833 service_checkin(void)
1835 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
1836 int error
; /* Check-in error, if any */
1837 size_t i
, /* Looping var */
1838 count
; /* Number of listeners */
1839 int *ld_sockets
; /* Listener sockets */
1840 cupsd_listener_t
*lis
; /* Listeners array */
1841 http_addr_t addr
; /* Address variable */
1842 socklen_t addrlen
; /* Length of address */
1843 char s
[256]; /* String addresss */
1846 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1849 * Check-in with launchd...
1852 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1854 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1856 return; /* anti-compiler-warning */
1860 * Try to match the launchd sockets to the cupsd listeners...
1863 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1865 for (i
= 0; i
< count
; i
++)
1868 * Get the launchd socket address...
1871 addrlen
= sizeof(addr
);
1873 if (getsockname(ld_sockets
[i
], (struct sockaddr
*)&addr
, &addrlen
))
1875 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1879 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, ld_sockets
[i
], httpAddrString(&addr
, s
, sizeof(s
)));
1881 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1883 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1884 if (httpAddrEqual(&lis
->address
, &addr
))
1888 * Add a new listener if there's no match...
1893 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1897 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1899 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1901 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
1905 cupsArrayAdd(Listeners
, lis
);
1907 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1910 lis
->fd
= ld_sockets
[i
];
1914 if (httpAddrPort(&(lis
->address
)) == 443)
1915 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1916 # endif /* HAVE_SSL */
1921 # elif defined(HAVE_LAUNCHD)
1922 size_t i
, /* Looping var */
1923 count
; /* Number of listeners */
1924 launch_data_t ld_msg
, /* Launch data message */
1925 ld_resp
, /* Launch data response */
1926 ld_array
, /* Launch data array */
1927 ld_sockets
, /* Launch data sockets dictionary */
1928 tmp
; /* Launch data */
1929 cupsd_listener_t
*lis
; /* Listeners array */
1930 http_addr_t addr
; /* Address variable */
1931 socklen_t addrlen
; /* Length of address */
1932 int fd
; /* File descriptor */
1933 char s
[256]; /* String addresss */
1936 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1939 * Check-in with launchd...
1942 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1943 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1945 cupsdLogMessage(CUPSD_LOG_ERROR
,
1946 "service_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1949 return; /* anti-compiler-warning */
1952 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1954 errno
= launch_data_get_errno(ld_resp
);
1955 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Check-in failed: %s",
1958 return; /* anti-compiler-warning */
1962 * Get the sockets dictionary...
1965 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1968 cupsdLogMessage(CUPSD_LOG_ERROR
,
1969 "service_checkin: No sockets found to answer requests on.");
1971 return; /* anti-compiler-warning */
1975 * Get the array of listener sockets...
1978 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1980 cupsdLogMessage(CUPSD_LOG_ERROR
,
1981 "service_checkin: No sockets found to answer requests on.");
1983 return; /* anti-compiler-warning */
1987 * Add listening fd(s) to the Listener array...
1990 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1992 count
= launch_data_array_get_count(ld_array
);
1994 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1996 for (i
= 0; i
< count
; i
++)
1999 * Get the launchd file descriptor and address...
2002 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
2004 fd
= launch_data_get_fd(tmp
);
2005 addrlen
= sizeof(addr
);
2007 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
2009 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2013 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
2016 * Try to match the launchd socket address to one of the listeners...
2019 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2021 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2022 if (httpAddrEqual(&lis
->address
, &addr
))
2026 * Add a new listener If there's no match...
2031 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2035 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2037 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2039 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s.", strerror(errno
));
2043 cupsArrayAdd(Listeners
, lis
);
2045 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2052 if (httpAddrPort(&(lis
->address
)) == 443)
2053 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2054 # endif /* HAVE_SSL */
2059 launch_data_free(ld_msg
);
2060 launch_data_free(ld_resp
);
2062 # else /* HAVE_SYSTEMD */
2063 int i
, /* Looping var */
2064 count
; /* Number of listeners */
2065 cupsd_listener_t
*lis
; /* Listeners array */
2066 http_addr_t addr
; /* Address variable */
2067 socklen_t addrlen
; /* Length of address */
2068 char s
[256]; /* String addresss */
2071 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
2074 * Check-in with systemd...
2077 if ((count
= sd_listen_fds(0)) < 0)
2079 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
2081 return; /* anti-compiler-warning */
2085 * Try to match the systemd sockets to the cupsd listeners...
2088 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
2090 for (i
= 0; i
< count
; i
++)
2093 * Get the launchd socket address...
2096 addrlen
= sizeof(addr
);
2098 if (getsockname(SD_LISTEN_FDS_START
+ i
, (struct sockaddr
*)&addr
, &addrlen
))
2100 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2104 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
)));
2106 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2108 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2109 if (httpAddrEqual(&lis
->address
, &addr
))
2113 * Add a new listener if there's no match...
2118 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2122 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2124 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2126 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
2130 cupsArrayAdd(Listeners
, lis
);
2132 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2135 lis
->fd
= SD_LISTEN_FDS_START
+ i
;
2139 if (httpAddrPort(&(lis
->address
)) == 443)
2140 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2141 # endif /* HAVE_SSL */
2143 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
2148 * 'service_checkout()' - Update the CUPS_KEEPALIVE file as needed.
2152 service_checkout(void)
2154 int fd
; /* File descriptor */
2158 * Create or remove the "keep-alive" file based on whether there are active
2159 * jobs or shared printers to advertise...
2162 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2163 WebInterface
|| /* Web interface enabled */
2164 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
2165 /* Printers being shared */
2167 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating keep-alive file \"" CUPS_KEEPALIVE
"\".");
2169 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
2174 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing keep-alive file \"" CUPS_KEEPALIVE
"\".");
2176 unlink(CUPS_KEEPALIVE
);
2179 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
2183 * 'usage()' - Show scheduler usage.
2187 usage(int status
) /* O - Exit status */
2189 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2192 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2193 _cupsLangPuts(fp
, _("Options:"));
2194 _cupsLangPuts(fp
, _(" -c cupsd.conf Set cupsd.conf file to use."));
2195 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2196 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
2197 "detach from console."));
2198 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2199 _cupsLangPuts(fp
, _(" -l Run cupsd on demand."));
2200 _cupsLangPuts(fp
, _(" -t Test the configuration "