2 * "$Id: main.c 12248 2014-11-12 16:32:57Z msweet $"
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 close_all
= 1, /* Close all file descriptors? */
104 disconnect
= 1, /* Disconnect from controlling terminal? */
105 fg
= 0, /* Run in foreground? */
107 /* Running as child process? */
108 int fds
; /* Number of ready descriptors */
109 cupsd_client_t
*con
; /* Current client */
110 cupsd_job_t
*job
; /* Current job */
111 cupsd_listener_t
*lis
; /* Current listener */
112 time_t current_time
, /* Current time */
113 activity
, /* Client activity timer */
114 senddoc_time
, /* Send-Document time */
115 expire_time
, /* Subscription expire time */
116 report_time
, /* Malloc/client/job report time */
117 event_time
; /* Last event notification time */
118 long timeout
; /* Timeout for cupsdDoSelect() */
119 struct rlimit limit
; /* Runtime limit */
120 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
121 struct sigaction action
; /* Actions for POSIX signals */
122 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
124 int use_sysman
= 1; /* Use system management functions? */
126 time_t netif_time
= 0; /* Time since last network update */
127 #endif /* __APPLE__ */
128 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
129 int service_idle_exit
;
130 /* Idle exit on select timeout? */
131 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
136 * Check for setuid invocation, which we do not support!
139 if (getuid() != geteuid())
141 fputs("cupsd: Cannot run as a setuid program.\n", stderr
);
144 #endif /* HAVE_GETEUID */
147 * Check for command-line arguments...
153 if (getenv("CUPSD_LAUNCHD"))
160 #endif /* HAVE_LAUNCHD */
162 for (i
= 1; i
< argc
; i
++)
163 if (argv
[i
][0] == '-')
164 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
167 case 'C' : /* Run as child with config file */
172 case 'c' : /* Configuration file */
176 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
177 "after \"-c\" option."));
181 if (argv
[i
][0] == '/')
184 * Absolute directory...
187 cupsdSetString(&ConfigurationFile
, argv
[i
]);
192 * Relative directory...
195 char *current
; /* Current directory */
198 * Allocate a buffer for the current working directory to
199 * reduce run-time stack usage; this approximates the
200 * behavior of some implementations of getcwd() when they
201 * are passed a NULL pointer.
204 if ((current
= malloc(1024)) == NULL
)
206 _cupsLangPuts(stderr
,
207 _("cupsd: Unable to get current directory."));
211 if (!getcwd(current
, 1024))
213 _cupsLangPuts(stderr
,
214 _("cupsd: Unable to get current directory."));
219 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
224 case 'f' : /* Run in foreground... */
230 case 'F' : /* Run in foreground, but disconnect from terminal... */
235 case 'h' : /* Show usage/help */
239 case 'l' : /* Started by launchd/systemd... */
240 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
246 _cupsLangPuts(stderr
, _("cupsd: On-demand support not compiled "
247 "in, running in normal mode."));
251 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
254 case 'p' : /* Stop immediately for profiling */
255 fputs("cupsd: -p (startup profiling) is for internal testing "
256 "use only!\n", stderr
);
263 case 'P' : /* Disable security profiles */
264 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr
);
268 case 's' : /* Set cups-files.conf location */
272 _cupsLangPuts(stderr
, _("cupsd: Expected cups-files.conf "
273 "filename after \"-s\" option."));
277 if (argv
[i
][0] != '/')
280 * Relative filename not allowed...
283 _cupsLangPuts(stderr
, _("cupsd: Relative cups-files.conf "
284 "filename not allowed."));
288 cupsdSetString(&CupsFilesFile
, argv
[i
]);
292 case 'S' : /* Disable system management functions */
293 fputs("cupsd: -S (disable system management) for internal "
294 "testing use only!\n", stderr
);
297 #endif /* __APPLE__ */
299 case 't' : /* Test the cupsd.conf file... */
306 default : /* Unknown option */
307 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
314 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
319 if (!ConfigurationFile
)
320 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
324 char *filename
, /* Copy of cupsd.conf filename */
325 *slash
; /* Final slash in cupsd.conf filename */
326 size_t len
; /* Size of buffer */
328 len
= strlen(ConfigurationFile
) + 15;
329 if ((filename
= malloc(len
)) == NULL
)
331 _cupsLangPrintf(stderr
,
332 _("cupsd: Unable to get path to "
333 "cups-files.conf file."));
337 strlcpy(filename
, ConfigurationFile
, len
);
338 if ((slash
= strrchr(filename
, '/')) == NULL
)
340 _cupsLangPrintf(stderr
,
341 _("cupsd: Unable to get path to "
342 "cups-files.conf file."));
346 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
347 cupsdSetString(&CupsFilesFile
, filename
);
354 * Make sure we aren't tying up any filesystems...
360 * Disconnect from the controlling terminal...
369 * Close all open files...
372 getrlimit(RLIMIT_NOFILE
, &limit
);
374 for (i
= 0; i
< (int)limit
.rlim_cur
&& i
< 1024; i
++)
378 * Redirect stdin/out/err to /dev/null...
381 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
387 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
393 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
401 * Run in the background as needed...
407 * Setup signal handlers for the parent...
410 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
411 sigset(SIGUSR1
, parent_handler
);
412 sigset(SIGCHLD
, parent_handler
);
414 sigset(SIGHUP
, SIG_IGN
);
415 #elif defined(HAVE_SIGACTION)
416 memset(&action
, 0, sizeof(action
));
417 sigemptyset(&action
.sa_mask
);
418 sigaddset(&action
.sa_mask
, SIGUSR1
);
419 action
.sa_handler
= parent_handler
;
420 sigaction(SIGUSR1
, &action
, NULL
);
421 sigaction(SIGCHLD
, &action
, NULL
);
423 sigemptyset(&action
.sa_mask
);
424 action
.sa_handler
= SIG_IGN
;
425 sigaction(SIGHUP
, &action
, NULL
);
427 signal(SIGUSR1
, parent_handler
);
428 signal(SIGCLD
, parent_handler
);
430 signal(SIGHUP
, SIG_IGN
);
431 #endif /* HAVE_SIGSET */
436 * OK, wait for the child to startup and send us SIGUSR1 or to crash
437 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
438 * might be sent by the init script to restart the scheduler...
441 for (; parent_signal
== 0;)
444 if (parent_signal
== SIGUSR1
)
452 else if (WIFEXITED(i
))
454 fprintf(stderr
, "cupsd: Child exited with status %d\n",
460 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
465 #if defined(__OpenBSD__) && OpenBSD < 201211
467 * Call _thread_sys_closefrom() so the child process doesn't reset the
468 * parent's file descriptors to be blocking. This is a workaround for a
469 * limitation of userland libpthread on older versions of OpenBSD.
472 _thread_sys_closefrom(0);
473 #endif /* __OpenBSD__ && OpenBSD < 201211 */
476 * Since many system libraries create fork-unsafe data on execution of a
477 * program, we need to re-execute the background cupsd with the "-C" and "-s"
478 * options to avoid problems. Unfortunately, we also have to assume that
479 * argv[0] contains the name of the cupsd executable - there is no portable
480 * way to get the real pathname...
483 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, "-s", CupsFilesFile
, (char *)0);
488 * Set the timezone info...
494 setlocale(LC_TIME
, "");
497 #ifdef HAVE_DBUS_THREADS_INIT
499 * Enable threading support for D-BUS...
502 dbus_threads_init_default();
503 #endif /* HAVE_DBUS_THREADS_INIT */
506 * Set the maximum number of files...
509 getrlimit(RLIMIT_NOFILE
, &limit
);
511 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
512 if (limit
.rlim_max
> FD_SETSIZE
)
515 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
517 if (limit
.rlim_max
== RLIM_INFINITY
)
520 #endif /* RLIM_INFINITY */
521 MaxFDs
= limit
.rlim_max
;
523 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
525 setrlimit(RLIMIT_NOFILE
, &limit
);
530 * Read configuration...
533 if (!cupsdReadConfiguration())
535 else if (TestConfigFile
)
537 printf("\"%s\" is OK.\n", CupsFilesFile
);
538 printf("\"%s\" is OK.\n", ConfigurationFile
);
543 * Clean out old temp files and printer cache data.
546 if (!strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
547 cupsdCleanFiles(TempDir
, NULL
);
549 cupsdCleanFiles(CacheDir
, "*.ipp");
551 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
555 * If we were started on demand by launchd or systemd get the listen sockets
556 * file descriptors...
562 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
565 * Startup the server...
573 * Catch hangup and child signals and ignore broken pipes...
576 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
577 sigset(SIGCHLD
, sigchld_handler
);
578 sigset(SIGHUP
, sighup_handler
);
579 sigset(SIGPIPE
, SIG_IGN
);
580 sigset(SIGTERM
, sigterm_handler
);
581 #elif defined(HAVE_SIGACTION)
582 memset(&action
, 0, sizeof(action
));
584 sigemptyset(&action
.sa_mask
);
585 sigaddset(&action
.sa_mask
, SIGTERM
);
586 sigaddset(&action
.sa_mask
, SIGCHLD
);
587 action
.sa_handler
= sigchld_handler
;
588 sigaction(SIGCHLD
, &action
, NULL
);
590 sigemptyset(&action
.sa_mask
);
591 sigaddset(&action
.sa_mask
, SIGHUP
);
592 action
.sa_handler
= sighup_handler
;
593 sigaction(SIGHUP
, &action
, NULL
);
595 sigemptyset(&action
.sa_mask
);
596 action
.sa_handler
= SIG_IGN
;
597 sigaction(SIGPIPE
, &action
, NULL
);
599 sigemptyset(&action
.sa_mask
);
600 sigaddset(&action
.sa_mask
, SIGTERM
);
601 sigaddset(&action
.sa_mask
, SIGCHLD
);
602 action
.sa_handler
= sigterm_handler
;
603 sigaction(SIGTERM
, &action
, NULL
);
605 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
606 signal(SIGHUP
, sighup_handler
);
607 signal(SIGPIPE
, SIG_IGN
);
608 signal(SIGTERM
, sigterm_handler
);
609 #endif /* HAVE_SIGSET */
612 * Initialize authentication certificates...
618 * If we are running in the background, signal the parent process that
619 * we are up and running...
622 if (!fg
|| run_as_child
)
625 * Send a signal to the parent process, but only if the parent is
626 * not PID 1 (init). This avoids accidentally shutting down the
627 * system on OpenBSD if you CTRL-C the server before it is up...
630 i
= getppid(); /* Save parent PID to avoid race condition */
638 * Start power management framework...
642 cupsdStartSystemMonitor();
643 #endif /* __APPLE__ */
646 * Send server-started event...
649 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
651 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
653 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
655 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
657 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
660 * Start any pending print jobs...
669 current_time
= time(NULL
);
670 event_time
= current_time
;
671 expire_time
= current_time
;
674 senddoc_time
= current_time
;
676 while (!stop_scheduler
)
679 * Check if there are dead children to handle...
686 * Check if we need to load the server configuration file...
692 * Close any idle clients...
695 if (cupsArrayCount(Clients
) > 0)
697 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
699 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
700 if (httpGetState(con
->http
) == HTTP_WAITING
)
701 cupsdCloseClient(con
);
703 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
705 cupsdPauseListening();
709 * Restart if all clients are closed and all jobs finished, or
710 * if the reload timeout has elapsed...
713 if ((cupsArrayCount(Clients
) == 0 &&
714 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
715 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
718 * Shutdown the server...
726 * Read configuration...
729 if (!cupsdReadConfiguration())
731 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting!",
737 * Startup the server...
745 * Send a server-restarted event...
748 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
749 "Scheduler restarted.");
754 * Check for available input or ready output. If cupsdDoSelect()
755 * returns 0 or -1, something bad happened and we should exit
758 * Note that we at least have one listening socket open at all
762 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
765 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
767 * If no other work is scheduled and we're being controlled by
768 * launchd then timeout after 'LaunchdTimeout' seconds of
772 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
773 !cupsArrayCount(ActiveJobs
) &&
776 # endif /* HAVE_SYSTEMD */
777 (!Browsing
|| !BrowseLocalProtocols
|| !cupsArrayCount(Printers
)))
779 timeout
= IdleExitTimeout
;
780 service_idle_exit
= 1;
783 service_idle_exit
= 0;
784 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
786 if ((fds
= cupsdDoSelect(timeout
)) < 0)
789 * Got an error from select!
792 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
793 cupsd_printer_t
*p
; /* Current printer */
794 #endif /* HAVE_DNSSD || HAVE_AVAHI */
797 if (errno
== EINTR
) /* Just interrupted by a signal */
801 * Log all sorts of debug info to help track down the problem.
804 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
807 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
809 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
810 cupsdLogMessage(CUPSD_LOG_EMERG
,
811 "Clients[%d] = %d, file = %d, state = %d",
812 i
, con
->number
, con
->file
, httpGetState(con
->http
));
814 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
816 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
817 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
819 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
822 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
824 #endif /* __APPLE__ */
826 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
828 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
829 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
831 job
->status_buffer
? job
->status_buffer
->fd
: -1,
832 job
->print_pipes
[0], job
->print_pipes
[1],
833 job
->back_pipes
[0], job
->back_pipes
[1]);
835 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
836 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
838 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
839 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
840 p
->reg_name
? p
->reg_name
: "(null)");
841 #endif /* HAVE_DNSSD || HAVE_AVAHI */
846 current_time
= time(NULL
);
849 * Write dirty config/state files...
852 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
857 * If we are going to sleep and still have pending jobs, stop them after
858 * a period of time...
861 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
862 cupsArrayCount(PrintingJobs
) > 0)
865 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
867 #endif /* __APPLE__ */
871 * Update the network interfaces once a minute...
874 if ((current_time
- netif_time
) >= 60)
876 netif_time
= current_time
;
879 #endif /* !__APPLE__ */
881 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
883 * If no other work was scheduled and we're being controlled by launchd
884 * then timeout after 'LaunchdTimeout' seconds of inactivity...
887 if (!fds
&& service_idle_exit
)
889 cupsdLogMessage(CUPSD_LOG_INFO
,
890 "Printer sharing is off and there are no jobs pending, "
891 "will restart on demand.");
895 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
898 * Resume listening for new connections as needed...
901 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
902 cupsArrayCount(Clients
) < MaxClients
)
903 cupsdResumeListening();
906 * Expire subscriptions and unload completed jobs as needed...
909 if (current_time
> expire_time
)
911 if (cupsArrayCount(Subscriptions
) > 0)
912 cupsdExpireSubscriptions(NULL
, NULL
);
914 cupsdUnloadCompletedJobs();
916 expire_time
= current_time
;
919 #ifndef HAVE_AUTHORIZATION_H
921 * Update the root certificate once every 5 minutes if we have client
925 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
926 !RunUser
&& cupsArrayCount(Clients
))
929 * Update the root certificate...
933 cupsdAddCert(0, "root", cupsdDefaultAuthType());
935 #endif /* !HAVE_AUTHORIZATION_H */
938 * Check for new data on the client sockets...
941 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
943 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
946 * Process pending data in the input buffer...
949 if (httpGetReady(con
->http
))
951 cupsdReadClient(con
);
956 * Check the activity and close old clients...
959 activity
= current_time
- Timeout
;
960 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
962 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
964 cupsdCloseClient(con
);
970 * Update any pending multi-file documents...
973 if ((current_time
- senddoc_time
) >= 10)
976 senddoc_time
= current_time
;
980 * Clean job history...
983 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
987 * Log statistics at most once a minute when in debug mode...
990 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
992 size_t string_count
, /* String count */
993 alloc_bytes
, /* Allocated string bytes */
994 total_bytes
; /* Total string bytes */
996 struct mallinfo mem
; /* Malloc information */
1000 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1002 mem
.usmblks
+ mem
.uordblks
);
1003 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1004 mem
.fsmblks
+ mem
.fordblks
);
1005 #endif /* HAVE_MALLINFO */
1007 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1008 cupsArrayCount(Clients
));
1009 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1010 cupsArrayCount(Jobs
));
1011 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1012 cupsArrayCount(ActiveJobs
));
1013 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1014 cupsArrayCount(Printers
));
1016 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1017 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1018 "Report: stringpool-string-count=" CUPS_LLFMT
,
1019 CUPS_LLCAST string_count
);
1020 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1021 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1022 CUPS_LLCAST alloc_bytes
);
1023 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1024 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1025 CUPS_LLCAST total_bytes
);
1027 report_time
= current_time
;
1031 * Handle OS-specific event notification for any events that have
1032 * accumulated. Don't send these more than once a second...
1035 if (LastEvent
&& (current_time
- event_time
) >= 1)
1037 #ifdef HAVE_NOTIFY_POST
1038 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1039 CUPSD_EVENT_PRINTER_DELETED
|
1040 CUPSD_EVENT_PRINTER_MODIFIED
))
1042 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1043 "notify_post(\"com.apple.printerListChange\")");
1044 notify_post("com.apple.printerListChange");
1047 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1049 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1050 "notify_post(\"com.apple.printerHistoryChange\")");
1051 notify_post("com.apple.printerHistoryChange");
1054 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1055 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1056 CUPSD_EVENT_JOB_PROGRESS
))
1058 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1059 "notify_post(\"com.apple.jobChange\")");
1060 notify_post("com.apple.jobChange");
1062 #endif /* HAVE_NOTIFY_POST */
1065 * Reset the accumulated events...
1068 LastEvent
= CUPSD_EVENT_NONE
;
1069 event_time
= current_time
;
1074 * Log a message based on what happened...
1079 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1080 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1081 "Scheduler shutting down normally.");
1085 cupsdLogMessage(CUPSD_LOG_ERROR
,
1086 "Scheduler shutting down due to program error.");
1087 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1088 "Scheduler shutting down due to program error.");
1092 * Close all network clients...
1099 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1101 * Update the keep-alive file as needed...
1106 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
1116 * Stop monitoring system event monitoring...
1120 cupsdStopSystemMonitor();
1121 #endif /* __APPLE__ */
1125 return (!stop_scheduler
);
1130 * 'cupsdAddString()' - Copy and add a string to an array.
1133 int /* O - 1 on success, 0 on failure */
1134 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1135 const char *s
) /* I - String to copy and add */
1138 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1139 (cups_ahash_func_t
)NULL
, 0,
1140 (cups_acopy_func_t
)_cupsStrAlloc
,
1141 (cups_afree_func_t
)_cupsStrFree
);
1143 return (cupsArrayAdd(*a
, (char *)s
));
1148 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1152 cupsdCheckProcess(void)
1155 * Flag that we have dead children...
1163 * 'cupsdClearString()' - Clear a string.
1167 cupsdClearString(char **s
) /* O - String value */
1178 * 'cupsdFreeStrings()' - Free an array of strings.
1182 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1186 cupsArrayDelete(*a
);
1193 * 'cupsdHoldSignals()' - Hold child and termination signals.
1197 cupsdHoldSignals(void)
1199 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1200 sigset_t newmask
; /* New POSIX signal mask */
1201 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1211 #elif defined(HAVE_SIGACTION)
1212 sigemptyset(&newmask
);
1213 sigaddset(&newmask
, SIGTERM
);
1214 sigaddset(&newmask
, SIGCHLD
);
1215 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1216 #endif /* HAVE_SIGSET */
1221 * 'cupsdReleaseSignals()' - Release signals for delivery.
1225 cupsdReleaseSignals(void)
1234 #elif defined(HAVE_SIGACTION)
1235 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1236 #endif /* HAVE_SIGSET */
1241 * 'cupsdSetString()' - Set a string value.
1245 cupsdSetString(char **s
, /* O - New string */
1246 const char *v
) /* I - String value */
1255 *s
= _cupsStrAlloc(v
);
1262 * 'cupsdSetStringf()' - Set a formatted string value.
1266 cupsdSetStringf(char **s
, /* O - New string */
1267 const char *f
, /* I - Printf-style format string */
1268 ...) /* I - Additional args as needed */
1270 char v
[65536 + 64]; /* Formatting string value */
1271 va_list ap
; /* Argument pointer */
1272 char *olds
; /* Old string */
1283 vsnprintf(v
, sizeof(v
), f
, ap
);
1286 *s
= _cupsStrAlloc(v
);
1297 * 'parent_handler()' - Catch USR1/CHLD signals...
1301 parent_handler(int sig
) /* I - Signal */
1304 * Store the signal we got from the OS and return...
1307 parent_signal
= sig
;
1312 * 'process_children()' - Process all dead children...
1316 process_children(void)
1318 int status
; /* Exit status of child */
1319 int pid
, /* Process ID of child */
1320 job_id
; /* Job ID of child */
1321 cupsd_job_t
*job
; /* Current job */
1322 int i
; /* Looping var */
1323 char name
[1024]; /* Process name */
1324 const char *type
; /* Type of program */
1327 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1330 * Reset the dead_children flag...
1336 * Collect the exit status of some children...
1340 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1341 #elif defined(HAVE_WAIT3)
1342 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1344 if ((pid
= wait(&status
)) > 0)
1345 #endif /* HAVE_WAITPID */
1348 * Collect the name of the process that finished...
1351 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1354 * Delete certificates for CGI processes...
1358 cupsdDeleteCert(pid
);
1361 * Handle completed job filters...
1365 job
= cupsdFindJob(job_id
);
1371 for (i
= 0; job
->filters
[i
]; i
++)
1372 if (job
->filters
[i
] == pid
)
1375 if (job
->filters
[i
] || job
->backend
== pid
)
1378 * OK, this process has gone away; what's left?
1381 if (job
->filters
[i
])
1383 job
->filters
[i
] = -pid
;
1388 job
->backend
= -pid
;
1392 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1396 * An error occurred; save the exit status so we know to stop
1397 * the printer or cancel the job when all of the filters finish...
1399 * A negative status indicates that the backend failed and the
1400 * printer needs to be stopped.
1402 * In order to preserve the most serious status, we always log
1403 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1404 * and SIGBUS) and prefer to log the backend exit status over a
1408 int old_status
= abs(job
->status
);
1410 if (WIFSIGNALED(status
) || /* This process crashed, or */
1411 !job
->status
|| /* No process had a status, or */
1412 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1413 { /* Backend and filter didn't crash */
1414 if (job
->filters
[i
])
1415 job
->status
= status
; /* Filter failed */
1417 job
->status
= -status
; /* Backend failed */
1420 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1421 job
->status_level
> CUPSD_LOG_ERROR
&&
1422 (job
->filters
[i
] || !WIFEXITED(status
)))
1424 char message
[1024]; /* New printer-state-message */
1427 job
->status_level
= CUPSD_LOG_ERROR
;
1429 snprintf(message
, sizeof(message
), "%s failed", type
);
1433 strlcpy(job
->printer
->state_message
, message
,
1434 sizeof(job
->printer
->state_message
));
1440 if (!job
->printer_message
&& job
->attrs
)
1442 if ((job
->printer_message
=
1443 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1444 IPP_TAG_TEXT
)) == NULL
)
1445 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1447 "job-printer-state-message",
1451 if (job
->printer_message
)
1452 cupsdSetString(&(job
->printer_message
->values
[0].string
.text
),
1458 * If this is not the last file in a job, see if all of the
1459 * filters are done, and if so move to the next file.
1462 if (job
->current_file
< job
->num_files
&& job
->printer
)
1464 for (i
= 0; job
->filters
[i
] < 0; i
++);
1466 if (!job
->filters
[i
] &&
1467 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1471 * Process the next file...
1474 cupsdContinueJob(job
);
1477 else if (job
->state_value
>= IPP_JOB_CANCELED
)
1480 * Remove the job from the active list if there are no processes still
1484 for (i
= 0; job
->filters
[i
] < 0; i
++);
1486 if (!job
->filters
[i
] && job
->backend
<= 0)
1487 cupsArrayRemove(ActiveJobs
, job
);
1493 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1494 * since they come when we kill/end a process...
1497 if (status
== SIGTERM
|| status
== SIGKILL
)
1499 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1500 "PID %d (%s) was terminated normally with signal %d.", pid
,
1503 else if (status
== SIGPIPE
)
1505 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1506 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1511 if (WIFEXITED(status
))
1513 int code
= WEXITSTATUS(status
); /* Exit code */
1516 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1517 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1518 code
, strerror(code
- 100));
1520 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1521 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1524 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1525 pid
, name
, WTERMSIG(status
));
1527 if (LogLevel
< CUPSD_LOG_DEBUG
)
1528 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1529 "Hint: Try setting the LogLevel to \"debug\" to find out "
1533 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1538 * If wait*() is interrupted by a signal, tell main() to call us again...
1541 if (pid
< 0 && errno
== EINTR
)
1547 * 'select_timeout()' - Calculate the select timeout value.
1551 static long /* O - Number of seconds */
1552 select_timeout(int fds
) /* I - Number of descriptors returned */
1554 long timeout
; /* Timeout for select */
1555 time_t now
; /* Current time */
1556 cupsd_client_t
*con
; /* Client information */
1557 cupsd_job_t
*job
; /* Job information */
1558 cupsd_subscription_t
*sub
; /* Subscription information */
1559 const char *why
; /* Debugging aid */
1562 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1563 (long)JobHistoryUpdate
);
1566 * Check to see if any of the clients have pending data to be
1567 * processed; if so, the timeout should be 0...
1570 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1572 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1573 if (httpGetReady(con
->http
))
1577 * If select has been active in the last second (fds > 0) or we have
1578 * many resources in use then don't bother trying to optimize the
1579 * timeout, just make it 1 second.
1582 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1586 * Otherwise, check all of the possible events that we need to wake for...
1590 timeout
= now
+ 86400; /* 86400 == 1 day */
1595 * When going to sleep, wake up to cancel jobs that don't complete in time.
1598 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1600 timeout
= SleepJobs
;
1601 why
= "cancel jobs before sleeping";
1603 #endif /* __APPLE__ */
1606 * Check whether we are accepting new connections...
1609 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1610 ListeningPaused
< timeout
)
1612 if (ListeningPaused
<= now
)
1615 timeout
= ListeningPaused
;
1617 why
= "resume listening";
1621 * Check the activity and close old clients...
1624 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1626 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1627 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1629 timeout
= httpGetActivity(con
->http
) + Timeout
;
1630 why
= "timeout a client connection";
1634 * Write out changes to configuration and state files...
1637 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1639 timeout
= DirtyCleanTime
;
1640 why
= "write dirty config/state files";
1644 * Check for any job activity...
1647 if (JobHistoryUpdate
&& timeout
> JobHistoryUpdate
)
1649 timeout
= JobHistoryUpdate
;
1650 why
= "update job history";
1653 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1655 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1657 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1659 timeout
= job
->cancel_time
;
1660 why
= "cancel stuck jobs";
1663 if (job
->kill_time
&& job
->kill_time
< timeout
)
1665 timeout
= job
->kill_time
;
1666 why
= "kill unresponsive jobs";
1669 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1671 timeout
= job
->hold_until
;
1672 why
= "release held jobs";
1675 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1678 why
= "start pending jobs";
1683 #ifdef HAVE_MALLINFO
1685 * Log memory usage every minute...
1688 if (LogLevel
>= CUPSD_LOG_DEBUG
&& (mallinfo_time
+ 60) < timeout
)
1690 timeout
= mallinfo_time
+ 60;
1691 why
= "display memory usage";
1693 #endif /* HAVE_MALLINFO */
1696 * Expire subscriptions as needed...
1699 for (sub
= (cupsd_subscription_t
*)cupsArrayFirst(Subscriptions
);
1701 sub
= (cupsd_subscription_t
*)cupsArrayNext(Subscriptions
))
1702 if (!sub
->job
&& sub
->expire
&& sub
->expire
< timeout
)
1704 timeout
= sub
->expire
;
1705 why
= "expire subscription";
1709 * Adjust from absolute to relative time. We add 1 second to the timeout since
1710 * events occur after the timeout expires, and limit the timeout to 86400
1711 * seconds (1 day) to avoid select() timeout limits present on some operating
1715 timeout
= timeout
- now
+ 1;
1719 else if (timeout
> 86400)
1723 * Log and return the timeout value...
1726 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1734 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1738 sigchld_handler(int sig
) /* I - Signal number */
1743 * Flag that we have dead children...
1749 * Reset the signal handler as needed...
1752 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1753 signal(SIGCLD
, sigchld_handler
);
1754 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1759 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1763 sighup_handler(int sig
) /* I - Signal number */
1767 NeedReload
= RELOAD_ALL
;
1768 ReloadTime
= time(NULL
);
1770 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1771 signal(SIGHUP
, sighup_handler
);
1772 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1777 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1781 sigterm_handler(int sig
) /* I - Signal number */
1783 (void)sig
; /* remove compiler warnings... */
1786 * Flag that we should stop and return...
1793 #if defined(HAVE_LAUNCHD) || defined(HAVE_SYSTEMD)
1795 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1799 service_checkin(void)
1801 # ifdef HAVE_LAUNCH_ACTIVATE_SOCKET
1802 int error
; /* Check-in error, if any */
1803 size_t i
, /* Looping var */
1804 count
; /* Number of listeners */
1805 int *ld_sockets
; /* Listener sockets */
1806 cupsd_listener_t
*lis
; /* Listeners array */
1807 http_addr_t addr
; /* Address variable */
1808 socklen_t addrlen
; /* Length of address */
1809 char s
[256]; /* String addresss */
1812 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1815 * Check-in with launchd...
1818 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1820 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1822 return; /* anti-compiler-warning */
1826 * Try to match the launchd sockets to the cupsd listeners...
1829 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1831 for (i
= 0; i
< count
; i
++)
1834 * Get the launchd socket address...
1837 addrlen
= sizeof(addr
);
1839 if (getsockname(ld_sockets
[i
], (struct sockaddr
*)&addr
, &addrlen
))
1841 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1845 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, ld_sockets
[i
], httpAddrString(&addr
, s
, sizeof(s
)));
1847 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1849 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1850 if (httpAddrEqual(&lis
->address
, &addr
))
1854 * Add a new listener if there's no match...
1859 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1863 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1865 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1867 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
1871 cupsArrayAdd(Listeners
, lis
);
1873 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1876 lis
->fd
= ld_sockets
[i
];
1880 if (httpAddrPort(&(lis
->address
)) == 443)
1881 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1882 # endif /* HAVE_SSL */
1887 # elif defined(HAVE_LAUNCHD)
1888 size_t i
, /* Looping var */
1889 count
; /* Number of listeners */
1890 launch_data_t ld_msg
, /* Launch data message */
1891 ld_resp
, /* Launch data response */
1892 ld_array
, /* Launch data array */
1893 ld_sockets
, /* Launch data sockets dictionary */
1894 tmp
; /* Launch data */
1895 cupsd_listener_t
*lis
; /* Listeners array */
1896 http_addr_t addr
; /* Address variable */
1897 socklen_t addrlen
; /* Length of address */
1898 int fd
; /* File descriptor */
1899 char s
[256]; /* String addresss */
1902 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1905 * Check-in with launchd...
1908 ld_msg
= launch_data_new_string(LAUNCH_KEY_CHECKIN
);
1909 if ((ld_resp
= launch_msg(ld_msg
)) == NULL
)
1911 cupsdLogMessage(CUPSD_LOG_ERROR
,
1912 "service_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
1915 return; /* anti-compiler-warning */
1918 if (launch_data_get_type(ld_resp
) == LAUNCH_DATA_ERRNO
)
1920 errno
= launch_data_get_errno(ld_resp
);
1921 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Check-in failed: %s",
1924 return; /* anti-compiler-warning */
1928 * Get the sockets dictionary...
1931 if ((ld_sockets
= launch_data_dict_lookup(ld_resp
, LAUNCH_JOBKEY_SOCKETS
))
1934 cupsdLogMessage(CUPSD_LOG_ERROR
,
1935 "service_checkin: No sockets found to answer requests on.");
1937 return; /* anti-compiler-warning */
1941 * Get the array of listener sockets...
1944 if ((ld_array
= launch_data_dict_lookup(ld_sockets
, "Listeners")) == NULL
)
1946 cupsdLogMessage(CUPSD_LOG_ERROR
,
1947 "service_checkin: No sockets found to answer requests on.");
1949 return; /* anti-compiler-warning */
1953 * Add listening fd(s) to the Listener array...
1956 if (launch_data_get_type(ld_array
) == LAUNCH_DATA_ARRAY
)
1958 count
= launch_data_array_get_count(ld_array
);
1960 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1962 for (i
= 0; i
< count
; i
++)
1965 * Get the launchd file descriptor and address...
1968 if ((tmp
= launch_data_array_get_index(ld_array
, i
)) != NULL
)
1970 fd
= launch_data_get_fd(tmp
);
1971 addrlen
= sizeof(addr
);
1973 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1975 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
1979 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Listener #%d at fd %d, \"%s\".", (int)i
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
1982 * Try to match the launchd socket address to one of the listeners...
1985 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1987 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1988 if (httpAddrEqual(&lis
->address
, &addr
))
1992 * Add a new listener If there's no match...
1997 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2001 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2003 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2005 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s.", strerror(errno
));
2009 cupsArrayAdd(Listeners
, lis
);
2011 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2018 if (httpAddrPort(&(lis
->address
)) == 443)
2019 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2020 # endif /* HAVE_SSL */
2025 launch_data_free(ld_msg
);
2026 launch_data_free(ld_resp
);
2028 # else /* HAVE_SYSTEMD */
2029 int i
, /* Looping var */
2030 count
; /* Number of listeners */
2031 cupsd_listener_t
*lis
; /* Listeners array */
2032 http_addr_t addr
; /* Address variable */
2033 socklen_t addrlen
; /* Length of address */
2034 char s
[256]; /* String addresss */
2037 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
2040 * Check-in with systemd...
2043 if ((count
= sd_listen_fds(0)) < 0)
2045 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
2047 return; /* anti-compiler-warning */
2051 * Try to match the systemd sockets to the cupsd listeners...
2054 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
2056 for (i
= 0; i
< count
; i
++)
2059 * Get the launchd socket address...
2062 addrlen
= sizeof(addr
);
2064 if (getsockname(SD_LISTEN_FDS_START
+ i
, (struct sockaddr
*)&addr
, &addrlen
))
2066 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get local address for listener #%d: %s", (int)i
+ 1, strerror(errno
));
2070 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
)));
2072 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
2074 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
2075 if (httpAddrEqual(&lis
->address
, &addr
))
2079 * Add a new listener if there's no match...
2084 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Matched existing listener #%d to %s.", (int)i
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
2088 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: Adding new listener #%d for %s.", (int)i
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
2090 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
2092 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to allocate listener: %s", strerror(errno
));
2096 cupsArrayAdd(Listeners
, lis
);
2098 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
2101 lis
->fd
= SD_LISTEN_FDS_START
+ i
;
2105 if (httpAddrPort(&(lis
->address
)) == 443)
2106 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
2107 # endif /* HAVE_SSL */
2109 # endif /* HAVE_LAUNCH_ACTIVATE_SOCKET */
2114 * 'service_checkout()' - Update the CUPS_KEEPALIVE file as needed.
2118 service_checkout(void)
2120 int fd
; /* File descriptor */
2124 * Create or remove the systemd path file based on whether there are active
2125 * jobs or shared printers to advertise...
2128 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2129 # ifdef HAVE_SYSTEMD
2130 WebInterface
|| /* Web interface enabled */
2131 # endif /* HAVE_SYSTEMD */
2132 (Browsing
&& BrowseLocalProtocols
&& cupsArrayCount(Printers
)))
2133 /* Printers being shared */
2135 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating keep-alive file \"" CUPS_KEEPALIVE
"\".");
2137 if ((fd
= open(CUPS_KEEPALIVE
, O_RDONLY
| O_CREAT
| O_EXCL
, S_IRUSR
)) >= 0)
2142 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing keep-alive file \"" CUPS_KEEPALIVE
"\".");
2144 unlink(CUPS_KEEPALIVE
);
2147 #endif /* HAVE_LAUNCHD || HAVE_SYSTEMD */
2151 * 'usage()' - Show scheduler usage.
2155 usage(int status
) /* O - Exit status */
2157 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2160 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2161 _cupsLangPuts(fp
, _("Options:"));
2162 _cupsLangPuts(fp
, _(" -c cupsd.conf Set cupsd.conf file to use."));
2163 _cupsLangPuts(fp
, _(" -f Run in the foreground."));
2164 _cupsLangPuts(fp
, _(" -F Run in the foreground but "
2165 "detach from console."));
2166 _cupsLangPuts(fp
, _(" -h Show this usage message."));
2167 _cupsLangPuts(fp
, _(" -l Run cupsd on demand."));
2168 _cupsLangPuts(fp
, _(" -t Test the configuration "
2176 * End of "$Id: main.c 12248 2014-11-12 16:32:57Z msweet $".