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
36 static const char copyright[] =
37 "@(#) Copyright (c) 1983, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
43 static char sccsid[] = "@(#)lpd.c 8.7 (Berkeley) 5/10/95";
45 static const char rcsid[] =
46 "$FreeBSD: src/usr.sbin/lpr/lpd/lpd.c,v 1.12.2.22 2002/06/30 04:09:11 gad Exp $";
50 * lpd -- line printer daemon.
52 * Listen for a connection and perform the requested operation.
55 * check the queue for jobs and print any found.
57 * receive a job from another machine and queue it.
58 * \3printer [users ...] [jobs ...]\n
59 * return the current state of the queue (short form).
60 * \4printer [users ...] [jobs ...]\n
61 * return the current state of the queue (long form).
62 * \5printer person [users ...] [jobs ...]\n
63 * remove jobs from the queue.
65 * Strategy to maintain protected spooling area:
66 * 1. Spooling area is writable only by daemon and spooling group
67 * 2. lpr runs setuid root and setgrp spooling group; it uses
68 * root to access any file it wants (verifying things before
69 * with an access call) and group id to know how it should
70 * set up ownership of files in the spooling area.
71 * 3. Files in spooling area are owned by root, group spooling
72 * group, with mode 660.
73 * 4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
74 * access files and printer. Users can't get to anything
75 * w/o help of lpq and lprm programs.
78 #include <sys/param.h>
80 #include <sys/types.h>
81 #include <sys/socket.h>
85 #include <netinet/in.h>
86 #include <arpa/inet.h>
102 #include "lp.local.h"
103 #include "pathnames.h"
106 int lflag; /* log requests flag */
107 int sflag; /* no incoming port flag */
108 int from_remote; /* from remote socket */
110 int main(int argc, char **_argv);
111 static void reapchild(int _signo);
112 static void mcleanup(int _signo);
113 static void doit(void);
114 static void startup(void);
115 static void chkhost(struct sockaddr *_f, int _ch_opts);
116 static int ckqueue(struct printer *_pp);
117 static void fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
118 static int *socksetup(int _af, int _debuglvl);
119 static void usage(void);
121 /* XXX from libc/net/rcmd.c */
122 extern int __ivaliduser_sa __P((FILE *, struct sockaddr *, socklen_t,
123 const char *, const char *));
127 #define LPD_NOPORTCHK 0001 /* skip reserved-port check */
128 #define LPD_LOGCONNERR 0002 /* (sys)log connection errors */
129 #define LPD_ADDFROMLINE 0004 /* just used for fhosterr() */
132 main(int argc, char **argv)
134 int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
136 struct sockaddr_un un, fromunix;
137 struct sockaddr_storage frominet;
139 sigset_t omask, nmask;
140 struct servent *sp, serv;
141 int inet_flag = 0, inet6_flag = 0;
143 euid = geteuid(); /* these shouldn't be different */
148 gethostname(local_host, sizeof(local_host));
153 errx(EX_NOPERM,"must run as root");
156 while ((i = getopt(argc, argv, "cdlpswW46")) != -1)
159 /* log all kinds of connection-errors to syslog */
160 ch_options |= LPD_LOGCONNERR;
168 case 'p': /* letter initially used for -s */
170 * This will probably be removed with 5.0-release.
173 case 's': /* secure (no inet) */
176 case 'w': /* netbsd uses -w for maxwait */
178 * This will be removed after the release of 4.4, as
179 * it conflicts with -w in netbsd's lpd. For now it
180 * is just a warning, so we won't suddenly break lpd
181 * for anyone who is currently using the option.
184 "NOTE: the -w option has been renamed -W");
186 "NOTE: please change your lpd config to use -W");
189 /* allow connections coming from a non-reserved port */
190 /* (done by some lpr-implementations for MS-Windows) */
191 ch_options |= LPD_NOPORTCHK;
202 errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
206 * The following options are not in FreeBSD (yet?), but are
207 * listed here to "reserve" them, because the option-letters
208 * are used by either NetBSD or OpenBSD (as of July 2001).
210 case 'b': /* set bind-addr */
211 case 'n': /* set max num of children */
212 case 'r': /* allow 'of' for remote ptrs */
213 /* ...[not needed in freebsd] */
218 if (inet_flag && inet6_flag)
226 if ((i = atoi(argv[0])) == 0)
228 if (i < 0 || i > USHRT_MAX)
229 errx(EX_USAGE, "port # %d is invalid", i);
231 serv.s_port = htons(i);
235 sp = getservbyname("printer", "tcp");
237 errx(EX_OSFILE, "printer/tcp: unknown service");
244 * We run chkprintcap right away to catch any errors and blat them
245 * to stderr while we still have it open, rather than sending them
246 * to syslog and leaving the user wondering why lpd started and
247 * then stopped. There should probably be a command-line flag to
248 * ignore errors from chkprintcap.
255 err(EX_OSERR, "cannot fork");
256 } else if (pid == 0) { /* child */
257 execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
258 err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
260 if (waitpid(pid, &status, 0) < 0) {
261 err(EX_OSERR, "cannot wait");
263 if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
264 errx(EX_OSFILE, "%d errors in printcap file, exiting",
265 WEXITSTATUS(status));
270 * Set up standard environment by detaching from the parent.
275 openlog("lpd", LOG_PID, LOG_LPR);
276 syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
277 socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
280 * NB: This depends on O_NONBLOCK semantics doing the right thing;
281 * i.e., applying only to the O_EXLOCK and not to the rest of the
282 * open/creation. As of 1997-12-02, this is the case for commonly-
283 * used filesystems. There are other places in this code which
284 * make the same assumption.
286 lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
289 if (errno == EWOULDBLOCK) /* active daemon present */
291 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
294 fcntl(lfd, F_SETFL, 0); /* turn off non-blocking mode */
297 * write process id for others to know
299 sprintf(line, "%u\n", getpid());
301 if (write(lfd, line, f) != f) {
302 syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
305 signal(SIGCHLD, reapchild);
307 * Restart all the printers.
310 (void) unlink(_PATH_SOCKETNAME);
311 funix = socket(AF_UNIX, SOCK_STREAM, 0);
313 syslog(LOG_ERR, "socket: %m");
318 sigaddset(&nmask, SIGHUP);
319 sigaddset(&nmask, SIGINT);
320 sigaddset(&nmask, SIGQUIT);
321 sigaddset(&nmask, SIGTERM);
322 sigprocmask(SIG_BLOCK, &nmask, &omask);
325 signal(SIGHUP, mcleanup);
326 signal(SIGINT, mcleanup);
327 signal(SIGQUIT, mcleanup);
328 signal(SIGTERM, mcleanup);
329 memset(&un, 0, sizeof(un));
330 un.sun_family = AF_UNIX;
331 strcpy(un.sun_path, _PATH_SOCKETNAME);
333 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
335 if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
336 syslog(LOG_ERR, "ubind: %m");
340 sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
341 FD_ZERO(&defreadfds);
342 FD_SET(funix, &defreadfds);
345 finet = socksetup(family, socket_debug);
347 finet = NULL; /* pretend we couldn't open TCP socket. */
349 for (i = 1; i <= *finet; i++) {
350 FD_SET(finet[i], &defreadfds);
355 * Main loop: accept, do a request, continue.
357 memset(&frominet, 0, sizeof(frominet));
358 memset(&fromunix, 0, sizeof(fromunix));
360 syslog(LOG_INFO, "lpd startup: ready to accept requests");
362 * XXX - should be redone for multi-protocol
368 FD_COPY(&defreadfds, &readfds);
369 nfds = select(20, &readfds, 0, 0, 0);
371 if (nfds < 0 && errno != EINTR)
372 syslog(LOG_WARNING, "select: %m");
375 domain = -1; /* avoid compile-time warning */
376 s = -1; /* avoid compile-time warning */
377 if (FD_ISSET(funix, &readfds)) {
378 domain = AF_UNIX, fromlen = sizeof(fromunix);
380 (struct sockaddr *)&fromunix, &fromlen);
382 for (i = 1; i <= *finet; i++)
383 if (FD_ISSET(finet[i], &readfds)) {
385 fromlen = sizeof(frominet);
387 (struct sockaddr *)&frominet,
393 syslog(LOG_WARNING, "accept: %m");
398 * Note that printjob() also plays around with
399 * signal-handling routines, and may need to be
400 * changed when making changes to signal-handling.
402 signal(SIGCHLD, SIG_DFL);
403 signal(SIGHUP, SIG_IGN);
404 signal(SIGINT, SIG_IGN);
405 signal(SIGQUIT, SIG_IGN);
406 signal(SIGTERM, SIG_IGN);
408 if (sflag == 0 && finet) {
409 for (i = 1; i <= *finet; i++)
410 (void)close(finet[i]);
414 if (domain == AF_INET) {
415 /* for both AF_INET and AF_INET6 */
417 chkhost((struct sockaddr *)&frominet,
429 reapchild(int signo __unused)
433 while (wait3(&status, WNOHANG, 0) > 0)
441 * XXX syslog(3) is not signal-safe.
445 syslog(LOG_INFO, "exiting on signal %d", signo);
447 syslog(LOG_INFO, "exiting");
449 unlink(_PATH_SOCKETNAME);
454 * Stuff for handling job specifications
456 char *user[MAXUSERS]; /* users to process */
457 int users; /* # of users in user array */
458 int requ[MAXREQUESTS]; /* job number of spool entries */
459 int requests; /* # of spool requests */
460 char *person; /* name of person doing lprm */
462 /* buffer to hold the client's machine-name */
463 static char frombuf[MAXHOSTNAMELEN];
464 char cbuf[BUFSIZ]; /* command line buffer */
465 const char *cmdnames[] = {
480 struct printer myprinter, *pp = &myprinter;
482 init_printer(&myprinter);
487 if (cp >= &cbuf[sizeof(cbuf) - 1])
488 fatal(0, "Command line too long");
489 if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
491 fatal(0, "Lost connection");
494 } while (*cp++ != '\n');
498 if (*cp >= '\1' && *cp <= '\5')
499 syslog(LOG_INFO, "%s requests %s %s",
500 from_host, cmdnames[(u_char)*cp], cp+1);
502 syslog(LOG_INFO, "bad request (%d) from %s",
506 case CMD_CHECK_QUE: /* check the queue, print any jobs there */
509 case CMD_TAKE_THIS: /* receive files to be queued */
511 syslog(LOG_INFO, "illegal request (%d)", *cp);
516 case CMD_SHOWQ_SHORT: /* display the queue (short form) */
517 case CMD_SHOWQ_LONG: /* display the queue (long form) */
518 /* XXX - this all needs to be redone. */
531 if (requests >= MAXREQUESTS)
532 fatal(0, "Too many requests");
533 requ[requests++] = atoi(cp);
535 if (users >= MAXUSERS)
536 fatal(0, "Too many users");
540 status = getprintcap(printer, pp);
542 fatal(pp, "%s", pcaperr(status));
543 displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
545 case CMD_RMJOB: /* remove a job from the queue */
547 syslog(LOG_INFO, "illegal request (%d)", *cp);
551 while (*cp && *cp != ' ')
568 if (requests >= MAXREQUESTS)
569 fatal(0, "Too many requests");
570 requ[requests++] = atoi(cp);
572 if (users >= MAXUSERS)
573 fatal(0, "Too many users");
580 fatal(0, "Illegal service request");
585 * Make a pass through the printcap database and start printing any
586 * files left from the last time the machine went down.
591 int pid, status, more;
592 struct printer myprinter, *pp = &myprinter;
594 more = firstprinter(pp, &status);
598 if (ckqueue(pp) <= 0) {
602 syslog(LOG_INFO, "lpd startup: work for %s",
604 if ((pid = fork()) < 0) {
605 syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
616 more = nextprinter(pp, &status);
620 "lpd startup: printcap entry for %s has errors, skipping",
621 pp->printer ? pp->printer : "<noname?>");
622 } while (more && status);
627 * Make sure there's some work to do before forking off a child
630 ckqueue(struct printer *pp)
632 register struct dirent *d;
636 spooldir = pp->spool_dir;
637 if ((dirp = opendir(spooldir)) == NULL)
639 while ((d = readdir(dirp)) != NULL) {
640 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
641 continue; /* daemon control files only */
643 return (1); /* found something */
649 #define DUMMY ":nobody::"
652 * Check to see if the host connecting to this host has access to any
653 * lpd services on this host.
656 chkhost(struct sockaddr *f, int ch_opts)
658 struct addrinfo hints, *res, *r;
659 register FILE *hostf;
660 char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
661 char serv[NI_MAXSERV];
662 char *syserr, *usererr;
663 int error, errsav, fpass, good, wantsl;
666 if (ch_opts & LPD_LOGCONNERR)
667 wantsl = 1; /* also syslog the errors */
671 /* Need real hostname for temporary filenames */
672 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
676 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
677 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID);
680 "can not determine hostname for remote host (%d,%d)",
683 "Host name for your address is not known");
684 fhosterr(ch_opts, syserr, usererr);
688 "Host name for remote host (%s) not known (%d)",
691 "Host name for your address (%s) is not known",
693 fhosterr(ch_opts, syserr, usererr);
697 strlcpy(frombuf, hostbuf, sizeof(frombuf));
699 ch_opts |= LPD_ADDFROMLINE;
701 /* Need address in stringform for comparison (no DNS lookup here) */
702 error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
703 NI_NUMERICHOST | NI_WITHSCOPEID);
705 asprintf(&syserr, "Cannot print IP address (error %d)",
707 asprintf(&usererr, "Cannot print IP address for your host");
708 fhosterr(ch_opts, syserr, usererr);
711 from_ip = strdup(hostbuf);
713 /* Reject numeric addresses */
714 memset(&hints, 0, sizeof(hints));
715 hints.ai_family = family;
716 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
717 hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
718 if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
720 /* This syslog message already includes from_host */
721 ch_opts &= ~LPD_ADDFROMLINE;
722 asprintf(&syserr, "reverse lookup results in non-FQDN %s",
724 /* same message to both syslog and remote user */
725 fhosterr(ch_opts, syserr, syserr);
729 /* Check for spoof, ala rlogind */
730 memset(&hints, 0, sizeof(hints));
731 hints.ai_family = family;
732 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
733 error = getaddrinfo(from_host, NULL, &hints, &res);
735 asprintf(&syserr, "dns lookup for address %s failed: %s",
736 from_ip, gai_strerror(error));
737 asprintf(&usererr, "hostname for your address (%s) unknown: %s",
738 from_ip, gai_strerror(error));
739 fhosterr(ch_opts, syserr, usererr);
743 for (r = res; good == 0 && r; r = r->ai_next) {
744 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
745 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID);
746 if (!error && !strcmp(from_ip, ip))
752 asprintf(&syserr, "address for remote host (%s) not matched",
755 "address for your hostname (%s) not matched", from_ip);
756 fhosterr(ch_opts, syserr, usererr);
761 hostf = fopen(_PATH_HOSTSEQUIV, "r");
764 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
765 (void) fclose(hostf);
768 (void) fclose(hostf);
772 hostf = fopen(_PATH_HOSTSLPD, "r");
775 /* This syslog message already includes from_host */
776 ch_opts &= ~LPD_ADDFROMLINE;
777 asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
780 "Print-services are not available to your host (%s).", from_host);
781 fhosterr(ch_opts, syserr, usererr);
785 if (ch_opts & LPD_NOPORTCHK)
786 return; /* skip the reserved-port check */
788 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
791 /* same message to both syslog and remote user */
792 asprintf(&syserr, "malformed from-address (%d)", error);
793 fhosterr(ch_opts, syserr, syserr);
797 if (atoi(serv) >= IPPORT_RESERVED) {
798 /* same message to both syslog and remote user */
799 asprintf(&syserr, "connected from invalid port (%s)", serv);
800 fhosterr(ch_opts, syserr, syserr);
806 * Handle fatal errors in chkhost. The first message will optionally be
807 * sent to syslog, the second one is sent to the connecting host.
809 * The idea is that the syslog message is meant for an administrator of a
810 * print server (the host receiving connections), while the usermsg is meant
811 * for a remote user who may or may not be clueful, and may or may not be
812 * doing something nefarious. Some remote users (eg, MS-Windows...) may not
813 * even see whatever message is sent, which is why there's the option to
814 * start 'lpd' with the connection-errors also sent to syslog.
816 * Given that hostnames can theoretically be fairly long (well, over 250
817 * bytes), it would probably be helpful to have the 'from_host' field at
818 * the end of any error messages which include that info.
820 * These are Fatal host-connection errors, so this routine does not return.
823 fhosterr(int ch_opts, char *sysmsg, char *usermsg)
827 * If lpd was started up to print connection errors, then write
828 * the syslog message before the user message.
829 * And for many of the syslog messages, it is helpful to first
830 * write the from_host (if it is known) as a separate syslog
831 * message, since the hostname may be so long.
833 if (ch_opts & LPD_LOGCONNERR) {
834 if (ch_opts & LPD_ADDFROMLINE) {
835 syslog(LOG_WARNING, "for connection from %s:", from_host);
837 syslog(LOG_WARNING, "%s", sysmsg);
841 * Now send the error message to the remote host which is trying
842 * to make the connection.
844 printf("%s [@%s]: %s\n", progname, local_host, usermsg);
848 * Add a minimal delay before exiting (and disconnecting from the
849 * sending-host). This is just in case that machine responds by
850 * INSTANTLY retrying (and instantly re-failing...). This may also
851 * give the other side more time to read the error message.
853 sleep(2); /* a paranoid throttling measure */
857 /* setup server socket for specified address family */
858 /* if af is PF_UNSPEC more than one socket may be returned */
859 /* the returned list is dynamically allocated, so caller needs to free it */
861 socksetup(int af, int debuglvl)
863 struct addrinfo hints, *res, *r;
864 int error, maxs, *s, *socks;
867 memset(&hints, 0, sizeof(hints));
868 hints.ai_flags = AI_PASSIVE;
869 hints.ai_family = af;
870 hints.ai_socktype = SOCK_STREAM;
871 error = getaddrinfo(NULL, "printer", &hints, &res);
873 syslog(LOG_ERR, "%s", gai_strerror(error));
877 /* Count max number of sockets we may open */
878 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
880 socks = malloc((maxs + 1) * sizeof(int));
882 syslog(LOG_ERR, "couldn't allocate memory for sockets");
886 *socks = 0; /* num of sockets counter at start of array */
888 for (r = res; r; r = r->ai_next) {
889 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
891 syslog(LOG_DEBUG, "socket(): %m");
894 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
896 syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
901 if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
902 sizeof(debuglvl)) < 0) {
903 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
907 #ifdef IPV6_BINDV6ONLY
908 if (r->ai_family == AF_INET6) {
909 if (setsockopt(*s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
910 &on, sizeof(on)) < 0) {
912 "setsockopt (IPV6_BINDV6ONLY): %m");
918 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
919 syslog(LOG_DEBUG, "bind(): %m");
931 syslog(LOG_ERR, "Couldn't bind to any socket");
942 fprintf(stderr, "usage: lpd [-cdlsW46] [port#]\n");
944 fprintf(stderr, "usage: lpd [-cdlsW] [port#]\n");