2 * Copyright (c) 1983, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 * must display the following acknowledgement:
16 * This product includes software developed by the University of
17 * California, Berkeley and its contributors.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#) Copyright (c) 1983, 1993, 1994 The Regents of the University of California. All rights reserved.
35 * @(#)lpd.c 8.7 (Berkeley) 5/10/95
36 * $FreeBSD: src/usr.sbin/lpr/lpd/lpd.c,v 1.12.2.22 2002/06/30 04:09:11 gad Exp $
40 * lpd -- line printer daemon.
42 * Listen for a connection and perform the requested operation.
45 * check the queue for jobs and print any found.
47 * receive a job from another machine and queue it.
48 * \3printer [users ...] [jobs ...]\n
49 * return the current state of the queue (short form).
50 * \4printer [users ...] [jobs ...]\n
51 * return the current state of the queue (long form).
52 * \5printer person [users ...] [jobs ...]\n
53 * remove jobs from the queue.
55 * Strategy to maintain protected spooling area:
56 * 1. Spooling area is writable only by daemon and spooling group
57 * 2. lpr runs setuid root and setgrp spooling group; it uses
58 * root to access any file it wants (verifying things before
59 * with an access call) and group id to know how it should
60 * set up ownership of files in the spooling area.
61 * 3. Files in spooling area are owned by root, group spooling
62 * group, with mode 660.
63 * 4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
64 * access files and printer. Users can't get to anything
65 * w/o help of lpq and lprm programs.
68 #include <sys/param.h>
70 #include <sys/types.h>
71 #include <sys/socket.h>
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
93 #include "pathnames.h"
96 int lflag; /* log requests flag */
97 int sflag; /* no incoming port flag */
98 int from_remote; /* from remote socket */
100 static void reapchild(int _signo);
101 static void mcleanup(int _signo);
102 static void doit(void);
103 static void startup(void);
104 static void chkhost(struct sockaddr *_f, int _ch_opts);
105 static int ckqueue(struct printer *_pp);
106 static void fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
107 static int *socksetup(int _af, int _debuglvl);
108 static void usage(void);
110 /* XXX from libc/net/rcmd.c */
111 extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
112 const char *, const char *);
116 #define LPD_NOPORTCHK 0001 /* skip reserved-port check */
117 #define LPD_LOGCONNERR 0002 /* (sys)log connection errors */
118 #define LPD_ADDFROMLINE 0004 /* just used for fhosterr() */
121 main(int argc, char **argv)
123 int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
125 struct sockaddr_un un, fromunix;
126 struct sockaddr_storage frominet;
128 sigset_t omask, nmask;
129 struct servent *sp, serv;
130 int inet_flag = 0, inet6_flag = 0;
132 euid = geteuid(); /* these shouldn't be different */
137 gethostname(local_host, sizeof(local_host));
142 errx(EX_NOPERM,"must run as root");
145 while ((i = getopt(argc, argv, "cdlpswW46")) != -1)
148 /* log all kinds of connection-errors to syslog */
149 ch_options |= LPD_LOGCONNERR;
157 case 'p': /* letter initially used for -s */
159 * This will probably be removed with 5.0-release.
162 case 's': /* secure (no inet) */
165 case 'w': /* netbsd uses -w for maxwait */
167 * This will be removed after the release of 4.4, as
168 * it conflicts with -w in netbsd's lpd. For now it
169 * is just a warning, so we won't suddenly break lpd
170 * for anyone who is currently using the option.
173 "NOTE: the -w option has been renamed -W");
175 "NOTE: please change your lpd config to use -W");
178 /* allow connections coming from a non-reserved port */
179 /* (done by some lpr-implementations for MS-Windows) */
180 ch_options |= LPD_NOPORTCHK;
191 errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
195 * The following options are not in FreeBSD (yet?), but are
196 * listed here to "reserve" them, because the option-letters
197 * are used by either NetBSD or OpenBSD (as of July 2001).
199 case 'b': /* set bind-addr */
200 case 'n': /* set max num of children */
201 case 'r': /* allow 'of' for remote ptrs */
202 /* ...[not needed in freebsd] */
207 if (inet_flag && inet6_flag)
215 if ((i = atoi(argv[0])) == 0)
217 if (i < 0 || i > USHRT_MAX)
218 errx(EX_USAGE, "port # %d is invalid", i);
220 serv.s_port = htons(i);
224 sp = getservbyname("printer", "tcp");
226 errx(EX_OSFILE, "printer/tcp: unknown service");
233 * We run chkprintcap right away to catch any errors and blat them
234 * to stderr while we still have it open, rather than sending them
235 * to syslog and leaving the user wondering why lpd started and
236 * then stopped. There should probably be a command-line flag to
237 * ignore errors from chkprintcap.
244 err(EX_OSERR, "cannot fork");
245 } else if (pid == 0) { /* child */
246 execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, NULL);
247 err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
249 if (waitpid(pid, &status, 0) < 0) {
250 err(EX_OSERR, "cannot wait");
252 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
253 errx(EX_OSFILE, "%d errors in printcap file, exiting",
254 WEXITSTATUS(status));
259 * Set up standard environment by detaching from the parent.
264 openlog("lpd", LOG_PID, LOG_LPR);
265 syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
266 socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
269 * NB: This depends on O_NONBLOCK semantics doing the right thing;
270 * i.e., applying only to the O_EXLOCK and not to the rest of the
271 * open/creation. As of 1997-12-02, this is the case for commonly-
272 * used filesystems. There are other places in this code which
273 * make the same assumption.
275 lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
278 if (errno == EWOULDBLOCK) /* active daemon present */
280 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
283 fcntl(lfd, F_SETFL, 0); /* turn off non-blocking mode */
286 * write process id for others to know
288 sprintf(line, "%u\n", getpid());
290 if (write(lfd, line, f) != f) {
291 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
294 signal(SIGCHLD, reapchild);
296 * Restart all the printers.
299 unlink(_PATH_SOCKETNAME);
300 funix = socket(AF_UNIX, SOCK_STREAM, 0);
302 syslog(LOG_ERR, "socket: %m");
307 sigaddset(&nmask, SIGHUP);
308 sigaddset(&nmask, SIGINT);
309 sigaddset(&nmask, SIGQUIT);
310 sigaddset(&nmask, SIGTERM);
311 sigprocmask(SIG_BLOCK, &nmask, &omask);
314 signal(SIGHUP, mcleanup);
315 signal(SIGINT, mcleanup);
316 signal(SIGQUIT, mcleanup);
317 signal(SIGTERM, mcleanup);
318 memset(&un, 0, sizeof(un));
319 un.sun_family = AF_UNIX;
320 strcpy(un.sun_path, _PATH_SOCKETNAME);
322 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
324 if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
325 syslog(LOG_ERR, "ubind: %m");
329 sigprocmask(SIG_SETMASK, &omask, NULL);
330 FD_ZERO(&defreadfds);
331 FD_SET(funix, &defreadfds);
334 finet = socksetup(family, socket_debug);
336 finet = NULL; /* pretend we couldn't open TCP socket. */
338 for (i = 1; i <= *finet; i++) {
339 FD_SET(finet[i], &defreadfds);
344 * Main loop: accept, do a request, continue.
346 memset(&frominet, 0, sizeof(frominet));
347 memset(&fromunix, 0, sizeof(fromunix));
349 syslog(LOG_INFO, "lpd startup: ready to accept requests");
351 * XXX - should be redone for multi-protocol
357 FD_COPY(&defreadfds, &readfds);
358 nfds = select(20, &readfds, 0, 0, 0);
360 if (nfds < 0 && errno != EINTR)
361 syslog(LOG_WARNING, "select: %m");
364 domain = -1; /* avoid compile-time warning */
365 s = -1; /* avoid compile-time warning */
366 if (FD_ISSET(funix, &readfds)) {
367 domain = AF_UNIX, fromlen = sizeof(fromunix);
369 (struct sockaddr *)&fromunix, &fromlen);
371 for (i = 1; i <= *finet; i++)
372 if (FD_ISSET(finet[i], &readfds)) {
374 fromlen = sizeof(frominet);
376 (struct sockaddr *)&frominet,
382 syslog(LOG_WARNING, "accept: %m");
387 * Note that printjob() also plays around with
388 * signal-handling routines, and may need to be
389 * changed when making changes to signal-handling.
391 signal(SIGCHLD, SIG_DFL);
392 signal(SIGHUP, SIG_IGN);
393 signal(SIGINT, SIG_IGN);
394 signal(SIGQUIT, SIG_IGN);
395 signal(SIGTERM, SIG_IGN);
397 if (sflag == 0 && finet) {
398 for (i = 1; i <= *finet; i++)
403 if (domain == AF_INET) {
404 /* for both AF_INET and AF_INET6 */
406 chkhost((struct sockaddr *)&frominet,
418 reapchild(int signo __unused)
422 while (wait3(&status, WNOHANG, 0) > 0)
430 * XXX syslog(3) is not signal-safe.
434 syslog(LOG_INFO, "exiting on signal %d", signo);
436 syslog(LOG_INFO, "exiting");
438 unlink(_PATH_SOCKETNAME);
443 * Stuff for handling job specifications
445 char *user[MAXUSERS]; /* users to process */
446 int users; /* # of users in user array */
447 int requ[MAXREQUESTS]; /* job number of spool entries */
448 int requests; /* # of spool requests */
449 char *person; /* name of person doing lprm */
451 /* buffer to hold the client's machine-name */
452 static char frombuf[MAXHOSTNAMELEN];
453 char cbuf[BUFSIZ]; /* command line buffer */
454 const char *cmdnames[] = {
469 struct printer myprinter, *pp = &myprinter;
471 init_printer(&myprinter);
476 if (cp >= &cbuf[sizeof(cbuf) - 1])
477 fatal(0, "Command line too long");
478 if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
480 fatal(0, "Lost connection");
483 } while (*cp++ != '\n');
487 if (*cp >= '\1' && *cp <= '\5')
488 syslog(LOG_INFO, "%s requests %s %s",
489 from_host, cmdnames[(u_char)*cp], cp+1);
491 syslog(LOG_INFO, "bad request (%d) from %s",
495 case CMD_CHECK_QUE: /* check the queue, print any jobs there */
498 case CMD_TAKE_THIS: /* receive files to be queued */
500 syslog(LOG_INFO, "illegal request (%d)", *cp);
505 case CMD_SHOWQ_SHORT: /* display the queue (short form) */
506 case CMD_SHOWQ_LONG: /* display the queue (long form) */
507 /* XXX - this all needs to be redone. */
520 if (requests >= MAXREQUESTS)
521 fatal(0, "Too many requests");
522 requ[requests++] = atoi(cp);
524 if (users >= MAXUSERS)
525 fatal(0, "Too many users");
529 status = getprintcap(printer, pp);
531 fatal(pp, "%s", pcaperr(status));
532 displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
534 case CMD_RMJOB: /* remove a job from the queue */
536 syslog(LOG_INFO, "illegal request (%d)", *cp);
540 while (*cp && *cp != ' ')
557 if (requests >= MAXREQUESTS)
558 fatal(0, "Too many requests");
559 requ[requests++] = atoi(cp);
561 if (users >= MAXUSERS)
562 fatal(0, "Too many users");
569 fatal(0, "Illegal service request");
574 * Make a pass through the printcap database and start printing any
575 * files left from the last time the machine went down.
580 int pid, status, more;
581 struct printer myprinter, *pp = &myprinter;
583 more = firstprinter(pp, &status);
587 if (ckqueue(pp) <= 0) {
591 syslog(LOG_INFO, "lpd startup: work for %s",
593 if ((pid = fork()) < 0) {
594 syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
605 more = nextprinter(pp, &status);
609 "lpd startup: printcap entry for %s has errors, skipping",
610 pp->printer ? pp->printer : "<noname?>");
611 } while (more && status);
616 * Make sure there's some work to do before forking off a child
619 ckqueue(struct printer *pp)
625 spooldir = pp->spool_dir;
626 if ((dirp = opendir(spooldir)) == NULL)
628 while ((d = readdir(dirp)) != NULL) {
629 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
630 continue; /* daemon control files only */
632 return (1); /* found something */
638 #define DUMMY ":nobody::"
641 * Check to see if the host connecting to this host has access to any
642 * lpd services on this host.
645 chkhost(struct sockaddr *f, int ch_opts)
647 struct addrinfo hints, *res, *r;
649 char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
650 char serv[NI_MAXSERV];
651 char *syserr, *usererr;
652 int error, errsav, fpass, good, wantsl;
655 if (ch_opts & LPD_LOGCONNERR)
656 wantsl = 1; /* also syslog the errors */
660 /* Need real hostname for temporary filenames */
661 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
665 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
666 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID);
669 "can not determine hostname for remote host (%d,%d)",
672 "Host name for your address is not known");
673 fhosterr(ch_opts, syserr, usererr);
677 "Host name for remote host (%s) not known (%d)",
680 "Host name for your address (%s) is not known",
682 fhosterr(ch_opts, syserr, usererr);
686 strlcpy(frombuf, hostbuf, sizeof(frombuf));
688 ch_opts |= LPD_ADDFROMLINE;
690 /* Need address in stringform for comparison (no DNS lookup here) */
691 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
692 NI_NUMERICHOST | NI_WITHSCOPEID);
694 asprintf(&syserr, "Cannot print IP address (error %d)",
696 asprintf(&usererr, "Cannot print IP address for your host");
697 fhosterr(ch_opts, syserr, usererr);
700 from_ip = strdup(hostbuf);
702 /* Reject numeric addresses */
703 memset(&hints, 0, sizeof(hints));
704 hints.ai_family = family;
705 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
706 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
707 if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
709 /* This syslog message already includes from_host */
710 ch_opts &= ~LPD_ADDFROMLINE;
711 asprintf(&syserr, "reverse lookup results in non-FQDN %s",
713 /* same message to both syslog and remote user */
714 fhosterr(ch_opts, syserr, syserr);
718 /* Check for spoof, ala rlogind */
719 memset(&hints, 0, sizeof(hints));
720 hints.ai_family = family;
721 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
722 error = getaddrinfo(from_host, NULL, &hints, &res);
724 asprintf(&syserr, "dns lookup for address %s failed: %s",
725 from_ip, gai_strerror(error));
726 asprintf(&usererr, "hostname for your address (%s) unknown: %s",
727 from_ip, gai_strerror(error));
728 fhosterr(ch_opts, syserr, usererr);
732 for (r = res; good == 0 && r; r = r->ai_next) {
733 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
734 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID);
735 if (!error && !strcmp(from_ip, ip))
741 asprintf(&syserr, "address for remote host (%s) not matched",
744 "address for your hostname (%s) not matched", from_ip);
745 fhosterr(ch_opts, syserr, usererr);
750 hostf = fopen(_PATH_HOSTSEQUIV, "r");
753 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
761 hostf = fopen(_PATH_HOSTSLPD, "r");
764 /* This syslog message already includes from_host */
765 ch_opts &= ~LPD_ADDFROMLINE;
766 asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
769 "Print-services are not available to your host (%s).", from_host);
770 fhosterr(ch_opts, syserr, usererr);
774 if (ch_opts & LPD_NOPORTCHK)
775 return; /* skip the reserved-port check */
777 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
780 /* same message to both syslog and remote user */
781 asprintf(&syserr, "malformed from-address (%d)", error);
782 fhosterr(ch_opts, syserr, syserr);
786 if (atoi(serv) >= IPPORT_RESERVED) {
787 /* same message to both syslog and remote user */
788 asprintf(&syserr, "connected from invalid port (%s)", serv);
789 fhosterr(ch_opts, syserr, syserr);
795 * Handle fatal errors in chkhost. The first message will optionally be
796 * sent to syslog, the second one is sent to the connecting host.
798 * The idea is that the syslog message is meant for an administrator of a
799 * print server (the host receiving connections), while the usermsg is meant
800 * for a remote user who may or may not be clueful, and may or may not be
801 * doing something nefarious. Some remote users (eg, MS-Windows...) may not
802 * even see whatever message is sent, which is why there's the option to
803 * start 'lpd' with the connection-errors also sent to syslog.
805 * Given that hostnames can theoretically be fairly long (well, over 250
806 * bytes), it would probably be helpful to have the 'from_host' field at
807 * the end of any error messages which include that info.
809 * These are Fatal host-connection errors, so this routine does not return.
812 fhosterr(int ch_opts, char *sysmsg, char *usermsg)
816 * If lpd was started up to print connection errors, then write
817 * the syslog message before the user message.
818 * And for many of the syslog messages, it is helpful to first
819 * write the from_host (if it is known) as a separate syslog
820 * message, since the hostname may be so long.
822 if (ch_opts & LPD_LOGCONNERR) {
823 if (ch_opts & LPD_ADDFROMLINE) {
824 syslog(LOG_WARNING, "for connection from %s:", from_host);
826 syslog(LOG_WARNING, "%s", sysmsg);
830 * Now send the error message to the remote host which is trying
831 * to make the connection.
833 printf("%s [@%s]: %s\n", progname, local_host, usermsg);
837 * Add a minimal delay before exiting (and disconnecting from the
838 * sending-host). This is just in case that machine responds by
839 * INSTANTLY retrying (and instantly re-failing...). This may also
840 * give the other side more time to read the error message.
842 sleep(2); /* a paranoid throttling measure */
846 /* setup server socket for specified address family */
847 /* if af is PF_UNSPEC more than one socket may be returned */
848 /* the returned list is dynamically allocated, so caller needs to free it */
850 socksetup(int af, int debuglvl)
852 struct addrinfo hints, *res, *r;
853 int error, maxs, *s, *socks;
856 memset(&hints, 0, sizeof(hints));
857 hints.ai_flags = AI_PASSIVE;
858 hints.ai_family = af;
859 hints.ai_socktype = SOCK_STREAM;
860 error = getaddrinfo(NULL, "printer", &hints, &res);
862 syslog(LOG_ERR, "%s", gai_strerror(error));
866 /* Count max number of sockets we may open */
867 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
869 socks = malloc((maxs + 1) * sizeof(int));
871 syslog(LOG_ERR, "couldn't allocate memory for sockets");
875 *socks = 0; /* num of sockets counter at start of array */
877 for (r = res; r; r = r->ai_next) {
878 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
880 syslog(LOG_DEBUG, "socket(): %m");
883 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
885 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
890 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
891 sizeof(debuglvl)) < 0) {
892 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
896 #ifdef IPV6_BINDV6ONLY
897 if (r->ai_family == AF_INET6) {
898 if (setsockopt(*s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
899 &on, sizeof(on)) < 0) {
901 "setsockopt (IPV6_BINDV6ONLY): %m");
907 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
908 syslog(LOG_DEBUG, "bind(): %m");
920 syslog(LOG_ERR, "Couldn't bind to any socket");
931 fprintf(stderr, "usage: lpd [-cdlsW46] [port#]\n");
933 fprintf(stderr, "usage: lpd [-cdlsW] [port#]\n");