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 * 4. Neither the name of the University nor the names of its contributors
15 * may be used to endorse or promote products derived from this software
16 * without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 static const char copyright[] =
33 "@(#) Copyright (c) 1983, 1993, 1994\n\
34 The Regents of the University of California. All rights reserved.\n";
39 static char sccsid[] = "@(#)lpd.c 8.7 (Berkeley) 5/10/95";
43 #include "lp.cdefs.h" /* A cross-platform version of <sys/cdefs.h> */
44 __FBSDID("$FreeBSD$");
47 * lpd -- line printer daemon.
49 * Listen for a connection and perform the requested operation.
52 * check the queue for jobs and print any found.
54 * receive a job from another machine and queue it.
55 * \3printer [users ...] [jobs ...]\n
56 * return the current state of the queue (short form).
57 * \4printer [users ...] [jobs ...]\n
58 * return the current state of the queue (long form).
59 * \5printer person [users ...] [jobs ...]\n
60 * remove jobs from the queue.
62 * Strategy to maintain protected spooling area:
63 * 1. Spooling area is writable only by daemon and spooling group
64 * 2. lpr runs setuid root and setgrp spooling group; it uses
65 * root to access any file it wants (verifying things before
66 * with an access call) and group id to know how it should
67 * set up ownership of files in the spooling area.
68 * 3. Files in spooling area are owned by root, group spooling
69 * group, with mode 660.
70 * 4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
71 * access files and printer. Users can't get to anything
72 * w/o help of lpq and lprm programs.
75 #include <sys/param.h>
77 #include <sys/types.h>
78 #include <sys/socket.h>
82 #include <netinet/in.h>
83 #include <arpa/inet.h>
100 #include "pathnames.h"
103 int lflag; /* log requests flag */
104 int sflag; /* no incoming port flag */
105 int from_remote; /* from remote socket */
107 int main(int argc, char **_argv);
108 static void reapchild(int _signo);
109 static void mcleanup(int _signo);
110 static void doit(void);
111 static void startup(void);
112 static void chkhost(struct sockaddr *_f, int _ch_opts);
113 static int ckqueue(struct printer *_pp);
114 static void fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
115 static int *socksetup(int _af, int _debuglvl);
116 static void usage(void);
118 /* XXX from libc/net/rcmd.c */
119 extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
120 const char *, const char *);
124 #define LPD_NOPORTCHK 0001 /* skip reserved-port check */
125 #define LPD_LOGCONNERR 0002 /* (sys)log connection errors */
126 #define LPD_ADDFROMLINE 0004 /* just used for fhosterr() */
129 main(int argc, char **argv)
131 int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
133 struct sockaddr_un un, fromunix;
134 struct sockaddr_storage frominet;
136 sigset_t omask, nmask;
137 struct servent *sp, serv;
138 int inet_flag = 0, inet6_flag = 0;
140 euid = geteuid(); /* these shouldn't be different */
145 gethostname(local_host, sizeof(local_host));
150 errx(EX_NOPERM,"must run as root");
153 while ((i = getopt(argc, argv, "cdlpswW46")) != -1)
156 /* log all kinds of connection-errors to syslog */
157 ch_options |= LPD_LOGCONNERR;
165 case 'p': /* letter initially used for -s */
167 * This will probably be removed with 5.0-release.
170 case 's': /* secure (no inet) */
173 case 'w': /* netbsd uses -w for maxwait */
175 * This will be removed after the release of 4.4, as
176 * it conflicts with -w in netbsd's lpd. For now it
177 * is just a warning, so we won't suddenly break lpd
178 * for anyone who is currently using the option.
181 "NOTE: the -w option has been renamed -W");
183 "NOTE: please change your lpd config to use -W");
186 /* allow connections coming from a non-reserved port */
187 /* (done by some lpr-implementations for MS-Windows) */
188 ch_options |= LPD_NOPORTCHK;
199 errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
203 * The following options are not in FreeBSD (yet?), but are
204 * listed here to "reserve" them, because the option-letters
205 * are used by either NetBSD or OpenBSD (as of July 2001).
207 case 'b': /* set bind-addr */
208 case 'n': /* set max num of children */
209 case 'r': /* allow 'of' for remote ptrs */
210 /* ...[not needed in freebsd] */
215 if (inet_flag && inet6_flag)
223 if ((i = atoi(argv[0])) == 0)
225 if (i < 0 || i > USHRT_MAX)
226 errx(EX_USAGE, "port # %d is invalid", i);
228 serv.s_port = htons(i);
232 sp = getservbyname("printer", "tcp");
234 errx(EX_OSFILE, "printer/tcp: unknown service");
241 * We run chkprintcap right away to catch any errors and blat them
242 * to stderr while we still have it open, rather than sending them
243 * to syslog and leaving the user wondering why lpd started and
244 * then stopped. There should probably be a command-line flag to
245 * ignore errors from chkprintcap.
252 err(EX_OSERR, "cannot fork");
253 } else if (pid == 0) { /* child */
254 execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
255 err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
257 if (waitpid(pid, &status, 0) < 0) {
258 err(EX_OSERR, "cannot wait");
260 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
261 errx(EX_OSFILE, "%d errors in printcap file, exiting",
262 WEXITSTATUS(status));
267 * Set up standard environment by detaching from the parent.
272 openlog("lpd", LOG_PID, LOG_LPR);
273 syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
274 socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
277 * NB: This depends on O_NONBLOCK semantics doing the right thing;
278 * i.e., applying only to the O_EXLOCK and not to the rest of the
279 * open/creation. As of 1997-12-02, this is the case for commonly-
280 * used filesystems. There are other places in this code which
281 * make the same assumption.
283 lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
286 if (errno == EWOULDBLOCK) /* active daemon present */
288 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
291 fcntl(lfd, F_SETFL, 0); /* turn off non-blocking mode */
294 * write process id for others to know
296 sprintf(line, "%u\n", getpid());
298 if (write(lfd, line, f) != f) {
299 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
302 signal(SIGCHLD, reapchild);
304 * Restart all the printers.
307 (void) unlink(_PATH_SOCKETNAME);
308 funix = socket(AF_UNIX, SOCK_STREAM, 0);
310 syslog(LOG_ERR, "socket: %m");
315 sigaddset(&nmask, SIGHUP);
316 sigaddset(&nmask, SIGINT);
317 sigaddset(&nmask, SIGQUIT);
318 sigaddset(&nmask, SIGTERM);
319 sigprocmask(SIG_BLOCK, &nmask, &omask);
322 signal(SIGHUP, mcleanup);
323 signal(SIGINT, mcleanup);
324 signal(SIGQUIT, mcleanup);
325 signal(SIGTERM, mcleanup);
326 memset(&un, 0, sizeof(un));
327 un.sun_family = AF_UNIX;
328 strcpy(un.sun_path, _PATH_SOCKETNAME);
330 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
332 if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
333 syslog(LOG_ERR, "ubind: %m");
337 sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
338 FD_ZERO(&defreadfds);
339 FD_SET(funix, &defreadfds);
342 finet = socksetup(family, socket_debug);
344 finet = NULL; /* pretend we couldn't open TCP socket. */
346 for (i = 1; i <= *finet; i++) {
347 FD_SET(finet[i], &defreadfds);
352 * Main loop: accept, do a request, continue.
354 memset(&frominet, 0, sizeof(frominet));
355 memset(&fromunix, 0, sizeof(fromunix));
357 syslog(LOG_INFO, "lpd startup: ready to accept requests");
359 * XXX - should be redone for multi-protocol
365 FD_COPY(&defreadfds, &readfds);
366 nfds = select(20, &readfds, 0, 0, 0);
368 if (nfds < 0 && errno != EINTR)
369 syslog(LOG_WARNING, "select: %m");
372 domain = -1; /* avoid compile-time warning */
373 s = -1; /* avoid compile-time warning */
374 if (FD_ISSET(funix, &readfds)) {
375 domain = AF_UNIX, fromlen = sizeof(fromunix);
377 (struct sockaddr *)&fromunix, &fromlen);
379 for (i = 1; i <= *finet; i++)
380 if (FD_ISSET(finet[i], &readfds)) {
382 fromlen = sizeof(frominet);
384 (struct sockaddr *)&frominet,
390 syslog(LOG_WARNING, "accept: %m");
395 * Note that printjob() also plays around with
396 * signal-handling routines, and may need to be
397 * changed when making changes to signal-handling.
399 signal(SIGCHLD, SIG_DFL);
400 signal(SIGHUP, SIG_IGN);
401 signal(SIGINT, SIG_IGN);
402 signal(SIGQUIT, SIG_IGN);
403 signal(SIGTERM, SIG_IGN);
405 if (sflag == 0 && finet) {
406 for (i = 1; i <= *finet; i++)
407 (void)close(finet[i]);
409 dup2(s, STDOUT_FILENO);
411 if (domain == AF_INET) {
412 /* for both AF_INET and AF_INET6 */
414 chkhost((struct sockaddr *)&frominet,
426 reapchild(int signo __unused)
430 while (wait3(&status, WNOHANG, 0) > 0)
438 * XXX syslog(3) is not signal-safe.
442 syslog(LOG_INFO, "exiting on signal %d", signo);
444 syslog(LOG_INFO, "exiting");
446 unlink(_PATH_SOCKETNAME);
451 * Stuff for handling job specifications
453 char *user[MAXUSERS]; /* users to process */
454 int users; /* # of users in user array */
455 int requ[MAXREQUESTS]; /* job number of spool entries */
456 int requests; /* # of spool requests */
457 char *person; /* name of person doing lprm */
459 /* buffer to hold the client's machine-name */
460 static char frombuf[MAXHOSTNAMELEN];
461 char cbuf[BUFSIZ]; /* command line buffer */
462 const char *cmdnames[] = {
477 struct printer myprinter, *pp = &myprinter;
479 init_printer(&myprinter);
484 if (cp >= &cbuf[sizeof(cbuf) - 1])
485 fatal(0, "Command line too long");
486 if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
488 fatal(0, "Lost connection");
491 } while (*cp++ != '\n');
495 if (*cp >= '\1' && *cp <= '\5')
496 syslog(LOG_INFO, "%s requests %s %s",
497 from_host, cmdnames[(u_char)*cp], cp+1);
499 syslog(LOG_INFO, "bad request (%d) from %s",
503 case CMD_CHECK_QUE: /* check the queue, print any jobs there */
506 case CMD_TAKE_THIS: /* receive files to be queued */
508 syslog(LOG_INFO, "illegal request (%d)", *cp);
513 case CMD_SHOWQ_SHORT: /* display the queue (short form) */
514 case CMD_SHOWQ_LONG: /* display the queue (long form) */
515 /* XXX - this all needs to be redone. */
528 if (requests >= MAXREQUESTS)
529 fatal(0, "Too many requests");
530 requ[requests++] = atoi(cp);
532 if (users >= MAXUSERS)
533 fatal(0, "Too many users");
537 status = getprintcap(printer, pp);
539 fatal(pp, "%s", pcaperr(status));
540 displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
542 case CMD_RMJOB: /* remove a job from the queue */
544 syslog(LOG_INFO, "illegal request (%d)", *cp);
548 while (*cp && *cp != ' ')
565 if (requests >= MAXREQUESTS)
566 fatal(0, "Too many requests");
567 requ[requests++] = atoi(cp);
569 if (users >= MAXUSERS)
570 fatal(0, "Too many users");
577 fatal(0, "Illegal service request");
582 * Make a pass through the printcap database and start printing any
583 * files left from the last time the machine went down.
588 int pid, status, more;
589 struct printer myprinter, *pp = &myprinter;
591 more = firstprinter(pp, &status);
595 if (ckqueue(pp) <= 0) {
599 syslog(LOG_INFO, "lpd startup: work for %s",
601 if ((pid = fork()) < 0) {
602 syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
613 more = nextprinter(pp, &status);
617 "lpd startup: printcap entry for %s has errors, skipping",
618 pp->printer ? pp->printer : "<noname?>");
619 } while (more && status);
624 * Make sure there's some work to do before forking off a child
627 ckqueue(struct printer *pp)
629 register struct dirent *d;
633 spooldir = pp->spool_dir;
634 if ((dirp = opendir(spooldir)) == NULL)
636 while ((d = readdir(dirp)) != NULL) {
637 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
638 continue; /* daemon control files only */
640 return (1); /* found something */
646 #define DUMMY ":nobody::"
649 * Check to see if the host connecting to this host has access to any
650 * lpd services on this host.
653 chkhost(struct sockaddr *f, int ch_opts)
655 struct addrinfo hints, *res, *r;
656 register FILE *hostf;
657 char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
658 char serv[NI_MAXSERV];
659 char *syserr, *usererr;
660 int error, errsav, fpass, good, wantsl;
663 if (ch_opts & LPD_LOGCONNERR)
664 wantsl = 1; /* also syslog the errors */
668 /* Need real hostname for temporary filenames */
669 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
673 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
674 NULL, 0, NI_NUMERICHOST);
677 "can not determine hostname for remote host (%d,%d)",
680 "Host name for your address is not known");
681 fhosterr(ch_opts, syserr, usererr);
685 "Host name for remote host (%s) not known (%d)",
688 "Host name for your address (%s) is not known",
690 fhosterr(ch_opts, syserr, usererr);
694 strlcpy(frombuf, hostbuf, sizeof(frombuf));
696 ch_opts |= LPD_ADDFROMLINE;
698 /* Need address in stringform for comparison (no DNS lookup here) */
699 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
702 asprintf(&syserr, "Cannot print IP address (error %d)",
704 asprintf(&usererr, "Cannot print IP address for your host");
705 fhosterr(ch_opts, syserr, usererr);
708 from_ip = strdup(hostbuf);
710 /* Reject numeric addresses */
711 memset(&hints, 0, sizeof(hints));
712 hints.ai_family = family;
713 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
714 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
715 if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
717 /* This syslog message already includes from_host */
718 ch_opts &= ~LPD_ADDFROMLINE;
719 asprintf(&syserr, "reverse lookup results in non-FQDN %s",
721 /* same message to both syslog and remote user */
722 fhosterr(ch_opts, syserr, syserr);
726 /* Check for spoof, ala rlogind */
727 memset(&hints, 0, sizeof(hints));
728 hints.ai_family = family;
729 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
730 error = getaddrinfo(from_host, NULL, &hints, &res);
732 asprintf(&syserr, "dns lookup for address %s failed: %s",
733 from_ip, gai_strerror(error));
734 asprintf(&usererr, "hostname for your address (%s) unknown: %s",
735 from_ip, gai_strerror(error));
736 fhosterr(ch_opts, syserr, usererr);
740 for (r = res; good == 0 && r; r = r->ai_next) {
741 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
742 NULL, 0, NI_NUMERICHOST);
743 if (!error && !strcmp(from_ip, ip))
749 asprintf(&syserr, "address for remote host (%s) not matched",
752 "address for your hostname (%s) not matched", from_ip);
753 fhosterr(ch_opts, syserr, usererr);
758 hostf = fopen(_PATH_HOSTSEQUIV, "r");
761 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
762 (void) fclose(hostf);
765 (void) fclose(hostf);
769 hostf = fopen(_PATH_HOSTSLPD, "r");
772 /* This syslog message already includes from_host */
773 ch_opts &= ~LPD_ADDFROMLINE;
774 asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
777 "Print-services are not available to your host (%s).", from_host);
778 fhosterr(ch_opts, syserr, usererr);
782 if (ch_opts & LPD_NOPORTCHK)
783 return; /* skip the reserved-port check */
785 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
788 /* same message to both syslog and remote user */
789 asprintf(&syserr, "malformed from-address (%d)", error);
790 fhosterr(ch_opts, syserr, syserr);
794 if (atoi(serv) >= IPPORT_RESERVED) {
795 /* same message to both syslog and remote user */
796 asprintf(&syserr, "connected from invalid port (%s)", serv);
797 fhosterr(ch_opts, syserr, syserr);
803 * Handle fatal errors in chkhost. The first message will optionally be
804 * sent to syslog, the second one is sent to the connecting host.
806 * The idea is that the syslog message is meant for an administrator of a
807 * print server (the host receiving connections), while the usermsg is meant
808 * for a remote user who may or may not be clueful, and may or may not be
809 * doing something nefarious. Some remote users (eg, MS-Windows...) may not
810 * even see whatever message is sent, which is why there's the option to
811 * start 'lpd' with the connection-errors also sent to syslog.
813 * Given that hostnames can theoretically be fairly long (well, over 250
814 * bytes), it would probably be helpful to have the 'from_host' field at
815 * the end of any error messages which include that info.
817 * These are Fatal host-connection errors, so this routine does not return.
820 fhosterr(int ch_opts, char *sysmsg, char *usermsg)
824 * If lpd was started up to print connection errors, then write
825 * the syslog message before the user message.
826 * And for many of the syslog messages, it is helpful to first
827 * write the from_host (if it is known) as a separate syslog
828 * message, since the hostname may be so long.
830 if (ch_opts & LPD_LOGCONNERR) {
831 if (ch_opts & LPD_ADDFROMLINE) {
832 syslog(LOG_WARNING, "for connection from %s:", from_host);
834 syslog(LOG_WARNING, "%s", sysmsg);
838 * Now send the error message to the remote host which is trying
839 * to make the connection.
841 printf("%s [@%s]: %s\n", progname, local_host, usermsg);
845 * Add a minimal delay before exiting (and disconnecting from the
846 * sending-host). This is just in case that machine responds by
847 * INSTANTLY retrying (and instantly re-failing...). This may also
848 * give the other side more time to read the error message.
850 sleep(2); /* a paranoid throttling measure */
854 /* setup server socket for specified address family */
855 /* if af is PF_UNSPEC more than one socket may be returned */
856 /* the returned list is dynamically allocated, so caller needs to free it */
858 socksetup(int af, int debuglvl)
860 struct addrinfo hints, *res, *r;
861 int error, maxs, *s, *socks;
864 memset(&hints, 0, sizeof(hints));
865 hints.ai_flags = AI_PASSIVE;
866 hints.ai_family = af;
867 hints.ai_socktype = SOCK_STREAM;
868 error = getaddrinfo(NULL, "printer", &hints, &res);
870 syslog(LOG_ERR, "%s", gai_strerror(error));
874 /* Count max number of sockets we may open */
875 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
877 socks = malloc((maxs + 1) * sizeof(int));
879 syslog(LOG_ERR, "couldn't allocate memory for sockets");
883 *socks = 0; /* num of sockets counter at start of array */
885 for (r = res; r; r = r->ai_next) {
886 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
888 syslog(LOG_DEBUG, "socket(): %m");
891 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
893 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
898 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
899 sizeof(debuglvl)) < 0) {
900 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
904 if (r->ai_family == AF_INET6) {
905 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
906 &on, sizeof(on)) < 0) {
908 "setsockopt (IPV6_V6ONLY): %m");
913 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
914 syslog(LOG_DEBUG, "bind(): %m");
926 syslog(LOG_ERR, "Couldn't bind to any socket");
937 fprintf(stderr, "usage: lpd [-cdlsW46] [port#]\n");
939 fprintf(stderr, "usage: lpd [-cdlsW] [port#]\n");