Home | History | Annotate | Line # | Download | only in lpd
lpd.c revision 1.20
      1 /*	$NetBSD: lpd.c,v 1.20 2000/01/27 05:39:50 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.20 2000/01/27 05:39:50 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 <netinet/in.h>
     89 
     90 #include <err.h>
     91 #include <netdb.h>
     92 #include <unistd.h>
     93 #include <syslog.h>
     94 #include <signal.h>
     95 #include <errno.h>
     96 #include <fcntl.h>
     97 #include <dirent.h>
     98 #include <stdio.h>
     99 #include <stdlib.h>
    100 #include <string.h>
    101 #include <ctype.h>
    102 #include <arpa/inet.h>
    103 
    104 #include "lp.h"
    105 #include "lp.local.h"
    106 #include "pathnames.h"
    107 #include "extern.h"
    108 
    109 int	lflag;				/* log requests flag */
    110 int	rflag;				/* allow of for remote printers */
    111 int	sflag;				/* secure (no inet) flag */
    112 int	from_remote;			/* from remote socket */
    113 
    114 int               main __P((int, char **));
    115 static void       reapchild __P((int));
    116 static void       mcleanup __P((int));
    117 static void       doit __P((void));
    118 static void       startup __P((void));
    119 static void       chkhost __P((struct sockaddr *));
    120 static int	  ckqueue __P((char *));
    121 static void	  usage __P((void));
    122 static int	  *socksetup __P((int, int));
    123 
    124 uid_t	uid, euid;
    125 int child_count;
    126 
    127 int
    128 main(argc, argv)
    129 	int argc;
    130 	char **argv;
    131 {
    132 	int f, funix, *finet, options, fromlen;
    133 	fd_set defreadfds;
    134 	struct sockaddr_un un, fromunix;
    135 	struct sockaddr_storage frominet;
    136 	int omask, lfd, errs, i;
    137 	int child_max = 32;	/* more then enough to hose the system */
    138 
    139 	euid = geteuid();	/* these shouldn't be different */
    140 	uid = getuid();
    141 	options = 0;
    142 	gethostname(host, sizeof(host));
    143 	host[sizeof(host) - 1] = '\0';
    144 	name = argv[0];
    145 
    146 	errs = 0;
    147 	while ((i = getopt(argc, argv, "dln:srw:")) != -1)
    148 		switch (i) {
    149 		case 'd':
    150 			options |= SO_DEBUG;
    151 			break;
    152 		case 'l':
    153 			lflag++;
    154 			break;
    155 		case 'n':
    156 			child_max = atoi(optarg);
    157 			if (child_max < 0 || child_max > 1024)
    158 				errx(1, "invalid number of children: %s",
    159 				    optarg);
    160 			break;
    161 		case 'r':
    162 			rflag++;
    163 			break;
    164 		case 's':
    165 			sflag++;
    166 			break;
    167 		case 'w':
    168 			wait_time = atoi(optarg);
    169 			if (wait_time < 0)
    170 				errx(1, "wait time must be postive: %s",
    171 				    optarg);
    172 			if (wait_time < 30)
    173 			    warnx("warning: wait time less than 30 seconds");
    174 			break;
    175 		default:
    176 			errs++;
    177 		}
    178 	argc -= optind;
    179 	argv += optind;
    180 	if (errs || argc != 0)
    181 		usage();
    182 
    183 #ifndef DEBUG
    184 	/*
    185 	 * Set up standard environment by detaching from the parent.
    186 	 */
    187 	daemon(0, 0);
    188 #endif
    189 
    190 	openlog("lpd", LOG_PID, LOG_LPR);
    191 	syslog(LOG_INFO, "restarted");
    192 	(void)umask(0);
    193 	lfd = open(_PATH_MASTERLOCK, O_WRONLY|O_CREAT, 0644);
    194 	if (lfd < 0) {
    195 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
    196 		exit(1);
    197 	}
    198 	if (flock(lfd, LOCK_EX|LOCK_NB) < 0) {
    199 		if (errno == EWOULDBLOCK)	/* active deamon present */
    200 			exit(0);
    201 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
    202 		exit(1);
    203 	}
    204 	ftruncate(lfd, 0);
    205 	/*
    206 	 * write process id for others to know
    207 	 */
    208 	(void)snprintf(line, sizeof(line), "%u\n", getpid());
    209 	f = strlen(line);
    210 	if (write(lfd, line, f) != f) {
    211 		syslog(LOG_ERR, "%s: %m", _PATH_MASTERLOCK);
    212 		exit(1);
    213 	}
    214 	signal(SIGCHLD, reapchild);
    215 	/*
    216 	 * Restart all the printers.
    217 	 */
    218 	startup();
    219 	(void)unlink(_PATH_SOCKETNAME);
    220 	funix = socket(AF_LOCAL, SOCK_STREAM, 0);
    221 	if (funix < 0) {
    222 		syslog(LOG_ERR, "socket: %m");
    223 		exit(1);
    224 	}
    225 #define	mask(s)	(1 << ((s) - 1))
    226 	omask = sigblock(mask(SIGHUP)|mask(SIGINT)|mask(SIGQUIT)|mask(SIGTERM));
    227 	signal(SIGHUP, mcleanup);
    228 	signal(SIGINT, mcleanup);
    229 	signal(SIGQUIT, mcleanup);
    230 	signal(SIGTERM, mcleanup);
    231 	memset(&un, 0, sizeof(un));
    232 	un.sun_family = AF_LOCAL;
    233 	strncpy(un.sun_path, _PATH_SOCKETNAME, sizeof(un.sun_path) - 1);
    234 #ifndef SUN_LEN
    235 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
    236 #endif
    237 	if (bind(funix, (struct sockaddr *)&un, SUN_LEN(&un)) < 0) {
    238 		syslog(LOG_ERR, "ubind: %m");
    239 		exit(1);
    240 	}
    241 	sigsetmask(omask);
    242 	FD_ZERO(&defreadfds);
    243 	FD_SET(funix, &defreadfds);
    244 	listen(funix, 5);
    245 	if (!sflag)
    246 		finet = socksetup(PF_UNSPEC, options);
    247 	else
    248 		finet = NULL;	/* pretend we couldn't open TCP socket. */
    249 
    250 	if (finet) {
    251 		for (i = 1; i <= *finet; i++) {
    252 			FD_SET(finet[i], &defreadfds);
    253 			listen(finet[i], 5);
    254 		}
    255 	}
    256 	/*
    257 	 * Main loop: accept, do a request, continue.
    258 	 */
    259 	memset(&frominet, 0, sizeof(frominet));
    260 	memset(&fromunix, 0, sizeof(fromunix));
    261 	for (;;) {
    262 		int domain, nfds, s;
    263 		fd_set readfds;
    264 		/* "short" so it overflows in about 2 hours */
    265 		short sleeptime = 10;
    266 
    267 		while (child_max < child_count) {
    268 			syslog(LOG_WARNING,
    269 			    "too many children, sleeping for %d seconds",
    270 				sleeptime);
    271 			sleep(sleeptime);
    272 			sleeptime <<= 1;
    273 			if (sleeptime < 0) {
    274 				syslog(LOG_CRIT, "sleeptime overflowed! help!");
    275 				sleeptime = 10;
    276 			}
    277 		}
    278 
    279 		FD_COPY(&defreadfds, &readfds);
    280 		nfds = select(20, &readfds, 0, 0, 0);
    281 		if (nfds <= 0) {
    282 			if (nfds < 0 && errno != EINTR)
    283 				syslog(LOG_WARNING, "select: %m");
    284 			continue;
    285 		}
    286 		if (FD_ISSET(funix, &readfds)) {
    287 			domain = AF_LOCAL, fromlen = sizeof(fromunix);
    288 			s = accept(funix,
    289 			    (struct sockaddr *)&fromunix, &fromlen);
    290 		} else {
    291                         for (i = 1; i <= *finet; i++)
    292 				if (FD_ISSET(finet[i], &readfds)) {
    293 					domain = AF_INET, fromlen = sizeof(frominet);
    294 					s = accept(finet[i], (struct sockaddr *)&frominet, &fromlen);
    295 				}
    296 		}
    297 		if (s < 0) {
    298 			if (errno != EINTR)
    299 				syslog(LOG_WARNING, "accept: %m");
    300 			continue;
    301 		}
    302 
    303 		switch (fork()) {
    304 		case 0:
    305 			signal(SIGCHLD, SIG_IGN);
    306 			signal(SIGHUP, SIG_IGN);
    307 			signal(SIGINT, SIG_IGN);
    308 			signal(SIGQUIT, SIG_IGN);
    309 			signal(SIGTERM, SIG_IGN);
    310 			(void)close(funix);
    311 			if (!sflag && finet)
    312                         	for (i = 1; i <= *finet; i++)
    313 					(void)close(finet[i]);
    314 			dup2(s, 1);
    315 			(void)close(s);
    316 			if (domain == AF_INET) {
    317 				/* for both AF_INET and AF_INET6 */
    318 				from_remote = 1;
    319 				chkhost((struct sockaddr *)&frominet);
    320 			} else
    321 				from_remote = 0;
    322 			doit();
    323 			exit(0);
    324 		case -1:
    325 			syslog(LOG_WARNING, "fork: %m, sleeping for 10 seconds...");
    326 			sleep(10);
    327 			continue;
    328 		default:
    329 			child_count++;
    330 		}
    331 		(void)close(s);
    332 	}
    333 }
    334 
    335 static void
    336 reapchild(signo)
    337 	int signo;
    338 {
    339 	union wait status;
    340 
    341 	while (wait3((int *)&status, WNOHANG, 0) > 0)
    342 		child_count--;
    343 }
    344 
    345 static void
    346 mcleanup(signo)
    347 	int signo;
    348 {
    349 	if (lflag)
    350 		syslog(LOG_INFO, "exiting");
    351 	unlink(_PATH_SOCKETNAME);
    352 	exit(0);
    353 }
    354 
    355 /*
    356  * Stuff for handling job specifications
    357  */
    358 char	*user[MAXUSERS];	/* users to process */
    359 int	users;			/* # of users in user array */
    360 int	requ[MAXREQUESTS];	/* job number of spool entries */
    361 int	requests;		/* # of spool requests */
    362 char	*person;		/* name of person doing lprm */
    363 
    364 char	fromb[NI_MAXHOST];	/* buffer for client's machine name */
    365 char	cbuf[BUFSIZ];		/* command line buffer */
    366 char	*cmdnames[] = {
    367 	"null",
    368 	"printjob",
    369 	"recvjob",
    370 	"displayq short",
    371 	"displayq long",
    372 	"rmjob"
    373 };
    374 
    375 static void
    376 doit()
    377 {
    378 	char *cp;
    379 	int n;
    380 
    381 	for (;;) {
    382 		cp = cbuf;
    383 		do {
    384 			if (cp >= &cbuf[sizeof(cbuf) - 1])
    385 				fatal("Command line too long");
    386 			if ((n = read(1, cp, 1)) != 1) {
    387 				if (n < 0)
    388 					fatal("Lost connection");
    389 				return;
    390 			}
    391 		} while (*cp++ != '\n');
    392 		*--cp = '\0';
    393 		cp = cbuf;
    394 		if (lflag) {
    395 			if (*cp >= '\1' && *cp <= '\5') {
    396 				syslog(LOG_INFO, "%s requests %s %s",
    397 					from, cmdnames[(int)*cp], cp+1);
    398 				setproctitle("serving %s: %s %s", from,
    399 				    cmdnames[(int)*cp], cp+1);
    400 			}
    401 			else
    402 				syslog(LOG_INFO, "bad request (%d) from %s",
    403 					*cp, from);
    404 		}
    405 		switch (*cp++) {
    406 		case '\1':	/* check the queue and print any jobs there */
    407 			printer = cp;
    408 			printjob();
    409 			break;
    410 		case '\2':	/* receive files to be queued */
    411 			if (!from_remote) {
    412 				syslog(LOG_INFO, "illegal request (%d)", *cp);
    413 				exit(1);
    414 			}
    415 			printer = cp;
    416 			recvjob();
    417 			break;
    418 		case '\3':	/* display the queue (short form) */
    419 		case '\4':	/* display the queue (long form) */
    420 			printer = cp;
    421 			while (*cp) {
    422 				if (*cp != ' ') {
    423 					cp++;
    424 					continue;
    425 				}
    426 				*cp++ = '\0';
    427 				while (isspace(*cp))
    428 					cp++;
    429 				if (*cp == '\0')
    430 					break;
    431 				if (isdigit(*cp)) {
    432 					if (requests >= MAXREQUESTS)
    433 						fatal("Too many requests");
    434 					requ[requests++] = atoi(cp);
    435 				} else {
    436 					if (users >= MAXUSERS)
    437 						fatal("Too many users");
    438 					user[users++] = cp;
    439 				}
    440 			}
    441 			displayq(cbuf[0] - '\3');
    442 			exit(0);
    443 		case '\5':	/* remove a job from the queue */
    444 			if (!from_remote) {
    445 				syslog(LOG_INFO, "illegal request (%d)", *cp);
    446 				exit(1);
    447 			}
    448 			printer = cp;
    449 			while (*cp && *cp != ' ')
    450 				cp++;
    451 			if (!*cp)
    452 				break;
    453 			*cp++ = '\0';
    454 			person = cp;
    455 			while (*cp) {
    456 				if (*cp != ' ') {
    457 					cp++;
    458 					continue;
    459 				}
    460 				*cp++ = '\0';
    461 				while (isspace(*cp))
    462 					cp++;
    463 				if (*cp == '\0')
    464 					break;
    465 				if (isdigit(*cp)) {
    466 					if (requests >= MAXREQUESTS)
    467 						fatal("Too many requests");
    468 					requ[requests++] = atoi(cp);
    469 				} else {
    470 					if (users >= MAXUSERS)
    471 						fatal("Too many users");
    472 					user[users++] = cp;
    473 				}
    474 			}
    475 			rmjob();
    476 			break;
    477 		}
    478 		fatal("Illegal service request");
    479 	}
    480 }
    481 
    482 /*
    483  * Make a pass through the printcap database and start printing any
    484  * files left from the last time the machine went down.
    485  */
    486 static void
    487 startup()
    488 {
    489 	char *buf;
    490 	char *cp;
    491 
    492 	/*
    493 	 * Restart the daemons.
    494 	 */
    495 	while (cgetnext(&buf, printcapdb) > 0) {
    496 		if (ckqueue(buf) <= 0) {
    497 			free(buf);
    498 			continue;	/* no work to do for this printer */
    499 		}
    500 		for (cp = buf; *cp; cp++)
    501 			if (*cp == '|' || *cp == ':') {
    502 				*cp = '\0';
    503 				break;
    504 			}
    505 		if (lflag)
    506 			syslog(LOG_INFO, "work for %s", buf);
    507 		switch (fork()) {
    508 		case -1:
    509 			syslog(LOG_WARNING, "startup: cannot fork");
    510 			mcleanup(0);
    511 		case 0:
    512 			printer = buf;
    513 			setproctitle("working on printer %s", printer);
    514 			cgetclose();
    515 			printjob();
    516 			/* NOTREACHED */
    517 		default:
    518 			child_count++;
    519 			free(buf);
    520 		}
    521 	}
    522 }
    523 
    524 /*
    525  * Make sure there's some work to do before forking off a child
    526  */
    527 static int
    528 ckqueue(cap)
    529 	char *cap;
    530 {
    531 	struct dirent *d;
    532 	DIR *dirp;
    533 	char *spooldir;
    534 
    535 	if (cgetstr(cap, "sd", &spooldir) == -1)
    536 		spooldir = _PATH_DEFSPOOL;
    537 	if ((dirp = opendir(spooldir)) == NULL)
    538 		return (-1);
    539 	while ((d = readdir(dirp)) != NULL) {
    540 		if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
    541 			continue;	/* daemon control files only */
    542 		closedir(dirp);
    543 		return (1);		/* found something */
    544 	}
    545 	closedir(dirp);
    546 	return (0);
    547 }
    548 
    549 #define DUMMY ":nobody::"
    550 
    551 /*
    552  * Check to see if the from host has access to the line printer.
    553  */
    554 static void
    555 chkhost(f)
    556 	struct sockaddr *f;
    557 {
    558 	struct addrinfo hints, *res, *r;
    559 	FILE *hostf;
    560 	int first = 1, good = 0;
    561 	char host[NI_MAXHOST], ip[NI_MAXHOST];
    562 	char serv[NI_MAXSERV];
    563 	int error;
    564 
    565 	error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
    566 			    NI_NUMERICSERV);
    567 	if (error || atoi(serv) >= IPPORT_RESERVED)
    568 		fatal("Malformed from address");
    569 
    570 	/* Need real hostname for temporary filenames */
    571 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    572 			    NI_NAMEREQD);
    573 	if (error) {
    574 		error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    575 				    NI_NUMERICHOST);
    576 		if (error)
    577 			fatal("Host name for your address unknown");
    578 		else
    579 			fatal("Host name for your address (%s) unknown", host);
    580 	}
    581 
    582 	(void)strncpy(fromb, host, sizeof(fromb) - 1);
    583 	fromb[sizeof(fromb) - 1] = '\0';
    584 	from = fromb;
    585 
    586 	/* need address in stringform for comparison (no DNS lookup here) */
    587 	error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
    588 			    NI_NUMERICHOST);
    589 	if (error)
    590 		fatal("Cannot print address");
    591 
    592 	/* Check for spoof, ala rlogind */
    593 	memset(&hints, 0, sizeof(hints));
    594 	hints.ai_family = PF_UNSPEC;
    595 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
    596 	error = getaddrinfo(fromb, NULL, &hints, &res);
    597 	if (error) {
    598 		fatal("hostname for your address (%s) unknown: %s", host,
    599 		    gai_strerror(error));
    600 	}
    601 	good = 0;
    602 	for (r = res; good == 0 && r; r = r->ai_next) {
    603 		error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
    604 				    NULL, 0, NI_NUMERICHOST);
    605 		if (!error && !strcmp(host, ip))
    606 			good = 1;
    607 	}
    608 	if (res)
    609 		freeaddrinfo(res);
    610 	if (good == 0)
    611 		fatal("address for your hostname (%s) not matched", host);
    612 	setproctitle("serving %s", from);
    613 	hostf = fopen(_PATH_HOSTSEQUIV, "r");
    614 again:
    615 	if (hostf) {
    616 		if (__ivaliduser_sa(hostf, f, DUMMY, DUMMY) == 0) {
    617 			(void)fclose(hostf);
    618 			return;
    619 		}
    620 		(void)fclose(hostf);
    621 	}
    622 	if (first == 1) {
    623 		first = 0;
    624 		hostf = fopen(_PATH_HOSTSLPD, "r");
    625 		goto again;
    626 	}
    627 	fatal("Your host does not have line printer access");
    628 	/*NOTREACHED*/
    629 }
    630 
    631 static void
    632 usage()
    633 {
    634 	extern char *__progname;	/* XXX */
    635 
    636 	fprintf(stderr, "usage: %s [-d] [-l]\n", __progname);
    637 	exit(1);
    638 }
    639 
    640 /* setup server socket for specified address family */
    641 /* if af is PF_UNSPEC more than one socket may be returned */
    642 /* the returned list is dynamically allocated, so caller needs to free it */
    643 int *
    644 socksetup(af, options)
    645         int af, options;
    646 {
    647 	struct addrinfo hints, *res, *r;
    648 	int error, maxs, *s, *socks;
    649 	const int on = 1;
    650 
    651 	memset(&hints, 0, sizeof(hints));
    652 	hints.ai_flags = AI_PASSIVE;
    653 	hints.ai_family = af;
    654 	hints.ai_socktype = SOCK_STREAM;
    655 	error = getaddrinfo(NULL, "printer", &hints, &res);
    656 	if (error) {
    657 		syslog(LOG_ERR, (gai_strerror(error)));
    658 		mcleanup(0);
    659 	}
    660 
    661 	/* Count max number of sockets we may open */
    662 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
    663 		;
    664 	socks = malloc((maxs + 1) * sizeof(int));
    665 	if (!socks) {
    666 		syslog(LOG_ERR, "couldn't allocate memory for sockets");
    667 		mcleanup(0);
    668 	}
    669 
    670 	*socks = 0;   /* num of sockets counter at start of array */
    671 	s = socks + 1;
    672 	for (r = res; r; r = r->ai_next) {
    673 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
    674 		if (*s < 0) {
    675 			syslog(LOG_DEBUG, "socket(): %m");
    676 			continue;
    677 		}
    678 		if (options & SO_DEBUG)
    679 			if (setsockopt(*s, SOL_SOCKET, SO_DEBUG,
    680 				       &on, sizeof(on)) < 0) {
    681 				syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
    682 				close (*s);
    683 				continue;
    684 			}
    685 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
    686 			syslog(LOG_DEBUG, "bind(): %m");
    687 			close (*s);
    688 			continue;
    689 		}
    690 		*socks = *socks + 1;
    691 		s++;
    692 	}
    693 
    694 	if (res)
    695 		freeaddrinfo(res);
    696 
    697 	if (*socks == 0) {
    698 		syslog(LOG_ERR, "Couldn't bind to any socket");
    699 		free(socks);
    700 		mcleanup(0);
    701 	}
    702 	return(socks);
    703 }
    704