xref: /netbsd-src/usr.sbin/lpr/lpd/lpd.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: lpd.c,v 1.45 2003/05/17 20:46:44 itojun Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 
39 #ifndef lint
40 __COPYRIGHT("@(#) Copyright (c) 1983, 1993, 1994\n\
41 	The Regents of the University of California.  All rights reserved.\n");
42 #endif /* not lint */
43 
44 #ifndef lint
45 #if 0
46 static char sccsid[] = "@(#)lpd.c	8.7 (Berkeley) 5/10/95";
47 #else
48 __RCSID("$NetBSD: lpd.c,v 1.45 2003/05/17 20:46:44 itojun Exp $");
49 #endif
50 #endif /* not lint */
51 
52 /*
53  * lpd -- line printer daemon.
54  *
55  * Listen for a connection and perform the requested operation.
56  * Operations are:
57  *	\1printer\n
58  *		check the queue for jobs and print any found.
59  *	\2printer\n
60  *		receive a job from another machine and queue it.
61  *	\3printer [users ...] [jobs ...]\n
62  *		return the current state of the queue (short form).
63  *	\4printer [users ...] [jobs ...]\n
64  *		return the current state of the queue (long form).
65  *	\5printer person [users ...] [jobs ...]\n
66  *		remove jobs from the queue.
67  *
68  * Strategy to maintain protected spooling area:
69  *	1. Spooling area is writable only by daemon and spooling group
70  *	2. lpr runs setuid root and setgrp spooling group; it uses
71  *	   root to access any file it wants (verifying things before
72  *	   with an access call) and group id to know how it should
73  *	   set up ownership of files in the spooling area.
74  *	3. Files in spooling area are owned by root, group spooling
75  *	   group, with mode 660.
76  *	4. lpd, lpq and lprm run setuid daemon and setgrp spooling group to
77  *	   access files and printer.  Users can't get to anything
78  *	   w/o help of lpq and lprm programs.
79  */
80 
81 #include <sys/param.h>
82 #include <sys/wait.h>
83 #include <sys/types.h>
84 #include <sys/socket.h>
85 #include <sys/un.h>
86 #include <sys/stat.h>
87 #include <sys/file.h>
88 #include <sys/poll.h>
89 #include <netinet/in.h>
90 
91 #include <err.h>
92 #include <netdb.h>
93 #include <unistd.h>
94 #include <syslog.h>
95 #include <signal.h>
96 #include <errno.h>
97 #include <fcntl.h>
98 #include <dirent.h>
99 #include <stdarg.h>
100 #include <stdio.h>
101 #include <stdlib.h>
102 #include <string.h>
103 #include <ctype.h>
104 #include <arpa/inet.h>
105 
106 #ifdef LIBWRAP
107 #include <tcpd.h>
108 #endif
109 
110 #include "lp.h"
111 #include "lp.local.h"
112 #include "pathnames.h"
113 #include "extern.h"
114 
115 /* XXX from libc/net/rcmd.c */
116 extern int __ivaliduser_sa(FILE *, struct sockaddr *, socklen_t,
117 			   const char *, const char *);
118 
119 #ifdef LIBWRAP
120 int allow_severity = LOG_AUTH|LOG_INFO;
121 int deny_severity = LOG_AUTH|LOG_WARNING;
122 #endif
123 
124 int	lflag;				/* log requests flag */
125 int	rflag;				/* allow of for remote printers */
126 int	sflag;				/* secure (no inet) flag */
127 int	from_remote;			/* from remote socket */
128 char	**blist;			/* list of addresses to bind(2) to */
129 int	blist_size;
130 int	blist_addrs;
131 
132 int			main(int, char **);
133 static void		reapchild(int);
134 static void		mcleanup(int);
135 static void		doit(void);
136 static void		startup(void);
137 static void		chkhost(struct sockaddr *, int);
138 static int		ckqueue(char *);
139 static void		usage(void);
140 static struct pollfd	*socksetup(int, int, const char *, int *);
141 
142 uid_t	uid, euid;
143 int child_count;
144 
145 #define LPD_NOPORTCHK	0001		/* skip reserved-port check */
146 
147 int
148 main(int argc, char **argv)
149 {
150 	struct sockaddr_storage from;
151 	socklen_t fromlen;
152 	sigset_t nmask, omask;
153 	int lfd, errs, i, f, nfds;
154 	struct pollfd *socks;
155 	int child_max = 32;	/* more than enough to hose the system */
156 	int options = 0, check_options = 0;
157 	struct servent *sp;
158 	const char *port = "printer";
159 
160 	euid = geteuid();	/* these shouldn't be different */
161 	uid = getuid();
162 	gethostname(host, sizeof(host));
163 	host[sizeof(host) - 1] = '\0';
164 	name = argv[0];
165 
166 	errs = 0;
167 	while ((i = getopt(argc, argv, "b:dln:srw:W")) != -1)
168 		switch (i) {
169 		case 'b':
170 			if (blist_addrs >= blist_size) {
171 				blist_size += sizeof(char *) * 4;
172 				if (blist == NULL)
173 					blist = malloc(blist_size);
174 				else
175 					blist = realloc(blist, blist_size);
176 				if (blist == NULL)
177 					err(1, "cant allocate bind addr list");
178 			}
179 			blist[blist_addrs++] = strdup(optarg);
180 			break;
181 		case 'd':
182 			options |= SO_DEBUG;
183 			break;
184 		case 'l':
185 			lflag++;
186 			break;
187 		case 'n':
188 			child_max = atoi(optarg);
189 			if (child_max < 0 || child_max > 1024)
190 				errx(1, "invalid number of children: %s",
191 				    optarg);
192 			break;
193 		case 'r':
194 			rflag++;
195 			break;
196 		case 's':
197 			sflag++;
198 			break;
199 		case 'w':
200 			wait_time = atoi(optarg);
201 			if (wait_time < 0)
202 				errx(1, "wait time must be postive: %s",
203 				    optarg);
204 			if (wait_time < 30)
205 			    warnx("warning: wait time less than 30 seconds");
206 			break;
207 		case 'W':/* allow connections coming from a non-reserved port */
208 			 /* (done by some lpr-implementations for MS-Windows) */
209 			check_options |= LPD_NOPORTCHK;
210 			break;
211 		default:
212 			errs++;
213 		}
214 	argc -= optind;
215 	argv += optind;
216 	if (errs)
217 		usage();
218 
219 	switch (argc) {
220 	case 1:
221 		if ((i = atoi(argv[0])) == 0)
222 			usage();
223 		if (i < 0 || i > USHRT_MAX)
224 			errx(1, "port # %d is invalid", i);
225 
226 		port = argv[0];
227 		break;
228 	case 0:
229 		sp = getservbyname(port, "tcp");
230 		if (sp == NULL)
231 			errx(1, "%s/tcp: unknown service", port);
232 		break;
233 	default:
234 		usage();
235 	}
236 
237 #ifndef DEBUG
238 	/*
239 	 * Set up standard environment by detaching from the parent.
240 	 */
241 	daemon(0, 0);
242 #endif
243 
244 	openlog("lpd", LOG_PID, LOG_LPR);
245 	syslog(LOG_INFO, "restarted");
246 	(void)umask(0);
247 	lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT, 0644);
248 	if (lfd < 0) {
249 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
250 		exit(1);
251 	}
252 	if (flock(lfd, LOCK_EX|LOCK_NB) < 0) {
253 		if (errno == EWOULDBLOCK) {	/* active daemon present */
254 			syslog(LOG_ERR, "%s is locked; another lpd is running",
255 			    _PATH_MASTERLOCK);
256 			exit(0);
257 		}
258 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
259 		exit(1);
260 	}
261 	ftruncate(lfd, 0);
262 	/*
263 	 * write process id for others to know
264 	 */
265 	(void)snprintf(line, sizeof(line), "%u\n", getpid());
266 	f = strlen(line);
267 	if (write(lfd, line, f) != f) {
268 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
269 		exit(1);
270 	}
271 	signal(SIGCHLD, reapchild);
272 	/*
273 	 * Restart all the printers.
274 	 */
275 	startup();
276 
277 	sigemptyset(&nmask);
278 	sigaddset(&nmask, SIGHUP);
279 	sigaddset(&nmask, SIGINT);
280 	sigaddset(&nmask, SIGQUIT);
281 	sigaddset(&nmask, SIGTERM);
282 	sigprocmask(SIG_BLOCK, &nmask, &omask);
283 
284 	signal(SIGHUP, mcleanup);
285 	signal(SIGINT, mcleanup);
286 	signal(SIGQUIT, mcleanup);
287 	signal(SIGTERM, mcleanup);
288 
289 	socks = socksetup(PF_UNSPEC, options, port, &nfds);
290 
291 	sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0);
292 
293 	if (blist != NULL) {
294 		for (i = 0; i < blist_addrs; i++)
295 			free(blist[i]);
296 		free(blist);
297 	}
298 
299 	/*
300 	 * Main loop: accept, do a request, continue.
301 	 */
302 	memset(&from, 0, sizeof(from));
303 	for (;;) {
304 		int rv, s;
305 		/* "short" so it overflows in about 2 hours */
306 		struct timespec sleeptime = {10, 0};
307 
308 		while (child_max < child_count) {
309 			syslog(LOG_WARNING,
310 			    "too many children, sleeping for %ld seconds",
311 				(long)sleeptime.tv_sec);
312 			nanosleep(&sleeptime, NULL);
313 			sleeptime.tv_sec <<= 1;
314 			if (sleeptime.tv_sec <= 0) {
315 				syslog(LOG_CRIT, "sleeptime overflowed! help!");
316 				sleeptime.tv_sec = 10;
317 			}
318 		}
319 
320 		rv = poll(socks, nfds, INFTIM);
321 		if (rv <= 0) {
322 			if (rv < 0 && errno != EINTR)
323 				syslog(LOG_WARNING, "poll: %m");
324 			continue;
325 		}
326                 for (i = 0; i < nfds; i++)
327 			if (socks[i].revents & POLLIN) {
328 				fromlen = sizeof(from);
329 				s = accept(socks[i].fd,
330 				    (struct sockaddr *)&from, &fromlen);
331 				break;
332 			}
333 		if (s < 0) {
334 			if (errno != EINTR)
335 				syslog(LOG_WARNING, "accept: %m");
336 			continue;
337 		}
338 
339 		switch (fork()) {
340 		case 0:
341 			signal(SIGCHLD, SIG_IGN);
342 			signal(SIGHUP, SIG_IGN);
343 			signal(SIGINT, SIG_IGN);
344 			signal(SIGQUIT, SIG_IGN);
345 			signal(SIGTERM, SIG_IGN);
346                        	for (i = 0; i < nfds; i++)
347 				(void)close(socks[i].fd);
348 			dup2(s, STDOUT_FILENO);
349 			(void)close(s);
350 			if (from.ss_family != AF_LOCAL) {
351 				/* for both AF_INET and AF_INET6 */
352 				from_remote = 1;
353 				chkhost((struct sockaddr *)&from, check_options);
354 			} else
355 				from_remote = 0;
356 			doit();
357 			exit(0);
358 		case -1:
359 			syslog(LOG_WARNING, "fork: %m, sleeping for 10 seconds...");
360 			sleep(10);
361 			continue;
362 		default:
363 			child_count++;
364 		}
365 		(void)close(s);
366 	}
367 }
368 
369 static void
370 reapchild(int signo)
371 {
372 	union wait status;
373 
374 	while (wait3((int *)&status, WNOHANG, 0) > 0)
375 		child_count--;
376 }
377 
378 static void
379 mcleanup(int signo)
380 {
381 	if (lflag)
382 		syslog(LOG_INFO, "exiting");
383 	unlink(_PATH_SOCKETNAME);
384 	exit(0);
385 }
386 
387 /*
388  * Stuff for handling job specifications
389  */
390 char	*user[MAXUSERS];	/* users to process */
391 int	users;			/* # of users in user array */
392 int	requ[MAXREQUESTS];	/* job number of spool entries */
393 int	requests;		/* # of spool requests */
394 char	*person;		/* name of person doing lprm */
395 
396 char	fromb[NI_MAXHOST];	/* buffer for client's machine name */
397 char	cbuf[BUFSIZ];		/* command line buffer */
398 char	*cmdnames[] = {
399 	"null",
400 	"printjob",
401 	"recvjob",
402 	"displayq short",
403 	"displayq long",
404 	"rmjob"
405 };
406 
407 static void
408 doit(void)
409 {
410 	char *cp;
411 	int n;
412 
413 	for (;;) {
414 		cp = cbuf;
415 		do {
416 			if (cp >= &cbuf[sizeof(cbuf) - 1])
417 				fatal("Command line too long");
418 			if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
419 				if (n < 0)
420 					fatal("Lost connection");
421 				return;
422 			}
423 		} while (*cp++ != '\n');
424 		*--cp = '\0';
425 		cp = cbuf;
426 		if (lflag) {
427 			if (*cp >= '\1' && *cp <= '\5') {
428 				syslog(LOG_INFO, "%s requests %s %s",
429 					from, cmdnames[(int)*cp], cp+1);
430 				setproctitle("serving %s: %s %s", from,
431 				    cmdnames[(int)*cp], cp+1);
432 			}
433 			else
434 				syslog(LOG_INFO, "bad request (%d) from %s",
435 					*cp, from);
436 		}
437 		switch (*cp++) {
438 		case '\1':	/* check the queue and print any jobs there */
439 			printer = cp;
440 			if (*printer == '\0')
441 				printer = DEFLP;
442 			printjob();
443 			break;
444 		case '\2':	/* receive files to be queued */
445 			if (!from_remote) {
446 				syslog(LOG_INFO, "illegal request (%d)", *cp);
447 				exit(1);
448 			}
449 			printer = cp;
450 			if (*printer == '\0')
451 				printer = DEFLP;
452 			recvjob();
453 			break;
454 		case '\3':	/* display the queue (short form) */
455 		case '\4':	/* display the queue (long form) */
456 			printer = cp;
457 			if (*printer == '\0')
458 				printer = DEFLP;
459 			while (*cp) {
460 				if (*cp != ' ') {
461 					cp++;
462 					continue;
463 				}
464 				*cp++ = '\0';
465 				while (isspace(*cp))
466 					cp++;
467 				if (*cp == '\0')
468 					break;
469 				if (isdigit(*cp)) {
470 					if (requests >= MAXREQUESTS)
471 						fatal("Too many requests");
472 					requ[requests++] = atoi(cp);
473 				} else {
474 					if (users >= MAXUSERS)
475 						fatal("Too many users");
476 					user[users++] = cp;
477 				}
478 			}
479 			displayq(cbuf[0] - '\3');
480 			exit(0);
481 		case '\5':	/* remove a job from the queue */
482 			if (!from_remote) {
483 				syslog(LOG_INFO, "illegal request (%d)", *cp);
484 				exit(1);
485 			}
486 			printer = cp;
487 			if (*printer == '\0')
488 				printer = DEFLP;
489 			while (*cp && *cp != ' ')
490 				cp++;
491 			if (!*cp)
492 				break;
493 			*cp++ = '\0';
494 			person = cp;
495 			while (*cp) {
496 				if (*cp != ' ') {
497 					cp++;
498 					continue;
499 				}
500 				*cp++ = '\0';
501 				while (isspace(*cp))
502 					cp++;
503 				if (*cp == '\0')
504 					break;
505 				if (isdigit(*cp)) {
506 					if (requests >= MAXREQUESTS)
507 						fatal("Too many requests");
508 					requ[requests++] = atoi(cp);
509 				} else {
510 					if (users >= MAXUSERS)
511 						fatal("Too many users");
512 					user[users++] = cp;
513 				}
514 			}
515 			rmjob();
516 			break;
517 		}
518 		fatal("Illegal service request");
519 	}
520 }
521 
522 /*
523  * Make a pass through the printcap database and start printing any
524  * files left from the last time the machine went down.
525  */
526 static void
527 startup(void)
528 {
529 	char *buf;
530 	char *cp;
531 
532 	/*
533 	 * Restart the daemons.
534 	 */
535 	while (cgetnext(&buf, printcapdb) > 0) {
536 		if (ckqueue(buf) <= 0) {
537 			free(buf);
538 			continue;	/* no work to do for this printer */
539 		}
540 		for (cp = buf; *cp; cp++)
541 			if (*cp == '|' || *cp == ':') {
542 				*cp = '\0';
543 				break;
544 			}
545 		if (lflag)
546 			syslog(LOG_INFO, "work for %s", buf);
547 		switch (fork()) {
548 		case -1:
549 			syslog(LOG_WARNING, "startup: cannot fork");
550 			mcleanup(0);
551 		case 0:
552 			printer = buf;
553 			setproctitle("working on printer %s", printer);
554 			cgetclose();
555 			printjob();
556 			/* NOTREACHED */
557 		default:
558 			child_count++;
559 			free(buf);
560 		}
561 	}
562 }
563 
564 /*
565  * Make sure there's some work to do before forking off a child
566  */
567 static int
568 ckqueue(char *cap)
569 {
570 	struct dirent *d;
571 	DIR *dirp;
572 	char *spooldir;
573 
574 	if (cgetstr(cap, "sd", &spooldir) == -1)
575 		spooldir = _PATH_DEFSPOOL;
576 	if ((dirp = opendir(spooldir)) == NULL)
577 		return (-1);
578 	while ((d = readdir(dirp)) != NULL) {
579 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
580 			continue;	/* daemon control files only */
581 		closedir(dirp);
582 		return (1);		/* found something */
583 	}
584 	closedir(dirp);
585 	return (0);
586 }
587 
588 #define DUMMY ":nobody::"
589 
590 /*
591  * Check to see if the from host has access to the line printer.
592  */
593 static void
594 chkhost(struct sockaddr *f, int check_opts)
595 {
596 	struct addrinfo hints, *res, *r;
597 	FILE *hostf;
598 	int good = 0;
599 	char host[NI_MAXHOST], ip[NI_MAXHOST];
600 	char serv[NI_MAXSERV];
601 	int error;
602 #ifdef LIBWRAP
603 	struct request_info req;
604 #endif
605 
606 	error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
607 			    NI_NUMERICSERV);
608 	if (error)
609 		fatal("Malformed from address: %s", gai_strerror(error));
610 
611          if (!(check_opts & LPD_NOPORTCHK) &&
612 	       atoi(serv) >= IPPORT_RESERVED)
613 		fatal("Connect from invalid port (%s)", serv);
614 
615 	/* Need real hostname for temporary filenames */
616 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
617 			    NI_NAMEREQD);
618 	if (error) {
619 		error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
620 				    NI_NUMERICHOST);
621 		if (error)
622 			fatal("Host name for your address unknown");
623 		else
624 			fatal("Host name for your address (%s) unknown", host);
625 	}
626 
627 	(void)strlcpy(fromb, host, sizeof(fromb));
628 	from = fromb;
629 
630 	/* need address in stringform for comparison (no DNS lookup here) */
631 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
632 			    NI_NUMERICHOST);
633 	if (error)
634 		fatal("Cannot print address");
635 
636 	/* Check for spoof, ala rlogind */
637 	memset(&hints, 0, sizeof(hints));
638 	hints.ai_family = PF_UNSPEC;
639 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
640 	error = getaddrinfo(fromb, NULL, &hints, &res);
641 	if (error) {
642 		fatal("hostname for your address (%s) unknown: %s", host,
643 		    gai_strerror(error));
644 	}
645 	good = 0;
646 	for (r = res; good == 0 && r; r = r->ai_next) {
647 		error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
648 				    NULL, 0, NI_NUMERICHOST);
649 		if (!error && !strcmp(host, ip))
650 			good = 1;
651 	}
652 	if (res)
653 		freeaddrinfo(res);
654 	if (good == 0)
655 		fatal("address for your hostname (%s) not matched", host);
656 
657 	setproctitle("serving %s", from);
658 
659 #ifdef LIBWRAP
660 	request_init(&req, RQ_DAEMON, "lpd", RQ_CLIENT_SIN, f,
661 	    RQ_FILE, STDOUT_FILENO, NULL);
662 	fromhost(&req);
663 	if (!hosts_access(&req))
664 		goto denied;
665 #endif
666 
667 	hostf = fopen(_PATH_HOSTSEQUIV, "r");
668 	if (hostf) {
669 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
670 			(void)fclose(hostf);
671 			return;
672 		}
673 		(void)fclose(hostf);
674 	}
675 	hostf = fopen(_PATH_HOSTSLPD, "r");
676 	if (hostf) {
677 		if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
678 			(void)fclose(hostf);
679 			return;
680 		}
681 		(void)fclose(hostf);
682 	}
683 #ifdef LIBWRAP
684   denied:
685 #endif
686 	fatal("Your host does not have line printer access");
687 	/*NOTREACHED*/
688 }
689 
690 
691 static void
692 usage(void)
693 {
694 
695 	fprintf(stderr, "usage: %s [-dlrsW] [-b bind-address] [-n maxchild] "
696 	    "[-w maxwait] [port]\n", getprogname());
697 	exit(1);
698 }
699 
700 /* setup server socket for specified address family */
701 /* if af is PF_UNSPEC more than one socket may be returned */
702 /* the returned list is dynamically allocated, so caller needs to free it */
703 struct pollfd *
704 socksetup(int af, int options, const char *port, int *nfds)
705 {
706 	struct sockaddr_un un;
707 	struct addrinfo hints, *res, *r;
708 	int error, s, blidx = 0, n;
709 	struct pollfd *socks;
710 	const int on = 1;
711 
712 	*nfds = 0;
713 
714 	socks = malloc(1 * sizeof(int));
715 	if (!socks) {
716 		syslog(LOG_ERR, "couldn't allocate memory for sockets");
717 		mcleanup(0);
718 	}
719 
720 	s = socket(AF_LOCAL, SOCK_STREAM, 0);
721 	if (s < 0) {
722 		syslog(LOG_ERR, "socket(): %m");
723 		exit(1);
724 	}
725 	memset(&un, 0, sizeof(un));
726 	un.sun_family = AF_LOCAL;
727 	strncpy(un.sun_path, _PATH_SOCKETNAME, sizeof(un.sun_path) - 1);
728 	un.sun_len = SUN_LEN(&un);
729 	(void)umask(07);
730 	(void)unlink(_PATH_SOCKETNAME);
731 	if (bind(s, (struct sockaddr *)&un, un.sun_len) < 0) {
732 		syslog(LOG_ERR, "bind(): %m");
733 		exit(1);
734 	}
735 	(void)umask(0);
736 	listen(s, 5);
737 	socks[*nfds].fd = s;
738 	socks[*nfds].events = POLLIN;
739 	(*nfds)++;
740 
741 	if (sflag && !blist_addrs)
742 		return (socks);
743 
744 	do {
745 		memset(&hints, 0, sizeof(hints));
746 		hints.ai_flags = AI_PASSIVE;
747 		hints.ai_family = af;
748 		hints.ai_socktype = SOCK_STREAM;
749 		error = getaddrinfo((blist_addrs == 0) ? NULL : blist[blidx],
750 		    port ? port : "printer", &hints, &res);
751 		if (error) {
752 			if (blist_addrs)
753 				syslog(LOG_ERR, "%s: %s", blist[blidx],
754 				    gai_strerror(error));
755 			else
756 				syslog(LOG_ERR, "%s", gai_strerror(error));
757 			mcleanup(0);
758 		}
759 
760 		/* Count max number of sockets we may open */
761 		for (r = res, n = 0; r; r = r->ai_next, n++)
762 			;
763 		socks = realloc(socks, (*nfds + n) * sizeof(int));
764 		if (!socks) {
765 			syslog(LOG_ERR, "couldn't allocate memory for sockets");
766 			mcleanup(0);
767 		}
768 
769 		for (r = res; r; r = r->ai_next) {
770 			s = socket(r->ai_family, r->ai_socktype,
771 			    r->ai_protocol);
772 			if (s < 0) {
773 				syslog(LOG_DEBUG, "socket(): %m");
774 				continue;
775 			}
776 			if (options & SO_DEBUG)
777 				if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
778 					       &on, sizeof(on)) < 0) {
779 					syslog(LOG_ERR,
780 					       "setsockopt (SO_DEBUG): %m");
781 					close(s);
782 					continue;
783 				}
784 			if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &on,
785 			    sizeof(on)) < 0) {
786 				syslog(LOG_ERR,
787 				    "setsockopt (SO_REUSEPORT): %m");
788 				close(s);
789 				continue;
790 			}
791 			if (r->ai_family == AF_INET6 && setsockopt(s,
792 			    IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
793 				syslog(LOG_ERR,
794 				    "setsockopt (IPV6_V6ONLY): %m");
795 				close(s);
796 				continue;
797 			}
798 			if (bind(s, r->ai_addr, r->ai_addrlen) < 0) {
799 				syslog(LOG_DEBUG, "bind(): %m");
800 				close(s);
801 				continue;
802 			}
803 			listen(s, 5);
804 			socks[*nfds].fd = s;
805 			socks[*nfds].events = POLLIN;
806 			(*nfds)++;
807 		}
808 
809 		if (res)
810 			freeaddrinfo(res);
811 	} while (++blidx < blist_addrs);
812 
813 	return (socks);
814 }
815