1872b698pfg/*-
2872b698pfg * SPDX-License-Identifier: BSD-3-Clause
3872b698pfg *
4862fdf1rgrimes * Copyright (c) 1983, 1993, 1994
5862fdf1rgrimes *	The Regents of the University of California.  All rights reserved.
6862fdf1rgrimes *
7862fdf1rgrimes *
8862fdf1rgrimes * Redistribution and use in source and binary forms, with or without
9862fdf1rgrimes * modification, are permitted provided that the following conditions
10862fdf1rgrimes * are met:
11862fdf1rgrimes * 1. Redistributions of source code must retain the above copyright
12862fdf1rgrimes *    notice, this list of conditions and the following disclaimer.
13862fdf1rgrimes * 2. Redistributions in binary form must reproduce the above copyright
14862fdf1rgrimes *    notice, this list of conditions and the following disclaimer in the
15862fdf1rgrimes *    documentation and/or other materials provided with the distribution.
167e6cabdimp * 3. Neither the name of the University nor the names of its contributors
17862fdf1rgrimes *    may be used to endorse or promote products derived from this software
18862fdf1rgrimes *    without specific prior written permission.
19862fdf1rgrimes *
20862fdf1rgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21862fdf1rgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22862fdf1rgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23862fdf1rgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24862fdf1rgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25862fdf1rgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26862fdf1rgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27862fdf1rgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28862fdf1rgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29862fdf1rgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30862fdf1rgrimes * SUCH DAMAGE.
31862fdf1rgrimes */
32862fdf1rgrimes
33862fdf1rgrimes#ifndef lint
3449a43f1charnierstatic const char copyright[] =
35862fdf1rgrimes"@(#) Copyright (c) 1983, 1993, 1994\n\
36862fdf1rgrimes	The Regents of the University of California.  All rights reserved.\n";
37862fdf1rgrimes#endif /* not lint */
38862fdf1rgrimes
3949a43f1charnier#if 0
406c501bagad#ifndef lint
410291e84joergstatic char sccsid[] = "@(#)lpd.c	8.7 (Berkeley) 5/10/95";
426c501bagad#endif /* not lint */
4301f9734charnier#endif
4401f9734charnier
45317e204gad#include "lp.cdefs.h"		/* A cross-platform version of <sys/cdefs.h> */
4601f9734charnier__FBSDID("$FreeBSD$");
47862fdf1rgrimes
48862fdf1rgrimes/*
49862fdf1rgrimes * lpd -- line printer daemon.
50862fdf1rgrimes *
51862fdf1rgrimes * Listen for a connection and perform the requested operation.
52862fdf1rgrimes * Operations are:
53862fdf1rgrimes *	\1printer\n
54862fdf1rgrimes *		check the queue for jobs and print any found.
55862fdf1rgrimes *	\2printer\n
56862fdf1rgrimes *		receive a job from another machine and queue it.
57862fdf1rgrimes *	\3printer [users ...] [jobs ...]\n
58862fdf1rgrimes *		return the current state of the queue (short form).
59862fdf1rgrimes *	\4printer [users ...] [jobs ...]\n
60862fdf1rgrimes *		return the current state of the queue (long form).
61862fdf1rgrimes *	\5printer person [users ...] [jobs ...]\n
62862fdf1rgrimes *		remove jobs from the queue.
63862fdf1rgrimes *
64862fdf1rgrimes * Strategy to maintain protected spooling area:
65862fdf1rgrimes *	1. Spooling area is writable only by daemon and spooling group
66862fdf1rgrimes *	2. lpr runs setuid root and setgrp spooling group; it uses
67862fdf1rgrimes *	   root to access any file it wants (verifying things before
68862fdf1rgrimes *	   with an access call) and group id to know how it should
69862fdf1rgrimes *	   set up ownership of files in the spooling area.
70862fdf1rgrimes *	3. Files in spooling area are owned by root, group spooling
71862fdf1rgrimes *	   group, with mode 660.
72862fdf1rgrimes *	4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
73862fdf1rgrimes *	   access files and printer.  Users can't get to anything
74862fdf1rgrimes *	   w/o help of lpq and lprm programs.
75862fdf1rgrimes */
76862fdf1rgrimes
77862fdf1rgrimes#include <sys/param.h>
78862fdf1rgrimes#include <sys/wait.h>
79862fdf1rgrimes#include <sys/types.h>
80862fdf1rgrimes#include <sys/socket.h>
81862fdf1rgrimes#include <sys/un.h>
82862fdf1rgrimes#include <sys/stat.h>
830291e84joerg#include <sys/file.h>
84862fdf1rgrimes#include <netinet/in.h>
8523a9b35joerg#include <arpa/inet.h>
86862fdf1rgrimes
87862fdf1rgrimes#include <netdb.h>
88862fdf1rgrimes#include <unistd.h>
89862fdf1rgrimes#include <syslog.h>
90862fdf1rgrimes#include <signal.h>
9192b95fajoerg#include <err.h>
92862fdf1rgrimes#include <errno.h>
93862fdf1rgrimes#include <fcntl.h>
94862fdf1rgrimes#include <dirent.h>
95862fdf1rgrimes#include <stdio.h>
96862fdf1rgrimes#include <stdlib.h>
97862fdf1rgrimes#include <string.h>
9892b95fajoerg#include <sysexits.h>
99862fdf1rgrimes#include <ctype.h>
100862fdf1rgrimes#include "lp.h"
101862fdf1rgrimes#include "lp.local.h"
102862fdf1rgrimes#include "pathnames.h"
103862fdf1rgrimes#include "extern.h"
104862fdf1rgrimes
105862fdf1rgrimesint	lflag;				/* log requests flag */
106ef6b62cgadint	sflag;				/* no incoming port flag */
107862fdf1rgrimesint	from_remote;			/* from remote socket */
108862fdf1rgrimes
109d614283gadint		 main(int argc, char **_argv);
110d614283gadstatic void	 reapchild(int _signo);
111d614283gadstatic void	 mcleanup(int _signo);
112d614283gadstatic void	 doit(void);
113d614283gadstatic void	 startup(void);
114e066facgadstatic void	 chkhost(struct sockaddr *_f, int _ch_opts);
115d614283gadstatic int	 ckqueue(struct printer *_pp);
116e9953bbgadstatic void	 fhosterr(int _ch_opts, char *_sysmsg, char *_usermsg);
11730c0318gadstatic int	*socksetup(int _af, int _debuglvl);
118d614283gadstatic void	 usage(void);
119bd199e3ume
120bd199e3ume/* XXX from libc/net/rcmd.c */
121fa3791ekevloextern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
122fa3791ekevlo				const char *, const char *);
123862fdf1rgrimes
124f080009impuid_t	uid, euid;
125f080009imp
126e066facgad#define LPD_NOPORTCHK	0001		/* skip reserved-port check */
127e066facgad#define LPD_LOGCONNERR	0002		/* (sys)log connection errors */
128e9953bbgad#define LPD_ADDFROMLINE	0004		/* just used for fhosterr() */
129e066facgad
130862fdf1rgrimesint
131d614283gadmain(int argc, char **argv)
132862fdf1rgrimes{
133e6b7d1bgad	int ch_options, errs, f, funix, *finet, i, lfd, socket_debug;
134862fdf1rgrimes	fd_set defreadfds;
135862fdf1rgrimes	struct sockaddr_un un, fromunix;
136bd199e3ume	struct sockaddr_storage frominet;
137e6b7d1bgad	socklen_t fromlen;
138bf21e6bwollman	sigset_t omask, nmask;
13992b95fajoerg	struct servent *sp, serv;
140bd199e3ume	int inet_flag = 0, inet6_flag = 0;
141862fdf1rgrimes
142f080009imp	euid = geteuid();	/* these shouldn't be different */
143f080009imp	uid = getuid();
144e066facgad
145e066facgad	ch_options = 0;
1464867b0dgad	socket_debug = 0;
147e402d6cgad	gethostname(local_host, sizeof(local_host));
148f080009imp
149a2e364fgad	progname = "lpd";
150f080009imp
15192b95fajoerg	if (euid != 0)
15292b95fajoerg		errx(EX_NOPERM,"must run as root");
153862fdf1rgrimes
15492b95fajoerg	errs = 0;
155ef6b62cgad	while ((i = getopt(argc, argv, "cdlpswW46")) != -1)
15692b95fajoerg		switch (i) {
157e066facgad		case 'c':
158e066facgad			/* log all kinds of connection-errors to syslog */
159e066facgad			ch_options |= LPD_LOGCONNERR;
160e066facgad			break;
16192b95fajoerg		case 'd':
1624867b0dgad			socket_debug++;
16392b95fajoerg			break;
16492b95fajoerg		case 'l':
16592b95fajoerg			lflag++;
16692b95fajoerg			break;
167ef6b62cgad		case 'p':		/* letter initially used for -s */
168ef6b62cgad			/*
169ef6b62cgad			 * This will probably be removed with 5.0-release.
170ef6b62cgad			 */
171ef6b62cgad			/* FALLTHROUGH */
172ef6b62cgad		case 's':		/* secure (no inet) */
173ef6b62cgad			sflag++;
174409bbf8sheldonh			break;
175088f7e2gad		case 'w':		/* netbsd uses -w for maxwait */
176088f7e2gad			/*
177088f7e2gad			 * This will be removed after the release of 4.4, as
178088f7e2gad			 * it conflicts with -w in netbsd's lpd.  For now it
179088f7e2gad			 * is just a warning, so we won't suddenly break lpd
180088f7e2gad			 * for anyone who is currently using the option.
181088f7e2gad			 */
182088f7e2gad			syslog(LOG_WARNING,
183088f7e2gad			    "NOTE: the -w option has been renamed -W");
184088f7e2gad			syslog(LOG_WARNING,
185088f7e2gad			    "NOTE: please change your lpd config to use -W");
186088f7e2gad			/* FALLTHROUGH */
187088f7e2gad		case 'W':
188e066facgad			/* allow connections coming from a non-reserved port */
189e066facgad			/* (done by some lpr-implementations for MS-Windows) */
190e066facgad			ch_options |= LPD_NOPORTCHK;
191e066facgad			break;
192bd199e3ume		case '4':
193bd199e3ume			family = PF_INET;
194bd199e3ume			inet_flag++;
195bd199e3ume			break;
196bd199e3ume		case '6':
1978f86229gad#ifdef INET6
198bd199e3ume			family = PF_INET6;
199bd199e3ume			inet6_flag++;
2008f86229gad#else
2018f86229gad			errx(EX_USAGE, "lpd compiled sans INET6 (IPv6 support)");
2028f86229gad#endif
203bd199e3ume			break;
204088f7e2gad		/*
205088f7e2gad		 * The following options are not in FreeBSD (yet?), but are
206088f7e2gad		 * listed here to "reserve" them, because the option-letters
207088f7e2gad		 * are used by either NetBSD or OpenBSD (as of July 2001).
208088f7e2gad		 */
209088f7e2gad		case 'b':		/* set bind-addr */
210088f7e2gad		case 'n':		/* set max num of children */
211088f7e2gad		case 'r':		/* allow 'of' for remote ptrs */
212088f7e2gad					/* ...[not needed in freebsd] */
213088f7e2gad			/* FALLTHROUGH */
21492b95fajoerg		default:
21592b95fajoerg			errs++;
21692b95fajoerg		}
217bd199e3ume	if (inet_flag && inet6_flag)
218bd199e3ume		family = PF_UNSPEC;
21992b95fajoerg	argc -= optind;
22092b95fajoerg	argv += optind;
22192b95fajoerg	if (errs)
22292b95fajoerg		usage();
22392b95fajoerg
22492b95fajoerg	if (argc == 1) {
22592b95fajoerg		if ((i = atoi(argv[0])) == 0)
22692b95fajoerg			usage();
22792b95fajoerg		if (i < 0 || i > USHRT_MAX)
22892b95fajoerg			errx(EX_USAGE, "port # %d is invalid", i);
22992b95fajoerg
23092b95fajoerg		serv.s_port = htons(i);
23192b95fajoerg		sp = &serv;
23292b95fajoerg		argc--;
23392b95fajoerg	} else {
23492b95fajoerg		sp = getservbyname("printer", "tcp");
23592b95fajoerg		if (sp == NULL)
23692b95fajoerg			errx(EX_OSFILE, "printer/tcp: unknown service");
237862fdf1rgrimes	}
238862fdf1rgrimes
23992b95fajoerg	if (argc != 0)
24092b95fajoerg		usage();
24192b95fajoerg
242bf21e6bwollman	/*
243bf21e6bwollman	 * We run chkprintcap right away to catch any errors and blat them
244bf21e6bwollman	 * to stderr while we still have it open, rather than sending them
245bf21e6bwollman	 * to syslog and leaving the user wondering why lpd started and
246bf21e6bwollman	 * then stopped.  There should probably be a command-line flag to
247bf21e6bwollman	 * ignore errors from chkprintcap.
248bf21e6bwollman	 */
249bf21e6bwollman	{
250bf21e6bwollman		pid_t pid;
251bf21e6bwollman		int status;
252bf21e6bwollman		pid = fork();
253bf21e6bwollman		if (pid < 0) {
254bf21e6bwollman			err(EX_OSERR, "cannot fork");
255bf21e6bwollman		} else if (pid == 0) {	/* child */
256bf21e6bwollman			execl(_PATH_CHKPRINTCAP, _PATH_CHKPRINTCAP, (char *)0);
257bf21e6bwollman			err(EX_OSERR, "cannot execute %s", _PATH_CHKPRINTCAP);
258bf21e6bwollman		}
259bf21e6bwollman		if (waitpid(pid, &status, 0) < 0) {
260bf21e6bwollman			err(EX_OSERR, "cannot wait");
261bf21e6bwollman		}
262bf21e6bwollman		if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
263bf21e6bwollman			errx(EX_OSFILE, "%d errors in printcap file, exiting",
264bf21e6bwollman			     WEXITSTATUS(status));
265bf21e6bwollman	}
266bf21e6bwollman
267862fdf1rgrimes#ifndef DEBUG
268862fdf1rgrimes	/*
269862fdf1rgrimes	 * Set up standard environment by detaching from the parent.
270862fdf1rgrimes	 */
271862fdf1rgrimes	daemon(0, 0);
272862fdf1rgrimes#endif
273862fdf1rgrimes
274862fdf1rgrimes	openlog("lpd", LOG_PID, LOG_LPR);
275ef6b62cgad	syslog(LOG_INFO, "lpd startup: logging=%d%s%s", lflag,
276ef6b62cgad	    socket_debug ? " dbg" : "", sflag ? " net-secure" : "");
277862fdf1rgrimes	(void) umask(0);
278bf21e6bwollman	/*
279bf21e6bwollman	 * NB: This depends on O_NONBLOCK semantics doing the right thing;
280bf21e6bwollman	 * i.e., applying only to the O_EXLOCK and not to the rest of the
281bf21e6bwollman	 * open/creation.  As of 1997-12-02, this is the case for commonly-
282bf21e6bwollman	 * used filesystems.  There are other places in this code which
283bf21e6bwollman	 * make the same assumption.
284bf21e6bwollman	 */
285bf21e6bwollman	lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT|O_EXLOCK|O_NONBLOCK,
286bf21e6bwollman		   LOCK_FILE_MODE);
287862fdf1rgrimes	if (lfd < 0) {
288e9f3129gad		if (errno == EWOULDBLOCK)	/* active daemon present */
289862fdf1rgrimes			exit(0);
290862fdf1rgrimes		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
291862fdf1rgrimes		exit(1);
292862fdf1rgrimes	}
293bf21e6bwollman	fcntl(lfd, F_SETFL, 0);	/* turn off non-blocking mode */
294862fdf1rgrimes	ftruncate(lfd, 0);
295862fdf1rgrimes	/*
296862fdf1rgrimes	 * write process id for others to know
297862fdf1rgrimes	 */
298862fdf1rgrimes	sprintf(line, "%u\n", getpid());
299862fdf1rgrimes	f = strlen(line);
300862fdf1rgrimes	if (write(lfd, line, f) != f) {
301862fdf1rgrimes		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
302862fdf1rgrimes		exit(1);
303862fdf1rgrimes	}
304862fdf1rgrimes	signal(SIGCHLD, reapchild);
305862fdf1rgrimes	/*
306862fdf1rgrimes	 * Restart all the printers.
307862fdf1rgrimes	 */
308862fdf1rgrimes	startup();
309862fdf1rgrimes	(void) unlink(_PATH_SOCKETNAME);
310862fdf1rgrimes	funix = socket(AF_UNIX, SOCK_STREAM, 0);
311862fdf1rgrimes	if (funix < 0) {
312862fdf1rgrimes		syslog(LOG_ERR, "socket: %m");
313862fdf1rgrimes		exit(1);
314862fdf1rgrimes	}
315bf21e6bwollman
316bf21e6bwollman	sigemptyset(&nmask);
317bf21e6bwollman	sigaddset(&nmask, SIGHUP);
318bf21e6bwollman	sigaddset(&nmask, SIGINT);
319bf21e6bwollman	sigaddset(&nmask, SIGQUIT);
320bf21e6bwollman	sigaddset(&nmask, SIGTERM);
321bf21e6bwollman	sigprocmask(SIG_BLOCK, &nmask, &omask);
322bf21e6bwollman
323354a4dbimp	(void) umask(07);
324862fdf1rgrimes	signal(SIGHUP, mcleanup);
325862fdf1rgrimes	signal(SIGINT, mcleanup);
326862fdf1rgrimes	signal(SIGQUIT, mcleanup);
327862fdf1rgrimes	signal(SIGTERM, mcleanup);
328862fdf1rgrimes	memset(&un, 0, sizeof(un));
329862fdf1rgrimes	un.sun_family = AF_UNIX;
330862fdf1rgrimes	strcpy(un.sun_path, _PATH_SOCKETNAME);
331862fdf1rgrimes#ifndef SUN_LEN
332862fdf1rgrimes#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
333862fdf1rgrimes#endif
334862fdf1rgrimes	if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
335862fdf1rgrimes		syslog(LOG_ERR, "ubind: %m");
336862fdf1rgrimes		exit(1);
337862fdf1rgrimes	}
338354a4dbimp	(void) umask(0);
339bf21e6bwollman	sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
340862fdf1rgrimes	FD_ZERO(&defreadfds);
341862fdf1rgrimes	FD_SET(funix, &defreadfds);
342862fdf1rgrimes	listen(funix, 5);
343ef6b62cgad	if (sflag == 0) {
34430c0318gad		finet = socksetup(family, socket_debug);
345bd199e3ume	} else
346bd199e3ume		finet = NULL;	/* pretend we couldn't open TCP socket. */
347bd199e3ume	if (finet) {
348bd199e3ume		for (i = 1; i <= *finet; i++) {
349bd199e3ume			FD_SET(finet[i], &defreadfds);
350bd199e3ume			listen(finet[i], 5);
351862fdf1rgrimes		}
352862fdf1rgrimes	}
353862fdf1rgrimes	/*
354862fdf1rgrimes	 * Main loop: accept, do a request, continue.
355862fdf1rgrimes	 */
356862fdf1rgrimes	memset(&frominet, 0, sizeof(frominet));
357862fdf1rgrimes	memset(&fromunix, 0, sizeof(fromunix));
3584867b0dgad	if (lflag)
3594867b0dgad		syslog(LOG_INFO, "lpd startup: ready to accept requests");
360bf21e6bwollman	/*
361bf21e6bwollman	 * XXX - should be redone for multi-protocol
362bf21e6bwollman	 */
363862fdf1rgrimes	for (;;) {
36430c0318gad		int domain, nfds, s;
365862fdf1rgrimes		fd_set readfds;
366862fdf1rgrimes
367862fdf1rgrimes		FD_COPY(&defreadfds, &readfds);
368862fdf1rgrimes		nfds = select(20, &readfds, 0, 0, 0);
369862fdf1rgrimes		if (nfds <= 0) {
370862fdf1rgrimes			if (nfds < 0 && errno != EINTR)
371862fdf1rgrimes				syslog(LOG_WARNING, "select: %m");
372862fdf1rgrimes			continue;
373862fdf1rgrimes		}
37430c0318gad		domain = -1;		    /* avoid compile-time warning */
37530c0318gad		s = -1;			    /* avoid compile-time warning */
376862fdf1rgrimes		if (FD_ISSET(funix, &readfds)) {
377862fdf1rgrimes			domain = AF_UNIX, fromlen = sizeof(fromunix);
378862fdf1rgrimes			s = accept(funix,
379862fdf1rgrimes			    (struct sockaddr *)&fromunix, &fromlen);
380bd199e3ume 		} else {
381bd199e3ume                        for (i = 1; i <= *finet; i++)
382bd199e3ume				if (FD_ISSET(finet[i], &readfds)) {
383bd199e3ume					domain = AF_INET;
384bd199e3ume					fromlen = sizeof(frominet);
385bd199e3ume					s = accept(finet[i],
386bd199e3ume					    (struct sockaddr *)&frominet,
387bd199e3ume					    &fromlen);
388bd199e3ume				}
389862fdf1rgrimes		}
390862fdf1rgrimes		if (s < 0) {
391862fdf1rgrimes			if (errno != EINTR)
392862fdf1rgrimes				syslog(LOG_WARNING, "accept: %m");
393862fdf1rgrimes			continue;
394862fdf1rgrimes		}
395862fdf1rgrimes		if (fork() == 0) {
3960055616gad			/*
3970055616gad			 * Note that printjob() also plays around with
3980055616gad			 * signal-handling routines, and may need to be
3990055616gad			 * changed when making changes to signal-handling.
4000055616gad			 */
4010055616gad			signal(SIGCHLD, SIG_DFL);
402862fdf1rgrimes			signal(SIGHUP, SIG_IGN);
403862fdf1rgrimes			signal(SIGINT, SIG_IGN);
404862fdf1rgrimes			signal(SIGQUIT, SIG_IGN);
405862fdf1rgrimes			signal(SIGTERM, SIG_IGN);
406862fdf1rgrimes			(void) close(funix);
407ef6b62cgad			if (sflag == 0 && finet) {
408bd199e3ume                        	for (i = 1; i <= *finet; i++)
409bd199e3ume					(void)close(finet[i]);
410409bbf8sheldonh			}
411fb44318gad			dup2(s, STDOUT_FILENO);
412862fdf1rgrimes			(void) close(s);
413862fdf1rgrimes			if (domain == AF_INET) {
414bd199e3ume				/* for both AF_INET and AF_INET6 */
415862fdf1rgrimes				from_remote = 1;
416e066facgad 				chkhost((struct sockaddr *)&frominet,
417e066facgad				    ch_options);
418862fdf1rgrimes			} else
419862fdf1rgrimes				from_remote = 0;
420862fdf1rgrimes			doit();
421862fdf1rgrimes			exit(0);
422862fdf1rgrimes		}
423862fdf1rgrimes		(void) close(s);
424862fdf1rgrimes	}
425862fdf1rgrimes}
426862fdf1rgrimes
427862fdf1rgrimesstatic void
428d614283gadreapchild(int signo __unused)
429862fdf1rgrimes{
430329e6ebgad	int status;
431862fdf1rgrimes
432329e6ebgad	while (wait3(&status, WNOHANG, 0) > 0)
433862fdf1rgrimes		;
434862fdf1rgrimes}
435862fdf1rgrimes
436862fdf1rgrimesstatic void
437d614283gadmcleanup(int signo)
438862fdf1rgrimes{
439b8ec81dwollman	/*
440b8ec81dwollman	 * XXX syslog(3) is not signal-safe.
441b8ec81dwollman	 */
442b8ec81dwollman	if (lflag) {
443b8ec81dwollman		if (signo)
444b8ec81dwollman			syslog(LOG_INFO, "exiting on signal %d", signo);
445b8ec81dwollman		else
446b8ec81dwollman			syslog(LOG_INFO, "exiting");
447b8ec81dwollman	}
448862fdf1rgrimes	unlink(_PATH_SOCKETNAME);
449862fdf1rgrimes	exit(0);
450862fdf1rgrimes}
451862fdf1rgrimes
452862fdf1rgrimes/*
453862fdf1rgrimes * Stuff for handling job specifications
454862fdf1rgrimes */
455862fdf1rgrimeschar	*user[MAXUSERS];	/* users to process */
456862fdf1rgrimesint	users;			/* # of users in user array */
457862fdf1rgrimesint	requ[MAXREQUESTS];	/* job number of spool entries */
458862fdf1rgrimesint	requests;		/* # of spool requests */
459862fdf1rgrimeschar	*person;		/* name of person doing lprm */
460862fdf1rgrimes
461e402d6cgad		 /* buffer to hold the client's machine-name */
462e402d6cgadstatic char	 frombuf[MAXHOSTNAMELEN];
463862fdf1rgrimeschar	cbuf[BUFSIZ];		/* command line buffer */
464d614283gadconst char	*cmdnames[] = {
465862fdf1rgrimes	"null",
466862fdf1rgrimes	"printjob",
467862fdf1rgrimes	"recvjob",
468862fdf1rgrimes	"displayq short",
469862fdf1rgrimes	"displayq long",
470862fdf1rgrimes	"rmjob"
471862fdf1rgrimes};
472862fdf1rgrimes
473862fdf1rgrimesstatic void
474d614283gaddoit(void)
475862fdf1rgrimes{
476bf21e6bwollman	char *cp, *printer;
477bf21e6bwollman	int n;
478bf21e6bwollman	int status;
479bf21e6bwollman	struct printer myprinter, *pp = &myprinter;
480bf21e6bwollman
481bf21e6bwollman	init_printer(&myprinter);
482862fdf1rgrimes
483862fdf1rgrimes	for (;;) {
484862fdf1rgrimes		cp = cbuf;
485862fdf1rgrimes		do {
486862fdf1rgrimes			if (cp >= &cbuf[sizeof(cbuf) - 1])
487bf21e6bwollman				fatal(0, "Command line too long");
488352a508gad			if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
489862fdf1rgrimes				if (n < 0)
490bf21e6bwollman					fatal(0, "Lost connection");
491862fdf1rgrimes				return;
492862fdf1rgrimes			}
493862fdf1rgrimes		} while (*cp++ != '\n');
494862fdf1rgrimes		*--cp = '\0';
495862fdf1rgrimes		cp = cbuf;
496862fdf1rgrimes		if (lflag) {
497862fdf1rgrimes			if (*cp >= '\1' && *cp <= '\5')
498862fdf1rgrimes				syslog(LOG_INFO, "%s requests %s %s",
499e402d6cgad					from_host, cmdnames[(u_char)*cp], cp+1);
500862fdf1rgrimes			else
501862fdf1rgrimes				syslog(LOG_INFO, "bad request (%d) from %s",
502e402d6cgad					*cp, from_host);
503862fdf1rgrimes		}
504862fdf1rgrimes		switch (*cp++) {
505bf21e6bwollman		case CMD_CHECK_QUE: /* check the queue, print any jobs there */
506bf21e6bwollman			startprinting(cp);
507862fdf1rgrimes			break;
508bf21e6bwollman		case CMD_TAKE_THIS: /* receive files to be queued */
509862fdf1rgrimes			if (!from_remote) {
510862fdf1rgrimes				syslog(LOG_INFO, "illegal request (%d)", *cp);
511862fdf1rgrimes				exit(1);
512862fdf1rgrimes			}
513bf21e6bwollman			recvjob(cp);
514862fdf1rgrimes			break;
515bf21e6bwollman		case CMD_SHOWQ_SHORT: /* display the queue (short form) */
516bf21e6bwollman		case CMD_SHOWQ_LONG: /* display the queue (long form) */
517bf21e6bwollman			/* XXX - this all needs to be redone. */
518862fdf1rgrimes			printer = cp;
519862fdf1rgrimes			while (*cp) {
520862fdf1rgrimes				if (*cp != ' ') {
521862fdf1rgrimes					cp++;
522862fdf1rgrimes					continue;
523862fdf1rgrimes				}
524862fdf1rgrimes				*cp++ = '\0';
525862fdf1rgrimes				while (isspace(*cp))
526862fdf1rgrimes					cp++;
527862fdf1rgrimes				if (*cp == '\0')
528862fdf1rgrimes					break;
529862fdf1rgrimes				if (isdigit(*cp)) {
530862fdf1rgrimes					if (requests >= MAXREQUESTS)
531bf21e6bwollman						fatal(0, "Too many requests");
532862fdf1rgrimes					requ[requests++] = atoi(cp);
533862fdf1rgrimes				} else {
534862fdf1rgrimes					if (users >= MAXUSERS)
535bf21e6bwollman						fatal(0, "Too many users");
536862fdf1rgrimes					user[users++] = cp;
537862fdf1rgrimes				}
538862fdf1rgrimes			}
539bf21e6bwollman			status = getprintcap(printer, pp);
540bf21e6bwollman			if (status < 0)
54175f5203gad				fatal(pp, "%s", pcaperr(status));
542bf21e6bwollman			displayq(pp, cbuf[0] == CMD_SHOWQ_LONG);
543862fdf1rgrimes			exit(0);
544bf21e6bwollman		case CMD_RMJOB:	/* remove a job from the queue */
545862fdf1rgrimes			if (!from_remote) {
546862fdf1rgrimes				syslog(LOG_INFO, "illegal request (%d)", *cp);
547862fdf1rgrimes				exit(1);
548862fdf1rgrimes			}
549862fdf1rgrimes			printer = cp;
550862fdf1rgrimes			while (*cp && *cp != ' ')
551862fdf1rgrimes				cp++;
552862fdf1rgrimes			if (!*cp)
553862fdf1rgrimes				break;
554862fdf1rgrimes			*cp++ = '\0';
555862fdf1rgrimes			person = cp;
556862fdf1rgrimes			while (*cp) {
557862fdf1rgrimes				if (*cp != ' ') {
558862fdf1rgrimes					cp++;
559862fdf1rgrimes					continue;
560862fdf1rgrimes				}
561862fdf1rgrimes				*cp++ = '\0';
562862fdf1rgrimes				while (isspace(*cp))
563862fdf1rgrimes					cp++;
564862fdf1rgrimes				if (*cp == '\0')
565862fdf1rgrimes					break;
566862fdf1rgrimes				if (isdigit(*cp)) {
567862fdf1rgrimes					if (requests >= MAXREQUESTS)
568bf21e6bwollman						fatal(0, "Too many requests");
569862fdf1rgrimes					requ[requests++] = atoi(cp);
570862fdf1rgrimes				} else {
571862fdf1rgrimes					if (users >= MAXUSERS)
572bf21e6bwollman						fatal(0, "Too many users");
573862fdf1rgrimes					user[users++] = cp;
574862fdf1rgrimes				}
575862fdf1rgrimes			}
576bf21e6bwollman			rmjob(printer);
577862fdf1rgrimes			break;
578862fdf1rgrimes		}
579bf21e6bwollman		fatal(0, "Illegal service request");
580862fdf1rgrimes	}
581862fdf1rgrimes}
582862fdf1rgrimes
583862fdf1rgrimes/*
584862fdf1rgrimes * Make a pass through the printcap database and start printing any
585862fdf1rgrimes * files left from the last time the machine went down.
586862fdf1rgrimes */
587862fdf1rgrimesstatic void
588d614283gadstartup(void)
589862fdf1rgrimes{
590bf21e6bwollman	int pid, status, more;
591bf21e6bwollman	struct printer myprinter, *pp = &myprinter;
592bf21e6bwollman
593bf21e6bwollman	more = firstprinter(pp, &status);
594bf21e6bwollman	if (status)
595bf21e6bwollman		goto errloop;
596bf21e6bwollman	while (more) {
597bf21e6bwollman		if (ckqueue(pp) <= 0) {
598bf21e6bwollman			goto next;
5993a163babrian		}
6000291e84joerg		if (lflag)
6014867b0dgad			syslog(LOG_INFO, "lpd startup: work for %s",
6024867b0dgad			    pp->printer);
603862fdf1rgrimes		if ((pid = fork()) < 0) {
6044867b0dgad			syslog(LOG_WARNING, "lpd startup: cannot fork for %s",
6054867b0dgad			    pp->printer);
606862fdf1rgrimes			mcleanup(0);
607862fdf1rgrimes		}
608bf21e6bwollman		if (pid == 0) {
609bf21e6bwollman			lastprinter();
610bf21e6bwollman			printjob(pp);
6110291e84joerg			/* NOTREACHED */
612862fdf1rgrimes		}
613bf21e6bwollman		do {
614bf21e6bwollmannext:
615bf21e6bwollman			more = nextprinter(pp, &status);
616bf21e6bwollmanerrloop:
617bf21e6bwollman			if (status)
618bf21e6bwollman				syslog(LOG_WARNING,
6194867b0dgad				    "lpd startup: printcap entry for %s has errors, skipping",
62095d8cd7gad				    pp->printer ? pp->printer : "<noname?>");
621bf21e6bwollman		} while (more && status);
6220291e84joerg	}
6230291e84joerg}
6240291e84joerg
6250291e84joerg/*
6260291e84joerg * Make sure there's some work to do before forking off a child
6270291e84joerg */
6280291e84joergstatic int
629d614283gadckqueue(struct printer *pp)
6300291e84joerg{
6310291e84joerg	register struct dirent *d;
6320291e84joerg	DIR *dirp;
6330291e84joerg	char *spooldir;
6340291e84joerg
635bf21e6bwollman	spooldir = pp->spool_dir;
6360291e84joerg	if ((dirp = opendir(spooldir)) == NULL)
6370291e84joerg		return (-1);
6380291e84joerg	while ((d = readdir(dirp)) != NULL) {
6390291e84joerg		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
6400291e84joerg			continue;	/* daemon control files only */
6410291e84joerg		closedir(dirp);
6420291e84joerg		return (1);		/* found something */
643862fdf1rgrimes	}
6440291e84joerg	closedir(dirp);
6450291e84joerg	return (0);
646862fdf1rgrimes}
647862fdf1rgrimes
648862fdf1rgrimes#define DUMMY ":nobody::"
649862fdf1rgrimes
650862fdf1rgrimes/*
651e066facgad * Check to see if the host connecting to this host has access to any
652e066facgad * lpd services on this host.
653862fdf1rgrimes */
654862fdf1rgrimesstatic void
655e066facgadchkhost(struct sockaddr *f, int ch_opts)
656862fdf1rgrimes{
657bd199e3ume	struct addrinfo hints, *res, *r;
658862fdf1rgrimes	register FILE *hostf;
659e402d6cgad	char hostbuf[NI_MAXHOST], ip[NI_MAXHOST];
660bd199e3ume	char serv[NI_MAXSERV];
661e9953bbgad	char *syserr, *usererr;
662ae5f819gad	int error, errsav, fpass, good;
663e066facgad
664e066facgad	from_host = ".na.";
665862fdf1rgrimes
666862fdf1rgrimes	/* Need real hostname for temporary filenames */
667e402d6cgad	error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
668e402d6cgad	    NI_NAMEREQD);
669bd199e3ume	if (error) {
670e066facgad		errsav = error;
671e402d6cgad		error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf),
6727ef908fume		    NULL, 0, NI_NUMERICHOST);
673e9953bbgad		if (error) {
674e9953bbgad			asprintf(&syserr,
675e9953bbgad			    "can not determine hostname for remote host (%d,%d)",
676e9953bbgad			    errsav, error);
677e9953bbgad			asprintf(&usererr,
678e9953bbgad			    "Host name for your address is not known");
679e9953bbgad			fhosterr(ch_opts, syserr, usererr);
680e9953bbgad			/* NOTREACHED */
681e9953bbgad		}
682e9953bbgad		asprintf(&syserr,
683e9953bbgad		    "Host name for remote host (%s) not known (%d)",
684e9953bbgad		    hostbuf, errsav);
685e9953bbgad		asprintf(&usererr,
686e9953bbgad		    "Host name for your address (%s) is not known",
687e9953bbgad		    hostbuf);
688e9953bbgad		fhosterr(ch_opts, syserr, usererr);
689e9953bbgad		/* NOTREACHED */
690bd199e3ume	}
691862fdf1rgrimes
692e402d6cgad	strlcpy(frombuf, hostbuf, sizeof(frombuf));
693e402d6cgad	from_host = frombuf;
694e9953bbgad	ch_opts |= LPD_ADDFROMLINE;
695bd199e3ume
696bd199e3ume	/* Need address in stringform for comparison (no DNS lookup here) */
697e402d6cgad	error = getnameinfo(f, f->sa_len, hostbuf, sizeof(hostbuf), NULL, 0,
6987ef908fume	    NI_NUMERICHOST);
699e9953bbgad	if (error) {
700e9953bbgad		asprintf(&syserr, "Cannot print IP address (error %d)",
701e9953bbgad		    error);
702e9953bbgad		asprintf(&usererr, "Cannot print IP address for your host");
703e9953bbgad		fhosterr(ch_opts, syserr, usererr);
704e9953bbgad		/* NOTREACHED */
705e9953bbgad	}
706e402d6cgad	from_ip = strdup(hostbuf);
707862fdf1rgrimes
708bd199e3ume	/* Reject numeric addresses */
709bd199e3ume	memset(&hints, 0, sizeof(hints));
710bd199e3ume	hints.ai_family = family;
711bd199e3ume	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
712bd199e3ume	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
713e402d6cgad	if (getaddrinfo(from_host, NULL, &hints, &res) == 0) {
714bd199e3ume		freeaddrinfo(res);
715e9953bbgad		/* This syslog message already includes from_host */
716e9953bbgad		ch_opts &= ~LPD_ADDFROMLINE;
717e9953bbgad		asprintf(&syserr, "reverse lookup results in non-FQDN %s",
718e066facgad		    from_host);
719e9953bbgad		/* same message to both syslog and remote user */
720e9953bbgad		fhosterr(ch_opts, syserr, syserr);
721e9953bbgad		/* NOTREACHED */
722bd199e3ume	}
723bd199e3ume
724354a4dbimp	/* Check for spoof, ala rlogind */
725bd199e3ume	memset(&hints, 0, sizeof(hints));
726bd199e3ume	hints.ai_family = family;
727bd199e3ume	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
728e402d6cgad	error = getaddrinfo(from_host, NULL, &hints, &res);
729bd199e3ume	if (error) {
730e9953bbgad		asprintf(&syserr, "dns lookup for address %s failed: %s",
731e9953bbgad		    from_ip, gai_strerror(error));
732e9953bbgad		asprintf(&usererr, "hostname for your address (%s) unknown: %s",
733e9953bbgad		    from_ip, gai_strerror(error));
734e9953bbgad		fhosterr(ch_opts, syserr, usererr);
735e9953bbgad		/* NOTREACHED */
736bd199e3ume	}
737bd199e3ume	good = 0;
738bd199e3ume	for (r = res; good == 0 && r; r = r->ai_next) {
739bd199e3ume		error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
7407ef908fume		    NULL, 0, NI_NUMERICHOST);
741bd199e3ume		if (!error && !strcmp(from_ip, ip))
742354a4dbimp			good = 1;
743354a4dbimp	}
744bd199e3ume	if (res)
745bd199e3ume		freeaddrinfo(res);
746e9953bbgad	if (good == 0) {
747e9953bbgad		asprintf(&syserr, "address for remote host (%s) not matched",
748e9953bbgad		    from_ip);
749e9953bbgad		asprintf(&usererr,
750e066facgad		    "address for your hostname (%s) not matched", from_ip);
751e9953bbgad		fhosterr(ch_opts, syserr, usererr);
752e9953bbgad		/* NOTREACHED */
753e9953bbgad	}
754354a4dbimp
755e066facgad	fpass = 1;
756862fdf1rgrimes	hostf = fopen(_PATH_HOSTSEQUIV, "r");
757862fdf1rgrimesagain:
758862fdf1rgrimes	if (hostf) {
759bd199e3ume		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
760862fdf1rgrimes			(void) fclose(hostf);
761e066facgad			goto foundhost;
762862fdf1rgrimes		}
763862fdf1rgrimes		(void) fclose(hostf);
764862fdf1rgrimes	}
765e066facgad	if (fpass == 1) {
766e066facgad		fpass = 2;
767862fdf1rgrimes		hostf = fopen(_PATH_HOSTSLPD, "r");
768862fdf1rgrimes		goto again;
769862fdf1rgrimes	}
770e9953bbgad	/* This syslog message already includes from_host */
771e9953bbgad	ch_opts &= ~LPD_ADDFROMLINE;
772e9953bbgad	asprintf(&syserr, "refused connection from %s, sip=%s", from_host,
773e066facgad	    from_ip);
774e9953bbgad	asprintf(&usererr,
775e9953bbgad	    "Print-services are not available to your host (%s).", from_host);
776e9953bbgad	fhosterr(ch_opts, syserr, usererr);
777e9953bbgad	/* NOTREACHED */
778e066facgad
779e066facgadfoundhost:
780e066facgad	if (ch_opts & LPD_NOPORTCHK)
781e066facgad		return;			/* skip the reserved-port check */
782e066facgad
783e066facgad	error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
784e066facgad	    NI_NUMERICSERV);
785e9953bbgad	if (error) {
786e9953bbgad		/* same message to both syslog and remote user */
787e9953bbgad		asprintf(&syserr, "malformed from-address (%d)", error);
788e9953bbgad		fhosterr(ch_opts, syserr, syserr);
789e9953bbgad		/* NOTREACHED */
790e9953bbgad	}
791e066facgad
792e9953bbgad	if (atoi(serv) >= IPPORT_RESERVED) {
793e9953bbgad		/* same message to both syslog and remote user */
794e9953bbgad		asprintf(&syserr, "connected from invalid port (%s)", serv);
795e9953bbgad		fhosterr(ch_opts, syserr, syserr);
796e9953bbgad		/* NOTREACHED */
797e9953bbgad	}
798e066facgad}
799e066facgad
800e066facgad/*
801e9953bbgad * Handle fatal errors in chkhost.  The first message will optionally be
802e9953bbgad * sent to syslog, the second one is sent to the connecting host.
803e066facgad *
804e066facgad * The idea is that the syslog message is meant for an administrator of a
805e066facgad * print server (the host receiving connections), while the usermsg is meant
806e066facgad * for a remote user who may or may not be clueful, and may or may not be
807e066facgad * doing something nefarious.  Some remote users (eg, MS-Windows...) may not
808e066facgad * even see whatever message is sent, which is why there's the option to
809e066facgad * start 'lpd' with the connection-errors also sent to syslog.
810e066facgad *
811e066facgad * Given that hostnames can theoretically be fairly long (well, over 250
812e066facgad * bytes), it would probably be helpful to have the 'from_host' field at
813e066facgad * the end of any error messages which include that info.
814e9953bbgad *
815e9953bbgad * These are Fatal host-connection errors, so this routine does not return.
816e066facgad */
817e9953bbgadstatic void
818e9953bbgadfhosterr(int ch_opts, char *sysmsg, char *usermsg)
819e066facgad{
820e9953bbgad
821e9953bbgad	/*
822e9953bbgad	 * If lpd was started up to print connection errors, then write
823e9953bbgad	 * the syslog message before the user message.
824e9953bbgad	 * And for many of the syslog messages, it is helpful to first
825e9953bbgad	 * write the from_host (if it is known) as a separate syslog
826e9953bbgad	 * message, since the hostname may be so long.
827e9953bbgad	 */
828e9953bbgad	if (ch_opts & LPD_LOGCONNERR) {
829e9953bbgad		if (ch_opts & LPD_ADDFROMLINE) {
830e066facgad		    syslog(LOG_WARNING, "for connection from %s:", from_host);
831e066facgad		}
832e9953bbgad		syslog(LOG_WARNING, "%s", sysmsg);
833e066facgad	}
834e066facgad
835e9953bbgad	/*
836e9953bbgad	 * Now send the error message to the remote host which is trying
837e9953bbgad	 * to make the connection.
838e9953bbgad	 */
839e9953bbgad	printf("%s [@%s]: %s\n", progname, local_host, usermsg);
840e066facgad	fflush(stdout);
841e066facgad
842e066facgad	/*
843e066facgad	 * Add a minimal delay before exiting (and disconnecting from the
844e066facgad	 * sending-host).  This is just in case that machine responds by
845e066facgad	 * INSTANTLY retrying (and instantly re-failing...).  This may also
846e066facgad	 * give the other side more time to read the error message.
847e066facgad	 */
848e066facgad	sleep(2);			/* a paranoid throttling measure */
849e066facgad	exit(1);
850862fdf1rgrimes}
85192b95fajoerg
852bd199e3ume/* setup server socket for specified address family */
853bd199e3ume/* if af is PF_UNSPEC more than one socket may be returned */
854bd199e3ume/* the returned list is dynamically allocated, so caller needs to free it */
855bd199e3umestatic int *
85630c0318gadsocksetup(int af, int debuglvl)
857bd199e3ume{
858bd199e3ume	struct addrinfo hints, *res, *r;
859bd199e3ume	int error, maxs, *s, *socks;
860bd199e3ume	const int on = 1;
861bd199e3ume
862bd199e3ume	memset(&hints, 0, sizeof(hints));
863bd199e3ume	hints.ai_flags = AI_PASSIVE;
864bd199e3ume	hints.ai_family = af;
865bd199e3ume	hints.ai_socktype = SOCK_STREAM;
866bd199e3ume	error = getaddrinfo(NULL, "printer", &hints, &res);
867bd199e3ume	if (error) {
868bd199e3ume		syslog(LOG_ERR, "%s", gai_strerror(error));
869bd199e3ume		mcleanup(0);
870bd199e3ume	}
871bd199e3ume
872bd199e3ume	/* Count max number of sockets we may open */
873bd199e3ume	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
874bd199e3ume		;
875bd199e3ume	socks = malloc((maxs + 1) * sizeof(int));
876bd199e3ume	if (!socks) {
877bd199e3ume		syslog(LOG_ERR, "couldn't allocate memory for sockets");
878bd199e3ume		mcleanup(0);
879bd199e3ume	}
880bd199e3ume
881bd199e3ume	*socks = 0;   /* num of sockets counter at start of array */
882bd199e3ume	s = socks + 1;
883bd199e3ume	for (r = res; r; r = r->ai_next) {
884bd199e3ume		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
885bd199e3ume		if (*s < 0) {
886bd199e3ume			syslog(LOG_DEBUG, "socket(): %m");
887