4 * Main loop for the CUPS scheduler.
6 * Copyright 2007-2014 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>
29 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
30 /* Name of the launchd KeepAlive file */
31 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
32 /* Update when we have a public header we can include */
33 extern int launch_activate_socket(const char *name
, int **fds
, size_t *cnt
);
34 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
35 #endif /* HAVE_LAUNCH_H */
38 # include <systemd/sd-daemon.h>
39 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
40 /* Name of the systemd path file */
41 #endif /* HAVE_SYSTEMD */
43 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
45 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
49 #endif /* HAVE_NOTIFY_H */
52 # include <dbus/dbus.h>
53 #endif /* HAVE_DBUS */
55 #ifdef HAVE_SYS_PARAM_H
56 # include <sys/param.h>
57 #endif /* HAVE_SYS_PARAM_H */
64 static void parent_handler(int sig
);
65 static void process_children(void);
66 static void sigchld_handler(int sig
);
67 static void sighup_handler(int sig
);
68 static void sigterm_handler(int sig
);
69 static long select_timeout(int fds
);
70 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
71 static void service_checkin(void);
72 static void service_checkout(void);
73 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
74 static void usage(int status
) __attribute__((noreturn
));
81 static int parent_signal
= 0;
82 /* Set to signal number from child */
83 static int holdcount
= 0; /* Number of times "hold" was called */
84 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
85 static sigset_t holdmask
; /* Old POSIX signal mask */
86 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
87 static int dead_children
= 0;
89 static int stop_scheduler
= 0;
90 /* Should the scheduler stop? */
94 * 'main()' - Main entry for the CUPS scheduler.
97 int /* O - Exit status */
98 main(int argc
, /* I - Number of command-line args */
99 char *argv
[]) /* I - Command-line arguments */
101 int i
; /* Looping var */
102 char *opt
; /* Option character */
103 int fg
; /* Run in the foreground */
104 int fds
; /* Number of ready descriptors */
105 cupsd_client_t
*con
; /* Current client */
106 cupsd_job_t
*job
; /* Current job */
107 cupsd_listener_t
*lis
; /* Current listener */
108 time_t current_time
, /* Current time */
109 activity
, /* Client activity timer */
110 senddoc_time
, /* Send-Document time */
111 expire_time
, /* Subscription expire time */
112 report_time
, /* Malloc/client/job report time */
113 event_time
; /* Last event notification time */
114 long timeout
; /* Timeout for cupsdDoSelect() */
115 struct rlimit limit
; /* Runtime limit */
116 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
117 struct sigaction action
; /* Actions for POSIX signals */
118 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
119 int run_as_child
= 0;
120 /* Needed for background fork/exec */
122 int use_sysman
= 1; /* Use system management functions? */
124 time_t netif_time
= 0; /* Time since last network update */
125 #endif /* __APPLE__ */
126 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
127 int service_idle_exit
;
128 /* Idle exit on select timeout? */
129 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
134 * Check for setuid invocation, which we do not support!
137 if (getuid() != geteuid())
139 fputs("cupsd: Cannot run as a setuid program.\n", stderr
);
142 #endif /* HAVE_GETEUID */
145 * Check for command-line arguments...
151 if (getenv("CUPSD_LAUNCHD"))
156 #endif /* HAVE_LAUNCHD */
158 for (i
= 1; i
< argc
; i
++)
159 if (argv
[i
][0] == '-')
160 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
163 case 'C' : /* Run as child with config file */
167 case 'c' : /* Configuration file */
171 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
172 "after \"-c\" option."));
176 if (argv
[i
][0] == '/')
179 * Absolute directory...
182 cupsdSetString(&ConfigurationFile
, argv
[i
]);
187 * Relative directory...
190 char *current
; /* Current directory */
193 * Allocate a buffer for the current working directory to
194 * reduce run-time stack usage; this approximates the
195 * behavior of some implementations of getcwd() when they
196 * are passed a NULL pointer.
199 if ((current
= malloc(1024)) == NULL
)
201 _cupsLangPuts(stderr
,
202 _("cupsd: Unable to get current directory."));
206 if (!getcwd(current
, 1024))
208 _cupsLangPuts(stderr
,
209 _("cupsd: Unable to get current directory."));
214 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
219 case 'f' : /* Run in foreground... */
223 case 'F' : /* Run in foreground, but disconnect from terminal... */
227 case 'h' : /* Show usage/help */
231 case 'l' : /* Started by launchd/systemd... */
232 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
236 _cupsLangPuts(stderr
, _("cupsd: On-demand support not compiled "
237 "in, running in normal mode."));
239 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
242 case 'p' : /* Stop immediately for profiling */
243 fputs("cupsd: -p (startup profiling) is for internal testing "
244 "use only!\n", stderr
);
249 case 'P' : /* Disable security profiles */
250 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr
);
254 case 's' : /* Set cups-files.conf location */
258 _cupsLangPuts(stderr
, _("cupsd: Expected cups-files.conf "
259 "filename after \"-s\" option."));
263 if (argv
[i
][0] != '/')
266 * Relative filename not allowed...
269 _cupsLangPuts(stderr
, _("cupsd: Relative cups-files.conf "
270 "filename not allowed."));
274 cupsdSetString(&CupsFilesFile
, argv
[i
]);
278 case 'S' : /* Disable system management functions */
279 fputs("cupsd: -S (disable system management) for internal "
280 "testing use only!\n", stderr
);
283 #endif /* __APPLE__ */
285 case 't' : /* Test the cupsd.conf file... */
290 default : /* Unknown option */
291 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
298 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
303 if (!ConfigurationFile
)
304 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
308 char *filename
, /* Copy of cupsd.conf filename */
309 *slash
; /* Final slash in cupsd.conf filename */
310 size_t len
; /* Size of buffer */
312 len
= strlen(ConfigurationFile
) + 15;
313 if ((filename
= malloc(len
)) == NULL
)
315 _cupsLangPrintf(stderr
,
316 _("cupsd: Unable to get path to "
317 "cups-files.conf file."));
321 strlcpy(filename
, ConfigurationFile
, len
);
322 if ((slash
= strrchr(filename
, '/')) == NULL
)
324 _cupsLangPrintf(stderr
,
325 _("cupsd: Unable to get path to "
326 "cups-files.conf file."));
330 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
331 cupsdSetString(&CupsFilesFile
, filename
);
336 * If the user hasn't specified "-f", run in the background...
342 * Setup signal handlers for the parent...
345 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
346 sigset(SIGUSR1
, parent_handler
);
347 sigset(SIGCHLD
, parent_handler
);
349 sigset(SIGHUP
, SIG_IGN
);
350 #elif defined(HAVE_SIGACTION)
351 memset(&action
, 0, sizeof(action
));
352 sigemptyset(&action
.sa_mask
);
353 sigaddset(&action
.sa_mask
, SIGUSR1
);
354 action
.sa_handler
= parent_handler
;
355 sigaction(SIGUSR1
, &action
, NULL
);
356 sigaction(SIGCHLD
, &action
, NULL
);
358 sigemptyset(&action
.sa_mask
);
359 action
.sa_handler
= SIG_IGN
;
360 sigaction(SIGHUP
, &action
, NULL
);
362 signal(SIGUSR1
, parent_handler
);
363 signal(SIGCLD
, parent_handler
);
365 signal(SIGHUP
, SIG_IGN
);
366 #endif /* HAVE_SIGSET */
371 * OK, wait for the child to startup and send us SIGUSR1 or to crash
372 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
373 * might be sent by the init script to restart the scheduler...
376 for (; parent_signal
== 0;)
379 if (parent_signal
== SIGUSR1
)
387 else if (WIFEXITED(i
))
389 fprintf(stderr
, "cupsd: Child exited with status %d\n",
395 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
400 #if defined(__OpenBSD__) && OpenBSD < 201211
402 * Call _thread_sys_closefrom() so the child process doesn't reset the
403 * parent's file descriptors to be blocking. This is a workaround for a
404 * limitation of userland libpthread on older versions of OpenBSD.
407 _thread_sys_closefrom(0);
408 #endif /* __OpenBSD__ && OpenBSD < 201211 */
411 * Since CoreFoundation and DBUS both create fork-unsafe data on execution of
412 * a program, and since this kind of really unfriendly behavior seems to be
413 * more common these days in system libraries, we need to re-execute the
414 * background cupsd with the "-C" option to avoid problems. Unfortunately,
415 * we also have to assume that argv[0] contains the name of the cupsd
416 * executable - there is no portable way to get the real pathname...
419 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, (char *)0);
426 * Make sure we aren't tying up any filesystems...
433 * Disable core dumps...
436 getrlimit(RLIMIT_CORE
, &limit
);
438 setrlimit(RLIMIT_CORE
, &limit
);
441 * Disconnect from the controlling terminal...
447 * Close all open files...
450 getrlimit(RLIMIT_NOFILE
, &limit
);
452 for (i
= 0; i
< limit
.rlim_cur
&& i
< 1024; i
++)
456 * Redirect stdin/out/err to /dev/null...
459 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
465 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
471 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
480 * Set the timezone info...
486 setlocale(LC_TIME
, "");
489 #ifdef HAVE_DBUS_THREADS_INIT
491 * Enable threading support for D-BUS...
494 dbus_threads_init_default();
495 #endif /* HAVE_DBUS_THREADS_INIT */
498 * Set the maximum number of files...
501 getrlimit(RLIMIT_NOFILE
, &limit
);
503 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
504 if (limit
.rlim_max
> FD_SETSIZE
)
507 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
509 if (limit
.rlim_max
== RLIM_INFINITY
)
512 #endif /* RLIM_INFINITY */
513 MaxFDs
= limit
.rlim_max
;
515 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
517 setrlimit(RLIMIT_NOFILE
, &limit
);
522 * Read configuration...
525 if (!cupsdReadConfiguration())
527 else if (TestConfigFile
)
529 printf("\"%s\" is OK.\n", CupsFilesFile
);
530 printf("\"%s\" is OK.\n", ConfigurationFile
);
535 * Clean out old temp files and printer cache data.
538 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
539 cupsdCleanFiles(TempDir
, NULL
);
541 cupsdCleanFiles(CacheDir
, "*.ipp");
543 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
547 * If we were started on demand by launchd or systemd get the listen sockets
548 * file descriptors...
554 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
557 * Startup the server...
565 * Catch hangup and child signals and ignore broken pipes...
568 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
569 sigset(SIGCHLD
, sigchld_handler
);
570 sigset(SIGHUP
, sighup_handler
);
571 sigset(SIGPIPE
, SIG_IGN
);
572 sigset(SIGTERM
, sigterm_handler
);
573 #elif defined(HAVE_SIGACTION)
574 memset(&action
, 0, sizeof(action
));
576 sigemptyset(&action
.sa_mask
);
577 sigaddset(&action
.sa_mask
, SIGTERM
);
578 sigaddset(&action
.sa_mask
, SIGCHLD
);
579 action
.sa_handler
= sigchld_handler
;
580 sigaction(SIGCHLD
, &action
, NULL
);
582 sigemptyset(&action
.sa_mask
);
583 sigaddset(&action
.sa_mask
, SIGHUP
);
584 action
.sa_handler
= sighup_handler
;
585 sigaction(SIGHUP
, &action
, NULL
);
587 sigemptyset(&action
.sa_mask
);
588 action
.sa_handler
= SIG_IGN
;
589 sigaction(SIGPIPE
, &action
, NULL
);
591 sigemptyset(&action
.sa_mask
);
592 sigaddset(&action
.sa_mask
, SIGTERM
);
593 sigaddset(&action
.sa_mask
, SIGCHLD
);
594 action
.sa_handler
= sigterm_handler
;
595 sigaction(SIGTERM
, &action
, NULL
);
597 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
598 signal(SIGHUP
, sighup_handler
);
599 signal(SIGPIPE
, SIG_IGN
);
600 signal(SIGTERM
, sigterm_handler
);
601 #endif /* HAVE_SIGSET */
604 * Initialize authentication certificates...
610 * If we are running in the background, signal the parent process that
611 * we are up and running...
614 if (!fg
|| run_as_child
)
617 * Send a signal to the parent process, but only if the parent is
618 * not PID 1 (init). This avoids accidentally shutting down the
619 * system on OpenBSD if you CTRL-C the server before it is up...
622 i
= getppid(); /* Save parent PID to avoid race condition */
630 * Start power management framework...
634 cupsdStartSystemMonitor();
635 #endif /* __APPLE__ */
638 * Send server-started event...
641 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
643 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
645 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
647 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
649 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
652 * Start any pending print jobs...
661 current_time
= time(NULL
);
662 event_time
= current_time
;
663 expire_time
= current_time
;
666 senddoc_time
= current_time
;
668 while (!stop_scheduler
)
671 * Check if there are dead children to handle...
678 * Check if we need to load the server configuration file...
684 * Close any idle clients...
687 if (cupsArrayCount(Clients
) > 0)
689 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
691 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
692 if (httpGetState(con
->http
) == HTTP_WAITING
)
693 cupsdCloseClient(con
);
695 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
697 cupsdPauseListening();
701 * Restart if all clients are closed and all jobs finished, or
702 * if the reload timeout has elapsed...
705 if ((cupsArrayCount(Clients
) == 0 &&
706 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
707 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
710 * Shutdown the server...
718 * Read configuration...
721 if (!cupsdReadConfiguration())
723 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
729 * Startup the server...
737 * Send a server-restarted event...
740 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
741 "Scheduler restarted.");
746 * Check for available input or ready output. If cupsdDoSelect()
747 * returns 0 or -1, something bad happened and we should exit
750 * Note that we at least have one listening socket open at all
754 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
757 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
759 * If no other work is scheduled and we're being controlled by
760 * launchd then timeout after 'LaunchdTimeout' seconds of
764 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
765 !cupsArrayCount(ActiveJobs
) &&
768 # endif /* HAVE_SYSTEMD */
769 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
771 timeout
= IdleExitTimeout
;
772 service_idle_exit
= 1;
775 service_idle_exit
= 0;
776 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
778 if ((fds
= cupsdDoSelect(timeout
)) < 0)
781 * Got an error from select!
784 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
785 cupsd_printer_t
*p
; /* Current printer */
786 #endif /* HAVE_DNSSD || HAVE_AVAHI */
789 if (errno
== EINTR
) /* Just interrupted by a signal */
793 * Log all sorts of debug info to help track down the problem.
796 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
799 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
801 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
802 cupsdLogMessage(CUPSD_LOG_EMERG
,
803 "Clients[%d] = %d, file = %d, state = %d",
804 i
, con
->number
, con
->file
, httpGetState(con
->http
));
806 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
808 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
809 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
811 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
814 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
816 #endif /* __APPLE__ */
818 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
820 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
821 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
823 job
->status_buffer
? job
->status_buffer
->fd
: -1,
824 job
->print_pipes
[0], job
->print_pipes
[1],
825 job
->back_pipes
[0], job
->back_pipes
[1]);
827 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
828 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
830 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
831 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
832 p
->reg_name
? p
->reg_name
: "(null)");
833 #endif /* HAVE_DNSSD || HAVE_AVAHI */
838 current_time
= time(NULL
);
841 * Write dirty config/state files...
844 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
849 * If we are going to sleep and still have pending jobs, stop them after
850 * a period of time...
853 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
854 cupsArrayCount(PrintingJobs
) > 0)
857 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
859 #endif /* __APPLE__ */
863 * Update the network interfaces once a minute...
866 if ((current_time
- netif_time
) >= 60)
868 netif_time
= current_time
;
871 #endif /* !__APPLE__ */
873 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
875 * If no other work was scheduled and we're being controlled by launchd
876 * then timeout after 'LaunchdTimeout' seconds of inactivity...
879 if (!fds
&& service_idle_exit
)
881 cupsdLogMessage(CUPSD_LOG_INFO
,
882 "Printer sharing is off and there are no jobs pending, "
883 "will restart on demand.");
887 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
890 * Resume listening for new connections as needed...
893 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
894 cupsArrayCount(Clients
) < MaxClients
)
895 cupsdResumeListening();
898 * Expire subscriptions and unload completed jobs as needed...
901 if (current_time
> expire_time
)
903 if (cupsArrayCount(Subscriptions
) > 0)
904 cupsdExpireSubscriptions(NULL
, NULL
);
906 cupsdUnloadCompletedJobs();
908 expire_time
= current_time
;
911 #ifndef HAVE_AUTHORIZATION_H
913 * Update the root certificate once every 5 minutes if we have client
917 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
918 !RunUser
&& cupsArrayCount(Clients
))
921 * Update the root certificate...
925 cupsdAddCert(0, "root", cupsdDefaultAuthType());
927 #endif /* !HAVE_AUTHORIZATION_H */
930 * Check for new data on the client sockets...
933 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
935 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
938 * Process pending data in the input buffer...
941 if (httpGetReady(con
->http
))
943 cupsdReadClient(con
);
948 * Check the activity and close old clients...
951 activity
= current_time
- Timeout
;
952 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
954 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
956 cupsdCloseClient(con
);
962 * Update any pending multi-file documents...
965 if ((current_time
- senddoc_time
) >= 10)
968 senddoc_time
= current_time
;
972 * Clean job history...
975 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
979 * Log statistics at most once a minute when in debug mode...
982 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
984 size_t string_count
, /* String count */
985 alloc_bytes
, /* Allocated string bytes */
986 total_bytes
; /* Total string bytes */
988 struct mallinfo mem
; /* Malloc information */
992 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
993 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
994 mem
.usmblks
+ mem
.uordblks
);
995 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
996 mem
.fsmblks
+ mem
.fordblks
);
997 #endif /* HAVE_MALLINFO */
999 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1000 cupsArrayCount(Clients
));
1001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1002 cupsArrayCount(Jobs
));
1003 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1004 cupsArrayCount(ActiveJobs
));
1005 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1006 cupsArrayCount(Printers
));
1008 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1009 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1010 "Report: stringpool-string-count=" CUPS_LLFMT
,
1011 CUPS_LLCAST string_count
);
1012 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1013 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1014 CUPS_LLCAST alloc_bytes
);
1015 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1016 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1017 CUPS_LLCAST total_bytes
);
1019 report_time
= current_time
;
1023 * Handle OS-specific event notification for any events that have
1024 * accumulated. Don't send these more than once a second...
1027 if (LastEvent
&& (current_time
- event_time
) >= 1)
1029 #ifdef HAVE_NOTIFY_POST
1030 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1031 CUPSD_EVENT_PRINTER_DELETED
|
1032 CUPSD_EVENT_PRINTER_MODIFIED
))
1034 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1035 "notify_post(\"com.apple.printerListChange\")");
1036 notify_post("com.apple.printerListChange");
1039 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1041 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1042 "notify_post(\"com.apple.printerHistoryChange\")");
1043 notify_post("com.apple.printerHistoryChange");
1046 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1047 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1048 CUPSD_EVENT_JOB_PROGRESS
))
1050 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1051 "notify_post(\"com.apple.jobChange\")");
1052 notify_post("com.apple.jobChange");
1054 #endif /* HAVE_NOTIFY_POST */
1057 * Reset the accumulated events...
1060 LastEvent
= CUPSD_EVENT_NONE
;
1061 event_time
= current_time
;
1066 * Log a message based on what happened...
1071 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1072 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1073 "Scheduler shutting down normally.");
1077 cupsdLogMessage(CUPSD_LOG_ERROR
,
1078 "Scheduler shutting down due to program error.");
1079 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1080 "Scheduler shutting down due to program error.");
1084 * Close all network clients...
1091 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1093 * Update the keep-alive file as needed...
1098 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
1108 * Stop monitoring system event monitoring...
1112 cupsdStopSystemMonitor();
1113 #endif /* __APPLE__ */
1117 return (!stop_scheduler
);
1122 * 'cupsdAddString()' - Copy and add a string to an array.
1125 int /* O - 1 on success, 0 on failure */
1126 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1127 const char *s
) /* I - String to copy and add */
1130 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1131 (cups_ahash_func_t
)NULL
, 0,
1132 (cups_acopy_func_t
)_cupsStrAlloc
,
1133 (cups_afree_func_t
)_cupsStrFree
);
1135 return (cupsArrayAdd(*a
, (char *)s
));
1140 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1144 cupsdCheckProcess(void)
1147 * Flag that we have dead children...
1155 * 'cupsdClearString()' - Clear a string.
1159 cupsdClearString(char **s
) /* O - String value */
1170 * 'cupsdFreeStrings()' - Free an array of strings.
1174 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1178 cupsArrayDelete(*a
);
1185 * 'cupsdHoldSignals()' - Hold child and termination signals.
1189 cupsdHoldSignals(void)
1191 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1192 sigset_t newmask
; /* New POSIX signal mask */
1193 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1203 #elif defined(HAVE_SIGACTION)
1204 sigemptyset(&newmask
);
1205 sigaddset(&newmask
, SIGTERM
);
1206 sigaddset(&newmask
, SIGCHLD
);
1207 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1208 #endif /* HAVE_SIGSET */
1213 * 'cupsdReleaseSignals()' - Release signals for delivery.
1217 cupsdReleaseSignals(void)
1226 #elif defined(HAVE_SIGACTION)
1227 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1228 #endif /* HAVE_SIGSET */
1233 * 'cupsdSetString()' - Set a string value.
1237 cupsdSetString(char **s
, /* O - New string */
1238 const char *v
) /* I - String value */
1247 *s
= _cupsStrAlloc(v
);
1254 * 'cupsdSetStringf()' - Set a formatted string value.
1258 cupsdSetStringf(char **s
, /* O - New string */
1259 const char *f
, /* I - Printf-style format string */
1260 ...) /* I - Additional args as needed */
1262 char v
[65536 + 64]; /* Formatting string value */
1263 va_list ap
; /* Argument pointer */
1264 char *olds
; /* Old string */
1275 vsnprintf(v
, sizeof(v
), f
, ap
);
1278 *s
= _cupsStrAlloc(v
);
1289 * 'parent_handler()' - Catch USR1/CHLD signals...
1293 parent_handler(int sig
) /* I - Signal */
1296 * Store the signal we got from the OS and return...
1299 parent_signal
= sig
;
1304 * 'process_children()' - Process all dead children...
1308 process_children(void)
1310 int status
; /* Exit status of child */
1311 int pid
, /* Process ID of child */
1312 job_id
; /* Job ID of child */
1313 cupsd_job_t
*job
; /* Current job */
1314 int i
; /* Looping var */
1315 char name
[1024]; /* Process name */
1316 const char *type
; /* Type of program */
1319 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1322 * Reset the dead_children flag...
1328 * Collect the exit status of some children...
1332 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1333 #elif defined(HAVE_WAIT3)
1334 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1336 if ((pid
= wait(&status
)) > 0)
1337 #endif /* HAVE_WAITPID */
1340 * Collect the name of the process that finished...
1343 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1346 * Delete certificates for CGI processes...
1350 cupsdDeleteCert(pid
);
1353 * Handle completed job filters...
1357 job
= cupsdFindJob(job_id
);
1363 for (i
= 0; job
->filters
[i
]; i
++)
1364 if (job
->filters
[i
] == pid
)
1367 if (job
->filters
[i
] || job
->backend
== pid
)
1370 * OK, this process has gone away; what's left?
1373 if (job
->filters
[i
])
1375 job
->filters
[i
] = -pid
;
1380 job
->backend
= -pid
;
1384 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1388 * An error occurred; save the exit status so we know to stop
1389 * the printer or cancel the job when all of the filters finish...
1391 * A negative status indicates that the backend failed and the
1392 * printer needs to be stopped.
1394 * In order to preserve the most serious status, we always log
1395 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1396 * and SIGBUS) and prefer to log the backend exit status over a
1400 int old_status
= abs(job
->status
);
1402 if (WIFSIGNALED(status
) || /* This process crashed, or */
1403 !job
->status
|| /* No process had a status, or */
1404 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1405 { /* Backend and filter didn't crash */
1406 if (job
->filters
[i
])
1407 job
->status
= status
; /* Filter failed */
1409 job
->status
= -status
; /* Backend failed */
1412 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1413 job
->status_level
> CUPSD_LOG_ERROR
&&
1414 (job
->filters
[i
] || !WIFEXITED(status
)))
1416 char message
[1024]; /* New printer-state-message */
1419 job
->status_level
= CUPSD_LOG_ERROR
;
1421 snprintf(message
, sizeof(message
), "%s failed", type
);
1425 strlcpy(job
->printer
->state_message
, message
,
1426 sizeof(job
->printer
->state_message
));
1432 if (!job
->printer_message
&& job
->attrs
)
1434 if ((job
->printer_message
=
1435 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1436 IPP_TAG_TEXT
)) == NULL
)
1437 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1439 "job-printer-state-message",
1443 if (job
->printer_message
)
1444 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1450 * If this is not the last file in a job, see if all of the
1451 * filters are done, and if so move to the next file.
1454 if (job
->current_file
< job
->num_files
&& job
->printer
)
1456 for (i
= 0; job
->filters
[i
] < 0; i
++);
1458 if (!job
->filters
[i
] &&
1459 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1463 * Process the next file...
1466 cupsdContinueJob(job
);
1469 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1472 * Remove the job from the active list if there are no processes still
1476 for (i
= 0; job
->filters
[i
] < 0; i
++);
1478 if (!job
->filters
[i
] && job
->backend
<= 0)
1479 cupsArrayRemove(ActiveJobs
, job
);
1485 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1486 * since they come when we kill/end a process...
1489 if (status
== SIGTERM
|| status
== SIGKILL
)
1491 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1492 "PID %d (%s) was terminated normally with signal %d.", pid
,
1495 else if (status
== SIGPIPE
)
1497 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1498 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1503 if (WIFEXITED(status
))
1505 int code
= WEXITSTATUS(status
); /* Exit code */
1508 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1509 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1510 code
, strerror(code
- 100));
1512 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1513 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1516 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1517 pid
, name
, WTERMSIG(status
));
1519 if (LogLevel
< CUPSD_LOG_DEBUG
)
1520 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1521 "Hint: Try setting the LogLevel to \"debug\" to find out "
1525 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1530 * If wait*() is interrupted by a signal, tell main() to call us again...
1533 if (pid
< 0 && errno
== EINTR
)
1539 * 'select_timeout()' - Calculate the select timeout value.
1543 static long /* O - Number of seconds */
1544 select_timeout(int fds
) /* I - Number of descriptors returned */
1546 long timeout
; /* Timeout for select */
1547 time_t now
; /* Current time */
1548 cupsd_client_t
*con
; /* Client information */
1549 cupsd_job_t
*job
; /* Job information */
1550 cupsd_subscription_t
*sub
; /* Subscription information */
1551 const char *why
; /* Debugging aid */
1554 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1555 (long)JobHistoryUpdate
);
1558 * Check to see if any of the clients have pending data to be
1559 * processed; if so, the timeout should be 0...
1562 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1564 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1565 if (httpGetReady(con
->http
))
1569 * If select has been active in the last second (fds > 0) or we have
1570 * many resources in use then don't bother trying to optimize the
1571 * timeout, just make it 1 second.
1574 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1578 * Otherwise, check all of the possible events that we need to wake for...
1582 timeout
= now
+ 86400; /* 86400 == 1 day */
1587 * When going to sleep, wake up to cancel jobs that don't complete in time.
1590 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1592 timeout
= SleepJobs
;
1593 why
= "cancel jobs before sleeping";
1595 #endif /* __APPLE__ */
1598 * Check whether we are accepting new connections...
1601 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1602 ListeningPaused
< timeout
)
1604 if (ListeningPaused
<= now
)
1607 timeout
= ListeningPaused
;
1609 why
= "resume listening";
1613 * Check the activity and close old clients...
1616 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1618 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1619 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1621 timeout
= httpGetActivity(con
->http
) + Timeout
;
1622 why
= "timeout a client connection";
1626 * Write out changes to configuration and state files...
1629 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1631 timeout
= DirtyCleanTime
;
1632 why
= "write dirty config/state files";
1636 * Check for any job activity...
1639 if (JobHistoryUpdate
&& timeout
> JobHistoryUpdate
)
1641 timeout
= JobHistoryUpdate
;
1642 why
= "update job history";
1645 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1647 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1649 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1651 timeout
= job
->cancel_time
;
1652 why
= "cancel stuck jobs";
1655 if (job
->kill_time
&& job
->kill_time
< timeout
)
1657 timeout
= job
->kill_time
;
1658 why
= "kill unresponsive jobs";
1661 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1663 timeout
= job
->hold_until
;
1664 why
= "release held jobs";
1667 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1670 why
= "start pending jobs";
1675 #ifdef HAVE_MALLINFO
1677 * Log memory usage every minute...
1680 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1682 timeout
= mallinfo_time
+ 60;
1683 why
= "display memory usage";
1685 #endif /* HAVE_MALLINFO */
1688 * Expire subscriptions as needed...
1691 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1693 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1694 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1696 timeout
= sub
->expire
;
1697 why
= "expire subscription";
1701 * Adjust from absolute to relative time. We add 1 second to the timeout since
1702 * events occur after the timeout expires, and limit the timeout to 86400
1703 * seconds (1 day) to avoid select() timeout limits present on some operating
1707 timeout
= timeout
- now
+ 1;
1711 else if (timeout
> 86400)
1715 * Log and return the timeout value...
1718 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1726 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1730 sigchld_handler(int sig
) /* I - Signal number */
1735 * Flag that we have dead children...
1741 * Reset the signal handler as needed...
1744 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1745 signal(SIGCLD
, sigchld_handler
);
1746 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1751 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1755 sighup_handler(int sig
) /* I - Signal number */
1759 NeedReload
= RELOAD_ALL
;
1760 ReloadTime
= time(NULL
);
1762 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1763 signal(SIGHUP
, sighup_handler
);
1764 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1769 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1773 sigterm_handler(int sig
) /* I - Signal number */
1775 (void)sig
; /* remove compiler warnings... */
1778 * Flag that we should stop and return...
1785 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1787 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1791 service_checkin(void)
1793 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
1794 int error
; /* Check-in error, if any */
1795 size_t i
, /* Looping var */
1796 count
; /* Number of listeners */
1797 int *ld_sockets
; /* Listener sockets */
1798 cupsd_listener_t
*lis
; /* Listeners array */
1799 http_addr_t addr
; /* Address variable */
1800 socklen_t addrlen
; /* Length of address */
1801 char s
[256]; /* String addresss */
1804 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1807 * Check-in with launchd...
1810 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1812 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1814 return; /* anti-compiler-warning */
1818 * Try to match the launchd sockets to the cupsd listeners...
1821 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1823 for (i
= 0; i
< count
; i
++)
1826 * Get the launchd socket address...
1829 addrlen
= sizeof(addr
);
1831 if (getsockname(ld_sockets
[i
], (struct sockaddr
*)&addr
, &addrlen
))
1833 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1837 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, ld_sockets
[i
], httpAddrString(&addr
, s
, sizeof(s
)));
1839 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1841 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1842 if (httpAddrEqual(&lis
->address
, &addr
))
1846 * Add a new listener if there's no match...
1851 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1855 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1857 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1859 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
1863 cupsArrayAdd(Listeners
, lis
);
1865 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1868 lis
->fd
= ld_sockets
[i
];
1872 if (httpAddrPort(&(lis
->address
)) == 443)
1873 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1874 # endif /* HAVE_SSL */
1879 # elif defined(HAVE_LAUNCHD)
1880 size_t i
, /* Looping var */
1881 count
; /* Number of listeners */
1882 launch_data_t ld_msg
, /* Launch data message */
1883 ld_resp
, /* Launch data response */
1884 ld_array
, /* Launch data array */
1885 ld_sockets
, /* Launch data sockets dictionary */
1886 tmp
; /* Launch data */
1887 cupsd_listener_t
*lis
; /* Listeners array */
1888 http_addr_t addr
; /* Address variable */
1889 socklen_t addrlen
; /* Length of address */
1890 int fd
; /* File descriptor */
1891 char s
[256]; /* String addresss */
1894 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1897 * Check-in with launchd...
1900 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1901 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1903 cupsdLogMessage(CUPSD_LOG_ERROR
,
1904 "service_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1907 return; /* anti-compiler-warning */
1910 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1912 errno
= launch_data_get_errno(ld_resp
);
1913 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Check-in failed: %s",
1916 return; /* anti-compiler-warning */
1920 * Get the sockets dictionary...
1923 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1926 cupsdLogMessage(CUPSD_LOG_ERROR
,
1927 "service_checkin: No sockets found to answer requests on.");
1929 return; /* anti-compiler-warning */
1933 * Get the array of listener sockets...
1936 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1938 cupsdLogMessage(CUPSD_LOG_ERROR
,
1939 "service_checkin: No sockets found to answer requests on.");
1941 return; /* anti-compiler-warning */
1945 * Add listening fd(s) to the Listener array...
1948 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1950 count
= launch_data_array_get_count(ld_array
);
1952 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1954 for (i
= 0; i
< count
; i
++)
1957 * Get the launchd file descriptor and address...
1960 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1962 fd
= launch_data_get_fd(tmp
);
1963 addrlen
= sizeof(addr
);
1965 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1967 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1971 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
1974 * Try to match the launchd socket address to one of the listeners...
1977 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1979 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1980 if (httpAddrEqual(&lis
->address
, &addr
))
1984 * Add a new listener If there's no match...
1989 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1993 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1995 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1997 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s.", strerror(errno
));
2001 cupsArrayAdd(Listeners
, lis
);
2003 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2010 if (httpAddrPort(&(lis
->address
)) == 443)
2011 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2012 # endif /* HAVE_SSL */
2017 launch_data_free(ld_msg
);
2018 launch_data_free(ld_resp
);
2020 # else /* HAVE_SYSTEMD */
2021 int i
, /* Looping var */
2022 count
; /* Number of listeners */
2023 cupsd_listener_t
*lis
; /* Listeners array */
2024 http_addr_t addr
; /* Address variable */
2025 socklen_t addrlen
; /* Length of address */
2026 char s
[256]; /* String addresss */
2029 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
2032 * Check-in with systemd...
2035 if ((count
= sd_listen_fds(0)) < 0)
2037 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
2039 return; /* anti-compiler-warning */
2043 * Try to match the systemd sockets to the cupsd listeners...
2046 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
2048 for (i
= 0; i
< count
; i
++)
2051 * Get the launchd socket address...
2054 addrlen
= sizeof(addr
);
2056 if (getsockname(SD_LISTEN_FDS_START
+ i
, (struct sockaddr
*)&addr
, &addrlen
))
2058 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2062 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
)));
2064 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2066 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2067 if (httpAddrEqual(&lis
->address
, &addr
))
2071 * Add a new listener if there's no match...
2076 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2080 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2082 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2084 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
2088 cupsArrayAdd(Listeners
, lis
);
2090 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2093 lis
->fd
= SD_LISTEN_FDS_START
+ i
;
2097 if (httpAddrPort(&(lis
->address
)) == 443)
2098 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2099 # endif /* HAVE_SSL */
2101 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
2106 * 'service_checkout()' - Update the CUPS_KEEPALIVE file as needed.
2110 service_checkout(void)
2112 int fd
; /* File descriptor */
2116 * Create or remove the systemd path file based on whether there are active
2117 * jobs or shared printers to advertise...
2120 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2121 # ifdef HAVE_SYSTEMD
2122 WebInterface
|| /* Web interface enabled */
2123 # endif /* HAVE_SYSTEMD */
2124 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
2125 /* Printers being shared */
2127 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating keep-alive file \"" CUPS_KEEPALIVE
"\".");
2129 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
2134 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing keep-alive file \"" CUPS_KEEPALIVE
"\".");
2136 unlink(CUPS_KEEPALIVE
);
2139 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
2143 * 'usage()' - Show scheduler usage.
2147 usage(int status
) /* O - Exit status */
2149 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2152 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2153 _cupsLangPuts(fp
, _("Options:"));
2154 _cupsLangPuts(fp
, _(" -c cupsd.conf Set cupsd.conf file to use."));
2155 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2156 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
2157 "detach from console."));
2158 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2159 _cupsLangPuts(fp
, _(" -l Run cupsd on demand."));
2160 _cupsLangPuts(fp
, _(" -t Test the configuration "