xref: /freebsd/usr.sbin/lpr/lpd/lpd.c (revision 055c9045)
1 /*
2  * Copyright (c) 1983, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
21  *
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
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1983, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #if 0
42 static char sccsid[] = "@(#)lpd.c	8.7 (Berkeley) 5/10/95";
43 #endif
44 
45 #include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
46 __FBSDID("$FreeBSD$");
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 <netinet/in.h>
85 #include <arpa/inet.h>
86 
87 #include <netdb.h>
88 #include <unistd.h>
89 #include <syslog.h>
90 #include <signal.h>
91 #include <err.h>
92 #include <errno.h>
93 #include <fcntl.h>
94 #include <dirent.h>
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <sysexits.h>
99 #include <ctype.h>
100 #include "lp.h"
101 #include "lp.local.h"
102 #include "pathnames.h"
103 #include "extern.h"
104 
105 int	lflag;				/* log requests flag */
106 int	sflag;				/* no incoming port flag */
107 int	from_remote;			/* from remote socket */
108 
109 int		 main(int argc, char **_argv);
110 static void	 reapchild(int _signo);
111 static void	 mcleanup(int _signo);
112 static void	 doit(void);
113 static void	 startup(void);
114 static void	 chkhost(struct sockaddr *_f, int _ch_opts);
115 static int	 ckqueue(struct printer *_pp);
116 static void	 fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
117 static int	*socksetup(int _af, int _debuglvl);
118 static void	 usage(void);
119 
120 /* XXX from libc/net/rcmd.c */
121 extern int __ivaliduser_sa __P((FILE *, struct sockaddr *, socklen_t,
122 				const char *, const char *));
123 
124 uid_t	uid, euid;
125 
126 #define LPD_NOPORTCHK	0001		/* skip reserved-port check */
127 #define LPD_LOGCONNERR	0002		/* (sys)log connection errors */
128 #define LPD_ADDFROMLINE	0004		/* just used for fhosterr() */
129 
130 int
131 main(int argc, char **argv)
132 {
133 	int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
134 	fd_set defreadfds;
135 	struct sockaddr_un un, fromunix;
136 	struct sockaddr_storage frominet;
137 	socklen_t fromlen;
138 	sigset_t omask, nmask;
139 	struct servent *sp, serv;
140 	int inet_flag = 0, inet6_flag = 0;
141 
142 	euid = geteuid();	/* these shouldn't be different */
143 	uid = getuid();
144 
145 	ch_options = 0;
146 	socket_debug = 0;
147 	gethostname(local_host, sizeof(local_host));
148 
149 	progname = "lpd";
150 
151 	if (euid != 0)
152 		errx(EX_NOPERM,"must run as root");
153 
154 	errs = 0;
155 	while ((i = getopt(argc, argv, "cdlpswW46")) != -1)
156 		switch (i) {
157 		case 'c':
158 			/* log all kinds of connection-errors to syslog */
159 			ch_options |= LPD_LOGCONNERR;
160 			break;
161 		case 'd':
162 			socket_debug++;
163 			break;
164 		case 'l':
165 			lflag++;
166 			break;
167 		case 'p':		/* letter initially used for -s */
168 			/*
169 			 * This will probably be removed with 5.0-release.
170 			 */
171 			/* FALLTHROUGH */
172 		case 's':		/* secure (no inet) */
173 			sflag++;
174 			break;
175 		case 'w':		/* netbsd uses -w for maxwait */
176 			/*
177 			 * This will be removed after the release of 4.4, as
178 			 * it conflicts with -w in netbsd's lpd.  For now it
179 			 * is just a warning, so we won't suddenly break lpd
180 			 * for anyone who is currently using the option.
181 			 */
182 			syslog(LOG_WARNING,
183 			    "NOTE: the -w option has been renamed -W");
184 			syslog(LOG_WARNING,
185 			    "NOTE: please change your lpd config to use -W");
186 			/* FALLTHROUGH */
187 		case 'W':
188 			/* allow connections coming from a non-reserved port */
189 			/* (done by some lpr-implementations for MS-Windows) */
190 			ch_options |= LPD_NOPORTCHK;
191 			break;
192 		case '4':
193 			family = PF_INET;
194 			inet_flag++;
195 			break;
196 		case '6':
197 #ifdef INET6
198 			family = PF_INET6;
199 			inet6_flag++;
200 #else
201 			errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
202 #endif
203 			break;
204 		/*
205 		 * The following options are not in FreeBSD (yet?), but are
206 		 * listed here to "reserve" them, because the option-letters
207 		 * are used by either NetBSD or OpenBSD (as of July 2001).
208 		 */
209 		case 'b':		/* set bind-addr */
210 		case 'n':		/* set max num of children */
211 		case 'r':		/* allow 'of' for remote ptrs */
212 					/* ...[not needed in freebsd] */
213 			/* FALLTHROUGH */
214 		default:
215 			errs++;
216 		}
217 	if (inet_flag && inet6_flag)
218 		family = PF_UNSPEC;
219 	argc -= optind;
220 	argv += optind;
221 	if (errs)
222 		usage();
223 
224 	if (argc == 1) {
225 		if ((i = atoi(argv[0])) == 0)
226 			usage();
227 		if (i < 0 || i > USHRT_MAX)
228 			errx(EX_USAGE, "port # %d is invalid", i);
229 
230 		serv.s_port = htons(i);
231 		sp = &serv;
232 		argc--;
233 	} else {
234 		sp = getservbyname("printer", "tcp");
235 		if (sp == NULL)
236 			errx(EX_OSFILE, "printer/tcp: unknown service");
237 	}
238 
239 	if (argc != 0)
240 		usage();
241 
242 	/*
243 	 * We run chkprintcap right away to catch any errors and blat them
244 	 * to stderr while we still have it open, rather than sending them
245 	 * to syslog and leaving the user wondering why lpd started and
246 	 * then stopped.  There should probably be a command-line flag to
247 	 * ignore errors from chkprintcap.
248 	 */
249 	{
250 		pid_t pid;
251 		int status;
252 		pid = fork();
253 		if (pid < 0) {
254 			err(EX_OSERR, "cannot fork");
255 		} else if (pid == 0) {	/* child */
256 			execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
257 			err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
258 		}
259 		if (waitpid(pid, &status, 0) < 0) {
260 			err(EX_OSERR, "cannot wait");
261 		}
262 		if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
263 			errx(EX_OSFILE, "%d errors in printcap file, exiting",
264 			     WEXITSTATUS(status));
265 	}
266 
267 #ifndef DEBUG
268 	/*
269 	 * Set up standard environment by detaching from the parent.
270 	 */
271 	daemon(0, 0);
272 #endif
273 
274 	openlog("lpd", LOG_PID, LOG_LPR);
275 	syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
276 	    socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
277 	(void) umask(0);
278 	/*
279 	 * NB: This depends on O_NONBLOCK semantics doing the right thing;
280 	 * i.e., applying only to the O_EXLOCK and not to the rest of the
281 	 * open/creation.  As of 1997-12-02, this is the case for commonly-
282 	 * used filesystems.  There are other places in this code which
283 	 * make the same assumption.
284 	 */
285 	lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
286 		   LOCK_FILE_MODE);
287 	if (lfd < 0) {
288 		if (errno == EWOULDBLOCK)	/* active daemon present */
289 			exit(0);
290 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
291 		exit(1);
292 	}
293 	fcntl(lfd, F_SETFL, 0);	/* turn off non-blocking mode */
294 	ftruncate(lfd, 0);
295 	/*
296 	 * write process id for others to know
297 	 */
298 	sprintf(line, "%u\n", getpid());
299 	f = strlen(line);
300 	if (write(lfd, line, f) != f) {
301 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
302 		exit(1);
303 	}
304 	signal(SIGCHLD, reapchild);
305 	/*
306 	 * Restart all the printers.
307 	 */
308 	startup();
309 	(void) unlink(_PATH_SOCKETNAME);
310 	funix = socket(AF_UNIX, SOCK_STREAM, 0);
311 	if (funix < 0) {
312 		syslog(LOG_ERR, "socket: %m");
313 		exit(1);
314 	}
315 
316 	sigemptyset(&nmask);
317 	sigaddset(&nmask, SIGHUP);
318 	sigaddset(&nmask, SIGINT);
319 	sigaddset(&nmask, SIGQUIT);
320 	sigaddset(&nmask, SIGTERM);
321 	sigprocmask(SIG_BLOCK, &nmask, &omask);
322 
323 	(void) umask(07);
324 	signal(SIGHUP, mcleanup);
325 	signal(SIGINT, mcleanup);
326 	signal(SIGQUIT, mcleanup);
327 	signal(SIGTERM, mcleanup);
328 	memset(&un, 0, sizeof(un));
329 	un.sun_family = AF_UNIX;
330 	strcpy(un.sun_path, _PATH_SOCKETNAME);
331 #ifndef SUN_LEN
332 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
333 #endif
334 	if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
335 		syslog(LOG_ERR, "ubind: %m");
336 		exit(1);
337 	}
338 	(void) umask(0);
339 	sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
340 	FD_ZERO(&defreadfds);
341 	FD_SET(funix, &defreadfds);
342 	listen(funix, 5);
343 	if (sflag == 0) {
344 		finet = socksetup(family, socket_debug);
345 	} else
346 		finet = NULL;	/* pretend we couldn't open TCP socket. */
347 	if (finet) {
348 		for (i = 1; i <= *finet; i++) {
349 			FD_SET(finet[i], &defreadfds);
350 			listen(finet[i], 5);
351 		}
352 	}
353 	/*
354 	 * Main loop: accept, do a request, continue.
355 	 */
356 	memset(&frominet, 0, sizeof(frominet));
357 	memset(&fromunix, 0, sizeof(fromunix));
358 	if (lflag)
359 		syslog(LOG_INFO, "lpd startup: ready to accept requests");
360 	/*
361 	 * XXX - should be redone for multi-protocol
362 	 */
363 	for (;;) {
364 		int domain, nfds, s;
365 		fd_set readfds;
366 
367 		FD_COPY(&defreadfds, &readfds);
368 		nfds = select(20, &readfds, 0, 0, 0);
369 		if (nfds <= 0) {
370 			if (nfds < 0 && errno != EINTR)
371 				syslog(LOG_WARNING, "select: %m");
372 			continue;
373 		}
374 		domain = -1;		    /* avoid compile-time warning */
375 		s = -1;			    /* avoid compile-time warning */
376 		if (FD_ISSET(funix, &readfds)) {
377 			domain = AF_UNIX, fromlen = sizeof(fromunix);
378 			s = accept(funix,
379 			    (struct sockaddr *)&fromunix, &fromlen);
380  		} else {
381                         for (i = 1; i <= *finet; i++)
382 				if (FD_ISSET(finet[i], &readfds)) {
383 					domain = AF_INET;
384 					fromlen = sizeof(frominet);
385 					s = accept(finet[i],
386 					    (struct sockaddr *)&frominet,
387 					    &fromlen);
388 				}
389 		}
390 		if (s < 0) {
391 			if (errno != EINTR)
392 				syslog(LOG_WARNING, "accept: %m");
393 			continue;
394 		}
395 		if (fork() == 0) {
396 			/*
397 			 * Note that printjob() also plays around with
398 			 * signal-handling routines, and may need to be
399 			 * changed when making changes to signal-handling.
400 			 */
401 			signal(SIGCHLD, SIG_DFL);
402 			signal(SIGHUP, SIG_IGN);
403 			signal(SIGINT, SIG_IGN);
404 			signal(SIGQUIT, SIG_IGN);
405 			signal(SIGTERM, SIG_IGN);
406 			(void) close(funix);
407 			if (sflag == 0 && finet) {
408                         	for (i = 1; i <= *finet; i++)
409 					(void)close(finet[i]);
410 			}
411 			dup2(s, 1);
412 			(void) close(s);
413 			if (domain == AF_INET) {
414 				/* for both AF_INET and AF_INET6 */
415 				from_remote = 1;
416  				chkhost((struct sockaddr *)&frominet,
417 				    ch_options);
418 			} else
419 				from_remote = 0;
420 			doit();
421 			exit(0);
422 		}
423 		(void) close(s);
424 	}
425 }
426 
427 static void
428 reapchild(int signo __unused)
429 {
430 	int status;
431 
432 	while (wait3(&status, WNOHANG, 0) > 0)
433 		;
434 }
435 
436 static void
437 mcleanup(int signo)
438 {
439 	/*
440 	 * XXX syslog(3) is not signal-safe.
441 	 */
442 	if (lflag) {
443 		if (signo)
444 			syslog(LOG_INFO, "exiting on signal %d", signo);
445 		else
446 			syslog(LOG_INFO, "exiting");
447 	}
448 	unlink(_PATH_SOCKETNAME);
449 	exit(0);
450 }
451 
452 /*
453  * Stuff for handling job specifications
454  */
455 char	*user[MAXUSERS];	/* users to process */
456 int	users;			/* # of users in user array */
457 int	requ[MAXREQUESTS];	/* job number of spool entries */
458 int	requests;		/* # of spool requests */
459 char	*person;		/* name of person doing lprm */
460 
461 		 /* buffer to hold the client's machine-name */
462 static char	 frombuf[MAXHOSTNAMELEN];
463 char	cbuf[BUFSIZ];		/* command line buffer */
464 const char	*cmdnames[] = {
465 	"null",
466 	"printjob",
467 	"recvjob",
468 	"displayq short",
469 	"displayq long",
470 	"rmjob"
471 };
472 
473 static void
474 doit(void)
475 {
476 	char *cp, *printer;
477 	int n;
478 	int status;
479 	struct printer myprinter, *pp = &myprinter;
480 
481 	init_printer(&myprinter);
482 
483 	for (;;) {
484 		cp = cbuf;
485 		do {
486 			if (cp >= &cbuf[sizeof(cbuf) - 1])
487 				fatal(0, "Command line too long");
488 			if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
489 				if (n < 0)
490 					fatal(0, "Lost connection");
491 				return;
492 			}
493 		} while (*cp++ != '\n');
494 		*--cp = '\0';
495 		cp = cbuf;
496 		if (lflag) {
497 			if (*cp >= '\1' && *cp <= '\5')
498 				syslog(LOG_INFO, "%s requests %s %s",
499 					from_host, cmdnames[(u_char)*cp], cp+1);
500 			else
501 				syslog(LOG_INFO, "bad request (%d) from %s",
502 					*cp, from_host);
503 		}
504 		switch (*cp++) {
505 		case CMD_CHECK_QUE: /* check the queue, print any jobs there */
506 			startprinting(cp);
507 			break;
508 		case CMD_TAKE_THIS: /* receive files to be queued */
509 			if (!from_remote) {
510 				syslog(LOG_INFO, "illegal request (%d)", *cp);
511 				exit(1);
512 			}
513 			recvjob(cp);
514 			break;
515 		case CMD_SHOWQ_SHORT: /* display the queue (short form) */
516 		case CMD_SHOWQ_LONG: /* display the queue (long form) */
517 			/* XXX - this all needs to be redone. */
518 			printer = cp;
519 			while (*cp) {
520 				if (*cp != ' ') {
521 					cp++;
522 					continue;
523 				}
524 				*cp++ = '\0';
525 				while (isspace(*cp))
526 					cp++;
527 				if (*cp == '\0')
528 					break;
529 				if (isdigit(*cp)) {
530 					if (requests >= MAXREQUESTS)
531 						fatal(0, "Too many requests");
532 					requ[requests++] = atoi(cp);
533 				} else {
534 					if (users >= MAXUSERS)
535 						fatal(0, "Too many users");
536 					user[users++] = cp;
537 				}
538 			}
539 			status = getprintcap(printer, pp);
540 			if (status < 0)
541 				fatal(pp, "%s", pcaperr(status));
542 			displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
543 			exit(0);
544 		case CMD_RMJOB:	/* remove a job from the queue */
545 			if (!from_remote) {
546 				syslog(LOG_INFO, "illegal request (%d)", *cp);
547 				exit(1);
548 			}
549 			printer = cp;
550 			while (*cp && *cp != ' ')
551 				cp++;
552 			if (!*cp)
553 				break;
554 			*cp++ = '\0';
555 			person = cp;
556 			while (*cp) {
557 				if (*cp != ' ') {
558 					cp++;
559 					continue;
560 				}
561 				*cp++ = '\0';
562 				while (isspace(*cp))
563 					cp++;
564 				if (*cp == '\0')
565 					break;
566 				if (isdigit(*cp)) {
567 					if (requests >= MAXREQUESTS)
568 						fatal(0, "Too many requests");
569 					requ[requests++] = atoi(cp);
570 				} else {
571 					if (users >= MAXUSERS)
572 						fatal(0, "Too many users");
573 					user[users++] = cp;
574 				}
575 			}
576 			rmjob(printer);
577 			break;
578 		}
579 		fatal(0, "Illegal service request");
580 	}
581 }
582 
583 /*
584  * Make a pass through the printcap database and start printing any
585  * files left from the last time the machine went down.
586  */
587 static void
588 startup(void)
589 {
590 	int pid, status, more;
591 	struct printer myprinter, *pp = &myprinter;
592 
593 	more = firstprinter(pp, &status);
594 	if (status)
595 		goto errloop;
596 	while (more) {
597 		if (ckqueue(pp) <= 0) {
598 			goto next;
599 		}
600 		if (lflag)
601 			syslog(LOG_INFO, "lpd startup: work for %s",
602 			    pp->printer);
603 		if ((pid = fork()) < 0) {
604 			syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
605 			    pp->printer);
606 			mcleanup(0);
607 		}
608 		if (pid == 0) {
609 			lastprinter();
610 			printjob(pp);
611 			/* NOTREACHED */
612 		}
613 		do {
614 next:
615 			more = nextprinter(pp, &status);
616 errloop:
617 			if (status)
618 				syslog(LOG_WARNING,
619 				    "lpd startup: printcap entry for %s has errors, skipping",
620 				    pp->printer ? pp->printer : "<noname?>");
621 		} while (more && status);
622 	}
623 }
624 
625 /*
626  * Make sure there's some work to do before forking off a child
627  */
628 static int
629 ckqueue(struct printer *pp)
630 {
631 	register struct dirent *d;
632 	DIR *dirp;
633 	char *spooldir;
634 
635 	spooldir = pp->spool_dir;
636 	if ((dirp = opendir(spooldir)) == NULL)
637 		return (-1);
638 	while ((d = readdir(dirp)) != NULL) {
639 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
640 			continue;	/* daemon control files only */
641 		closedir(dirp);
642 		return (1);		/* found something */
643 	}
644 	closedir(dirp);
645 	return (0);
646 }
647 
648 #define DUMMY ":nobody::"
649 
650 /*
651  * Check to see if the host connecting to this host has access to any
652  * lpd services on this host.
653  */
654 static void
655 chkhost(struct sockaddr *f, int ch_opts)
656 {
657 	struct addrinfo hints, *res, *r;
658 	register FILE *hostf;
659 	char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
660 	char serv[NI_MAXSERV];
661 	char *syserr, *usererr;
662 	int error, errsav, fpass, good, wantsl;
663 
664 	wantsl = 0;
665 	if (ch_opts & LPD_LOGCONNERR)
666 		wantsl = 1;			/* also syslog the errors */
667 
668 	from_host = ".na.";
669 
670 	/* Need real hostname for temporary filenames */
671 	error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
672 	    NI_NAMEREQD);
673 	if (error) {
674 		errsav = error;
675 		error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
676 		    NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID);
677 		if (error) {
678 			asprintf(&syserr,
679 			    "can not determine hostname for remote host (%d,%d)",
680 			    errsav, error);
681 			asprintf(&usererr,
682 			    "Host name for your address is not known");
683 			fhosterr(ch_opts, syserr, usererr);
684 			/* NOTREACHED */
685 		}
686 		asprintf(&syserr,
687 		    "Host name for remote host (%s) not known (%d)",
688 		    hostbuf, errsav);
689 		asprintf(&usererr,
690 		    "Host name for your address (%s) is not known",
691 		    hostbuf);
692 		fhosterr(ch_opts, syserr, usererr);
693 		/* NOTREACHED */
694 	}
695 
696 	strlcpy(frombuf, hostbuf, sizeof(frombuf));
697 	from_host = frombuf;
698 	ch_opts |= LPD_ADDFROMLINE;
699 
700 	/* Need address in stringform for comparison (no DNS lookup here) */
701 	error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
702 	    NI_NUMERICHOST | NI_WITHSCOPEID);
703 	if (error) {
704 		asprintf(&syserr, "Cannot print IP address (error %d)",
705 		    error);
706 		asprintf(&usererr, "Cannot print IP address for your host");
707 		fhosterr(ch_opts, syserr, usererr);
708 		/* NOTREACHED */
709 	}
710 	from_ip = strdup(hostbuf);
711 
712 	/* Reject numeric addresses */
713 	memset(&hints, 0, sizeof(hints));
714 	hints.ai_family = family;
715 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
716 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
717 	if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
718 		freeaddrinfo(res);
719 		/* This syslog message already includes from_host */
720 		ch_opts &= ~LPD_ADDFROMLINE;
721 		asprintf(&syserr, "reverse lookup results in non-FQDN %s",
722 		    from_host);
723 		/* same message to both syslog and remote user */
724 		fhosterr(ch_opts, syserr, syserr);
725 		/* NOTREACHED */
726 	}
727 
728 	/* Check for spoof, ala rlogind */
729 	memset(&hints, 0, sizeof(hints));
730 	hints.ai_family = family;
731 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
732 	error = getaddrinfo(from_host, NULL, &hints, &res);
733 	if (error) {
734 		asprintf(&syserr, "dns lookup for address %s failed: %s",
735 		    from_ip, gai_strerror(error));
736 		asprintf(&usererr, "hostname for your address (%s) unknown: %s",
737 		    from_ip, gai_strerror(error));
738 		fhosterr(ch_opts, syserr, usererr);
739 		/* NOTREACHED */
740 	}
741 	good = 0;
742 	for (r = res; good == 0 && r; r = r->ai_next) {
743 		error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
744 		    NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID);
745 		if (!error && !strcmp(from_ip, ip))
746 			good = 1;
747 	}
748 	if (res)
749 		freeaddrinfo(res);
750 	if (good == 0) {
751 		asprintf(&syserr, "address for remote host (%s) not matched",
752 		    from_ip);
753 		asprintf(&usererr,
754 		    "address for your hostname (%s) not matched", from_ip);
755 		fhosterr(ch_opts, syserr, usererr);
756 		/* NOTREACHED */
757 	}
758 
759 	fpass = 1;
760 	hostf = fopen(_PATH_HOSTSEQUIV, "r");
761 again:
762 	if (hostf) {
763 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
764 			(void) fclose(hostf);
765 			goto foundhost;
766 		}
767 		(void) fclose(hostf);
768 	}
769 	if (fpass == 1) {
770 		fpass = 2;
771 		hostf = fopen(_PATH_HOSTSLPD, "r");
772 		goto again;
773 	}
774 	/* This syslog message already includes from_host */
775 	ch_opts &= ~LPD_ADDFROMLINE;
776 	asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
777 	    from_ip);
778 	asprintf(&usererr,
779 	    "Print-services are not available to your host (%s).", from_host);
780 	fhosterr(ch_opts, syserr, usererr);
781 	/* NOTREACHED */
782 
783 foundhost:
784 	if (ch_opts & LPD_NOPORTCHK)
785 		return;			/* skip the reserved-port check */
786 
787 	error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
788 	    NI_NUMERICSERV);
789 	if (error) {
790 		/* same message to both syslog and remote user */
791 		asprintf(&syserr, "malformed from-address (%d)", error);
792 		fhosterr(ch_opts, syserr, syserr);
793 		/* NOTREACHED */
794 	}
795 
796 	if (atoi(serv) >= IPPORT_RESERVED) {
797 		/* same message to both syslog and remote user */
798 		asprintf(&syserr, "connected from invalid port (%s)", serv);
799 		fhosterr(ch_opts, syserr, syserr);
800 		/* NOTREACHED */
801 	}
802 }
803 
804 /*
805  * Handle fatal errors in chkhost.  The first message will optionally be
806  * sent to syslog, the second one is sent to the connecting host.
807  *
808  * The idea is that the syslog message is meant for an administrator of a
809  * print server (the host receiving connections), while the usermsg is meant
810  * for a remote user who may or may not be clueful, and may or may not be
811  * doing something nefarious.  Some remote users (eg, MS-Windows...) may not
812  * even see whatever message is sent, which is why there's the option to
813  * start 'lpd' with the connection-errors also sent to syslog.
814  *
815  * Given that hostnames can theoretically be fairly long (well, over 250
816  * bytes), it would probably be helpful to have the 'from_host' field at
817  * the end of any error messages which include that info.
818  *
819  * These are Fatal host-connection errors, so this routine does not return.
820  */
821 static void
822 fhosterr(int ch_opts, char *sysmsg, char *usermsg)
823 {
824 
825 	/*
826 	 * If lpd was started up to print connection errors, then write
827 	 * the syslog message before the user message.
828 	 * And for many of the syslog messages, it is helpful to first
829 	 * write the from_host (if it is known) as a separate syslog
830 	 * message, since the hostname may be so long.
831 	 */
832 	if (ch_opts & LPD_LOGCONNERR) {
833 		if (ch_opts & LPD_ADDFROMLINE) {
834 		    syslog(LOG_WARNING, "for connection from %s:", from_host);
835 		}
836 		syslog(LOG_WARNING, "%s", sysmsg);
837 	}
838 
839 	/*
840 	 * Now send the error message to the remote host which is trying
841 	 * to make the connection.
842 	 */
843 	printf("%s [@%s]: %s\n", progname, local_host, usermsg);
844 	fflush(stdout);
845 
846 	/*
847 	 * Add a minimal delay before exiting (and disconnecting from the
848 	 * sending-host).  This is just in case that machine responds by
849 	 * INSTANTLY retrying (and instantly re-failing...).  This may also
850 	 * give the other side more time to read the error message.
851 	 */
852 	sleep(2);			/* a paranoid throttling measure */
853 	exit(1);
854 }
855 
856 /* setup server socket for specified address family */
857 /* if af is PF_UNSPEC more than one socket may be returned */
858 /* the returned list is dynamically allocated, so caller needs to free it */
859 static int *
860 socksetup(int af, int debuglvl)
861 {
862 	struct addrinfo hints, *res, *r;
863 	int error, maxs, *s, *socks;
864 	const int on = 1;
865 
866 	memset(&hints, 0, sizeof(hints));
867 	hints.ai_flags = AI_PASSIVE;
868 	hints.ai_family = af;
869 	hints.ai_socktype = SOCK_STREAM;
870 	error = getaddrinfo(NULL, "printer", &hints, &res);
871 	if (error) {
872 		syslog(LOG_ERR, "%s", gai_strerror(error));
873 		mcleanup(0);
874 	}
875 
876 	/* Count max number of sockets we may open */
877 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
878 		;
879 	socks = malloc((maxs + 1) * sizeof(int));
880 	if (!socks) {
881 		syslog(LOG_ERR, "couldn't allocate memory for sockets");
882 		mcleanup(0);
883 	}
884 
885 	*socks = 0;   /* num of sockets counter at start of array */
886 	s = socks + 1;
887 	for (r = res; r; r = r->ai_next) {
888 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
889 		if (*s < 0) {
890 			syslog(LOG_DEBUG, "socket(): %m");
891 			continue;
892 		}
893 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
894 		    < 0) {
895 			syslog(LOG_ERR, "setsockopt(SO_REUSEADDR): %m");
896 			close(*s);
897 			continue;
898 		}
899 		if (debuglvl)
900 			if (setsockopt(*s, SOL_SOCKET, SO_DEBUG, &debuglvl,
901 			    sizeof(debuglvl)) < 0) {
902 				syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
903 				close(*s);
904 				continue;
905 			}
906 		if (r->ai_family == AF_INET6) {
907 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
908 				       &on, sizeof(on)) < 0) {
909 				syslog(LOG_ERR,
910 				       "setsockopt (IPV6_V6ONLY): %m");
911 				close(*s);
912 				continue;
913 			}
914 		}
915 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
916 			syslog(LOG_DEBUG, "bind(): %m");
917 			close(*s);
918 			continue;
919 		}
920 		(*socks)++;
921 		s++;
922 	}
923 
924 	if (res)
925 		freeaddrinfo(res);
926 
927 	if (*socks == 0) {
928 		syslog(LOG_ERR, "Couldn't bind to any socket");
929 		free(socks);
930 		mcleanup(0);
931 	}
932 	return(socks);
933 }
934 
935 static void
936 usage(void)
937 {
938 #ifdef INET6
939 	fprintf(stderr, "usage: lpd [-cdlsW46] [port#]\n");
940 #else
941 	fprintf(stderr, "usage: lpd [-cdlsW] [port#]\n");
942 #endif
943 	exit(EX_USAGE);
944 }
945