#define _MAIN_C_
#include "cupsd.h"
#include <sys/resource.h>
#include <syslog.h>
#include <grp.h>
#ifdef HAVE_LAUNCH_H
# include <launch.h>
# include <libgen.h>
# define CUPS_KEEPALIVE CUPS_CACHEDIR "/org.cups.cupsd"
# ifndef LAUNCH_JOBKEY_KEEPALIVE
# define LAUNCH_JOBKEY_KEEPALIVE "KeepAlive"
# endif
# ifndef LAUNCH_JOBKEY_PATHSTATE
# define LAUNCH_JOBKEY_PATHSTATE "PathState"
# endif
# ifndef LAUNCH_JOBKEY_SERVICEIPC
# define LAUNCH_JOBKEY_SERVICEIPC "ServiceIPC"
# endif
#endif
#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO)
# include <malloc.h>
#endif
#ifdef HAVE_NOTIFY_H
# include <notify.h>
#endif
#ifdef HAVE_LAUNCHD
static void launchd_checkin(void);
static void launchd_checkout(void);
#endif
static void parent_handler(int sig);
static void process_children(void);
static void sigchld_handler(int sig);
static void sighup_handler(int sig);
static void sigterm_handler(int sig);
static long select_timeout(int fds);
static void usage(int status);
static int parent_signal = 0;
static int holdcount = 0;
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
static sigset_t holdmask;
#endif
static int dead_children = 0;
static int stop_scheduler = 0;
int
main(int argc,
char *argv[])
{
int i;
char *opt;
int fg;
int fds;
cupsd_client_t *con;
cupsd_job_t *job;
cupsd_listener_t *lis;
time_t current_time,
activity,
browse_time,
senddoc_time,
expire_time,
report_time,
event_time;
long timeout;
struct rlimit limit;
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
struct sigaction action;
#endif
#ifdef __sgi
cups_file_t *fp;
struct stat statbuf;
#endif
int run_as_child = 0;
#ifdef __APPLE__
int use_sysman = !getuid();
#else
time_t netif_time = 0;
#endif
#if HAVE_LAUNCHD
int launchd_idle_exit;
#endif
#ifdef HAVE_GETEUID
if (getuid() != geteuid())
{
fputs("cupsd: Cannot run as a setuid program\n", stderr);
return (1);
}
#endif
fg = 0;
#ifdef HAVE_LAUNCHD
if (getenv("CUPSD_LAUNCHD"))
{
Launchd = 1;
fg = 1;
}
#endif
for (i = 1; i < argc; i ++)
if (argv[i][0] == '-')
for (opt = argv[i] + 1; *opt != '\0'; opt ++)
switch (*opt)
{
case 'C' :
run_as_child = 1;
fg = -1;
case 'c' :
i ++;
if (i >= argc)
{
_cupsLangPuts(stderr, _("cupsd: Expected config filename "
"after \"-c\" option."));
usage(1);
}
if (argv[i][0] == '/')
{
cupsdSetString(&ConfigurationFile, argv[i]);
}
else
{
char *current;
if ((current = malloc(1024)) == NULL)
{
_cupsLangPuts(stderr,
_("cupsd: Unable to get current directory."));
return (1);
}
if (!getcwd(current, 1024))
{
_cupsLangPuts(stderr,
_("cupsd: Unable to get current directory."));
free(current);
return (1);
}
cupsdSetStringf(&ConfigurationFile, "%s/%s", current, argv[i]);
free(current);
}
break;
case 'f' :
fg = 1;
break;
case 'F' :
fg = -1;
break;
case 'h' :
usage(0);
break;
case 'l' :
#ifdef HAVE_LAUNCHD
Launchd = 1;
fg = 1;
#else
_cupsLangPuts(stderr, _("cupsd: launchd(8) support not compiled "
"in, running in normal mode."));
fg = 0;
#endif
break;
case 'p' :
fputs("cupsd: -p (startup profiling) is for internal testing "
"use only!\n", stderr);
stop_scheduler = 1;
fg = 1;
break;
case 'P' :
fputs("cupsd: -P (disable security profiles) is for internal "
"testing use only!\n", stderr);
UseProfiles = 0;
break;
#ifdef __APPLE__
case 'S' :
fputs("cupsd: -S (disable system management) for internal "
"testing use only!\n", stderr);
use_sysman = 0;
break;
#endif
case 't' :
TestConfigFile = 1;
fg = 1;
break;
default :
_cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
"aborting."), *opt);
usage(1);
break;
}
else
{
_cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting."),
argv[i]);
usage(1);
}
if (!ConfigurationFile)
cupsdSetString(&ConfigurationFile, CUPS_SERVERROOT "/cupsd.conf");
if (!fg)
{
#ifdef HAVE_SIGSET
sigset(SIGUSR1, parent_handler);
sigset(SIGCHLD, parent_handler);
sigset(SIGHUP, SIG_IGN);
#elif defined(HAVE_SIGACTION)
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
sigaddset(&action.sa_mask, SIGUSR1);
action.sa_handler = parent_handler;
sigaction(SIGUSR1, &action, NULL);
sigaction(SIGCHLD, &action, NULL);
sigemptyset(&action.sa_mask);
action.sa_handler = SIG_IGN;
sigaction(SIGHUP, &action, NULL);
#else
signal(SIGUSR1, parent_handler);
signal(SIGCLD, parent_handler);
signal(SIGHUP, SIG_IGN);
#endif
if (fork() > 0)
{
for (; parent_signal == 0;)
sleep(1);
if (parent_signal == SIGUSR1)
return (0);
if (wait(&i) < 0)
{
perror("cupsd");
return (1);
}
else if (WIFEXITED(i))
{
fprintf(stderr, "cupsd: Child exited with status %d\n",
WEXITSTATUS(i));
return (2);
}
else
{
fprintf(stderr, "cupsd: Child exited on signal %d\n", WTERMSIG(i));
return (3);
}
}
#ifdef __OpenBSD__
_thread_sys_closefrom(0);
#endif
execlp(argv[0], argv[0], "-C", ConfigurationFile, (char *)0);
exit(errno);
}
if (fg < 1)
{
chdir("/");
#ifndef DEBUG
getrlimit(RLIMIT_CORE, &limit);
limit.rlim_cur = 0;
setrlimit(RLIMIT_CORE, &limit);
setsid();
getrlimit(RLIMIT_NOFILE, &limit);
for (i = 0; i < limit.rlim_cur && i < 1024; i ++)
close(i);
if ((i = open("/dev/null", O_RDONLY)) != 0)
{
dup2(i, 0);
close(i);
}
if ((i = open("/dev/null", O_WRONLY)) != 1)
{
dup2(i, 1);
close(i);
}
if ((i = open("/dev/null", O_WRONLY)) != 2)
{
dup2(i, 2);
close(i);
}
#endif
}
tzset();
#ifdef LC_TIME
setlocale(LC_TIME, "");
#endif
getrlimit(RLIMIT_NOFILE, &limit);
#if !defined(HAVE_POLL) && !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
if (limit.rlim_max > FD_SETSIZE)
MaxFDs = FD_SETSIZE;
else
#endif
#ifdef RLIM_INFINITY
if (limit.rlim_max == RLIM_INFINITY)
MaxFDs = 16384;
else
#endif
MaxFDs = limit.rlim_max;
limit.rlim_cur = MaxFDs;
setrlimit(RLIMIT_NOFILE, &limit);
cupsdStartSelect();
if (!cupsdReadConfiguration())
{
if (TestConfigFile)
printf("%s contains errors\n", ConfigurationFile);
else
syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
ConfigurationFile);
return (1);
}
else if (TestConfigFile)
{
printf("%s is OK\n", ConfigurationFile);
return (0);
}
if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)))
cupsdCleanFiles(TempDir, NULL);
cupsdCleanFiles(CacheDir, "*.ipp");
#if HAVE_LAUNCHD
if (Launchd)
{
launchd_checkin();
launchd_checkout();
}
#endif
httpInitialize();
cupsdStartServer();
#ifdef HAVE_SIGSET
sigset(SIGCHLD, sigchld_handler);
sigset(SIGHUP, sighup_handler);
sigset(SIGPIPE, SIG_IGN);
sigset(SIGTERM, sigterm_handler);
#elif defined(HAVE_SIGACTION)
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
sigaddset(&action.sa_mask, SIGTERM);
sigaddset(&action.sa_mask, SIGCHLD);
action.sa_handler = sigchld_handler;
sigaction(SIGCHLD, &action, NULL);
sigemptyset(&action.sa_mask);
sigaddset(&action.sa_mask, SIGHUP);
action.sa_handler = sighup_handler;
sigaction(SIGHUP, &action, NULL);
sigemptyset(&action.sa_mask);
action.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &action, NULL);
sigemptyset(&action.sa_mask);
sigaddset(&action.sa_mask, SIGTERM);
sigaddset(&action.sa_mask, SIGCHLD);
action.sa_handler = sigterm_handler;
sigaction(SIGTERM, &action, NULL);
#else
signal(SIGCLD, sigchld_handler);
signal(SIGHUP, sighup_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGTERM, sigterm_handler);
#endif
#ifdef __sgi
if ((fp = cupsFileOpen("/var/spool/lp/SCHEDLOCK", "w")) == NULL)
{
syslog(LOG_LPR, "Unable to create fake lpsched lock file "
"\"/var/spool/lp/SCHEDLOCK\"\' - %s!",
strerror(errno));
}
else
{
fchmod(cupsFileNumber(fp), 0644);
fchown(cupsFileNumber(fp), User, Group);
cupsFileClose(fp);
}
#endif
cupsdInitCerts();
if (!fg || run_as_child)
{
i = getppid();
if (i != 1)
kill(i, SIGUSR1);
}
#ifdef __APPLE__
if (use_sysman)
cupsdStartSystemMonitor();
#endif
#ifdef HAVE_LAUNCHD
if (Launchd)
cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
"Scheduler started via launchd.");
else
#endif
if (fg)
cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
"Scheduler started in foreground.");
else
cupsdAddEvent(CUPSD_EVENT_SERVER_STARTED, NULL, NULL,
"Scheduler started in background.");
cupsdCheckJobs();
current_time = time(NULL);
browse_time = current_time;
event_time = current_time;
expire_time = current_time;
fds = 1;
report_time = 0;
senddoc_time = current_time;
while (!stop_scheduler)
{
if (dead_children)
process_children();
if (NeedReload)
{
if (cupsArrayCount(Clients) > 0)
{
for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
con = (cupsd_client_t *)cupsArrayNext(Clients))
if (con->http.state == HTTP_WAITING)
cupsdCloseClient(con);
else
con->http.keep_alive = HTTP_KEEPALIVE_OFF;
cupsdPauseListening();
}
if ((cupsArrayCount(Clients) == 0 &&
(cupsArrayCount(PrintingJobs) == 0 || NeedReload != RELOAD_ALL)) ||
(time(NULL) - ReloadTime) >= ReloadTimeout)
{
DoingShutdown = 1;
cupsdStopServer();
if (!cupsdReadConfiguration())
{
syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
ConfigurationFile);
break;
}
#if HAVE_LAUNCHD
if (Launchd)
{
launchd_checkin();
launchd_checkout();
}
#endif
DoingShutdown = 0;
cupsdStartServer();
cupsdAddEvent(CUPSD_EVENT_SERVER_RESTARTED, NULL, NULL,
"Scheduler restarted.");
}
}
if ((timeout = select_timeout(fds)) > 1 && LastEvent)
timeout = 1;
#if HAVE_LAUNCHD
if (timeout == 86400 && Launchd && LaunchdTimeout && !NumPolled &&
!cupsArrayCount(ActiveJobs) &&
(!Browsing ||
(!BrowseRemoteProtocols &&
(!BrowseLocalProtocols || !cupsArrayCount(Printers)))))
{
timeout = LaunchdTimeout;
launchd_idle_exit = 1;
}
else
launchd_idle_exit = 0;
#endif
if ((fds = cupsdDoSelect(timeout)) < 0)
{
#ifdef HAVE_DNSSD
cupsd_printer_t *p;
#endif
if (errno == EINTR)
continue;
cupsdLogMessage(CUPSD_LOG_EMERG, "cupsdDoSelect() failed - %s!",
strerror(errno));
for (i = 0, con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
i ++, con = (cupsd_client_t *)cupsArrayNext(Clients))
cupsdLogMessage(CUPSD_LOG_EMERG,
"Clients[%d] = %d, file = %d, state = %d",
i, con->http.fd, con->file, con->http.state);
for (i = 0, lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
lis;
i ++, lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
cupsdLogMessage(CUPSD_LOG_EMERG, "Listeners[%d] = %d", i, lis->fd);
cupsdLogMessage(CUPSD_LOG_EMERG, "BrowseSocket = %d", BrowseSocket);
cupsdLogMessage(CUPSD_LOG_EMERG, "CGIPipes[0] = %d", CGIPipes[0]);
#ifdef __APPLE__
cupsdLogMessage(CUPSD_LOG_EMERG, "SysEventPipes[0] = %d",
SysEventPipes[0]);
#endif
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
cupsdLogMessage(CUPSD_LOG_EMERG, "Jobs[%d] = %d < [%d %d] > [%d %d]",
job->id,
job->status_buffer ? job->status_buffer->fd : -1,
job->print_pipes[0], job->print_pipes[1],
job->back_pipes[0], job->back_pipes[1]);
#ifdef HAVE_DNSSD
for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
p;
p = (cupsd_printer_t *)cupsArrayNext(Printers))
cupsdLogMessage(CUPSD_LOG_EMERG, "printer[%s] reg_name=\"%s\"", p->name,
p->reg_name ? p->reg_name : "(null)");
#endif
break;
}
current_time = time(NULL);
if (DirtyCleanTime && current_time >= DirtyCleanTime)
cupsdCleanDirty();
#ifdef __APPLE__
if (SleepJobs > 0 && current_time >= SleepJobs &&
cupsArrayCount(PrintingJobs) > 0)
{
SleepJobs = 0;
cupsdStopAllJobs(CUPSD_JOB_DEFAULT, 5);
}
#endif
#ifndef __APPLE__
if ((current_time - netif_time) >= 60)
{
netif_time = current_time;
NetIFUpdate = 1;
}
#endif
#if HAVE_LAUNCHD
if (!fds && launchd_idle_exit)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Printer sharing is off and there are no jobs pending, "
"will restart on demand.");
stop_scheduler = 1;
break;
}
#endif
if (ListeningPaused && ListeningPaused <= current_time &&
cupsArrayCount(Clients) < MaxClients)
cupsdResumeListening();
if (current_time > expire_time)
{
if (cupsArrayCount(Subscriptions) > 0)
cupsdExpireSubscriptions(NULL, NULL);
cupsdUnloadCompletedJobs();
expire_time = current_time;
}
if (Browsing)
{
#ifdef HAVE_LIBSLP
if ((BrowseRemoteProtocols & BROWSE_SLP) &&
BrowseSLPRefresh <= current_time)
cupsdUpdateSLPBrowse();
#endif
#ifdef HAVE_LDAP
if ((BrowseRemoteProtocols & BROWSE_LDAP) &&
BrowseLDAPRefresh <= current_time)
cupsdUpdateLDAPBrowse();
#endif
}
if (Browsing && current_time > browse_time)
{
cupsdSendBrowseList();
browse_time = current_time;
}
#ifndef HAVE_AUTHORIZATION_H
if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
!RunUser && cupsArrayCount(Clients))
{
cupsdDeleteCert(0);
cupsdAddCert(0, "root", NULL);
}
#endif
for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
con = (cupsd_client_t *)cupsArrayNext(Clients))
{
if (con->http.used)
{
cupsdReadClient(con);
continue;
}
activity = current_time - Timeout;
if (con->http.activity < activity && !con->pipe_pid)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Closing client %d after %d seconds of inactivity...",
con->http.fd, Timeout);
cupsdCloseClient(con);
continue;
}
}
if ((current_time - senddoc_time) >= 10)
{
cupsdCheckJobs();
cupsdCleanJobs();
senddoc_time = current_time;
}
if ((current_time - report_time) >= 60 && LogLevel >= CUPSD_LOG_DEBUG)
{
size_t string_count,
alloc_bytes,
total_bytes;
#ifdef HAVE_MALLINFO
struct mallinfo mem;
mem = mallinfo();
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-arena=%lu", mem.arena);
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-used=%lu",
mem.usmblks + mem.uordblks);
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: malloc-free=%lu",
mem.fsmblks + mem.fordblks);
#endif
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: clients=%d",
cupsArrayCount(Clients));
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs=%d",
cupsArrayCount(Jobs));
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: jobs-active=%d",
cupsArrayCount(ActiveJobs));
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers=%d",
cupsArrayCount(Printers));
cupsdLogMessage(CUPSD_LOG_DEBUG, "Report: printers-implicit=%d",
cupsArrayCount(ImplicitPrinters));
string_count = _cupsStrStatistics(&alloc_bytes, &total_bytes);
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Report: stringpool-string-count=" CUPS_LLFMT,
CUPS_LLCAST string_count);
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Report: stringpool-alloc-bytes=" CUPS_LLFMT,
CUPS_LLCAST alloc_bytes);
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Report: stringpool-total-bytes=" CUPS_LLFMT,
CUPS_LLCAST total_bytes);
report_time = current_time;
}
if (LastEvent && (current_time - event_time) >= 1)
{
#ifdef HAVE_NOTIFY_POST
if (LastEvent & (CUPSD_EVENT_PRINTER_ADDED |
CUPSD_EVENT_PRINTER_DELETED |
CUPSD_EVENT_PRINTER_MODIFIED))
{
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"notify_post(\"com.apple.printerListChange\")");
notify_post("com.apple.printerListChange");
}
if (LastEvent & CUPSD_EVENT_PRINTER_STATE_CHANGED)
{
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"notify_post(\"com.apple.printerHistoryChange\")");
notify_post("com.apple.printerHistoryChange");
}
if (LastEvent & (CUPSD_EVENT_JOB_STATE_CHANGED |
CUPSD_EVENT_JOB_CONFIG_CHANGED |
CUPSD_EVENT_JOB_PROGRESS))
{
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"notify_post(\"com.apple.jobChange\")");
notify_post("com.apple.jobChange");
}
#endif
LastEvent = CUPSD_EVENT_NONE;
event_time = current_time;
}
}
if (stop_scheduler)
{
cupsdLogMessage(CUPSD_LOG_INFO, "Scheduler shutting down normally.");
cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
"Scheduler shutting down normally.");
}
else
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"Scheduler shutting down due to program error.");
cupsdAddEvent(CUPSD_EVENT_SERVER_STOPPED, NULL, NULL,
"Scheduler shutting down due to program error.");
}
DoingShutdown = 1;
cupsdStopServer();
#ifdef HAVE_LAUNCHD
if (Launchd)
launchd_checkout();
#endif
cupsdFreeAllJobs();
#ifdef __APPLE__
if (use_sysman)
cupsdStopSystemMonitor();
#endif
#ifdef HAVE_GSSAPI
# ifdef __APPLE__
if (krb5_init_context != NULL)
# endif
if (KerberosContext)
krb5_free_context(KerberosContext);
#endif
#ifdef __sgi
if (!stat("/var/spool/lp/FIFO", &statbuf))
if (!S_ISFIFO(statbuf.st_mode))
unlink("/var/spool/lp/SCHEDLOCK");
#endif
cupsdStopSelect();
return (!stop_scheduler);
}
int
cupsdAddString(cups_array_t **a,
const char *s)
{
if (!*a)
*a = cupsArrayNew3((cups_array_func_t)strcmp, NULL,
(cups_ahash_func_t)NULL, 0,
(cups_acopy_func_t)_cupsStrAlloc,
(cups_afree_func_t)_cupsStrFree);
return (cupsArrayAdd(*a, (char *)s));
}
void
cupsdCheckProcess(void)
{
dead_children = 1;
}
void
cupsdClearString(char **s)
{
if (s && *s)
{
_cupsStrFree(*s);
*s = NULL;
}
}
void
cupsdFreeStrings(cups_array_t **a)
{
if (*a)
{
cupsArrayDelete(*a);
*a = NULL;
}
}
void
cupsdHoldSignals(void)
{
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
sigset_t newmask;
#endif
holdcount ++;
if (holdcount > 1)
return;
#ifdef HAVE_SIGSET
sighold(SIGTERM);
sighold(SIGCHLD);
#elif defined(HAVE_SIGACTION)
sigemptyset(&newmask);
sigaddset(&newmask, SIGTERM);
sigaddset(&newmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &newmask, &holdmask);
#endif
}
void
cupsdReleaseSignals(void)
{
holdcount --;
if (holdcount > 0)
return;
#ifdef HAVE_SIGSET
sigrelse(SIGTERM);
sigrelse(SIGCHLD);
#elif defined(HAVE_SIGACTION)
sigprocmask(SIG_SETMASK, &holdmask, NULL);
#endif
}
void
cupsdSetString(char **s,
const char *v)
{
if (!s || *s == v)
return;
if (*s)
_cupsStrFree(*s);
if (v)
*s = _cupsStrAlloc(v);
else
*s = NULL;
}
void
cupsdSetStringf(char **s,
const char *f,
...)
{
char v[4096];
va_list ap;
char *olds;
if (!s)
return;
olds = *s;
if (f)
{
va_start(ap, f);
vsnprintf(v, sizeof(v), f, ap);
va_end(ap);
*s = _cupsStrAlloc(v);
}
else
*s = NULL;
if (olds)
_cupsStrFree(olds);
}
#ifdef HAVE_LAUNCHD
static void
launchd_checkin(void)
{
size_t i,
count;
launch_data_t ld_msg,
ld_resp,
ld_array,
ld_sockets,
tmp;
cupsd_listener_t *lis;
http_addr_t addr;
socklen_t addrlen;
int fd;
char s[256];
cupsdLogMessage(CUPSD_LOG_DEBUG, "launchd_checkin: pid=%d", (int)getpid());
ld_msg = launch_data_new_string(LAUNCH_KEY_CHECKIN);
if ((ld_resp = launch_msg(ld_msg)) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: launch_msg(\"" LAUNCH_KEY_CHECKIN
"\") IPC failure");
exit(EXIT_FAILURE);
return;
}
if (launch_data_get_type(ld_resp) == LAUNCH_DATA_ERRNO)
{
errno = launch_data_get_errno(ld_resp);
cupsdLogMessage(CUPSD_LOG_ERROR, "launchd_checkin: Check-in failed: %s",
strerror(errno));
exit(EXIT_FAILURE);
return;
}
if ((ld_sockets = launch_data_dict_lookup(ld_resp, LAUNCH_JOBKEY_SOCKETS))
== NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: No sockets found to answer requests on!");
exit(EXIT_FAILURE);
return;
}
if ((ld_array = launch_data_dict_lookup(ld_sockets, "Listeners")) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: No sockets found to answer requests on!");
exit(EXIT_FAILURE);
return;
}
if (launch_data_get_type(ld_array) == LAUNCH_DATA_ARRAY)
{
count = launch_data_array_get_count(ld_array);
for (i = 0; i < count; i ++)
{
if ((tmp = launch_data_array_get_index(ld_array, i)) != NULL)
{
fd = launch_data_get_fd(tmp);
addrlen = sizeof(addr);
if (getsockname(fd, (struct sockaddr *)&addr, &addrlen))
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: Unable to get local address - %s",
strerror(errno));
continue;
}
for (lis = (cupsd_listener_t *)cupsArrayFirst(Listeners);
lis;
lis = (cupsd_listener_t *)cupsArrayNext(Listeners))
if (httpAddrEqual(&lis->address, &addr))
break;
if (lis)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"launchd_checkin: Matched existing listener %s with fd %d...",
httpAddrString(&(lis->address), s, sizeof(s)), fd);
}
else
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"launchd_checkin: Adding new listener %s with fd %d...",
httpAddrString(&addr, s, sizeof(s)), fd);
if ((lis = calloc(1, sizeof(cupsd_listener_t))) == NULL)
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: Unable to allocate listener - "
"%s.", strerror(errno));
exit(EXIT_FAILURE);
}
cupsArrayAdd(Listeners, lis);
memcpy(&lis->address, &addr, sizeof(lis->address));
}
lis->fd = fd;
# ifdef HAVE_SSL
if (_httpAddrPort(&(lis->address)) == 443)
lis->encryption = HTTP_ENCRYPT_ALWAYS;
# endif
}
}
}
launch_data_free(ld_msg);
launch_data_free(ld_resp);
}
static void
launchd_checkout(void)
{
int fd;
if (cupsArrayCount(ActiveJobs) || NumPolled ||
(Browsing &&
(BrowseRemoteProtocols ||
(BrowseLocalProtocols && cupsArrayCount(Printers)))))
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Creating launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
if ((fd = open(CUPS_KEEPALIVE, O_RDONLY | O_CREAT | O_EXCL, S_IRUSR)) >= 0)
close(fd);
}
else
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"Removing launchd keepalive file \"" CUPS_KEEPALIVE
"\"...");
unlink(CUPS_KEEPALIVE);
}
}
#endif
static void
parent_handler(int sig)
{
parent_signal = sig;
}
static void
process_children(void)
{
int status;
int pid,
job_id;
cupsd_job_t *job;
int i;
char name[1024];
cupsdLogMessage(CUPSD_LOG_DEBUG2, "process_children()");
dead_children = 0;
#ifdef HAVE_WAITPID
while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
#elif defined(HAVE_WAIT3)
while ((pid = wait3(&status, WNOHANG, NULL)) > 0)
#else
if ((pid = wait(&status)) > 0)
#endif
{
cupsdFinishProcess(pid, name, sizeof(name), &job_id);
if (pid)
cupsdDeleteCert(pid);
if (job_id > 0 && (job = cupsdFindJob(job_id)) != NULL)
{
for (i = 0; job->filters[i]; i ++)
if (job->filters[i] == pid)
break;
if (job->filters[i] || job->backend == pid)
{
if (job->filters[i])
job->filters[i] = -pid;
else
job->backend = -pid;
if (status && status != SIGTERM && status != SIGKILL &&
status != SIGPIPE && job->status >= 0)
{
if (job->filters[i])
job->status = status;
else
job->status = -status;
if (job->state_value == IPP_JOB_PROCESSING &&
job->status_level > CUPSD_LOG_ERROR)
{
char message[1024];
job->status_level = CUPSD_LOG_ERROR;
snprintf(message, sizeof(message), "%s failed", name);
if (job->printer)
{
strlcpy(job->printer->state_message, message,
sizeof(job->printer->state_message));
}
if (!job->attrs)
cupsdLoadJob(job);
if (!job->printer_message && job->attrs)
{
if ((job->printer_message =
ippFindAttribute(job->attrs, "job-printer-state-message",
IPP_TAG_TEXT)) == NULL)
job->printer_message = ippAddString(job->attrs, IPP_TAG_JOB,
IPP_TAG_TEXT,
"job-printer-state-message",
NULL, NULL);
}
if (job->printer_message)
cupsdSetString(&(job->printer_message->values[0].string.text),
message);
}
}
if (job->current_file < job->num_files && job->printer)
{
for (i = 0; job->filters[i] < 0; i ++);
if (!job->filters[i] &&
(!job->printer->pc || !job->printer->pc->single_file ||
job->backend <= 0))
{
cupsdContinueJob(job);
}
}
else if (job->state_value >= IPP_JOB_CANCELED)
{
for (i = 0; job->filters[i] < 0; i++);
if (!job->filters[i] && job->backend <= 0)
cupsArrayRemove(ActiveJobs, job);
}
}
}
if (status == SIGTERM || status == SIGKILL)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"PID %d (%s) was terminated normally with signal %d.",
pid, name, status);
}
else if (status == SIGPIPE)
{
cupsdLogMessage(CUPSD_LOG_DEBUG,
"PID %d (%s) did not catch or ignore signal %d.",
pid, name, status);
}
else if (status)
{
if (WIFEXITED(status))
{
int code = WEXITSTATUS(status);
if (code > 100)
cupsdLogMessage(CUPSD_LOG_DEBUG,
"PID %d (%s) stopped with status %d (%s)", pid, name,
code, strerror(code - 100));
else
cupsdLogMessage(CUPSD_LOG_DEBUG,
"PID %d (%s) stopped with status %d.", pid, name,
code);
}
else
cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) crashed on signal %d.",
pid, name, WTERMSIG(status));
if (LogLevel < CUPSD_LOG_DEBUG)
cupsdLogMessage(CUPSD_LOG_INFO,
"Hint: Try setting the LogLevel to \"debug\" to find "
"out more.");
}
else
cupsdLogMessage(CUPSD_LOG_DEBUG, "PID %d (%s) exited with no errors.",
pid, name);
}
if (pid < 0 && errno == EINTR)
dead_children = 1;
}
static long
select_timeout(int fds)
{
long timeout;
time_t now;
cupsd_client_t *con;
cupsd_printer_t *p;
cupsd_job_t *job;
cupsd_subscription_t *sub;
const char *why;
for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
con = (cupsd_client_t *)cupsArrayNext(Clients))
if (con->http.used > 0)
return (0);
if (fds > 0 || cupsArrayCount(Clients) > 50)
return (1);
now = time(NULL);
timeout = now + 86400;
why = "do nothing";
#ifdef __APPLE__
if (SleepJobs > 0 && SleepJobs < timeout)
{
timeout = SleepJobs;
why = "cancel jobs before sleeping";
}
#endif
if (ListeningPaused > 0 && cupsArrayCount(Clients) < MaxClients &&
ListeningPaused < timeout)
{
if (ListeningPaused <= now)
timeout = now;
else
timeout = ListeningPaused;
why = "resume listening";
}
for (con = (cupsd_client_t *)cupsArrayFirst(Clients);
con;
con = (cupsd_client_t *)cupsArrayNext(Clients))
if ((con->http.activity + Timeout) < timeout)
{
timeout = con->http.activity + Timeout;
why = "timeout a client connection";
}
if (Browsing && BrowseLocalProtocols)
{
#ifdef HAVE_LIBSLP
if ((BrowseLocalProtocols & BROWSE_SLP) && (BrowseSLPRefresh < timeout))
{
timeout = BrowseSLPRefresh;
why = "update SLP browsing";
}
#endif
#ifdef HAVE_LDAP
if ((BrowseLocalProtocols & BROWSE_LDAP) && (BrowseLDAPRefresh < timeout))
{
timeout = BrowseLDAPRefresh;
why = "update LDAP browsing";
}
#endif
if ((BrowseLocalProtocols & BROWSE_CUPS) && NumBrowsers)
{
for (p = (cupsd_printer_t *)cupsArrayFirst(Printers);
p;
p = (cupsd_printer_t *)cupsArrayNext(Printers))
{
if (p->type & CUPS_PRINTER_REMOTE)
{
if ((p->browse_time + BrowseTimeout) < timeout)
{
timeout = p->browse_time + BrowseTimeout;
why = "browse timeout a printer";
}
}
else if (p->shared && !(p->type & CUPS_PRINTER_IMPLICIT))
{
if (BrowseInterval && (p->browse_time + BrowseInterval) < timeout)
{
timeout = p->browse_time + BrowseInterval;
why = "send browse update";
}
}
}
}
}
if (DirtyCleanTime && timeout > DirtyCleanTime)
{
timeout = DirtyCleanTime;
why = "write dirty config/state files";
}
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
{
if (job->kill_time && job->kill_time < timeout)
{
timeout = job->kill_time;
why = "kill unresponsive jobs";
}
if (job->state_value == IPP_JOB_HELD && job->hold_until < timeout)
{
timeout = job->hold_until;
why = "release held jobs";
}
else if (job->state_value == IPP_JOB_PENDING && timeout > (now + 10))
{
timeout = now + 10;
why = "start pending jobs";
break;
}
}
#ifdef HAVE_MALLINFO
if (LogLevel >= CUPSD_LOG_DEBUG && (mallinfo_time + 60) < timeout)
{
timeout = mallinfo_time + 60;
why = "display memory usage";
}
#endif
for (sub = (cupsd_subscription_t *)cupsArrayFirst(Subscriptions);
sub;
sub = (cupsd_subscription_t *)cupsArrayNext(Subscriptions))
if (!sub->job && sub->expire && sub->expire < timeout)
{
timeout = sub->expire;
why = "expire subscription";
}
timeout = timeout - now + 1;
if (timeout < 1)
timeout = 1;
else if (timeout > 86400)
timeout = 86400;
cupsdLogMessage(CUPSD_LOG_DEBUG2, "select_timeout(%d): %ld seconds to %s",
fds, timeout, why);
return (timeout);
}
static void
sigchld_handler(int sig)
{
(void)sig;
dead_children = 1;
#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
signal(SIGCLD, sigchld_handler);
#endif
}
static void
sighup_handler(int sig)
{
(void)sig;
NeedReload = RELOAD_ALL;
ReloadTime = time(NULL);
#if !defined(HAVE_SIGSET) && !defined(HAVE_SIGACTION)
signal(SIGHUP, sighup_handler);
#endif
}
static void
sigterm_handler(int sig)
{
(void)sig;
stop_scheduler = 1;
}
static void
usage(int status)
{
FILE *fp = status ? stderr : stdout;
_cupsLangPuts(fp, _("Usage: cupsd [options]"));
_cupsLangPuts(fp, _("Options:"));
_cupsLangPuts(fp, _(" -c config-file Load alternate configuration "
"file."));
_cupsLangPuts(fp, _(" -f Run in the foreground."));
_cupsLangPuts(fp, _(" -F Run in the foreground but "
"detach from console."));
_cupsLangPuts(fp, _(" -h Show this usage message."));
_cupsLangPuts(fp, _(" -l Run cupsd from launchd(8)."));
_cupsLangPuts(fp, _(" -t Test the configuration "
"file."));
exit(status);
}