#define _MAIN_C_
#include "cupsd.h"
#include <sys/resource.h>
#include <syslog.h>
#include <grp.h>
#include <cups/dir.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
#if defined(__APPLE__) && defined(HAVE_DLFCN_H)
# include <dlfcn.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;
#if defined(__APPLE__) && defined(HAVE_DLFCN_H)
static const char *PSQLibPath = "/usr/lib/libPrintServiceQuota.dylib";
static const char *PSQLibFuncName = "PSQUpdateQuota";
static void *PSQLibRef;
#endif
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
#ifdef __APPLE__
int run_as_child = 0;
#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)
{
#ifdef __APPLE__
case 'C' :
run_as_child = 1;
fg = -1;
#endif
case 'c' :
i ++;
if (i >= argc)
{
_cupsLangPuts(stderr, _("cupsd: Expected config filename "
"after \"-c\" option!\n"));
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!\n"));
return (1);
}
if (!getcwd(current, 1024))
{
_cupsLangPuts(stderr,
_("cupsd: Unable to get current directory!\n"));
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.\n"));
fg = 0;
#endif
break;
case 'p' :
puts("Warning: -p option is for internal testing use only!");
stop_scheduler = 1;
fg = 1;
break;
default :
_cupsLangPrintf(stderr, _("cupsd: Unknown option \"%c\" - "
"aborting!\n"), *opt);
usage(1);
break;
}
else
{
_cupsLangPrintf(stderr, _("cupsd: Unknown argument \"%s\" - aborting!\n"),
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 __APPLE__
execlp(argv[0], argv[0], "-C", ConfigurationFile, (char *)0);
exit(errno);
#endif
}
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);
#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())
{
syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
ConfigurationFile);
return (1);
}
if (!strncmp(TempDir, RequestRoot, strlen(RequestRoot)))
{
cups_dir_t *dir;
cups_dentry_t *dent;
char tempfile[1024];
if ((dir = cupsDirOpen(TempDir)) != NULL)
{
cupsdLogMessage(CUPSD_LOG_INFO,
"Cleaning out old temporary files in \"%s\"...", TempDir);
while ((dent = cupsDirRead(dir)) != NULL)
{
snprintf(tempfile, sizeof(tempfile), "%s/%s", TempDir, dent->filename);
if (cupsdRemoveFile(tempfile))
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to remove temporary file \"%s\" - %s",
tempfile, strerror(errno));
else
cupsdLogMessage(CUPSD_LOG_DEBUG, "Removed temporary file \"%s\"...",
tempfile);
}
cupsDirClose(dir);
}
else
cupsdLogMessage(CUPSD_LOG_ERROR,
"Unable to open temporary directory \"%s\" - %s",
TempDir, strerror(errno));
}
#if HAVE_LAUNCHD
if (Launchd)
{
launchd_checkin();
}
#endif
#if defined(__APPLE__) && defined(HAVE_DLFCN_H)
PSQLibRef = dlopen(PSQLibPath, RTLD_LAZY);
if (PSQLibRef)
PSQUpdateQuotaProc = dlsym(PSQLibRef, PSQLibFuncName);
#endif
#ifdef HAVE_GSSAPI
# ifdef __APPLE__
if (krb5_init_context != NULL)
# endif
if (krb5_init_context(&KerberosContext))
{
KerberosContext = NULL;
cupsdLogMessage(CUPSD_LOG_ERROR, "Unable to initialize Kerberos context");
}
#endif
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();
#ifdef __APPLE__
if (!fg || run_as_child)
#else
if (!fg)
#endif
{
i = getppid();
if (i != 1)
kill(i, SIGUSR1);
}
#ifdef __APPLE__
cupsdStartSystemMonitor();
#endif
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)
{
#ifdef DEBUG
cupsdLogMessage(CUPSD_LOG_DEBUG2,
"main: Top of loop, dead_children=%d, NeedReload=%d",
dead_children, NeedReload);
#endif
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();
}
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value == IPP_JOB_PROCESSING)
break;
if ((cupsArrayCount(Clients) == 0 &&
(!job || NeedReload != RELOAD_ALL)) ||
(time(NULL) - ReloadTime) >= ReloadTimeout)
{
cupsdStopServer();
if (!cupsdReadConfiguration())
{
syslog(LOG_LPR, "Unable to read configuration file \'%s\' - exiting!",
ConfigurationFile);
break;
}
#if HAVE_LAUNCHD
if (Launchd)
{
launchd_checkin();
}
#endif
cupsdStartServer();
}
}
if ((timeout = select_timeout(fds)) > 1 && LastEvent)
timeout = 1;
#if HAVE_LAUNCHD
if (timeout == 86400 && Launchd && LaunchdTimeout && !NumPolled &&
!cupsArrayCount(ActiveJobs) &&
(!Browsing ||
(!BrowseRemoteProtocols &&
(!NumBrowsers || !BrowseLocalProtocols ||
cupsArrayCount(Printers) == 0))))
{
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] %d", p->name,
p->dnssd_ipp_fd);
#endif
break;
}
current_time = time(NULL);
#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;
}
if ((current_time - RootCertTime) >= RootCertDuration && RootCertDuration &&
!RunUser && cupsArrayCount(Clients))
{
cupsdDeleteCert(0);
cupsdAddCert(0, "root", NULL);
}
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();
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.");
else
cupsdLogMessage(CUPSD_LOG_ERROR,
"Scheduler shutting down due to program error.");
cupsdStopServer();
#ifdef HAVE_LAUNCHD
if (Launchd)
launchd_checkout();
#endif
cupsdFreeAllJobs();
#ifdef __APPLE__
cupsdStopSystemMonitor();
#endif
#ifdef HAVE_GSSAPI
# ifdef __APPLE__
if (krb5_init_context != NULL)
# endif
if (KerberosContext)
krb5_free_context(KerberosContext);
#endif
#ifdef __APPLE__
#ifdef HAVE_DLFCN_H
PSQUpdateQuotaProc = NULL;
if (PSQLibRef)
{
dlclose(PSQLibRef);
PSQLibRef = NULL;
}
#endif
#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);
}
void
cupsdClosePipe(int *fds)
{
if (fds[0] >= 0)
{
close(fds[0]);
fds[0] = -1;
}
if (fds[1] >= 0)
{
close(fds[1]);
fds[1] = -1;
}
}
int
cupsdOpenPipe(int *fds)
{
if (pipe(fds))
{
fds[0] = -1;
fds[1] = -1;
return (-1);
}
if (fcntl(fds[0], F_SETFD, fcntl(fds[0], F_GETFD) | FD_CLOEXEC))
{
close(fds[0]);
close(fds[1]);
fds[0] = -1;
fds[1] = -1;
return (-1);
}
if (fcntl(fds[1], F_SETFD, fcntl(fds[1], F_GETFD) | FD_CLOEXEC))
{
close(fds[0]);
close(fds[1]);
fds[0] = -1;
fds[1] = -1;
return (-1);
}
return (0);
}
void
cupsdClearString(char **s)
{
if (s && *s)
{
_cupsStrFree(*s);
*s = 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)
{
int i,
count,
portnum;
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);
}
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);
}
if (!(ld_sockets = launch_data_dict_lookup(ld_resp, LAUNCH_JOBKEY_SOCKETS)))
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: No sockets found to answer requests on!");
exit(EXIT_FAILURE);
}
if (!(ld_array = launch_data_dict_lookup(ld_sockets, "Listeners")))
{
cupsdLogMessage(CUPSD_LOG_ERROR,
"launchd_checkin: No sockets found to answer requests on!");
exit(EXIT_FAILURE);
}
if (launch_data_get_type(ld_array) == LAUNCH_DATA_ARRAY)
{
count = launch_data_array_get_count(ld_array);
for (i = 0; i < count; i ++)
{
tmp = launch_data_array_get_index(ld_array, i);
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
portnum = 0;
# ifdef AF_INET6
if (lis->address.addr.sa_family == AF_INET6)
portnum = ntohs(lis->address.ipv6.sin6_port);
else
# endif
if (lis->address.addr.sa_family == AF_INET)
portnum = ntohs(lis->address.ipv4.sin_port);
if (portnum == 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 && NumBrowsers && 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;
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));
if (pid)
cupsdDeleteCert(pid);
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value == IPP_JOB_PROCESSING)
{
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 (job->state_value == IPP_JOB_CANCELED)
status = 0;
if (status && job->status >= 0)
{
if (job->filters[i])
job->status = status;
else
job->status = -status;
if (job->printer && !(job->printer->type & CUPS_PRINTER_FAX) &&
job->status_level > CUPSD_LOG_ERROR)
{
job->status_level = CUPSD_LOG_ERROR;
snprintf(job->printer->state_message,
sizeof(job->printer->state_message), "%s failed", name);
cupsdAddPrinterHistory(job->printer);
}
}
if (job->current_file < job->num_files)
{
for (i = 0; job->filters[i] < 0; i ++);
if (!job->filters[i])
{
cupsdFinishJob(job);
}
}
break;
}
}
if (status == SIGTERM)
status = 0;
if (status)
{
if (WIFEXITED(status))
cupsdLogMessage(CUPSD_LOG_ERROR, "PID %d (%s) stopped with status %d!",
pid, name, WEXITSTATUS(status));
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);
}
}
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 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";
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 (timeout > (now + 10) && ActiveJobs)
{
for (job = (cupsd_job_t *)cupsArrayFirst(ActiveJobs);
job;
job = (cupsd_job_t *)cupsArrayNext(ActiveJobs))
if (job->state_value <= IPP_JOB_PROCESSING)
{
timeout = now + 10;
why = "process active 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
usage(int status)
{
_cupsLangPuts(status ? stderr : stdout,
_("Usage: cupsd [-c config-file] [-f] [-F] [-h] [-l]\n"
"\n"
"-c config-file Load alternate configuration file\n"
"-f Run in the foreground\n"
"-F Run in the foreground but detach\n"
"-h Show this usage message\n"
"-l Run cupsd from launchd(8)\n"));
exit(status);
}