#include "lp.cdefs.h"
#include <sys/param.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <dirent.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <syslog.h>
#include <unistd.h>
#include "lp.h"
#include "lp.local.h"
#include "pathnames.h"
#include "extern.h"
int lflag;
int sflag;
int Fflag;
int from_remote;
int main(int argc, char **_argv);
static void reapchild(int _signo);
static void mcleanup(int _signo);
static void doit(void);
static void startup(void);
static void chkhost(struct sockaddr *_f, int _ch_opts);
static int ckqueue(struct printer *_pp);
static void fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
static int *socksetup(int _af, int _debuglvl);
static void usage(void);
extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
const char *, const char *);
uid_t uid, euid;
#define LPD_NOPORTCHK 0001
#define LPD_LOGCONNERR 0002
#define LPD_ADDFROMLINE 0004
int
main(int argc, char **argv)
{
struct timeval tv = { .tv_sec = 120 };
int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
fd_set defreadfds;
struct sockaddr_un un, fromunix;
struct sockaddr_storage frominet;
socklen_t fromlen;
sigset_t omask, nmask;
struct servent *sp, serv;
int inet_flag = 0, inet6_flag = 0;
euid = geteuid();
uid = getuid();
ch_options = 0;
socket_debug = 0;
gethostname(local_host, sizeof(local_host));
progname = "lpd";
if (euid != 0)
errx(EX_NOPERM,"must run as root");
errs = 0;
while ((i = getopt(argc, argv, "cdlpst:wFW46")) != -1)
switch (i) {
case 'c':
ch_options |= LPD_LOGCONNERR;
break;
case 'd':
socket_debug++;
break;
case 'l':
lflag++;
break;
case 'p':
case 's':
sflag++;
break;
case 't':
tv.tv_sec = atol(optarg);
break;
case 'w':
syslog(LOG_WARNING,
"NOTE: the -w option has been renamed -W");
syslog(LOG_WARNING,
"NOTE: please change your lpd config to use -W");
case 'F':
Fflag++;
break;
case 'W':
ch_options |= LPD_NOPORTCHK;
break;
case '4':
family = PF_INET;
inet_flag++;
break;
case '6':
#ifdef INET6
family = PF_INET6;
inet6_flag++;
#else
errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
#endif
break;
case 'b':
case 'n':
case 'r':
default:
errs++;
}
if (inet_flag && inet6_flag)
family = PF_UNSPEC;
argc -= optind;
argv += optind;
if (errs)
usage();
if (argc == 1) {
if ((i = atoi(argv[0])) == 0)
usage();
if (i < 0 || i > USHRT_MAX)
errx(EX_USAGE, "port # %d is invalid", i);
serv.s_port = htons(i);
sp = &serv;
argc--;
} else {
sp = getservbyname("printer", "tcp");
if (sp == NULL)
errx(EX_OSFILE, "printer/tcp: unknown service");
}
if (argc != 0)
usage();
{
pid_t pid;
int status;
pid = fork();
if (pid < 0) {
err(EX_OSERR, "cannot fork");
} else if (pid == 0) {
execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
}
if (waitpid(pid, &status, 0) < 0) {
err(EX_OSERR, "cannot wait");
}
if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
errx(EX_OSFILE, "%d errors in printcap file, exiting",
WEXITSTATUS(status));
}
#ifdef DEBUG
Fflag++;
#endif
if (Fflag == 0) {
daemon(0, 0);
}
openlog("lpd", LOG_PID, LOG_LPR);
syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
(void) umask(0);
lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
LOCK_FILE_MODE);
if (lfd < 0) {
if (errno == EWOULDBLOCK)
exit(0);
syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
exit(1);
}
fcntl(lfd, F_SETFL, 0);
ftruncate(lfd, 0);
sprintf(line, "%u\n", getpid());
f = strlen(line);
if (write(lfd, line, f) != f) {
syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
exit(1);
}
signal(SIGCHLD, reapchild);
startup();
(void) unlink(_PATH_SOCKETNAME);
funix = socket(AF_UNIX, SOCK_STREAM, 0);
if (funix < 0) {
syslog(LOG_ERR, "socket: %m");
exit(1);
}
sigemptyset(&nmask);
sigaddset(&nmask, SIGHUP);
sigaddset(&nmask, SIGINT);
sigaddset(&nmask, SIGQUIT);
sigaddset(&nmask, SIGTERM);
sigprocmask(SIG_BLOCK, &nmask, &omask);
(void) umask(077);
signal(SIGHUP, mcleanup);
signal(SIGINT, mcleanup);
signal(SIGQUIT, mcleanup);
signal(SIGTERM, mcleanup);
memset(&un, 0, sizeof(un));
un.sun_family = AF_UNIX;
strcpy(un.sun_path, _PATH_SOCKETNAME);
#ifndef SUN_LEN
#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
#endif
if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
syslog(LOG_ERR, "ubind: %m");
exit(1);
}
(void) umask(0);
sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
FD_ZERO(&defreadfds);
FD_SET(funix, &defreadfds);
listen(funix, 5);
if (sflag == 0) {
finet = socksetup(family, socket_debug);
} else
finet = NULL;
if (finet) {
for (i = 1; i <= *finet; i++) {
FD_SET(finet[i], &defreadfds);
listen(finet[i], 5);
}
}
memset(&frominet, 0, sizeof(frominet));
memset(&fromunix, 0, sizeof(fromunix));
if (lflag)
syslog(LOG_INFO, "lpd startup: ready to accept requests");
for (;;) {
int domain, nfds, s;
fd_set readfds;
FD_COPY(&defreadfds, &readfds);
nfds = select(20, &readfds, 0, 0, 0);
if (nfds <= 0) {
if (nfds < 0 && errno != EINTR)
syslog(LOG_WARNING, "select: %m");
continue;
}
domain = -1;
s = -1;
if (FD_ISSET(funix, &readfds)) {
domain = AF_UNIX, fromlen = sizeof(fromunix);
s = accept(funix,
(struct sockaddr *)&fromunix, &fromlen);
} else {
for (i = 1; i <= *finet; i++)
if (FD_ISSET(finet[i], &readfds)) {
domain = AF_INET;
fromlen = sizeof(frominet);
s = accept(finet[i],
(struct sockaddr *)&frominet,
&fromlen);
}
}
if (s < 0) {
if (errno != EINTR)
syslog(LOG_WARNING, "accept: %m");
continue;
}
if (tv.tv_sec > 0) {
(void) setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(tv));
}
if (fork() == 0) {
signal(SIGCHLD, SIG_DFL);
signal(SIGHUP, SIG_IGN);
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
(void) close(funix);
if (sflag == 0 && finet) {
for (i = 1; i <= *finet; i++)
(void)close(finet[i]);
}
dup2(s, STDOUT_FILENO);
(void) close(s);
if (domain == AF_INET) {
from_remote = 1;
chkhost((struct sockaddr *)&frominet,
ch_options);
} else
from_remote = 0;
doit();
exit(0);
}
(void) close(s);
}
}
static void
reapchild(int signo __unused)
{
int status;
while (wait3(&status, WNOHANG, 0) > 0)
;
}
static void
mcleanup(int signo)
{
if (lflag) {
if (signo)
syslog(LOG_INFO, "exiting on signal %d", signo);
else
syslog(LOG_INFO, "exiting");
}
unlink(_PATH_SOCKETNAME);
exit(0);
}
char *user[MAXUSERS];
int users;
int requ[MAXREQUESTS];
int requests;
char *person;
static char frombuf[MAXHOSTNAMELEN];
char cbuf[BUFSIZ];
const char *cmdnames[] = {
"null",
"printjob",
"recvjob",
"displayq short",
"displayq long",
"rmjob"
};
static void
doit(void)
{
char *cp, *printer;
int n;
int status;
struct printer myprinter, *pp = &myprinter;
init_printer(&myprinter);
for (;;) {
cp = cbuf;
do {
if (cp >= &cbuf[sizeof(cbuf) - 1])
fatal(0, "Command line too long");
if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
if (n < 0)
fatal(0, "Lost connection");
return;
}
} while (*cp++ != '\n');
*--cp = '\0';
cp = cbuf;
if (lflag) {
if (*cp >= '\1' && *cp <= '\5')
syslog(LOG_INFO, "%s requests %s %s",
from_host, cmdnames[(u_char)*cp], cp+1);
else
syslog(LOG_INFO, "bad request (%d) from %s",
*cp, from_host);
}
switch (*cp++) {
case CMD_CHECK_QUE:
startprinting(cp);
break;
case CMD_TAKE_THIS:
if (!from_remote) {
syslog(LOG_INFO, "illegal request (%d)", *cp);
exit(1);
}
recvjob(cp);
break;
case CMD_SHOWQ_SHORT:
case CMD_SHOWQ_LONG:
printer = cp;
while (*cp) {
if (*cp != ' ') {
cp++;
continue;
}
*cp++ = '\0';
while (isspace(*cp))
cp++;
if (*cp == '\0')
break;
if (isdigit(*cp)) {
if (requests >= MAXREQUESTS)
fatal(0, "Too many requests");
requ[requests++] = atoi(cp);
} else {
if (users >= MAXUSERS)
fatal(0, "Too many users");
user[users++] = cp;
}
}
status = getprintcap(printer, pp);
if (status < 0)
fatal(pp, "%s", pcaperr(status));
displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
exit(0);
case CMD_RMJOB:
if (!from_remote) {
syslog(LOG_INFO, "illegal request (%d)", *cp);
exit(1);
}
printer = cp;
while (*cp && *cp != ' ')
cp++;
if (!*cp)
break;
*cp++ = '\0';
person = cp;
while (*cp) {
if (*cp != ' ') {
cp++;
continue;
}
*cp++ = '\0';
while (isspace(*cp))
cp++;
if (*cp == '\0')
break;
if (isdigit(*cp)) {
if (requests >= MAXREQUESTS)
fatal(0, "Too many requests");
requ[requests++] = atoi(cp);
} else {
if (users >= MAXUSERS)
fatal(0, "Too many users");
user[users++] = cp;
}
}
rmjob(printer);
break;
}
fatal(0, "Illegal service request");
}
}
static void
startup(void)
{
int pid, status, more;
struct printer myprinter, *pp = &myprinter;
more = firstprinter(pp, &status);
if (status)
goto errloop;
while (more) {
if (ckqueue(pp) <= 0) {
goto next;
}
if (lflag)
syslog(LOG_INFO, "lpd startup: work for %s",
pp->printer);
if ((pid = fork()) < 0) {
syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
pp->printer);
mcleanup(0);
}
if (pid == 0) {
lastprinter();
printjob(pp);
}
do {
next:
more = nextprinter(pp, &status);
errloop:
if (status)
syslog(LOG_WARNING,
"lpd startup: printcap entry for %s has errors, skipping",
pp->printer ? pp->printer : "<noname?>");
} while (more && status);
}
}
static int
ckqueue(struct printer *pp)
{
register struct dirent *d;
DIR *dirp;
char *spooldir;
spooldir = pp->spool_dir;
if ((dirp = opendir(spooldir)) == NULL)
return (-1);
while ((d = readdir(dirp)) != NULL) {
if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
continue;
closedir(dirp);
return (1);
}
closedir(dirp);
return (0);
}
#define DUMMY ":nobody::"
static void
chkhost(struct sockaddr *f, int ch_opts)
{
struct addrinfo hints, *res, *r;
register FILE *hostf;
char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
char serv[NI_MAXSERV];
char *syserr, *usererr;
int error, errsav, fpass, good;
from_host = ".na.";
error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
NI_NAMEREQD);
if (error) {
errsav = error;
error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
NULL, 0, NI_NUMERICHOST);
if (error) {
asprintf(&syserr,
"can not determine hostname for remote host (%d,%d)",
errsav, error);
asprintf(&usererr,
"Host name for your address is not known");
fhosterr(ch_opts, syserr, usererr);
}
asprintf(&syserr,
"Host name for remote host (%s) not known (%d)",
hostbuf, errsav);
asprintf(&usererr,
"Host name for your address (%s) is not known",
hostbuf);
fhosterr(ch_opts, syserr, usererr);
}
strlcpy(frombuf, hostbuf, sizeof(frombuf));
from_host = frombuf;
ch_opts |= LPD_ADDFROMLINE;
error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
NI_NUMERICHOST);
if (error) {
asprintf(&syserr, "Cannot print IP address (error %d)",
error);
asprintf(&usererr, "Cannot print IP address for your host");
fhosterr(ch_opts, syserr, usererr);
}
from_ip = strdup(hostbuf);
memset(&hints, 0, sizeof(hints));
hints.ai_family = family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
freeaddrinfo(res);
ch_opts &= ~LPD_ADDFROMLINE;
asprintf(&syserr, "reverse lookup results in non-FQDN %s",
from_host);
fhosterr(ch_opts, syserr, syserr);
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = family;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(from_host, NULL, &hints, &res);
if (error) {
asprintf(&syserr, "dns lookup for address %s failed: %s",
from_ip, gai_strerror(error));
asprintf(&usererr, "hostname for your address (%s) unknown: %s",
from_ip, gai_strerror(error));
fhosterr(ch_opts, syserr, usererr);
}
good = 0;
for (r = res; good == 0 && r; r = r->ai_next) {
error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
NULL, 0, NI_NUMERICHOST);
if (!error && !strcmp(from_ip, ip))
good = 1;
}
if (res)
freeaddrinfo(res);
if (good == 0) {
asprintf(&syserr, "address for remote host (%s) not matched",
from_ip);
asprintf(&usererr,
"address for your hostname (%s) not matched", from_ip);
fhosterr(ch_opts, syserr, usererr);
}
fpass = 1;
hostf = fopen(_PATH_HOSTSEQUIV, "r");
again:
if (hostf) {
if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
(void) fclose(hostf);
goto foundhost;
}
(void) fclose(hostf);
}
if (fpass == 1) {
fpass = 2;
hostf = fopen(_PATH_HOSTSLPD, "r");
goto again;
}
ch_opts &= ~LPD_ADDFROMLINE;
asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
from_ip);
asprintf(&usererr,
"Print-services are not available to your host (%s).", from_host);
fhosterr(ch_opts, syserr, usererr);
foundhost:
if (ch_opts & LPD_NOPORTCHK)
return;
error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
NI_NUMERICSERV);
if (error) {
asprintf(&syserr, "malformed from-address (%d)", error);
fhosterr(ch_opts, syserr, syserr);
}
if (atoi(serv) >= IPPORT_RESERVED) {
asprintf(&syserr, "connected from invalid port (%s)", serv);
fhosterr(ch_opts, syserr, syserr);
}
}
static void
fhosterr(int ch_opts, char *sysmsg, char *usermsg)
{
if (ch_opts & LPD_LOGCONNERR) {
if (ch_opts & LPD_ADDFROMLINE) {
syslog(LOG_WARNING, "for connection from %s:", from_host);
}
syslog(LOG_WARNING, "%s", sysmsg);
}
printf("%s [@%s]: %s\n", progname, local_host, usermsg);
fflush(stdout);
sleep(2);
exit(1);
}
static int *
socksetup(int af, int debuglvl)
{
struct addrinfo hints, *res, *r;
int error, maxs, *s, *socks;
const int on = 1;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = af;
hints.ai_socktype = SOCK_STREAM;
error = getaddrinfo(NULL, "printer", &hints, &res);
if (error) {
syslog(LOG_ERR, "%s", gai_strerror(error));
mcleanup(0);
}
for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
;
socks = malloc((maxs + 1) * sizeof(int));
if (!socks) {
syslog(LOG_ERR, "couldn't allocate memory for sockets");
mcleanup(0);
}
*socks = 0;
s = socks + 1;
for (r = res; r; r = r->ai_next) {
*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
if (*s < 0) {
syslog(LOG_DEBUG, "socket(): %m");
continue;
}
if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
< 0) {
syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
close(*s);
continue;
}
if (debuglvl)
if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
sizeof(debuglvl)) < 0) {
syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
close(*s);
continue;
}
if (r->ai_family == AF_INET6) {
if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
&on, sizeof(on)) < 0) {
syslog(LOG_ERR,
"setsockopt (IPV6_V6ONLY): %m");
close(*s);
continue;
}
}
if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
syslog(LOG_DEBUG, "bind(): %m");
close(*s);
continue;
}
(*socks)++;
s++;
}
if (res)
freeaddrinfo(res);
if (*socks == 0) {
syslog(LOG_ERR, "Couldn't bind to any socket");
free(socks);
mcleanup(0);
}
return(socks);
}
static void
usage(void)
{
#ifdef INET6
fprintf(stderr, "usage: lpd [-cdlsFW46] [port#]\n");
#else
fprintf(stderr, "usage: lpd [-cdlsFW] [port#]\n");
#endif
exit(EX_USAGE);
}