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