Home | History | Annotate | Line # | Download | only in lpd
lpd.c revision 1.38
      1 /*	$NetBSD: lpd.c,v 1.38 2002/08/12 18:03:41 itojun 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.38 2002/08/12 18:03:41 itojun 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(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(int, char **);
    132 static void       reapchild(int);
    133 static void       mcleanup(int);
    134 static void       doit(void);
    135 static void       startup(void);
    136 static void       chkhost(struct sockaddr *, int);
    137 static int	  ckqueue(char *);
    138 static void	  usage(void);
    139 static int	  *socksetup(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:dln: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 	if (funix >= FD_SETSIZE) {
    305 		syslog(LOG_ERR, "descriptor too big");
    306 		exit(1);
    307 	}
    308 	FD_SET(funix, &defreadfds);
    309 	listen(funix, 5);
    310 	if (!sflag || blist_addrs)
    311 		finet = socksetup(PF_UNSPEC, options, port);
    312 	else
    313 		finet = NULL;	/* pretend we couldn't open TCP socket. */
    314 
    315 	if (blist != NULL) {
    316 		for (i = 0; i < blist_addrs; i++)
    317 			free(blist[i]);
    318 		free(blist);
    319 	}
    320 
    321 	if (finet) {
    322 		for (i = 1; i <= *finet; i++) {
    323 			if (finet[i] >= FD_SETSIZE) {
    324 				syslog(LOG_ERR, "descriptor too big");
    325 				exit(1);
    326 			}
    327 			FD_SET(finet[i], &defreadfds);
    328 			listen(finet[i], 5);
    329 		}
    330 	}
    331 	/*
    332 	 * Main loop: accept, do a request, continue.
    333 	 */
    334 	memset(&frominet, 0, sizeof(frominet));
    335 	memset(&fromunix, 0, sizeof(fromunix));
    336 	for (;;) {
    337 		int domain, nfds, s, fromlen;
    338 		fd_set readfds;
    339 		/* "short" so it overflows in about 2 hours */
    340 		short sleeptime = 10;
    341 
    342 		while (child_max < child_count) {
    343 			syslog(LOG_WARNING,
    344 			    "too many children, sleeping for %d seconds",
    345 				sleeptime);
    346 			sleep(sleeptime);
    347 			sleeptime <<= 1;
    348 			if (sleeptime < 0) {
    349 				syslog(LOG_CRIT, "sleeptime overflowed! help!");
    350 				sleeptime = 10;
    351 			}
    352 		}
    353 
    354 		FD_COPY(&defreadfds, &readfds);
    355 		nfds = select(20, &readfds, 0, 0, 0);
    356 		if (nfds <= 0) {
    357 			if (nfds < 0 && errno != EINTR)
    358 				syslog(LOG_WARNING, "select: %m");
    359 			continue;
    360 		}
    361 		if (FD_ISSET(funix, &readfds)) {
    362 			domain = AF_LOCAL;
    363 			fromlen = sizeof(fromunix);
    364 			s = accept(funix,
    365 			    (struct sockaddr *)&fromunix, &fromlen);
    366 		} else {
    367                         for (i = 1; i <= *finet; i++)
    368 				if (FD_ISSET(finet[i], &readfds)) {
    369 					domain = AF_INET, fromlen = sizeof(frominet);
    370 					s = accept(finet[i], (struct sockaddr *)&frominet, &fromlen);
    371 				}
    372 		}
    373 		if (s < 0) {
    374 			if (errno != EINTR)
    375 				syslog(LOG_WARNING, "accept: %m");
    376 			continue;
    377 		}
    378 
    379 		switch (fork()) {
    380 		case 0:
    381 			signal(SIGCHLD, SIG_IGN);
    382 			signal(SIGHUP, SIG_IGN);
    383 			signal(SIGINT, SIG_IGN);
    384 			signal(SIGQUIT, SIG_IGN);
    385 			signal(SIGTERM, SIG_IGN);
    386 			(void)close(funix);
    387 			if (!sflag && finet)
    388                         	for (i = 1; i <= *finet; i++)
    389 					(void)close(finet[i]);
    390 			dup2(s, 1);
    391 			(void)close(s);
    392 			if (domain == AF_INET) {
    393 				/* for both AF_INET and AF_INET6 */
    394 				from_remote = 1;
    395 				chkhost((struct sockaddr *)&frominet, check_options);
    396 			} else
    397 				from_remote = 0;
    398 			doit();
    399 			exit(0);
    400 		case -1:
    401 			syslog(LOG_WARNING, "fork: %m, sleeping for 10 seconds...");
    402 			sleep(10);
    403 			continue;
    404 		default:
    405 			child_count++;
    406 		}
    407 		(void)close(s);
    408 	}
    409 }
    410 
    411 static void
    412 reapchild(int signo)
    413 {
    414 	union wait status;
    415 
    416 	while (wait3((int *)&status, WNOHANG, 0) > 0)
    417 		child_count--;
    418 }
    419 
    420 static void
    421 mcleanup(int signo)
    422 {
    423 	if (lflag)
    424 		syslog(LOG_INFO, "exiting");
    425 	unlink(_PATH_SOCKETNAME);
    426 	exit(0);
    427 }
    428 
    429 /*
    430  * Stuff for handling job specifications
    431  */
    432 char	*user[MAXUSERS];	/* users to process */
    433 int	users;			/* # of users in user array */
    434 int	requ[MAXREQUESTS];	/* job number of spool entries */
    435 int	requests;		/* # of spool requests */
    436 char	*person;		/* name of person doing lprm */
    437 
    438 char	fromb[NI_MAXHOST];	/* buffer for client's machine name */
    439 char	cbuf[BUFSIZ];		/* command line buffer */
    440 char	*cmdnames[] = {
    441 	"null",
    442 	"printjob",
    443 	"recvjob",
    444 	"displayq short",
    445 	"displayq long",
    446 	"rmjob"
    447 };
    448 
    449 static void
    450 doit(void)
    451 {
    452 	char *cp;
    453 	int n;
    454 
    455 	for (;;) {
    456 		cp = cbuf;
    457 		do {
    458 			if (cp >= &cbuf[sizeof(cbuf) - 1])
    459 				fatal("Command line too long");
    460 			if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
    461 				if (n < 0)
    462 					fatal("Lost connection");
    463 				return;
    464 			}
    465 		} while (*cp++ != '\n');
    466 		*--cp = '\0';
    467 		cp = cbuf;
    468 		if (lflag) {
    469 			if (*cp >= '\1' && *cp <= '\5') {
    470 				syslog(LOG_INFO, "%s requests %s %s",
    471 					from, cmdnames[(int)*cp], cp+1);
    472 				setproctitle("serving %s: %s %s", from,
    473 				    cmdnames[(int)*cp], cp+1);
    474 			}
    475 			else
    476 				syslog(LOG_INFO, "bad request (%d) from %s",
    477 					*cp, from);
    478 		}
    479 		switch (*cp++) {
    480 		case '\1':	/* check the queue and print any jobs there */
    481 			printer = cp;
    482 			if (*printer == '\0')
    483 				printer = DEFLP;
    484 			printjob();
    485 			break;
    486 		case '\2':	/* receive files to be queued */
    487 			if (!from_remote) {
    488 				syslog(LOG_INFO, "illegal request (%d)", *cp);
    489 				exit(1);
    490 			}
    491 			printer = cp;
    492 			if (*printer == '\0')
    493 				printer = DEFLP;
    494 			recvjob();
    495 			break;
    496 		case '\3':	/* display the queue (short form) */
    497 		case '\4':	/* display the queue (long form) */
    498 			printer = cp;
    499 			if (*printer == '\0')
    500 				printer = DEFLP;
    501 			while (*cp) {
    502 				if (*cp != ' ') {
    503 					cp++;
    504 					continue;
    505 				}
    506 				*cp++ = '\0';
    507 				while (isspace(*cp))
    508 					cp++;
    509 				if (*cp == '\0')
    510 					break;
    511 				if (isdigit(*cp)) {
    512 					if (requests >= MAXREQUESTS)
    513 						fatal("Too many requests");
    514 					requ[requests++] = atoi(cp);
    515 				} else {
    516 					if (users >= MAXUSERS)
    517 						fatal("Too many users");
    518 					user[users++] = cp;
    519 				}
    520 			}
    521 			displayq(cbuf[0] - '\3');
    522 			exit(0);
    523 		case '\5':	/* remove a job from the queue */
    524 			if (!from_remote) {
    525 				syslog(LOG_INFO, "illegal request (%d)", *cp);
    526 				exit(1);
    527 			}
    528 			printer = cp;
    529 			if (*printer == '\0')
    530 				printer = DEFLP;
    531 			while (*cp && *cp != ' ')
    532 				cp++;
    533 			if (!*cp)
    534 				break;
    535 			*cp++ = '\0';
    536 			person = cp;
    537 			while (*cp) {
    538 				if (*cp != ' ') {
    539 					cp++;
    540 					continue;
    541 				}
    542 				*cp++ = '\0';
    543 				while (isspace(*cp))
    544 					cp++;
    545 				if (*cp == '\0')
    546 					break;
    547 				if (isdigit(*cp)) {
    548 					if (requests >= MAXREQUESTS)
    549 						fatal("Too many requests");
    550 					requ[requests++] = atoi(cp);
    551 				} else {
    552 					if (users >= MAXUSERS)
    553 						fatal("Too many users");
    554 					user[users++] = cp;
    555 				}
    556 			}
    557 			rmjob();
    558 			break;
    559 		}
    560 		fatal("Illegal service request");
    561 	}
    562 }
    563 
    564 /*
    565  * Make a pass through the printcap database and start printing any
    566  * files left from the last time the machine went down.
    567  */
    568 static void
    569 startup(void)
    570 {
    571 	char *buf;
    572 	char *cp;
    573 
    574 	/*
    575 	 * Restart the daemons.
    576 	 */
    577 	while (cgetnext(&buf, printcapdb) > 0) {
    578 		if (ckqueue(buf) <= 0) {
    579 			free(buf);
    580 			continue;	/* no work to do for this printer */
    581 		}
    582 		for (cp = buf; *cp; cp++)
    583 			if (*cp == '|' || *cp == ':') {
    584 				*cp = '\0';
    585 				break;
    586 			}
    587 		if (lflag)
    588 			syslog(LOG_INFO, "work for %s", buf);
    589 		switch (fork()) {
    590 		case -1:
    591 			syslog(LOG_WARNING, "startup: cannot fork");
    592 			mcleanup(0);
    593 		case 0:
    594 			printer = buf;
    595 			setproctitle("working on printer %s", printer);
    596 			cgetclose();
    597 			printjob();
    598 			/* NOTREACHED */
    599 		default:
    600 			child_count++;
    601 			free(buf);
    602 		}
    603 	}
    604 }
    605 
    606 /*
    607  * Make sure there's some work to do before forking off a child
    608  */
    609 static int
    610 ckqueue(char *cap)
    611 {
    612 	struct dirent *d;
    613 	DIR *dirp;
    614 	char *spooldir;
    615 
    616 	if (cgetstr(cap, "sd", &spooldir) == -1)
    617 		spooldir = _PATH_DEFSPOOL;
    618 	if ((dirp = opendir(spooldir)) == NULL)
    619 		return (-1);
    620 	while ((d = readdir(dirp)) != NULL) {
    621 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    622 			continue;	/* daemon control files only */
    623 		closedir(dirp);
    624 		return (1);		/* found something */
    625 	}
    626 	closedir(dirp);
    627 	return (0);
    628 }
    629 
    630 #define DUMMY ":nobody::"
    631 
    632 /*
    633  * Check to see if the from host has access to the line printer.
    634  */
    635 static void
    636 chkhost(struct sockaddr *f, int check_opts)
    637 {
    638 	struct addrinfo hints, *res, *r;
    639 	FILE *hostf;
    640 	int good = 0;
    641 	char host[NI_MAXHOST], ip[NI_MAXHOST];
    642 	char serv[NI_MAXSERV];
    643 	int error;
    644 #ifdef LIBWRAP
    645 	struct request_info req;
    646 #endif
    647 
    648 	error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
    649 			    NI_NUMERICSERV);
    650 	if (error)
    651 		fatal("Malformed from address: %s", gai_strerror(error));
    652 
    653          if (!(check_opts & LPD_NOPORTCHK) &&
    654 	       atoi(serv) >= IPPORT_RESERVED)
    655 		fatal("Connect from invalid port (%s)", serv);
    656 
    657 	/* Need real hostname for temporary filenames */
    658 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    659 			    NI_NAMEREQD);
    660 	if (error) {
    661 		error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    662 				    NI_NUMERICHOST);
    663 		if (error)
    664 			fatal("Host name for your address unknown");
    665 		else
    666 			fatal("Host name for your address (%s) unknown", host);
    667 	}
    668 
    669 	(void)strncpy(fromb, host, sizeof(fromb) - 1);
    670 	fromb[sizeof(fromb) - 1] = '\0';
    671 	from = fromb;
    672 
    673 	/* need address in stringform for comparison (no DNS lookup here) */
    674 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    675 			    NI_NUMERICHOST);
    676 	if (error)
    677 		fatal("Cannot print address");
    678 
    679 	/* Check for spoof, ala rlogind */
    680 	memset(&hints, 0, sizeof(hints));
    681 	hints.ai_family = PF_UNSPEC;
    682 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
    683 	error = getaddrinfo(fromb, NULL, &hints, &res);
    684 	if (error) {
    685 		fatal("hostname for your address (%s) unknown: %s", host,
    686 		    gai_strerror(error));
    687 	}
    688 	good = 0;
    689 	for (r = res; good == 0 && r; r = r->ai_next) {
    690 		error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
    691 				    NULL, 0, NI_NUMERICHOST);
    692 		if (!error && !strcmp(host, ip))
    693 			good = 1;
    694 	}
    695 	if (res)
    696 		freeaddrinfo(res);
    697 	if (good == 0)
    698 		fatal("address for your hostname (%s) not matched", host);
    699 
    700 	setproctitle("serving %s", from);
    701 
    702 #ifdef LIBWRAP
    703 	request_init(&req, RQ_DAEMON, "lpd", RQ_CLIENT_SIN, f, NULL);
    704 	fromhost(&req);
    705 	if (!hosts_access(&req))
    706 		goto denied;
    707 #endif
    708 
    709 	hostf = fopen(_PATH_HOSTSEQUIV, "r");
    710 	if (hostf) {
    711 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
    712 			(void)fclose(hostf);
    713 			return;
    714 		}
    715 		(void)fclose(hostf);
    716 	}
    717 	hostf = fopen(_PATH_HOSTSLPD, "r");
    718 	if (hostf) {
    719 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
    720 			(void)fclose(hostf);
    721 			return;
    722 		}
    723 		(void)fclose(hostf);
    724 	}
    725 #ifdef LIBWRAP
    726   denied:
    727 #endif
    728 	fatal("Your host does not have line printer access");
    729 	/*NOTREACHED*/
    730 }
    731 
    732 
    733 static void
    734 usage(void)
    735 {
    736 
    737 	fprintf(stderr, "usage: %s [-dlrsW] [-b bind-address] [-n maxchild] "
    738 	    "[-w maxwait] [port]\n", getprogname());
    739 	exit(1);
    740 }
    741 
    742 /* setup server socket for specified address family */
    743 /* if af is PF_UNSPEC more than one socket may be returned */
    744 /* the returned list is dynamically allocated, so caller needs to free it */
    745 int *
    746 socksetup(int af, int options, const char *port)
    747 {
    748 	struct addrinfo hints, *res, *r;
    749 	int error, maxs = 0, *s, *socks = NULL, blidx = 0;
    750 	const int on = 1;
    751 
    752 	do {
    753 		memset(&hints, 0, sizeof(hints));
    754 		hints.ai_flags = AI_PASSIVE;
    755 		hints.ai_family = af;
    756 		hints.ai_socktype = SOCK_STREAM;
    757 		error = getaddrinfo((blist_addrs == 0) ? NULL : blist[blidx],
    758 		    port ? port : "printer", &hints, &res);
    759 		if (error) {
    760 			if (blist_addrs)
    761 				syslog(LOG_ERR, "%s: %s", blist[blidx],
    762 				    gai_strerror(error));
    763 			else
    764 				syslog(LOG_ERR, "%s", gai_strerror(error));
    765 			mcleanup(0);
    766 		}
    767 
    768 		/* Count max number of sockets we may open */
    769 		for (r = res; r; r = r->ai_next, maxs++)
    770 			;
    771 		if (socks == NULL) {
    772 			socks = malloc((maxs + 1) * sizeof(int));
    773 			if (socks)
    774 				*socks = 0; /* num of sockets ctr at start */
    775 		} else
    776 			socks = realloc(socks, (maxs + 1) * sizeof(int));
    777 		if (!socks) {
    778 			syslog(LOG_ERR, "couldn't allocate memory for sockets");
    779 			mcleanup(0);
    780 		}
    781 
    782 		s = socks + *socks + 1;
    783 		for (r = res; r; r = r->ai_next) {
    784 			*s = socket(r->ai_family, r->ai_socktype,
    785 			            r->ai_protocol);
    786 			if (*s < 0) {
    787 				syslog(LOG_DEBUG, "socket(): %m");
    788 				continue;
    789 			}
    790 			if (options & SO_DEBUG)
    791 				if (setsockopt(*s, SOL_SOCKET, SO_DEBUG,
    792 					       &on, sizeof(on)) < 0) {
    793 					syslog(LOG_ERR,
    794 					       "setsockopt (SO_DEBUG): %m");
    795 					close (*s);
    796 					continue;
    797 				}
    798 			if (setsockopt(*s, SOL_SOCKET, SO_REUSEPORT, &on,
    799 			    sizeof(on)) < 0) {
    800 				syslog(LOG_ERR,
    801 				    "setsockopt (SO_REUSEPORT): %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