2 * Main loop for the CUPS scheduler.
4 * Copyright © 2007-2019 by Apple Inc.
5 * Copyright © 1997-2007 by Easy Software Products, all rights reserved.
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more
12 * Include necessary headers...
17 #include <sys/resource.h>
20 # include <pthread/qos.h>
21 #endif /* __APPLE__ */
24 #elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
25 # define SD_JOURNAL_SUPPRESS_LOCATION
26 # include <systemd/sd-journal.h>
27 #endif /* HAVE_ASL_H */
33 #endif /* HAVE_LAUNCH_H */
36 # include <systemd/sd-daemon.h>
37 #endif /* HAVE_SYSTEMD */
40 # define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
41 /* Name of the KeepAlive file */
42 #endif /* HAVE_ONDEMAND */
44 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
46 #endif /* HAVE_MALLOC_H && HAVE_MALLINFO */
50 #endif /* HAVE_NOTIFY_H */
53 # include <dbus/dbus.h>
54 #endif /* HAVE_DBUS */
56 #ifdef HAVE_SYS_PARAM_H
57 # include <sys/param.h>
58 #endif /* HAVE_SYS_PARAM_H */
65 static void parent_handler(int sig
);
66 static void process_children(void);
67 static void sigchld_handler(int sig
);
68 static void sighup_handler(int sig
);
69 static void sigterm_handler(int sig
);
70 static long select_timeout(int fds
);
71 static void service_checkin(void);
72 static void service_checkout(int shutdown
);
73 static void usage(int status
) _CUPS_NORETURN
;
80 static int parent_signal
= 0;
81 /* Set to signal number from child */
82 static int holdcount
= 0; /* Number of times "hold" was called */
83 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
84 static sigset_t holdmask
; /* Old POSIX signal mask */
85 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
86 static int dead_children
= 0;
88 static int stop_scheduler
= 0;
89 /* Should the scheduler stop? */
90 static time_t local_timeout
= 0;
91 /* Next local printer timeout */
95 * 'main()' - Main entry for the CUPS scheduler.
98 int /* O - Exit status */
99 main(int argc
, /* I - Number of command-line args */
100 char *argv
[]) /* I - Command-line arguments */
102 int i
; /* Looping var */
103 char *opt
; /* Option character */
104 int close_all
= 1, /* Close all file descriptors? */
105 disconnect
= 1, /* Disconnect from controlling terminal? */
106 fg
= 0, /* Run in foreground? */
108 /* Running as child process? */
110 /* Print the sandbox profile to stdout? */
111 int fds
; /* Number of ready descriptors */
112 cupsd_client_t
*con
; /* Current client */
113 cupsd_job_t
*job
; /* Current job */
114 cupsd_listener_t
*lis
; /* Current listener */
115 time_t current_time
, /* Current time */
116 activity
, /* Client activity timer */
117 senddoc_time
, /* Send-Document time */
118 expire_time
, /* Subscription expire time */
119 report_time
, /* Malloc/client/job report time */
120 event_time
; /* Last event notification time */
121 long timeout
; /* Timeout for cupsdDoSelect() */
122 struct rlimit limit
; /* Runtime limit */
123 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
124 struct sigaction action
; /* Actions for POSIX signals */
125 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
127 int use_sysman
= 1; /* Use system management functions? */
129 time_t netif_time
= 0; /* Time since last network update */
130 #endif /* __APPLE__ */
131 #if defined(HAVE_ONDEMAND)
132 int service_idle_exit
= 0;
133 /* Idle exit on select timeout? */
134 #endif /* HAVE_ONDEMAND */
139 * Check for setuid invocation, which we do not support!
142 if (getuid() != geteuid())
144 fputs("cupsd: Cannot run as a setuid program.\n", stderr
);
147 #endif /* HAVE_GETEUID */
150 * Check for command-line arguments...
155 for (i
= 1; i
< argc
; i
++)
157 if (!strcmp(argv
[i
], "--help"))
159 else if (argv
[i
][0] == '-')
161 for (opt
= argv
[i
] + 1; *opt
!= '\0'; opt
++)
165 case 'C' : /* Run as child with config file */
170 case 'c' : /* Configuration file */
174 _cupsLangPuts(stderr
, _("cupsd: Expected config filename "
175 "after \"-c\" option."));
179 if (argv
[i
][0] == '/')
182 * Absolute directory...
185 cupsdSetString(&ConfigurationFile
, argv
[i
]);
190 * Relative directory...
193 char *current
; /* Current directory */
196 * Allocate a buffer for the current working directory to
197 * reduce run-time stack usage; this approximates the
198 * behavior of some implementations of getcwd() when they
199 * are passed a NULL pointer.
202 if ((current
= malloc(1024)) == NULL
)
204 _cupsLangPuts(stderr
,
205 _("cupsd: Unable to get current directory."));
209 if (!getcwd(current
, 1024))
211 _cupsLangPuts(stderr
,
212 _("cupsd: Unable to get current directory."));
217 cupsdSetStringf(&ConfigurationFile
, "%s/%s", current
, argv
[i
]);
222 case 'f' : /* Run in foreground... */
228 case 'F' : /* Run in foreground, but disconnect from terminal... */
233 case 'h' : /* Show usage/help */
236 case 'l' : /* Started by launchd/systemd/upstart... */
243 _cupsLangPuts(stderr
, _("cupsd: On-demand support not compiled "
244 "in, running in normal mode."));
248 #endif /* HAVE_ONDEMAND */
251 case 'p' : /* Stop immediately for profiling */
252 fputs("cupsd: -p (startup profiling) is for internal testing "
253 "use only!\n", stderr
);
260 case 'P' : /* Disable security profiles */
261 fputs("cupsd: -P (disable sandboxing) is for internal testing use only.\n", stderr
);
265 case 's' : /* Set cups-files.conf location */
269 _cupsLangPuts(stderr
, _("cupsd: Expected cups-files.conf "
270 "filename after \"-s\" option."));
274 if (argv
[i
][0] != '/')
277 * Relative filename not allowed...
280 _cupsLangPuts(stderr
, _("cupsd: Relative cups-files.conf "
281 "filename not allowed."));
285 cupsdSetString(&CupsFilesFile
, argv
[i
]);
289 case 'S' : /* Disable system management functions */
290 fputs("cupsd: -S (disable system management) for internal "
291 "testing use only!\n", stderr
);
294 #endif /* __APPLE__ */
296 case 't' : /* Test the cupsd.conf file... */
303 case 'T' : /* Print security profile */
310 default : /* Unknown option */
311 _cupsLangPrintf(stderr
, _("cupsd: Unknown option \"%c\" - "
319 _cupsLangPrintf(stderr
, _("cupsd: Unknown argument \"%s\" - aborting."),
325 if (!ConfigurationFile
)
326 cupsdSetString(&ConfigurationFile
, CUPS_SERVERROOT
"/cupsd.conf");
330 char *filename
, /* Copy of cupsd.conf filename */
331 *slash
; /* Final slash in cupsd.conf filename */
332 size_t len
; /* Size of buffer */
334 len
= strlen(ConfigurationFile
) + 15;
335 if ((filename
= malloc(len
)) == NULL
)
337 _cupsLangPrintf(stderr
,
338 _("cupsd: Unable to get path to "
339 "cups-files.conf file."));
343 strlcpy(filename
, ConfigurationFile
, len
);
344 if ((slash
= strrchr(filename
, '/')) == NULL
)
347 _cupsLangPrintf(stderr
,
348 _("cupsd: Unable to get path to "
349 "cups-files.conf file."));
353 strlcpy(slash
, "/cups-files.conf", len
- (size_t)(slash
- filename
));
354 cupsdSetString(&CupsFilesFile
, filename
);
361 * Make sure we aren't tying up any filesystems...
367 * Disconnect from the controlling terminal...
376 * Close all open files...
379 getrlimit(RLIMIT_NOFILE
, &limit
);
381 for (i
= 0; i
< (int)limit
.rlim_cur
&& i
< 1024; i
++)
385 * Redirect stdin/out/err to /dev/null...
388 if ((i
= open("/dev/null", O_RDONLY
)) != 0)
394 if ((i
= open("/dev/null", O_WRONLY
)) != 1)
400 if ((i
= open("/dev/null", O_WRONLY
)) != 2)
407 LogStderr
= cupsFileStderr();
410 * Run in the background as needed...
416 * Setup signal handlers for the parent...
419 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
420 sigset(SIGUSR1
, parent_handler
);
421 sigset(SIGCHLD
, parent_handler
);
423 sigset(SIGHUP
, SIG_IGN
);
424 #elif defined(HAVE_SIGACTION)
425 memset(&action
, 0, sizeof(action
));
426 sigemptyset(&action
.sa_mask
);
427 sigaddset(&action
.sa_mask
, SIGUSR1
);
428 action
.sa_handler
= parent_handler
;
429 sigaction(SIGUSR1
, &action
, NULL
);
430 sigaction(SIGCHLD
, &action
, NULL
);
432 sigemptyset(&action
.sa_mask
);
433 action
.sa_handler
= SIG_IGN
;
434 sigaction(SIGHUP
, &action
, NULL
);
436 signal(SIGUSR1
, parent_handler
);
437 signal(SIGCLD
, parent_handler
);
439 signal(SIGHUP
, SIG_IGN
);
440 #endif /* HAVE_SIGSET */
445 * OK, wait for the child to startup and send us SIGUSR1 or to crash
446 * and the OS send us SIGCHLD... We also need to ignore SIGHUP which
447 * might be sent by the init script to restart the scheduler...
450 for (; parent_signal
== 0;)
453 if (parent_signal
== SIGUSR1
)
461 else if (WIFEXITED(i
))
463 fprintf(stderr
, "cupsd: Child exited with status %d\n",
469 fprintf(stderr
, "cupsd: Child exited on signal %d\n", WTERMSIG(i
));
474 #if defined(__OpenBSD__) && OpenBSD < 201211
476 * Call _thread_sys_closefrom() so the child process doesn't reset the
477 * parent's file descriptors to be blocking. This is a workaround for a
478 * limitation of userland libpthread on older versions of OpenBSD.
481 _thread_sys_closefrom(0);
482 #endif /* __OpenBSD__ && OpenBSD < 201211 */
485 * Since many system libraries create fork-unsafe data on execution of a
486 * program, we need to re-execute the background cupsd with the "-C" and "-s"
487 * options to avoid problems. Unfortunately, we also have to assume that
488 * argv[0] contains the name of the cupsd executable - there is no portable
489 * way to get the real pathname...
492 execlp(argv
[0], argv
[0], "-C", ConfigurationFile
, "-s", CupsFilesFile
, (char *)0);
497 * Let the system know we are busy while we bring up cupsd...
500 cupsdSetBusyState(1);
503 * Set the timezone info...
509 setlocale(LC_TIME
, "");
512 #ifdef HAVE_DBUS_THREADS_INIT
514 * Enable threading support for D-BUS...
517 dbus_threads_init_default();
518 #endif /* HAVE_DBUS_THREADS_INIT */
521 * Set the maximum number of files...
524 getrlimit(RLIMIT_NOFILE
, &limit
);
526 #if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
527 if (limit
.rlim_max
> FD_SETSIZE
)
530 #endif /* !HAVE_POLL && !HAVE_EPOLL && !HAVE_KQUEUE */
532 if (limit
.rlim_max
== RLIM_INFINITY
)
535 #endif /* RLIM_INFINITY */
536 MaxFDs
= limit
.rlim_max
;
538 limit
.rlim_cur
= (rlim_t
)MaxFDs
;
540 setrlimit(RLIMIT_NOFILE
, &limit
);
545 * Read configuration...
548 if (!cupsdReadConfiguration())
550 else if (TestConfigFile
)
552 printf("\"%s\" is OK.\n", CupsFilesFile
);
553 printf("\"%s\" is OK.\n", ConfigurationFile
);
556 else if (print_profile
)
558 cups_file_t
*fp
; /* File pointer */
559 const char *profile
= cupsdCreateProfile(42, 0);
561 char line
[1024]; /* Line from file */
564 if ((fp
= cupsFileOpen(profile
, "r")) == NULL
)
566 printf("Unable to open profile file \"%s\": %s\n", profile
? profile
: "(null)", strerror(errno
));
570 while (cupsFileGets(fp
, line
, sizeof(line
)))
579 * Clean out old temp files and printer cache data.
582 if (!RequestRoot
|| !strncmp(TempDir
, RequestRoot
, strlen(RequestRoot
)))
583 cupsdCleanFiles(TempDir
, NULL
);
585 cupsdCleanFiles(CacheDir
, "*.ipp");
588 * If we were started on demand by launchd or systemd get the listen sockets
589 * file descriptors...
596 * Startup the server...
604 * Catch hangup and child signals and ignore broken pipes...
607 #ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
608 sigset(SIGCHLD
, sigchld_handler
);
609 sigset(SIGHUP
, sighup_handler
);
610 sigset(SIGPIPE
, SIG_IGN
);
611 sigset(SIGTERM
, sigterm_handler
);
612 #elif defined(HAVE_SIGACTION)
613 memset(&action
, 0, sizeof(action
));
615 sigemptyset(&action
.sa_mask
);
616 sigaddset(&action
.sa_mask
, SIGTERM
);
617 sigaddset(&action
.sa_mask
, SIGCHLD
);
618 action
.sa_handler
= sigchld_handler
;
619 sigaction(SIGCHLD
, &action
, NULL
);
621 sigemptyset(&action
.sa_mask
);
622 sigaddset(&action
.sa_mask
, SIGHUP
);
623 action
.sa_handler
= sighup_handler
;
624 sigaction(SIGHUP
, &action
, NULL
);
626 sigemptyset(&action
.sa_mask
);
627 action
.sa_handler
= SIG_IGN
;
628 sigaction(SIGPIPE
, &action
, NULL
);
630 sigemptyset(&action
.sa_mask
);
631 sigaddset(&action
.sa_mask
, SIGTERM
);
632 sigaddset(&action
.sa_mask
, SIGCHLD
);
633 action
.sa_handler
= sigterm_handler
;
634 sigaction(SIGTERM
, &action
, NULL
);
636 signal(SIGCLD
, sigchld_handler
); /* No, SIGCLD isn't a typo... */
637 signal(SIGHUP
, sighup_handler
);
638 signal(SIGPIPE
, SIG_IGN
);
639 signal(SIGTERM
, sigterm_handler
);
640 #endif /* HAVE_SIGSET */
643 * Initialize authentication certificates...
649 * If we are running in the background, signal the parent process that
650 * we are up and running...
653 if (!fg
|| run_as_child
)
656 * Send a signal to the parent process, but only if the parent is
657 * not PID 1 (init). This avoids accidentally shutting down the
658 * system on OpenBSD if you CTRL-C the server before it is up...
661 i
= getppid(); /* Save parent PID to avoid race condition */
669 * Start power management framework...
673 cupsdStartSystemMonitor();
674 #endif /* __APPLE__ */
677 * Send server-started event...
682 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started on demand.");
684 #endif /* HAVE_ONDEMAND */
686 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in foreground.");
688 cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED
, NULL
, NULL
, "Scheduler started in background.");
690 cupsdSetBusyState(0);
693 * Start any pending print jobs...
702 current_time
= time(NULL
);
703 event_time
= current_time
;
704 expire_time
= current_time
;
708 senddoc_time
= current_time
;
710 while (!stop_scheduler
)
713 * Check if there are dead children to handle...
720 * Check if we need to load the server configuration file...
726 * Close any idle clients...
729 if (cupsArrayCount(Clients
) > 0)
731 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
733 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
734 if (httpGetState(con
->http
) == HTTP_WAITING
)
735 cupsdCloseClient(con
);
737 con
->http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
739 cupsdPauseListening();
743 * Restart if all clients are closed and all jobs finished, or
744 * if the reload timeout has elapsed...
747 if ((cupsArrayCount(Clients
) == 0 &&
748 (cupsArrayCount(PrintingJobs
) == 0 || NeedReload
!= RELOAD_ALL
)) ||
749 (time(NULL
) - ReloadTime
) >= ReloadTimeout
)
752 * Shutdown the server...
758 # ifndef HAVE_SYSTEMD /* Issue #5640: systemd doesn't actually support launch-on-demand services, need to fake it */
760 # endif /* HAVE_SYSTEMD */
763 #endif /* HAVE_ONDEMAND */
770 * Read configuration...
773 if (!cupsdReadConfiguration())
775 #ifdef HAVE_SYSTEMD_SD_JOURNAL_H
776 sd_journal_print(LOG_ERR
, "Unable to read configuration file \"%s\" - exiting.", ConfigurationFile
);
778 syslog(LOG_LPR
, "Unable to read configuration file \'%s\' - exiting.", ConfigurationFile
);
779 #endif /* HAVE_SYSTEMD_SD_JOURNAL_H */
785 * Startup the server...
793 * Send a server-restarted event...
796 cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED
, NULL
, NULL
,
797 "Scheduler restarted.");
802 * Check for available input or ready output. If cupsdDoSelect()
803 * returns 0 or -1, something bad happened and we should exit
806 * Note that we at least have one listening socket open at all
810 if ((timeout
= select_timeout(fds
)) > 1 && LastEvent
)
815 * If no other work is scheduled and we're being controlled by launchd,
816 * systemd, etc. then timeout after 'IdleExitTimeout' seconds of
820 if (timeout
== 86400 && OnDemand
&& IdleExitTimeout
&&
823 # endif /* HAVE_SYSTEMD */
824 !cupsArrayCount(ActiveJobs
))
826 cupsd_printer_t
*p
= NULL
; /* Current printer */
828 if (Browsing
&& BrowseLocalProtocols
)
830 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
); p
; p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
837 timeout
= IdleExitTimeout
;
838 service_idle_exit
= 1;
842 service_idle_exit
= 0;
843 #endif /* HAVE_ONDEMAND */
845 if ((fds
= cupsdDoSelect(timeout
)) < 0)
848 * Got an error from select!
851 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
852 cupsd_printer_t
*p
; /* Current printer */
853 #endif /* HAVE_DNSSD || HAVE_AVAHI */
855 if (errno
== EINTR
) /* Just interrupted by a signal */
859 * Log all sorts of debug info to help track down the problem.
862 cupsdLogMessage(CUPSD_LOG_EMERG
, "cupsdDoSelect() failed - %s!",
865 for (i
= 0, con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
867 i
++, con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
868 cupsdLogMessage(CUPSD_LOG_EMERG
,
869 "Clients[%d] = %d, file = %d, state = %d",
870 i
, con
->number
, con
->file
, httpGetState(con
->http
));
872 for (i
= 0, lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
874 i
++, lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
875 cupsdLogMessage(CUPSD_LOG_EMERG
, "Listeners[%d] = %d", i
, lis
->fd
);
877 cupsdLogMessage(CUPSD_LOG_EMERG
, "CGIPipes[0] = %d", CGIPipes
[0]);
880 cupsdLogMessage(CUPSD_LOG_EMERG
, "SysEventPipes[0] = %d",
882 #endif /* __APPLE__ */
884 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
886 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
887 cupsdLogMessage(CUPSD_LOG_EMERG
, "Jobs[%d] = %d < [%d %d] > [%d %d]",
889 job
->status_buffer
? job
->status_buffer
->fd
: -1,
890 job
->print_pipes
[0], job
->print_pipes
[1],
891 job
->back_pipes
[0], job
->back_pipes
[1]);
893 #if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
894 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
);
896 p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
897 cupsdLogMessage(CUPSD_LOG_EMERG
, "printer[%s] reg_name=\"%s\"", p
->name
,
898 p
->reg_name
? p
->reg_name
: "(null)");
899 #endif /* HAVE_DNSSD || HAVE_AVAHI */
904 current_time
= time(NULL
);
907 * Write dirty config/state files...
910 if (DirtyCleanTime
&& current_time
>= DirtyCleanTime
)
915 * If we are going to sleep and still have pending jobs, stop them after
916 * a period of time...
919 if (SleepJobs
> 0 && current_time
>= SleepJobs
&&
920 cupsArrayCount(PrintingJobs
) > 0)
923 cupsdStopAllJobs(CUPSD_JOB_DEFAULT
, 5);
925 #endif /* __APPLE__ */
929 * Update the network interfaces once a minute...
932 if ((current_time
- netif_time
) >= 60)
934 netif_time
= current_time
;
937 #endif /* !__APPLE__ */
941 * If no other work was scheduled and we're being controlled by launchd,
942 * systemd, or upstart then timeout after 'LaunchdTimeout' seconds of
946 if (!fds
&& service_idle_exit
)
948 cupsdLogMessage(CUPSD_LOG_INFO
,
949 "Printer sharing is off and there are no jobs pending, "
950 "will restart on demand.");
954 #endif /* HAVE_ONDEMAND */
957 * Resume listening for new connections as needed...
960 if (ListeningPaused
&& ListeningPaused
<= current_time
&&
961 cupsArrayCount(Clients
) < MaxClients
)
962 cupsdResumeListening();
965 * Expire subscriptions and unload completed jobs as needed...
968 if (current_time
> expire_time
)
970 cupsdExpireSubscriptions(NULL
, NULL
);
972 cupsdUnloadCompletedJobs();
974 expire_time
= current_time
;
978 * Delete stale local printers...
981 if (current_time
>= local_timeout
)
983 cupsdDeleteTemporaryPrinters(0);
987 #ifndef HAVE_AUTHORIZATION_H
989 * Update the root certificate once every 5 minutes if we have client
993 if ((current_time
- RootCertTime
) >= RootCertDuration
&& RootCertDuration
&&
994 !RunUser
&& cupsArrayCount(Clients
))
997 * Update the root certificate...
1001 cupsdAddCert(0, "root", cupsdDefaultAuthType());
1003 #endif /* !HAVE_AUTHORIZATION_H */
1006 * Clean job history...
1009 if (JobHistoryUpdate
&& current_time
>= JobHistoryUpdate
)
1013 * Update any pending multi-file documents...
1016 if ((current_time
- senddoc_time
) >= 10)
1019 senddoc_time
= current_time
;
1023 * Check for new data on the client sockets...
1026 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1028 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1031 * Process pending data in the input buffer...
1034 if (httpGetReady(con
->http
))
1036 cupsdReadClient(con
);
1041 * Check the activity and close old clients...
1044 activity
= current_time
- Timeout
;
1045 if (httpGetActivity(con
->http
) < activity
&& !con
->pipe_pid
)
1047 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Closing client %d after %d seconds of inactivity.", con
->number
, Timeout
);
1049 cupsdCloseClient(con
);
1055 * Log statistics at most once a minute when in debug mode...
1058 if ((current_time
- report_time
) >= 60 && LogLevel
>= CUPSD_LOG_DEBUG
)
1060 size_t string_count
, /* String count */
1061 alloc_bytes
, /* Allocated string bytes */
1062 total_bytes
; /* Total string bytes */
1063 #ifdef HAVE_MALLINFO
1064 struct mallinfo mem
; /* Malloc information */
1068 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-arena=%lu", mem
.arena
);
1069 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-used=%lu",
1070 mem
.usmblks
+ mem
.uordblks
);
1071 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: malloc-free=%lu",
1072 mem
.fsmblks
+ mem
.fordblks
);
1073 #endif /* HAVE_MALLINFO */
1075 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: clients=%d",
1076 cupsArrayCount(Clients
));
1077 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs=%d",
1078 cupsArrayCount(Jobs
));
1079 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: jobs-active=%d",
1080 cupsArrayCount(ActiveJobs
));
1081 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Report: printers=%d",
1082 cupsArrayCount(Printers
));
1084 string_count
= _cupsStrStatistics(&alloc_bytes
, &total_bytes
);
1085 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1086 "Report: stringpool-string-count=" CUPS_LLFMT
,
1087 CUPS_LLCAST string_count
);
1088 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1089 "Report: stringpool-alloc-bytes=" CUPS_LLFMT
,
1090 CUPS_LLCAST alloc_bytes
);
1091 cupsdLogMessage(CUPSD_LOG_DEBUG
,
1092 "Report: stringpool-total-bytes=" CUPS_LLFMT
,
1093 CUPS_LLCAST total_bytes
);
1095 report_time
= current_time
;
1099 * Handle OS-specific event notification for any events that have
1100 * accumulated. Don't send these more than once a second...
1103 if (LastEvent
&& (current_time
- event_time
) >= 1)
1105 #ifdef HAVE_NOTIFY_POST
1106 if (LastEvent
& (CUPSD_EVENT_PRINTER_ADDED
|
1107 CUPSD_EVENT_PRINTER_DELETED
|
1108 CUPSD_EVENT_PRINTER_MODIFIED
))
1110 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1111 "notify_post(\"com.apple.printerListChange\")");
1112 notify_post("com.apple.printerListChange");
1115 if (LastEvent
& CUPSD_EVENT_PRINTER_STATE_CHANGED
)
1117 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1118 "notify_post(\"com.apple.printerHistoryChange\")");
1119 notify_post("com.apple.printerHistoryChange");
1122 if (LastEvent
& (CUPSD_EVENT_JOB_STATE_CHANGED
|
1123 CUPSD_EVENT_JOB_CONFIG_CHANGED
|
1124 CUPSD_EVENT_JOB_PROGRESS
))
1126 cupsdLogMessage(CUPSD_LOG_DEBUG2
,
1127 "notify_post(\"com.apple.jobChange\")");
1128 notify_post("com.apple.jobChange");
1130 #endif /* HAVE_NOTIFY_POST */
1133 * Reset the accumulated events...
1136 LastEvent
= CUPSD_EVENT_NONE
;
1137 event_time
= current_time
;
1142 * Log a message based on what happened...
1147 cupsdLogMessage(CUPSD_LOG_INFO
, "Scheduler shutting down normally.");
1148 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1149 "Scheduler shutting down normally.");
1153 cupsdLogMessage(CUPSD_LOG_ERROR
,
1154 "Scheduler shutting down due to program error.");
1155 cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED
, NULL
, NULL
,
1156 "Scheduler shutting down due to program error.");
1160 * Close all network clients...
1168 * Update the KeepAlive/PID file as needed...
1171 service_checkout(1);
1180 * Delete all temporary printers...
1183 cupsdDeleteTemporaryPrinters(1);
1187 * Stop monitoring system event monitoring...
1191 cupsdStopSystemMonitor();
1192 #endif /* __APPLE__ */
1196 return (!stop_scheduler
);
1201 * 'cupsdAddString()' - Copy and add a string to an array.
1204 int /* O - 1 on success, 0 on failure */
1205 cupsdAddString(cups_array_t
**a
, /* IO - String array */
1206 const char *s
) /* I - String to copy and add */
1209 *a
= cupsArrayNew3((cups_array_func_t
)strcmp
, NULL
,
1210 (cups_ahash_func_t
)NULL
, 0,
1211 (cups_acopy_func_t
)strdup
,
1212 (cups_afree_func_t
)free
);
1214 return (cupsArrayAdd(*a
, (char *)s
));
1219 * 'cupsdCheckProcess()' - Tell the main loop to check for dead children.
1223 cupsdCheckProcess(void)
1226 * Flag that we have dead children...
1234 * 'cupsdClearString()' - Clear a string.
1238 cupsdClearString(char **s
) /* O - String value */
1249 * 'cupsdFreeStrings()' - Free an array of strings.
1253 cupsdFreeStrings(cups_array_t
**a
) /* IO - String array */
1257 cupsArrayDelete(*a
);
1264 * 'cupsdHoldSignals()' - Hold child and termination signals.
1268 cupsdHoldSignals(void)
1270 #if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
1271 sigset_t newmask
; /* New POSIX signal mask */
1272 #endif /* HAVE_SIGACTION && !HAVE_SIGSET */
1282 #elif defined(HAVE_SIGACTION)
1283 sigemptyset(&newmask
);
1284 sigaddset(&newmask
, SIGTERM
);
1285 sigaddset(&newmask
, SIGCHLD
);
1286 sigprocmask(SIG_BLOCK
, &newmask
, &holdmask
);
1287 #endif /* HAVE_SIGSET */
1292 * 'cupsdReleaseSignals()' - Release signals for delivery.
1296 cupsdReleaseSignals(void)
1305 #elif defined(HAVE_SIGACTION)
1306 sigprocmask(SIG_SETMASK
, &holdmask
, NULL
);
1307 #endif /* HAVE_SIGSET */
1312 * 'cupsdSetString()' - Set a string value.
1316 cupsdSetString(char **s
, /* O - New string */
1317 const char *v
) /* I - String value */
1333 * 'cupsdSetStringf()' - Set a formatted string value.
1337 cupsdSetStringf(char **s
, /* O - New string */
1338 const char *f
, /* I - Printf-style format string */
1339 ...) /* I - Additional args as needed */
1341 char v
[65536 + 64]; /* Formatting string value */
1342 va_list ap
; /* Argument pointer */
1343 char *olds
; /* Old string */
1354 vsnprintf(v
, sizeof(v
), f
, ap
);
1368 * 'parent_handler()' - Catch USR1/CHLD signals...
1372 parent_handler(int sig
) /* I - Signal */
1375 * Store the signal we got from the OS and return...
1378 parent_signal
= sig
;
1383 * 'process_children()' - Process all dead children...
1387 process_children(void)
1389 int status
; /* Exit status of child */
1390 int pid
, /* Process ID of child */
1391 job_id
; /* Job ID of child */
1392 cupsd_job_t
*job
; /* Current job */
1393 int i
; /* Looping var */
1394 char name
[1024]; /* Process name */
1395 const char *type
; /* Type of program */
1398 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "process_children()");
1401 * Reset the dead_children flag...
1407 * Collect the exit status of some children...
1411 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0)
1412 #elif defined(HAVE_WAIT3)
1413 while ((pid
= wait3(&status
, WNOHANG
, NULL
)) > 0)
1415 if ((pid
= wait(&status
)) > 0)
1416 #endif /* HAVE_WAITPID */
1419 * Collect the name of the process that finished...
1422 cupsdFinishProcess(pid
, name
, sizeof(name
), &job_id
);
1425 * Delete certificates for CGI processes...
1429 cupsdDeleteCert(pid
);
1432 * Handle completed job filters...
1436 job
= cupsdFindJob(job_id
);
1442 for (i
= 0; job
->filters
[i
]; i
++)
1443 if (job
->filters
[i
] == pid
)
1446 if (job
->filters
[i
] || job
->backend
== pid
)
1449 * OK, this process has gone away; what's left?
1452 if (job
->filters
[i
])
1454 job
->filters
[i
] = -pid
;
1459 job
->backend
= -pid
;
1463 if (status
&& status
!= SIGTERM
&& status
!= SIGKILL
&&
1467 * An error occurred; save the exit status so we know to stop
1468 * the printer or cancel the job when all of the filters finish...
1470 * A negative status indicates that the backend failed and the
1471 * printer needs to be stopped.
1473 * In order to preserve the most serious status, we always log
1474 * when a process dies due to a signal (e.g. SIGABRT, SIGSEGV,
1475 * and SIGBUS) and prefer to log the backend exit status over a
1479 int old_status
= abs(job
->status
);
1481 if (WIFSIGNALED(status
) || /* This process crashed, or */
1482 !job
->status
|| /* No process had a status, or */
1483 (!job
->filters
[i
] && WIFEXITED(old_status
)))
1484 { /* Backend and filter didn't crash */
1485 if (job
->filters
[i
])
1487 job
->status
= status
; /* Filter failed */
1491 job
->status
= -status
; /* Backend failed */
1493 if (job
->current_file
< job
->num_files
)
1494 cupsdSetJobState(job
, IPP_JOB_ABORTED
, CUPSD_JOB_FORCE
, "Canceling multi-file job due to backend failure.");
1498 if (job
->state_value
== IPP_JOB_PROCESSING
&&
1499 job
->status_level
> CUPSD_LOG_ERROR
&&
1500 (job
->filters
[i
] || !WIFEXITED(status
)))
1502 char message
[1024]; /* New printer-state-message */
1505 job
->status_level
= CUPSD_LOG_ERROR
;
1507 snprintf(message
, sizeof(message
), "%s failed", type
);
1511 strlcpy(job
->printer
->state_message
, message
,
1512 sizeof(job
->printer
->state_message
));
1518 if (!job
->printer_message
&& job
->attrs
)
1520 if ((job
->printer_message
=
1521 ippFindAttribute(job
->attrs
, "job-printer-state-message",
1522 IPP_TAG_TEXT
)) == NULL
)
1523 job
->printer_message
= ippAddString(job
->attrs
, IPP_TAG_JOB
,
1525 "job-printer-state-message",
1529 if (job
->printer_message
)
1530 ippSetString(job
->attrs
, &job
->printer_message
, 0, message
);
1535 * If this is not the last file in a job, see if all of the
1536 * filters are done, and if so move to the next file.
1539 if (job
->state_value
>= IPP_JOB_CANCELED
)
1542 * Remove the job from the active list if there are no processes still
1546 for (i
= 0; job
->filters
[i
] < 0; i
++);
1548 if (!job
->filters
[i
] && job
->backend
<= 0)
1549 cupsArrayRemove(ActiveJobs
, job
);
1551 else if (job
->current_file
< job
->num_files
&& job
->printer
)
1553 for (i
= 0; job
->filters
[i
] < 0; i
++);
1555 if (!job
->filters
[i
] &&
1556 (!job
->printer
->pc
|| !job
->printer
->pc
->single_file
||
1560 * Process the next file...
1563 cupsdContinueJob(job
);
1570 * Show the exit status as needed, ignoring SIGTERM and SIGKILL errors
1571 * since they come when we kill/end a process...
1574 if (status
== SIGTERM
|| status
== SIGKILL
)
1576 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1577 "PID %d (%s) was terminated normally with signal %d.", pid
,
1580 else if (status
== SIGPIPE
)
1582 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1583 "PID %d (%s) did not catch or ignore signal %d.", pid
, name
,
1588 if (WIFEXITED(status
))
1590 int code
= WEXITSTATUS(status
); /* Exit code */
1593 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1594 "PID %d (%s) stopped with status %d (%s)", pid
, name
,
1595 code
, strerror(code
- 100));
1597 cupsdLogJob(job
, CUPSD_LOG_DEBUG
,
1598 "PID %d (%s) stopped with status %d.", pid
, name
, code
);
1601 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) crashed on signal %d.",
1602 pid
, name
, WTERMSIG(status
));
1604 if (LogLevel
< CUPSD_LOG_DEBUG
)
1605 cupsdLogJob(job
, CUPSD_LOG_INFO
,
1606 "Hint: Try setting the LogLevel to \"debug\" to find out "
1610 cupsdLogJob(job
, CUPSD_LOG_DEBUG
, "PID %d (%s) exited with no errors.",
1615 * If wait*() is interrupted by a signal, tell main() to call us again...
1618 if (pid
< 0 && errno
== EINTR
)
1624 * 'select_timeout()' - Calculate the select timeout value.
1628 static long /* O - Number of seconds */
1629 select_timeout(int fds
) /* I - Number of descriptors returned */
1631 long timeout
; /* Timeout for select */
1632 time_t now
; /* Current time */
1633 cupsd_client_t
*con
; /* Client information */
1634 cupsd_job_t
*job
; /* Job information */
1635 const char *why
; /* Debugging aid */
1638 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout: JobHistoryUpdate=%ld",
1639 (long)JobHistoryUpdate
);
1642 * Check to see if any of the clients have pending data to be
1643 * processed; if so, the timeout should be 0...
1646 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1648 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1649 if (httpGetReady(con
->http
))
1653 * If select has been active in the last second (fds > 0) or we have
1654 * many resources in use then don't bother trying to optimize the
1655 * timeout, just make it 1 second.
1658 if (fds
> 0 || cupsArrayCount(Clients
) > 50)
1662 * Otherwise, check all of the possible events that we need to wake for...
1666 timeout
= now
+ 86400; /* 86400 == 1 day */
1671 * When going to sleep, wake up to abort jobs that don't complete in time.
1674 if (SleepJobs
> 0 && SleepJobs
< timeout
)
1676 timeout
= SleepJobs
;
1677 why
= "abort jobs before sleeping";
1679 #endif /* __APPLE__ */
1682 * Check whether we are accepting new connections...
1685 if (ListeningPaused
> 0 && cupsArrayCount(Clients
) < MaxClients
&&
1686 ListeningPaused
< timeout
)
1688 if (ListeningPaused
<= now
)
1691 timeout
= ListeningPaused
;
1693 why
= "resume listening";
1697 * Check the activity and close old clients...
1700 for (con
= (cupsd_client_t
*)cupsArrayFirst(Clients
);
1702 con
= (cupsd_client_t
*)cupsArrayNext(Clients
))
1703 if ((httpGetActivity(con
->http
) + Timeout
) < timeout
)
1705 timeout
= httpGetActivity(con
->http
) + Timeout
;
1706 why
= "timeout a client connection";
1710 * Write out changes to configuration and state files...
1713 if (DirtyCleanTime
&& timeout
> DirtyCleanTime
)
1715 timeout
= DirtyCleanTime
;
1716 why
= "write dirty config/state files";
1720 * Check for any job activity...
1723 for (job
= (cupsd_job_t
*)cupsArrayFirst(ActiveJobs
);
1725 job
= (cupsd_job_t
*)cupsArrayNext(ActiveJobs
))
1727 if (job
->cancel_time
&& job
->cancel_time
< timeout
)
1729 timeout
= job
->cancel_time
;
1730 why
= "cancel stuck jobs";
1733 if (job
->kill_time
&& job
->kill_time
< timeout
)
1735 timeout
= job
->kill_time
;
1736 why
= "kill unresponsive jobs";
1739 if (job
->state_value
== IPP_JOB_HELD
&& job
->hold_until
< timeout
)
1741 timeout
= job
->hold_until
;
1742 why
= "release held jobs";
1745 if (job
->state_value
== IPP_JOB_PENDING
&& timeout
> (now
+ 10))
1748 why
= "start pending jobs";
1754 * Adjust from absolute to relative time. We add 1 second to the timeout since
1755 * events occur after the timeout expires, and limit the timeout to 86400
1756 * seconds (1 day) to avoid select() timeout limits present on some operating
1760 timeout
= timeout
- now
+ 1;
1764 else if (timeout
> 86400)
1768 * Log and return the timeout value...
1771 cupsdLogMessage(CUPSD_LOG_DEBUG2
, "select_timeout(%d): %ld seconds to %s",
1779 * 'sigchld_handler()' - Handle 'child' signals from old processes.
1783 sigchld_handler(int sig
) /* I - Signal number */
1788 * Flag that we have dead children...
1794 * Reset the signal handler as needed...
1797 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1798 signal(SIGCLD
, sigchld_handler
);
1799 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1804 * 'sighup_handler()' - Handle 'hangup' signals to reconfigure the scheduler.
1808 sighup_handler(int sig
) /* I - Signal number */
1812 NeedReload
= RELOAD_ALL
;
1813 ReloadTime
= time(NULL
);
1815 #if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
1816 signal(SIGHUP
, sighup_handler
);
1817 #endif /* !HAVE_SIGSET && !HAVE_SIGACTION */
1822 * 'sigterm_handler()' - Handle 'terminate' signals that stop the scheduler.
1826 sigterm_handler(int sig
) /* I - Signal number */
1828 (void)sig
; /* remove compiler warnings... */
1831 * Flag that we should stop and return...
1838 #ifdef HAVE_ONDEMAND
1840 * 'service_add_listener()' - Bind an open fd as a Listener.
1844 service_add_listener(int fd
, /* I - Socket file descriptor */
1845 int idx
) /* I - Listener number, for logging */
1847 cupsd_listener_t
*lis
; /* Listeners array */
1848 http_addr_t addr
; /* Address variable */
1849 socklen_t addrlen
; /* Length of address */
1850 char s
[256]; /* String addresss */
1853 addrlen
= sizeof(addr
);
1855 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
))
1857 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_add_listener: Unable to get local address for listener #%d: %s", idx
+ 1, strerror(errno
));
1861 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_add_listener: Listener #%d at fd %d, \"%s\".", idx
+ 1, fd
, httpAddrString(&addr
, s
, sizeof(s
)));
1864 * Try to match the on-demand socket address to one of the listeners...
1867 for (lis
= (cupsd_listener_t
*)cupsArrayFirst(Listeners
);
1869 lis
= (cupsd_listener_t
*)cupsArrayNext(Listeners
))
1870 if (httpAddrEqual(&lis
->address
, &addr
))
1874 * Add a new listener If there's no match...
1879 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_add_listener: Matched existing listener #%d to %s.", idx
+ 1, httpAddrString(&(lis
->address
), s
, sizeof(s
)));
1883 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_add_listener: Adding new listener #%d for %s.", idx
+ 1, httpAddrString(&addr
, s
, sizeof(s
)));
1885 if ((lis
= calloc(1, sizeof(cupsd_listener_t
))) == NULL
)
1887 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_add_listener: Unable to allocate listener: %s.", strerror(errno
));
1891 cupsArrayAdd(Listeners
, lis
);
1893 memcpy(&lis
->address
, &addr
, sizeof(lis
->address
));
1900 if (httpAddrPort(&(lis
->address
)) == 443)
1901 lis
->encryption
= HTTP_ENCRYPT_ALWAYS
;
1902 # endif /* HAVE_SSL */
1904 #endif /* HAVE_ONDEMAND */
1908 * 'service_checkin()' - Check-in with launchd and collect the listening fds.
1912 service_checkin(void)
1914 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: pid=%d", (int)getpid());
1919 int error
; /* Check-in error, if any */
1920 size_t i
, /* Looping var */
1921 count
; /* Number of listeners */
1922 int *ld_sockets
; /* Listener sockets */
1926 * Force "user initiated" priority for the main thread...
1929 pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED
, 0);
1930 # endif /* __APPLE__ */
1933 * Check-in with launchd...
1936 if ((error
= launch_activate_socket("Listeners", &ld_sockets
, &count
)) != 0)
1938 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(error
));
1943 * Try to match the launchd sockets to the cupsd listeners...
1946 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", (int)count
);
1948 for (i
= 0; i
< count
; i
++)
1949 service_add_listener(ld_sockets
[i
], (int)i
);
1954 xpc_transaction_begin();
1955 # endif /* __APPLE__ */
1958 #elif defined(HAVE_SYSTEMD)
1961 int i
, /* Looping var */
1962 count
; /* Number of listeners */
1965 * Check-in with systemd...
1968 if ((count
= sd_listen_fds(0)) < 0)
1970 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets: %s", strerror(-count
));
1972 return; /* anti-compiler-warning */
1976 * Try to match the systemd sockets to the cupsd listeners...
1979 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: %d listeners.", count
);
1981 for (i
= 0; i
< count
; i
++)
1982 service_add_listener(SD_LISTEN_FDS_START
+ i
, i
);
1985 #elif defined(HAVE_UPSTART)
1988 const char *e
; /* Environment var */
1989 int fd
; /* File descriptor */
1992 if (!(e
= getenv("UPSTART_EVENTS")))
1994 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: We did not get started via Upstart.");
1999 if (strcasecmp(e
, "socket"))
2001 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: We did not get triggered via an Upstart socket event.");
2006 if ((e
= getenv("UPSTART_FDS")) == NULL
)
2008 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Unable to get listener sockets from UPSTART_FDS.");
2013 cupsdLogMessage(CUPSD_LOG_DEBUG
, "service_checkin: UPSTART_FDS=%s", e
);
2015 fd
= (int)strtol(e
, NULL
, 10);
2018 cupsdLogMessage(CUPSD_LOG_ERROR
, "service_checkin: Could not parse UPSTART_FDS: %s", strerror(errno
));
2024 * Upstart only supportst a single on-demand socket file descriptor...
2027 service_add_listener(fd
, 0);
2029 #endif /* HAVE_LAUNCHD */
2034 * 'service_checkout()' - Update the KeepAlive/PID file as needed.
2038 service_checkout(int shutdown
) /* I - Shutting down? */
2040 cups_file_t
*fp
; /* File */
2041 char pidfile
[1024]; /* PID/KeepAlive file */
2045 * When running on-demand, use the KeepAlive file, otherwise write a PID file
2049 #ifdef HAVE_ONDEMAND
2052 int shared_printers
= 0; /* Do we have shared printers? */
2054 strlcpy(pidfile
, CUPS_KEEPALIVE
, sizeof(pidfile
));
2057 * If printer sharing is on see if there are any actual shared printers...
2060 if (Browsing
&& BrowseLocalProtocols
)
2062 cupsd_printer_t
*p
= NULL
; /* Current printer */
2064 for (p
= (cupsd_printer_t
*)cupsArrayFirst(Printers
); p
; p
= (cupsd_printer_t
*)cupsArrayNext(Printers
))
2070 shared_printers
= (p
!= NULL
);
2073 if (cupsArrayCount(ActiveJobs
) || /* Active jobs */
2074 WebInterface
|| /* Web interface enabled */
2075 NeedReload
|| /* Doing a reload */
2076 shared_printers
) /* Printers being shared */
2079 * Create or remove the "keep-alive" file based on whether there are active
2080 * jobs or shared printers to advertise...
2087 #endif /* HAVE_ONDEMAND */
2088 snprintf(pidfile
, sizeof(pidfile
), "%s/cupsd.pid", StateDir
);
2092 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Removing KeepAlive/PID file \"%s\".", pidfile
);
2098 cupsdLogMessage(CUPSD_LOG_DEBUG
, "Creating KeepAlive/PID file \"%s\".", pidfile
);
2100 if ((fp
= cupsFileOpen(pidfile
, "w")) != NULL
)
2103 * Save the PID in the file...
2106 cupsFilePrintf(fp
, "%d\n", (int)getpid());
2110 cupsdLogMessage(CUPSD_LOG_ERROR
, "Unable to create KeepAlive/PID file \"%s\": %s", pidfile
, strerror(errno
));
2114 if (OnDemand
&& shutdown
)
2115 xpc_transaction_end();
2116 # endif /* __APPLE__ */
2121 * 'usage()' - Show scheduler usage.
2125 usage(int status
) /* O - Exit status */
2127 FILE *fp
= status
? stderr
: stdout
; /* Output file */
2130 _cupsLangPuts(fp
, _("Usage: cupsd [options]"));
2131 _cupsLangPuts(fp
, _("Options:"));
2132 _cupsLangPuts(fp
, _("-c cupsd.conf Set cupsd.conf file to use."));
2133 _cupsLangPuts(fp
, _("-f Run in the foreground."));
2134 _cupsLangPuts(fp
, _("-F Run in the foreground but detach from console."));
2135 _cupsLangPuts(fp
, _("-h Show this usage message."));
2136 #ifdef HAVE_ONDEMAND
2137 _cupsLangPuts(fp
, _("-l Run cupsd on demand."));
2138 #endif /* HAVE_ONDEMAND */
2139 _cupsLangPuts(fp
, _("-s cups-files.conf Set cups-files.conf file to use."));
2140 _cupsLangPuts(fp
, _("-t Test the configuration file."));