Home | History | Annotate | Line # | Download | only in lpd
lpd.c revision 1.51
      1 /*	$NetBSD: lpd.c,v 1.51 2005/06/02 05:57:03 lukem Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1983, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     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.
     19  *
     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
     30  * SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 
     35 #ifndef lint
     36 __COPYRIGHT("@(#) Copyright (c) 1983, 1993, 1994\n\
     37 	The Regents of the University of California.  All rights reserved.\n");
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 #if 0
     42 static char sccsid[] = "@(#)lpd.c	8.7 (Berkeley) 5/10/95";
     43 #else
     44 __RCSID("$NetBSD: lpd.c,v 1.51 2005/06/02 05:57:03 lukem Exp $");
     45 #endif
     46 #endif /* not lint */
     47 
     48 /*
     49  * lpd -- line printer daemon.
     50  *
     51  * Listen for a connection and perform the requested operation.
     52  * Operations are:
     53  *	\1printer\n
     54  *		check the queue for jobs and print any found.
     55  *	\2printer\n
     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.
     63  *
     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.
     75  */
     76 
     77 #include <sys/param.h>
     78 #include <sys/wait.h>
     79 #include <sys/types.h>
     80 #include <sys/socket.h>
     81 #include <sys/un.h>
     82 #include <sys/stat.h>
     83 #include <sys/file.h>
     84 #include <sys/poll.h>
     85 #include <netinet/in.h>
     86 
     87 #include <err.h>
     88 #include <netdb.h>
     89 #include <unistd.h>
     90 #include <syslog.h>
     91 #include <signal.h>
     92 #include <errno.h>
     93 #include <fcntl.h>
     94 #include <dirent.h>
     95 #include <stdarg.h>
     96 #include <stdio.h>
     97 #include <stdlib.h>
     98 #include <string.h>
     99 #include <ctype.h>
    100 #include <arpa/inet.h>
    101 
    102 #ifdef LIBWRAP
    103 #include <tcpd.h>
    104 #endif
    105 
    106 #include "lp.h"
    107 #include "lp.local.h"
    108 #include "pathnames.h"
    109 #include "extern.h"
    110 
    111 /* XXX from libc/net/rcmd.c */
    112 extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
    113 			   const char *, const char *);
    114 
    115 #ifdef LIBWRAP
    116 int allow_severity = LOG_AUTH|LOG_INFO;
    117 int deny_severity = LOG_AUTH|LOG_WARNING;
    118 #endif
    119 
    120 int	lflag;				/* log requests flag */
    121 int	rflag;				/* allow of for remote printers */
    122 int	sflag;				/* secure (no inet) flag */
    123 int	from_remote;			/* from remote socket */
    124 char	**blist;			/* list of addresses to bind(2) to */
    125 int	blist_size;
    126 int	blist_addrs;
    127 
    128 int			main(int, char **);
    129 static void		reapchild(int);
    130 static void		mcleanup(int);
    131 static void		doit(void);
    132 static void		startup(void);
    133 static void		chkhost(struct sockaddr *, int);
    134 static int		ckqueue(char *);
    135 static void		usage(void);
    136 static struct pollfd	*socksetup(int, int, const char *, int *);
    137 
    138 uid_t	uid, euid;
    139 int child_count;
    140 
    141 #define LPD_NOPORTCHK	0001		/* skip reserved-port check */
    142 
    143 int
    144 main(int argc, char **argv)
    145 {
    146 	struct sockaddr_storage from;
    147 	socklen_t fromlen;
    148 	sigset_t nmask, omask;
    149 	int lfd, errs, i, f, nfds;
    150 	struct pollfd *socks;
    151 	int child_max = 32;	/* more than enough to hose the system */
    152 	int options = 0, check_options = 0;
    153 	struct servent *sp;
    154 	const char *port = "printer";
    155 	char **newblist;
    156 
    157 	euid = geteuid();	/* these shouldn't be different */
    158 	uid = getuid();
    159 	gethostname(host, sizeof(host));
    160 	host[sizeof(host) - 1] = '\0';
    161 	name = argv[0];
    162 
    163 	errs = 0;
    164 	while ((i = getopt(argc, argv, "b:dln:srw:W")) != -1)
    165 		switch (i) {
    166 		case 'b':
    167 			if (blist_addrs >= blist_size) {
    168 				newblist = realloc(blist,
    169 				    blist_size + sizeof(char *) * 4);
    170 				if (newblist == NULL)
    171 					err(1, "cant allocate bind addr list");
    172 				blist = newblist;
    173 				blist_size += sizeof(char *) * 4;
    174 			}
    175 			blist[blist_addrs++] = strdup(optarg);
    176 			break;
    177 		case 'd':
    178 			options |= SO_DEBUG;
    179 			break;
    180 		case 'l':
    181 			lflag++;
    182 			break;
    183 		case 'n':
    184 			child_max = atoi(optarg);
    185 			if (child_max < 0 || child_max > 1024)
    186 				errx(1, "invalid number of children: %s",
    187 				    optarg);
    188 			break;
    189 		case 'r':
    190 			rflag++;
    191 			break;
    192 		case 's':
    193 			sflag++;
    194 			break;
    195 		case 'w':
    196 			wait_time = atoi(optarg);
    197 			if (wait_time < 0)
    198 				errx(1, "wait time must be postive: %s",
    199 				    optarg);
    200 			if (wait_time < 30)
    201 			    warnx("warning: wait time less than 30 seconds");
    202 			break;
    203 		case 'W':/* allow connections coming from a non-reserved port */
    204 			 /* (done by some lpr-implementations for MS-Windows) */
    205 			check_options |= LPD_NOPORTCHK;
    206 			break;
    207 		default:
    208 			errs++;
    209 		}
    210 	argc -= optind;
    211 	argv += optind;
    212 	if (errs)
    213 		usage();
    214 
    215 	switch (argc) {
    216 	case 1:
    217 		if ((i = atoi(argv[0])) == 0)
    218 			usage();
    219 		if (i < 0 || i > USHRT_MAX)
    220 			errx(1, "port # %d is invalid", i);
    221 
    222 		port = argv[0];
    223 		break;
    224 	case 0:
    225 		sp = getservbyname(port, "tcp");
    226 		if (sp == NULL)
    227 			errx(1, "%s/tcp: unknown service", port);
    228 		break;
    229 	default:
    230 		usage();
    231 	}
    232 
    233 #ifndef DEBUG
    234 	/*
    235 	 * Set up standard environment by detaching from the parent.
    236 	 */
    237 	daemon(0, 0);
    238 #endif
    239 
    240 	openlog("lpd", LOG_PID, LOG_LPR);
    241 	syslog(LOG_INFO, "restarted");
    242 	(void)umask(0);
    243 	lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT, 0644);
    244 	if (lfd < 0) {
    245 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
    246 		exit(1);
    247 	}
    248 	if (flock(lfd, LOCK_EX|LOCK_NB) < 0) {
    249 		if (errno == EWOULDBLOCK) {	/* active daemon present */
    250 			syslog(LOG_ERR, "%s is locked; another lpd is running",
    251 			    _PATH_MASTERLOCK);
    252 			exit(0);
    253 		}
    254 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
    255 		exit(1);
    256 	}
    257 	ftruncate(lfd, 0);
    258 	/*
    259 	 * write process id for others to know
    260 	 */
    261 	(void)snprintf(line, sizeof(line), "%u\n", getpid());
    262 	f = strlen(line);
    263 	if (write(lfd, line, f) != f) {
    264 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
    265 		exit(1);
    266 	}
    267 	signal(SIGCHLD, reapchild);
    268 	/*
    269 	 * Restart all the printers.
    270 	 */
    271 	startup();
    272 
    273 	sigemptyset(&nmask);
    274 	sigaddset(&nmask, SIGHUP);
    275 	sigaddset(&nmask, SIGINT);
    276 	sigaddset(&nmask, SIGQUIT);
    277 	sigaddset(&nmask, SIGTERM);
    278 	sigprocmask(SIG_BLOCK, &nmask, &omask);
    279 
    280 	signal(SIGHUP, mcleanup);
    281 	signal(SIGINT, mcleanup);
    282 	signal(SIGQUIT, mcleanup);
    283 	signal(SIGTERM, mcleanup);
    284 
    285 	socks = socksetup(PF_UNSPEC, options, port, &nfds);
    286 
    287 	sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
    288 
    289 	if (blist != NULL) {
    290 		for (i = 0; i < blist_addrs; i++)
    291 			free(blist[i]);
    292 		free(blist);
    293 	}
    294 
    295 	/*
    296 	 * Main loop: accept, do a request, continue.
    297 	 */
    298 	memset(&from, 0, sizeof(from));
    299 	for (;;) {
    300 		int rv, s;
    301 		/* "short" so it overflows in about 2 hours */
    302 		struct timespec sleeptime = {10, 0};
    303 
    304 		while (child_max < child_count) {
    305 			syslog(LOG_WARNING,
    306 			    "too many children, sleeping for %ld seconds",
    307 				(long)sleeptime.tv_sec);
    308 			nanosleep(&sleeptime, NULL);
    309 			sleeptime.tv_sec <<= 1;
    310 			if (sleeptime.tv_sec <= 0) {
    311 				syslog(LOG_CRIT, "sleeptime overflowed! help!");
    312 				sleeptime.tv_sec = 10;
    313 			}
    314 		}
    315 
    316 		rv = poll(socks, nfds, INFTIM);
    317 		if (rv <= 0) {
    318 			if (rv < 0 && errno != EINTR)
    319 				syslog(LOG_WARNING, "poll: %m");
    320 			continue;
    321 		}
    322 		s = -1;
    323                 for (i = 0; i < nfds; i++)
    324 			if (socks[i].revents & POLLIN) {
    325 				fromlen = sizeof(from);
    326 				s = accept(socks[i].fd,
    327 				    (struct sockaddr *)&from, &fromlen);
    328 				break;
    329 			}
    330 		if (s < 0) {
    331 			if (errno != EINTR)
    332 				syslog(LOG_WARNING, "accept: %m");
    333 			continue;
    334 		}
    335 
    336 		switch (fork()) {
    337 		case 0:
    338 			signal(SIGCHLD, SIG_IGN);
    339 			signal(SIGHUP, SIG_IGN);
    340 			signal(SIGINT, SIG_IGN);
    341 			signal(SIGQUIT, SIG_IGN);
    342 			signal(SIGTERM, SIG_IGN);
    343                        	for (i = 0; i < nfds; i++)
    344 				(void)close(socks[i].fd);
    345 			dup2(s, STDOUT_FILENO);
    346 			(void)close(s);
    347 			if (from.ss_family != AF_LOCAL) {
    348 				/* for both AF_INET and AF_INET6 */
    349 				from_remote = 1;
    350 				chkhost((struct sockaddr *)&from, check_options);
    351 			} else
    352 				from_remote = 0;
    353 			doit();
    354 			exit(0);
    355 		case -1:
    356 			syslog(LOG_WARNING, "fork: %m, sleeping for 10 seconds...");
    357 			sleep(10);
    358 			continue;
    359 		default:
    360 			child_count++;
    361 		}
    362 		(void)close(s);
    363 	}
    364 }
    365 
    366 static void
    367 reapchild(int signo)
    368 {
    369 	union wait status;
    370 
    371 	while (wait3((int *)&status, WNOHANG, 0) > 0)
    372 		child_count--;
    373 }
    374 
    375 static void
    376 mcleanup(int signo)
    377 {
    378 	if (lflag)
    379 		syslog(LOG_INFO, "exiting");
    380 	unlink(_PATH_SOCKETNAME);
    381 	exit(0);
    382 }
    383 
    384 /*
    385  * Stuff for handling job specifications
    386  */
    387 char	*user[MAXUSERS];	/* users to process */
    388 int	users;			/* # of users in user array */
    389 int	requ[MAXREQUESTS];	/* job number of spool entries */
    390 int	requests;		/* # of spool requests */
    391 char	*person;		/* name of person doing lprm */
    392 
    393 char	fromb[NI_MAXHOST];	/* buffer for client's machine name */
    394 char	cbuf[BUFSIZ];		/* command line buffer */
    395 char	*cmdnames[] = {
    396 	"null",
    397 	"printjob",
    398 	"recvjob",
    399 	"displayq short",
    400 	"displayq long",
    401 	"rmjob"
    402 };
    403 
    404 static void
    405 doit(void)
    406 {
    407 	char *cp;
    408 	int n;
    409 
    410 	for (;;) {
    411 		cp = cbuf;
    412 		do {
    413 			if (cp >= &cbuf[sizeof(cbuf) - 1])
    414 				fatal("Command line too long");
    415 			if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
    416 				if (n < 0)
    417 					fatal("Lost connection");
    418 				return;
    419 			}
    420 		} while (*cp++ != '\n');
    421 		*--cp = '\0';
    422 		cp = cbuf;
    423 		if (lflag) {
    424 			if (*cp >= '\1' && *cp <= '\5') {
    425 				syslog(LOG_INFO, "%s requests %s %s",
    426 					from, cmdnames[(int)*cp], cp+1);
    427 				setproctitle("serving %s: %s %s", from,
    428 				    cmdnames[(int)*cp], cp+1);
    429 			}
    430 			else
    431 				syslog(LOG_INFO, "bad request (%d) from %s",
    432 					*cp, from);
    433 		}
    434 		switch (*cp++) {
    435 		case '\1':	/* check the queue and print any jobs there */
    436 			printer = cp;
    437 			if (*printer == '\0')
    438 				printer = DEFLP;
    439 			printjob();
    440 			break;
    441 		case '\2':	/* receive files to be queued */
    442 			if (!from_remote) {
    443 				syslog(LOG_INFO, "illegal request (%d)", *cp);
    444 				exit(1);
    445 			}
    446 			printer = cp;
    447 			if (*printer == '\0')
    448 				printer = DEFLP;
    449 			recvjob();
    450 			break;
    451 		case '\3':	/* display the queue (short form) */
    452 		case '\4':	/* display the queue (long form) */
    453 			printer = cp;
    454 			if (*printer == '\0')
    455 				printer = DEFLP;
    456 			while (*cp) {
    457 				if (*cp != ' ') {
    458 					cp++;
    459 					continue;
    460 				}
    461 				*cp++ = '\0';
    462 				while (isspace((unsigned char)*cp))
    463 					cp++;
    464 				if (*cp == '\0')
    465 					break;
    466 				if (isdigit((unsigned char)*cp)) {
    467 					if (requests >= MAXREQUESTS)
    468 						fatal("Too many requests");
    469 					requ[requests++] = atoi(cp);
    470 				} else {
    471 					if (users >= MAXUSERS)
    472 						fatal("Too many users");
    473 					user[users++] = cp;
    474 				}
    475 			}
    476 			displayq(cbuf[0] - '\3');
    477 			exit(0);
    478 		case '\5':	/* remove a job from the queue */
    479 			if (!from_remote) {
    480 				syslog(LOG_INFO, "illegal request (%d)", *cp);
    481 				exit(1);
    482 			}
    483 			printer = cp;
    484 			if (*printer == '\0')
    485 				printer = DEFLP;
    486 			while (*cp && *cp != ' ')
    487 				cp++;
    488 			if (!*cp)
    489 				break;
    490 			*cp++ = '\0';
    491 			person = cp;
    492 			while (*cp) {
    493 				if (*cp != ' ') {
    494 					cp++;
    495 					continue;
    496 				}
    497 				*cp++ = '\0';
    498 				while (isspace((unsigned char)*cp))
    499 					cp++;
    500 				if (*cp == '\0')
    501 					break;
    502 				if (isdigit((unsigned char)*cp)) {
    503 					if (requests >= MAXREQUESTS)
    504 						fatal("Too many requests");
    505 					requ[requests++] = atoi(cp);
    506 				} else {
    507 					if (users >= MAXUSERS)
    508 						fatal("Too many users");
    509 					user[users++] = cp;
    510 				}
    511 			}
    512 			rmjob();
    513 			break;
    514 		}
    515 		fatal("Illegal service request");
    516 	}
    517 }
    518 
    519 /*
    520  * Make a pass through the printcap database and start printing any
    521  * files left from the last time the machine went down.
    522  */
    523 static void
    524 startup(void)
    525 {
    526 	char *buf;
    527 	char *cp;
    528 
    529 	/*
    530 	 * Restart the daemons.
    531 	 */
    532 	while (cgetnext(&buf, printcapdb) > 0) {
    533 		if (ckqueue(buf) <= 0) {
    534 			free(buf);
    535 			continue;	/* no work to do for this printer */
    536 		}
    537 		for (cp = buf; *cp; cp++)
    538 			if (*cp == '|' || *cp == ':') {
    539 				*cp = '\0';
    540 				break;
    541 			}
    542 		if (lflag)
    543 			syslog(LOG_INFO, "work for %s", buf);
    544 		switch (fork()) {
    545 		case -1:
    546 			syslog(LOG_WARNING, "startup: cannot fork");
    547 			mcleanup(0);
    548 		case 0:
    549 			printer = buf;
    550 			setproctitle("working on printer %s", printer);
    551 			cgetclose();
    552 			printjob();
    553 			/* NOTREACHED */
    554 		default:
    555 			child_count++;
    556 			free(buf);
    557 		}
    558 	}
    559 }
    560 
    561 /*
    562  * Make sure there's some work to do before forking off a child
    563  */
    564 static int
    565 ckqueue(char *cap)
    566 {
    567 	struct dirent *d;
    568 	DIR *dirp;
    569 	char *spooldir;
    570 
    571 	if (cgetstr(cap, "sd", &spooldir) == -1)
    572 		spooldir = _PATH_DEFSPOOL;
    573 	if ((dirp = opendir(spooldir)) == NULL) {
    574 		if (spooldir != _PATH_DEFSPOOL)
    575 			free(spooldir);
    576 		return (-1);
    577 	}
    578 	while ((d = readdir(dirp)) != NULL) {
    579 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    580 			continue;	/* daemon control files only */
    581 		closedir(dirp);
    582 		if (spooldir != _PATH_DEFSPOOL)
    583 			free(spooldir);
    584 		return (1);		/* found something */
    585 	}
    586 	closedir(dirp);
    587 	if (spooldir != _PATH_DEFSPOOL)
    588 		free(spooldir);
    589 	return (0);
    590 }
    591 
    592 #define DUMMY ":nobody::"
    593 
    594 /*
    595  * Check to see if the from host has access to the line printer.
    596  */
    597 static void
    598 chkhost(struct sockaddr *f, int check_opts)
    599 {
    600 	struct addrinfo hints, *res, *r;
    601 	FILE *hostf;
    602 	int good = 0;
    603 	char host[NI_MAXHOST], ip[NI_MAXHOST];
    604 	char serv[NI_MAXSERV];
    605 	int error;
    606 #ifdef LIBWRAP
    607 	struct request_info req;
    608 #endif
    609 
    610 	error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
    611 			    NI_NUMERICSERV);
    612 	if (error)
    613 		fatal("Malformed from address: %s", gai_strerror(error));
    614 
    615          if (!(check_opts & LPD_NOPORTCHK) &&
    616 	       atoi(serv) >= IPPORT_RESERVED)
    617 		fatal("Connect from invalid port (%s)", serv);
    618 
    619 	/* Need real hostname for temporary filenames */
    620 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    621 			    NI_NAMEREQD);
    622 	if (error) {
    623 		error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    624 				    NI_NUMERICHOST);
    625 		if (error)
    626 			fatal("Host name for your address unknown");
    627 		else
    628 			fatal("Host name for your address (%s) unknown", host);
    629 	}
    630 
    631 	(void)strlcpy(fromb, host, sizeof(fromb));
    632 	from = fromb;
    633 
    634 	/* need address in stringform for comparison (no DNS lookup here) */
    635 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    636 			    NI_NUMERICHOST);
    637 	if (error)
    638 		fatal("Cannot print address");
    639 
    640 	/* Check for spoof, ala rlogind */
    641 	memset(&hints, 0, sizeof(hints));
    642 	hints.ai_family = PF_UNSPEC;
    643 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
    644 	error = getaddrinfo(fromb, NULL, &hints, &res);
    645 	if (error) {
    646 		fatal("hostname for your address (%s) unknown: %s", host,
    647 		    gai_strerror(error));
    648 	}
    649 	good = 0;
    650 	for (r = res; good == 0 && r; r = r->ai_next) {
    651 		error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
    652 				    NULL, 0, NI_NUMERICHOST);
    653 		if (!error && !strcmp(host, ip))
    654 			good = 1;
    655 	}
    656 	if (res)
    657 		freeaddrinfo(res);
    658 	if (good == 0)
    659 		fatal("address for your hostname (%s) not matched", host);
    660 
    661 	setproctitle("serving %s", from);
    662 
    663 #ifdef LIBWRAP
    664 	request_init(&req, RQ_DAEMON, "lpd", RQ_CLIENT_SIN, f,
    665 	    RQ_FILE, STDOUT_FILENO, NULL);
    666 	fromhost(&req);
    667 	if (!hosts_access(&req))
    668 		goto denied;
    669 #endif
    670 
    671 	hostf = fopen(_PATH_HOSTSEQUIV, "r");
    672 	if (hostf) {
    673 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
    674 			(void)fclose(hostf);
    675 			return;
    676 		}
    677 		(void)fclose(hostf);
    678 	}
    679 	hostf = fopen(_PATH_HOSTSLPD, "r");
    680 	if (hostf) {
    681 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
    682 			(void)fclose(hostf);
    683 			return;
    684 		}
    685 		(void)fclose(hostf);
    686 	}
    687 #ifdef LIBWRAP
    688   denied:
    689 #endif
    690 	fatal("Your host does not have line printer access");
    691 	/*NOTREACHED*/
    692 }
    693 
    694 
    695 static void
    696 usage(void)
    697 {
    698 
    699 	fprintf(stderr, "usage: %s [-dlrsW] [-b bind-address] [-n maxchild] "
    700 	    "[-w maxwait] [port]\n", getprogname());
    701 	exit(1);
    702 }
    703 
    704 /* setup server socket for specified address family */
    705 /* if af is PF_UNSPEC more than one socket may be returned */
    706 /* the returned list is dynamically allocated, so caller needs to free it */
    707 struct pollfd *
    708 socksetup(int af, int options, const char *port, int *nfds)
    709 {
    710 	struct sockaddr_un un;
    711 	struct addrinfo hints, *res, *r;
    712 	int error, s, blidx = 0, n;
    713 	struct pollfd *socks, *newsocks;
    714 	const int on = 1;
    715 
    716 	*nfds = 0;
    717 
    718 	socks = malloc(1 * sizeof(socks[0]));
    719 	if (!socks) {
    720 		syslog(LOG_ERR, "couldn't allocate memory for sockets");
    721 		mcleanup(0);
    722 	}
    723 
    724 	s = socket(AF_LOCAL, SOCK_STREAM, 0);
    725 	if (s < 0) {
    726 		syslog(LOG_ERR, "socket(): %m");
    727 		exit(1);
    728 	}
    729 	memset(&un, 0, sizeof(un));
    730 	un.sun_family = AF_LOCAL;
    731 	strncpy(un.sun_path, _PATH_SOCKETNAME, sizeof(un.sun_path) - 1);
    732 	un.sun_len = SUN_LEN(&un);
    733 	(void)umask(07);
    734 	(void)unlink(_PATH_SOCKETNAME);
    735 	if (bind(s, (struct sockaddr *)&un, un.sun_len) < 0) {
    736 		syslog(LOG_ERR, "bind(): %m");
    737 		exit(1);
    738 	}
    739 	(void)umask(0);
    740 	listen(s, 5);
    741 	socks[*nfds].fd = s;
    742 	socks[*nfds].events = POLLIN;
    743 	(*nfds)++;
    744 
    745 	if (sflag && !blist_addrs)
    746 		return (socks);
    747 
    748 	do {
    749 		memset(&hints, 0, sizeof(hints));
    750 		hints.ai_flags = AI_PASSIVE;
    751 		hints.ai_family = af;
    752 		hints.ai_socktype = SOCK_STREAM;
    753 		error = getaddrinfo((blist_addrs == 0) ? NULL : blist[blidx],
    754 		    port ? port : "printer", &hints, &res);
    755 		if (error) {
    756 			if (blist_addrs)
    757 				syslog(LOG_ERR, "%s: %s", blist[blidx],
    758 				    gai_strerror(error));
    759 			else
    760 				syslog(LOG_ERR, "%s", gai_strerror(error));
    761 			mcleanup(0);
    762 		}
    763 
    764 		/* Count max number of sockets we may open */
    765 		for (r = res, n = 0; r; r = r->ai_next, n++)
    766 			;
    767 		newsocks = realloc(socks, (*nfds + n) * sizeof(socks[0]));
    768 		if (!newsocks) {
    769 			syslog(LOG_ERR, "couldn't allocate memory for sockets");
    770 			mcleanup(0);
    771 		}
    772 		socks = newsocks;
    773 
    774 		for (r = res; r; r = r->ai_next) {
    775 			s = socket(r->ai_family, r->ai_socktype,
    776 			    r->ai_protocol);
    777 			if (s < 0) {
    778 				syslog(LOG_DEBUG, "socket(): %m");
    779 				continue;
    780 			}
    781 			if (options & SO_DEBUG)
    782 				if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
    783 					       &on, sizeof(on)) < 0) {
    784 					syslog(LOG_ERR,
    785 					       "setsockopt (SO_DEBUG): %m");
    786 					close(s);
    787 					continue;
    788 				}
    789 			if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &on,
    790 			    sizeof(on)) < 0) {
    791 				syslog(LOG_ERR,
    792 				    "setsockopt (SO_REUSEPORT): %m");
    793 				close(s);
    794 				continue;
    795 			}
    796 			if (r->ai_family == AF_INET6 && setsockopt(s,
    797 			    IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
    798 				syslog(LOG_ERR,
    799 				    "setsockopt (IPV6_V6ONLY): %m");
    800 				close(s);
    801 				continue;
    802 			}
    803 			if (bind(s, r->ai_addr, r->ai_addrlen) < 0) {
    804 				syslog(LOG_DEBUG, "bind(): %m");
    805 				close(s);
    806 				continue;
    807 			}
    808 			listen(s, 5);
    809 			socks[*nfds].fd = s;
    810 			socks[*nfds].events = POLLIN;
    811 			(*nfds)++;
    812 		}
    813 
    814 		if (res)
    815 			freeaddrinfo(res);
    816 	} while (++blidx < blist_addrs);
    817 
    818 	return (socks);
    819 }
    820