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