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