2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1983, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1983, 1993, 1994\n\
36 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)lpd.c 8.7 (Berkeley) 5/10/95";
45 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
46 __FBSDID("$FreeBSD$");
49 * lpd -- line printer daemon.
51 * Listen for a connection and perform the requested operation.
54 * check the queue for jobs and print any found.
56 * receive a job from another machine and queue it.
57 * \3printer [users ...] [jobs ...]\n
58 * return the current state of the queue (short form).
59 * \4printer [users ...] [jobs ...]\n
60 * return the current state of the queue (long form).
61 * \5printer person [users ...] [jobs ...]\n
62 * remove jobs from the queue.
64 * Strategy to maintain protected spooling area:
65 * 1. Spooling area is writable only by daemon and spooling group
66 * 2. lpr runs setuid root and setgrp spooling group; it uses
67 * root to access any file it wants (verifying things before
68 * with an access call) and group id to know how it should
69 * set up ownership of files in the spooling area.
70 * 3. Files in spooling area are owned by root, group spooling
71 * group, with mode 660.
72 * 4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
73 * access files and printer. Users can't get to anything
74 * w/o help of lpq and lprm programs.
77 #include <sys/param.h>
79 #include <sys/types.h>
80 #include <sys/socket.h>
84 #include <netinet/in.h>
85 #include <arpa/inet.h>
101 #include "lp.local.h"
102 #include "pathnames.h"
105 int lflag; /* log requests flag */
106 int sflag; /* no incoming port flag */
107 int from_remote; /* from remote socket */
109 int main(int argc, char **_argv);
110 static void reapchild(int _signo);
111 static void mcleanup(int _signo);
112 static void doit(void);
113 static void startup(void);
114 static void chkhost(struct sockaddr *_f, int _ch_opts);
115 static int ckqueue(struct printer *_pp);
116 static void fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
117 static int *socksetup(int _af, int _debuglvl);
118 static void usage(void);
120 /* XXX from libc/net/rcmd.c */
121 extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
122 const char *, const char *);
126 #define LPD_NOPORTCHK 0001 /* skip reserved-port check */
127 #define LPD_LOGCONNERR 0002 /* (sys)log connection errors */
128 #define LPD_ADDFROMLINE 0004 /* just used for fhosterr() */
131 main(int argc, char **argv)
133 int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
135 struct sockaddr_un un, fromunix;
136 struct sockaddr_storage frominet;
138 sigset_t omask, nmask;
139 struct servent *sp, serv;
140 int inet_flag = 0, inet6_flag = 0;
142 euid = geteuid(); /* these shouldn't be different */
147 gethostname(local_host, sizeof(local_host));
152 errx(EX_NOPERM,"must run as root");
155 while ((i = getopt(argc, argv, "cdlpswW46")) != -1)
158 /* log all kinds of connection-errors to syslog */
159 ch_options |= LPD_LOGCONNERR;
167 case 'p': /* letter initially used for -s */
169 * This will probably be removed with 5.0-release.
172 case 's': /* secure (no inet) */
175 case 'w': /* netbsd uses -w for maxwait */
177 * This will be removed after the release of 4.4, as
178 * it conflicts with -w in netbsd's lpd. For now it
179 * is just a warning, so we won't suddenly break lpd
180 * for anyone who is currently using the option.
183 "NOTE: the -w option has been renamed -W");
185 "NOTE: please change your lpd config to use -W");
188 /* allow connections coming from a non-reserved port */
189 /* (done by some lpr-implementations for MS-Windows) */
190 ch_options |= LPD_NOPORTCHK;
201 errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
205 * The following options are not in FreeBSD (yet?), but are
206 * listed here to "reserve" them, because the option-letters
207 * are used by either NetBSD or OpenBSD (as of July 2001).
209 case 'b': /* set bind-addr */
210 case 'n': /* set max num of children */
211 case 'r': /* allow 'of' for remote ptrs */
212 /* ...[not needed in freebsd] */
217 if (inet_flag && inet6_flag)
225 if ((i = atoi(argv[0])) == 0)
227 if (i < 0 || i > USHRT_MAX)
228 errx(EX_USAGE, "port # %d is invalid", i);
230 serv.s_port = htons(i);
234 sp = getservbyname("printer", "tcp");
236 errx(EX_OSFILE, "printer/tcp: unknown service");
243 * We run chkprintcap right away to catch any errors and blat them
244 * to stderr while we still have it open, rather than sending them
245 * to syslog and leaving the user wondering why lpd started and
246 * then stopped. There should probably be a command-line flag to
247 * ignore errors from chkprintcap.
254 err(EX_OSERR, "cannot fork");
255 } else if (pid == 0) { /* child */
256 execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
257 err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
259 if (waitpid(pid, &status, 0) < 0) {
260 err(EX_OSERR, "cannot wait");
262 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
263 errx(EX_OSFILE, "%d errors in printcap file, exiting",
264 WEXITSTATUS(status));
269 * Set up standard environment by detaching from the parent.
274 openlog("lpd", LOG_PID, LOG_LPR);
275 syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
276 socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
279 * NB: This depends on O_NONBLOCK semantics doing the right thing;
280 * i.e., applying only to the O_EXLOCK and not to the rest of the
281 * open/creation. As of 1997-12-02, this is the case for commonly-
282 * used filesystems. There are other places in this code which
283 * make the same assumption.
285 lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
288 if (errno == EWOULDBLOCK) /* active daemon present */
290 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
293 fcntl(lfd, F_SETFL, 0); /* turn off non-blocking mode */
296 * write process id for others to know
298 sprintf(line, "%u\n", getpid());
300 if (write(lfd, line, f) != f) {
301 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
304 signal(SIGCHLD, reapchild);
306 * Restart all the printers.
309 (void) unlink(_PATH_SOCKETNAME);
310 funix = socket(AF_UNIX, SOCK_STREAM, 0);
312 syslog(LOG_ERR, "socket: %m");
317 sigaddset(&nmask, SIGHUP);
318 sigaddset(&nmask, SIGINT);
319 sigaddset(&nmask, SIGQUIT);
320 sigaddset(&nmask, SIGTERM);
321 sigprocmask(SIG_BLOCK, &nmask, &omask);
324 signal(SIGHUP, mcleanup);
325 signal(SIGINT, mcleanup);
326 signal(SIGQUIT, mcleanup);
327 signal(SIGTERM, mcleanup);
328 memset(&un, 0, sizeof(un));
329 un.sun_family = AF_UNIX;
330 strcpy(un.sun_path, _PATH_SOCKETNAME);
332 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
334 if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
335 syslog(LOG_ERR, "ubind: %m");
339 sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
340 FD_ZERO(&defreadfds);
341 FD_SET(funix, &defreadfds);
344 finet = socksetup(family, socket_debug);
346 finet = NULL; /* pretend we couldn't open TCP socket. */
348 for (i = 1; i <= *finet; i++) {
349 FD_SET(finet[i], &defreadfds);
354 * Main loop: accept, do a request, continue.
356 memset(&frominet, 0, sizeof(frominet));
357 memset(&fromunix, 0, sizeof(fromunix));
359 syslog(LOG_INFO, "lpd startup: ready to accept requests");
361 * XXX - should be redone for multi-protocol
367 FD_COPY(&defreadfds, &readfds);
368 nfds = select(20, &readfds, 0, 0, 0);
370 if (nfds < 0 && errno != EINTR)
371 syslog(LOG_WARNING, "select: %m");
374 domain = -1; /* avoid compile-time warning */
375 s = -1; /* avoid compile-time warning */
376 if (FD_ISSET(funix, &readfds)) {
377 domain = AF_UNIX, fromlen = sizeof(fromunix);
379 (struct sockaddr *)&fromunix, &fromlen);
381 for (i = 1; i <= *finet; i++)
382 if (FD_ISSET(finet[i], &readfds)) {
384 fromlen = sizeof(frominet);
386 (struct sockaddr *)&frominet,
392 syslog(LOG_WARNING, "accept: %m");
397 * Note that printjob() also plays around with
398 * signal-handling routines, and may need to be
399 * changed when making changes to signal-handling.
401 signal(SIGCHLD, SIG_DFL);
402 signal(SIGHUP, SIG_IGN);
403 signal(SIGINT, SIG_IGN);
404 signal(SIGQUIT, SIG_IGN);
405 signal(SIGTERM, SIG_IGN);
407 if (sflag == 0 && finet) {
408 for (i = 1; i <= *finet; i++)
409 (void)close(finet[i]);
411 dup2(s, STDOUT_FILENO);
413 if (domain == AF_INET) {
414 /* for both AF_INET and AF_INET6 */
416 chkhost((struct sockaddr *)&frominet,
428 reapchild(int signo __unused)
432 while (wait3(&status, WNOHANG, 0) > 0)
440 * XXX syslog(3) is not signal-safe.
444 syslog(LOG_INFO, "exiting on signal %d", signo);
446 syslog(LOG_INFO, "exiting");
448 unlink(_PATH_SOCKETNAME);
453 * Stuff for handling job specifications
455 char *user[MAXUSERS]; /* users to process */
456 int users; /* # of users in user array */
457 int requ[MAXREQUESTS]; /* job number of spool entries */
458 int requests; /* # of spool requests */
459 char *person; /* name of person doing lprm */
461 /* buffer to hold the client's machine-name */
462 static char frombuf[MAXHOSTNAMELEN];
463 char cbuf[BUFSIZ]; /* command line buffer */
464 const char *cmdnames[] = {
479 struct printer myprinter, *pp = &myprinter;
481 init_printer(&myprinter);
486 if (cp >= &cbuf[sizeof(cbuf) - 1])
487 fatal(0, "Command line too long");
488 if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
490 fatal(0, "Lost connection");
493 } while (*cp++ != '\n');
497 if (*cp >= '\1' && *cp <= '\5')
498 syslog(LOG_INFO, "%s requests %s %s",
499 from_host, cmdnames[(u_char)*cp], cp+1);
501 syslog(LOG_INFO, "bad request (%d) from %s",
505 case CMD_CHECK_QUE: /* check the queue, print any jobs there */
508 case CMD_TAKE_THIS: /* receive files to be queued */
510 syslog(LOG_INFO, "illegal request (%d)", *cp);
515 case CMD_SHOWQ_SHORT: /* display the queue (short form) */
516 case CMD_SHOWQ_LONG: /* display the queue (long form) */
517 /* XXX - this all needs to be redone. */
530 if (requests >= MAXREQUESTS)
531 fatal(0, "Too many requests");
532 requ[requests++] = atoi(cp);
534 if (users >= MAXUSERS)
535 fatal(0, "Too many users");
539 status = getprintcap(printer, pp);
541 fatal(pp, "%s", pcaperr(status));
542 displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
544 case CMD_RMJOB: /* remove a job from the queue */
546 syslog(LOG_INFO, "illegal request (%d)", *cp);
550 while (*cp && *cp != ' ')
567 if (requests >= MAXREQUESTS)
568 fatal(0, "Too many requests");
569 requ[requests++] = atoi(cp);
571 if (users >= MAXUSERS)
572 fatal(0, "Too many users");
579 fatal(0, "Illegal service request");
584 * Make a pass through the printcap database and start printing any
585 * files left from the last time the machine went down.
590 int pid, status, more;
591 struct printer myprinter, *pp = &myprinter;
593 more = firstprinter(pp, &status);
597 if (ckqueue(pp) <= 0) {
601 syslog(LOG_INFO, "lpd startup: work for %s",
603 if ((pid = fork()) < 0) {
604 syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
615 more = nextprinter(pp, &status);
619 "lpd startup: printcap entry for %s has errors, skipping",
620 pp->printer ? pp->printer : "<noname?>");
621 } while (more && status);
626 * Make sure there's some work to do before forking off a child
629 ckqueue(struct printer *pp)
631 register struct dirent *d;
635 spooldir = pp->spool_dir;
636 if ((dirp = opendir(spooldir)) == NULL)
638 while ((d = readdir(dirp)) != NULL) {
639 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
640 continue; /* daemon control files only */
642 return (1); /* found something */
648 #define DUMMY ":nobody::"
651 * Check to see if the host connecting to this host has access to any
652 * lpd services on this host.
655 chkhost(struct sockaddr *f, int ch_opts)
657 struct addrinfo hints, *res, *r;
658 register FILE *hostf;
659 char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
660 char serv[NI_MAXSERV];
661 char *syserr, *usererr;
662 int error, errsav, fpass, good;
666 /* Need real hostname for temporary filenames */
667 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
671 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
672 NULL, 0, NI_NUMERICHOST);
675 "can not determine hostname for remote host (%d,%d)",
678 "Host name for your address is not known");
679 fhosterr(ch_opts, syserr, usererr);
683 "Host name for remote host (%s) not known (%d)",
686 "Host name for your address (%s) is not known",
688 fhosterr(ch_opts, syserr, usererr);
692 strlcpy(frombuf, hostbuf, sizeof(frombuf));
694 ch_opts |= LPD_ADDFROMLINE;
696 /* Need address in stringform for comparison (no DNS lookup here) */
697 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
700 asprintf(&syserr, "Cannot print IP address (error %d)",
702 asprintf(&usererr, "Cannot print IP address for your host");
703 fhosterr(ch_opts, syserr, usererr);
706 from_ip = strdup(hostbuf);
708 /* Reject numeric addresses */
709 memset(&hints, 0, sizeof(hints));
710 hints.ai_family = family;
711 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
712 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
713 if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
715 /* This syslog message already includes from_host */
716 ch_opts &= ~LPD_ADDFROMLINE;
717 asprintf(&syserr, "reverse lookup results in non-FQDN %s",
719 /* same message to both syslog and remote user */
720 fhosterr(ch_opts, syserr, syserr);
724 /* Check for spoof, ala rlogind */
725 memset(&hints, 0, sizeof(hints));
726 hints.ai_family = family;
727 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
728 error = getaddrinfo(from_host, NULL, &hints, &res);
730 asprintf(&syserr, "dns lookup for address %s failed: %s",
731 from_ip, gai_strerror(error));
732 asprintf(&usererr, "hostname for your address (%s) unknown: %s",
733 from_ip, gai_strerror(error));
734 fhosterr(ch_opts, syserr, usererr);
738 for (r = res; good == 0 && r; r = r->ai_next) {
739 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
740 NULL, 0, NI_NUMERICHOST);
741 if (!error && !strcmp(from_ip, ip))
747 asprintf(&syserr, "address for remote host (%s) not matched",
750 "address for your hostname (%s) not matched", from_ip);
751 fhosterr(ch_opts, syserr, usererr);
756 hostf = fopen(_PATH_HOSTSEQUIV, "r");
759 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
760 (void) fclose(hostf);
763 (void) fclose(hostf);
767 hostf = fopen(_PATH_HOSTSLPD, "r");
770 /* This syslog message already includes from_host */
771 ch_opts &= ~LPD_ADDFROMLINE;
772 asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
775 "Print-services are not available to your host (%s).", from_host);
776 fhosterr(ch_opts, syserr, usererr);
780 if (ch_opts & LPD_NOPORTCHK)
781 return; /* skip the reserved-port check */
783 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
786 /* same message to both syslog and remote user */
787 asprintf(&syserr, "malformed from-address (%d)", error);
788 fhosterr(ch_opts, syserr, syserr);
792 if (atoi(serv) >= IPPORT_RESERVED) {
793 /* same message to both syslog and remote user */
794 asprintf(&syserr, "connected from invalid port (%s)", serv);
795 fhosterr(ch_opts, syserr, syserr);
801 * Handle fatal errors in chkhost. The first message will optionally be
802 * sent to syslog, the second one is sent to the connecting host.
804 * The idea is that the syslog message is meant for an administrator of a
805 * print server (the host receiving connections), while the usermsg is meant
806 * for a remote user who may or may not be clueful, and may or may not be
807 * doing something nefarious. Some remote users (eg, MS-Windows...) may not
808 * even see whatever message is sent, which is why there's the option to
809 * start 'lpd' with the connection-errors also sent to syslog.
811 * Given that hostnames can theoretically be fairly long (well, over 250
812 * bytes), it would probably be helpful to have the 'from_host' field at
813 * the end of any error messages which include that info.
815 * These are Fatal host-connection errors, so this routine does not return.
818 fhosterr(int ch_opts, char *sysmsg, char *usermsg)
822 * If lpd was started up to print connection errors, then write
823 * the syslog message before the user message.
824 * And for many of the syslog messages, it is helpful to first
825 * write the from_host (if it is known) as a separate syslog
826 * message, since the hostname may be so long.
828 if (ch_opts & LPD_LOGCONNERR) {
829 if (ch_opts & LPD_ADDFROMLINE) {
830 syslog(LOG_WARNING, "for connection from %s:", from_host);
832 syslog(LOG_WARNING, "%s", sysmsg);
836 * Now send the error message to the remote host which is trying
837 * to make the connection.
839 printf("%s [@%s]: %s\n", progname, local_host, usermsg);
843 * Add a minimal delay before exiting (and disconnecting from the
844 * sending-host). This is just in case that machine responds by
845 * INSTANTLY retrying (and instantly re-failing...). This may also
846 * give the other side more time to read the error message.
848 sleep(2); /* a paranoid throttling measure */
852 /* setup server socket for specified address family */
853 /* if af is PF_UNSPEC more than one socket may be returned */
854 /* the returned list is dynamically allocated, so caller needs to free it */
856 socksetup(int af, int debuglvl)
858 struct addrinfo hints, *res, *r;
859 int error, maxs, *s, *socks;
862 memset(&hints, 0, sizeof(hints));
863 hints.ai_flags = AI_PASSIVE;
864 hints.ai_family = af;
865 hints.ai_socktype = SOCK_STREAM;
866 error = getaddrinfo(NULL, "printer", &hints, &res);
868 syslog(LOG_ERR, "%s", gai_strerror(error));
872 /* Count max number of sockets we may open */
873 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
875 socks = malloc((maxs + 1) * sizeof(int));
877 syslog(LOG_ERR, "couldn't allocate memory for sockets");
881 *socks = 0; /* num of sockets counter at start of array */
883 for (r = res; r; r = r->ai_next) {
884 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
886 syslog(LOG_DEBUG, "socket(): %m");
889 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
891 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
896 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
897 sizeof(debuglvl)) < 0) {
898 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
902 if (r->ai_family == AF_INET6) {
903 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
904 &on, sizeof(on)) < 0) {
906 "setsockopt (IPV6_V6ONLY): %m");
911 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
912 syslog(LOG_DEBUG, "bind(): %m");
924 syslog(LOG_ERR, "Couldn't bind to any socket");
935 fprintf(stderr, "usage: lpd [-cdlsW46] [port#]\n");
937 fprintf(stderr, "usage: lpd [-cdlsW] [port#]\n");