lpd.c revision 1.40 1 /* $NetBSD: lpd.c,v 1.40 2002/09/19 20:22:32 mycroft 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.40 2002/09/19 20:22:32 mycroft 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_un fromunix;
151 struct sockaddr_storage frominet;
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(&frominet, 0, sizeof(frominet));
303 memset(&fromunix, 0, sizeof(fromunix));
304 for (;;) {
305 int domain, rv, s, fromlen;
306 /* "short" so it overflows in about 2 hours */
307 struct timespec sleeptime = {10, 0};
308
309 while (child_max < child_count) {
310 syslog(LOG_WARNING,
311 "too many children, sleeping for %ld seconds",
312 sleeptime.tv_sec);
313 nanosleep(&sleeptime, NULL);
314 sleeptime.tv_sec <<= 1;
315 if (sleeptime.tv_sec <= 0) {
316 syslog(LOG_CRIT, "sleeptime overflowed! help!");
317 sleeptime.tv_sec = 10;
318 }
319 }
320
321 rv = poll(socks, nfds, INFTIM);
322 if (rv <= 0) {
323 if (rv < 0 && errno != EINTR)
324 syslog(LOG_WARNING, "poll: %m");
325 continue;
326 }
327 for (i = 0; i < nfds; i++)
328 if (socks[i].revents & POLLIN) {
329 if (i == 0) {
330 domain = AF_LOCAL;
331 fromlen = sizeof(fromunix);
332 s = accept(socks[i].fd, (struct sockaddr *)&fromunix, &fromlen);
333 } else {
334 domain = AF_INET;
335 fromlen = sizeof(frominet);
336 s = accept(socks[i].fd, (struct sockaddr *)&frominet, &fromlen);
337 }
338 break;
339 }
340 if (s < 0) {
341 if (errno != EINTR)
342 syslog(LOG_WARNING, "accept: %m");
343 continue;
344 }
345
346 switch (fork()) {
347 case 0:
348 signal(SIGCHLD, SIG_IGN);
349 signal(SIGHUP, SIG_IGN);
350 signal(SIGINT, SIG_IGN);
351 signal(SIGQUIT, SIG_IGN);
352 signal(SIGTERM, SIG_IGN);
353 for (i = 0; i < nfds; i++)
354 (void)close(socks[i].fd);
355 dup2(s, 1);
356 (void)close(s);
357 if (domain == AF_INET) {
358 /* for both AF_INET and AF_INET6 */
359 from_remote = 1;
360 chkhost((struct sockaddr *)&frominet, check_options);
361 } else
362 from_remote = 0;
363 doit();
364 exit(0);
365 case -1:
366 syslog(LOG_WARNING, "fork: %m, sleeping for 10 seconds...");
367 sleep(10);
368 continue;
369 default:
370 child_count++;
371 }
372 (void)close(s);
373 }
374 }
375
376 static void
377 reapchild(int signo)
378 {
379 union wait status;
380
381 while (wait3((int *)&status, WNOHANG, 0) > 0)
382 child_count--;
383 }
384
385 static void
386 mcleanup(int signo)
387 {
388 if (lflag)
389 syslog(LOG_INFO, "exiting");
390 unlink(_PATH_SOCKETNAME);
391 exit(0);
392 }
393
394 /*
395 * Stuff for handling job specifications
396 */
397 char *user[MAXUSERS]; /* users to process */
398 int users; /* # of users in user array */
399 int requ[MAXREQUESTS]; /* job number of spool entries */
400 int requests; /* # of spool requests */
401 char *person; /* name of person doing lprm */
402
403 char fromb[NI_MAXHOST]; /* buffer for client's machine name */
404 char cbuf[BUFSIZ]; /* command line buffer */
405 char *cmdnames[] = {
406 "null",
407 "printjob",
408 "recvjob",
409 "displayq short",
410 "displayq long",
411 "rmjob"
412 };
413
414 static void
415 doit(void)
416 {
417 char *cp;
418 int n;
419
420 for (;;) {
421 cp = cbuf;
422 do {
423 if (cp >= &cbuf[sizeof(cbuf) - 1])
424 fatal("Command line too long");
425 if ((n = read(STDOUT_FILENO, cp, 1)) != 1) {
426 if (n < 0)
427 fatal("Lost connection");
428 return;
429 }
430 } while (*cp++ != '\n');
431 *--cp = '\0';
432 cp = cbuf;
433 if (lflag) {
434 if (*cp >= '\1' && *cp <= '\5') {
435 syslog(LOG_INFO, "%s requests %s %s",
436 from, cmdnames[(int)*cp], cp+1);
437 setproctitle("serving %s: %s %s", from,
438 cmdnames[(int)*cp], cp+1);
439 }
440 else
441 syslog(LOG_INFO, "bad request (%d) from %s",
442 *cp, from);
443 }
444 switch (*cp++) {
445 case '\1': /* check the queue and print any jobs there */
446 printer = cp;
447 if (*printer == '\0')
448 printer = DEFLP;
449 printjob();
450 break;
451 case '\2': /* receive files to be queued */
452 if (!from_remote) {
453 syslog(LOG_INFO, "illegal request (%d)", *cp);
454 exit(1);
455 }
456 printer = cp;
457 if (*printer == '\0')
458 printer = DEFLP;
459 recvjob();
460 break;
461 case '\3': /* display the queue (short form) */
462 case '\4': /* display the queue (long form) */
463 printer = cp;
464 if (*printer == '\0')
465 printer = DEFLP;
466 while (*cp) {
467 if (*cp != ' ') {
468 cp++;
469 continue;
470 }
471 *cp++ = '\0';
472 while (isspace(*cp))
473 cp++;
474 if (*cp == '\0')
475 break;
476 if (isdigit(*cp)) {
477 if (requests >= MAXREQUESTS)
478 fatal("Too many requests");
479 requ[requests++] = atoi(cp);
480 } else {
481 if (users >= MAXUSERS)
482 fatal("Too many users");
483 user[users++] = cp;
484 }
485 }
486 displayq(cbuf[0] - '\3');
487 exit(0);
488 case '\5': /* remove a job from the queue */
489 if (!from_remote) {
490 syslog(LOG_INFO, "illegal request (%d)", *cp);
491 exit(1);
492 }
493 printer = cp;
494 if (*printer == '\0')
495 printer = DEFLP;
496 while (*cp && *cp != ' ')
497 cp++;
498 if (!*cp)
499 break;
500 *cp++ = '\0';
501 person = cp;
502 while (*cp) {
503 if (*cp != ' ') {
504 cp++;
505 continue;
506 }
507 *cp++ = '\0';
508 while (isspace(*cp))
509 cp++;
510 if (*cp == '\0')
511 break;
512 if (isdigit(*cp)) {
513 if (requests >= MAXREQUESTS)
514 fatal("Too many requests");
515 requ[requests++] = atoi(cp);
516 } else {
517 if (users >= MAXUSERS)
518 fatal("Too many users");
519 user[users++] = cp;
520 }
521 }
522 rmjob();
523 break;
524 }
525 fatal("Illegal service request");
526 }
527 }
528
529 /*
530 * Make a pass through the printcap database and start printing any
531 * files left from the last time the machine went down.
532 */
533 static void
534 startup(void)
535 {
536 char *buf;
537 char *cp;
538
539 /*
540 * Restart the daemons.
541 */
542 while (cgetnext(&buf, printcapdb) > 0) {
543 if (ckqueue(buf) <= 0) {
544 free(buf);
545 continue; /* no work to do for this printer */
546 }
547 for (cp = buf; *cp; cp++)
548 if (*cp == '|' || *cp == ':') {
549 *cp = '\0';
550 break;
551 }
552 if (lflag)
553 syslog(LOG_INFO, "work for %s", buf);
554 switch (fork()) {
555 case -1:
556 syslog(LOG_WARNING, "startup: cannot fork");
557 mcleanup(0);
558 case 0:
559 printer = buf;
560 setproctitle("working on printer %s", printer);
561 cgetclose();
562 printjob();
563 /* NOTREACHED */
564 default:
565 child_count++;
566 free(buf);
567 }
568 }
569 }
570
571 /*
572 * Make sure there's some work to do before forking off a child
573 */
574 static int
575 ckqueue(char *cap)
576 {
577 struct dirent *d;
578 DIR *dirp;
579 char *spooldir;
580
581 if (cgetstr(cap, "sd", &spooldir) == -1)
582 spooldir = _PATH_DEFSPOOL;
583 if ((dirp = opendir(spooldir)) == NULL)
584 return (-1);
585 while ((d = readdir(dirp)) != NULL) {
586 if (d->d_name[0] != 'c' || d->d_name[1] != 'f')
587 continue; /* daemon control files only */
588 closedir(dirp);
589 return (1); /* found something */
590 }
591 closedir(dirp);
592 return (0);
593 }
594
595 #define DUMMY ":nobody::"
596
597 /*
598 * Check to see if the from host has access to the line printer.
599 */
600 static void
601 chkhost(struct sockaddr *f, int check_opts)
602 {
603 struct addrinfo hints, *res, *r;
604 FILE *hostf;
605 int good = 0;
606 char host[NI_MAXHOST], ip[NI_MAXHOST];
607 char serv[NI_MAXSERV];
608 int error;
609 #ifdef LIBWRAP
610 struct request_info req;
611 #endif
612
613 error = getnameinfo(f, f->sa_len, NULL, 0, serv, sizeof(serv),
614 NI_NUMERICSERV);
615 if (error)
616 fatal("Malformed from address: %s", gai_strerror(error));
617
618 if (!(check_opts & LPD_NOPORTCHK) &&
619 atoi(serv) >= IPPORT_RESERVED)
620 fatal("Connect from invalid port (%s)", serv);
621
622 /* Need real hostname for temporary filenames */
623 error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
624 NI_NAMEREQD);
625 if (error) {
626 error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
627 NI_NUMERICHOST);
628 if (error)
629 fatal("Host name for your address unknown");
630 else
631 fatal("Host name for your address (%s) unknown", host);
632 }
633
634 (void)strncpy(fromb, host, sizeof(fromb) - 1);
635 fromb[sizeof(fromb) - 1] = '\0';
636 from = fromb;
637
638 /* need address in stringform for comparison (no DNS lookup here) */
639 error = getnameinfo(f, f->sa_len, host, sizeof(host), NULL, 0,
640 NI_NUMERICHOST);
641 if (error)
642 fatal("Cannot print address");
643
644 /* Check for spoof, ala rlogind */
645 memset(&hints, 0, sizeof(hints));
646 hints.ai_family = PF_UNSPEC;
647 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
648 error = getaddrinfo(fromb, NULL, &hints, &res);
649 if (error) {
650 fatal("hostname for your address (%s) unknown: %s", host,
651 gai_strerror(error));
652 }
653 good = 0;
654 for (r = res; good == 0 && r; r = r->ai_next) {
655 error = getnameinfo(r->ai_addr, r->ai_addrlen, ip, sizeof(ip),
656 NULL, 0, NI_NUMERICHOST);
657 if (!error && !strcmp(host, ip))
658 good = 1;
659 }
660 if (res)
661 freeaddrinfo(res);
662 if (good == 0)
663 fatal("address for your hostname (%s) not matched", host);
664
665 setproctitle("serving %s", from);
666
667 #ifdef LIBWRAP
668 request_init(&req, RQ_DAEMON, "lpd", RQ_CLIENT_SIN, f, NULL);
669 fromhost(&req);
670 if (!hosts_access(&req))
671 goto denied;
672 #endif
673
674 hostf = fopen(_PATH_HOSTSEQUIV, "r");
675 if (hostf) {
676 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
677 (void)fclose(hostf);
678 return;
679 }
680 (void)fclose(hostf);
681 }
682 hostf = fopen(_PATH_HOSTSLPD, "r");
683 if (hostf) {
684 if (__ivaliduser_sa(hostf, f, f->sa_len, DUMMY, DUMMY) == 0) {
685 (void)fclose(hostf);
686 return;
687 }
688 (void)fclose(hostf);
689 }
690 #ifdef LIBWRAP
691 denied:
692 #endif
693 fatal("Your host does not have line printer access");
694 /*NOTREACHED*/
695 }
696
697
698 static void
699 usage(void)
700 {
701
702 fprintf(stderr, "usage: %s [-dlrsW] [-b bind-address] [-n maxchild] "
703 "[-w maxwait] [port]\n", getprogname());
704 exit(1);
705 }
706
707 /* setup server socket for specified address family */
708 /* if af is PF_UNSPEC more than one socket may be returned */
709 /* the returned list is dynamically allocated, so caller needs to free it */
710 struct pollfd *
711 socksetup(int af, int options, const char *port, int *nfds)
712 {
713 struct sockaddr_un un;
714 struct addrinfo hints, *res, *r;
715 int error, s, blidx = 0, n;
716 struct pollfd *socks;
717 const int on = 1;
718
719 *nfds = 0;
720
721 socks = malloc(1 * sizeof(int));
722 if (!socks) {
723 syslog(LOG_ERR, "couldn't allocate memory for sockets");
724 mcleanup(0);
725 }
726
727 s = socket(AF_LOCAL, SOCK_STREAM, 0);
728 if (s < 0) {
729 syslog(LOG_ERR, "socket(): %m");
730 exit(1);
731 }
732 memset(&un, 0, sizeof(un));
733 un.sun_family = AF_LOCAL;
734 strncpy(un.sun_path, _PATH_SOCKETNAME, sizeof(un.sun_path) - 1);
735 un.sun_len = SUN_LEN(&un);
736 (void)umask(07);
737 (void)unlink(_PATH_SOCKETNAME);
738 if (bind(s, (struct sockaddr *)&un, un.sun_len) < 0) {
739 syslog(LOG_ERR, "bind(): %m");
740 exit(1);
741 }
742 (void)umask(0);
743 listen(s, 5);
744 socks[*nfds].fd = s;
745 socks[*nfds].events = POLLIN;
746 (*nfds)++;
747
748 if (sflag && !blist_addrs)
749 return (socks);
750
751 do {
752 memset(&hints, 0, sizeof(hints));
753 hints.ai_flags = AI_PASSIVE;
754 hints.ai_family = af;
755 hints.ai_socktype = SOCK_STREAM;
756 error = getaddrinfo((blist_addrs == 0) ? NULL : blist[blidx],
757 port ? port : "printer", &hints, &res);
758 if (error) {
759 if (blist_addrs)
760 syslog(LOG_ERR, "%s: %s", blist[blidx],
761 gai_strerror(error));
762 else
763 syslog(LOG_ERR, "%s", gai_strerror(error));
764 mcleanup(0);
765 }
766
767 /* Count max number of sockets we may open */
768 for (r = res, n = 0; r; r = r->ai_next, n++)
769 ;
770 socks = realloc(socks, (*nfds + n) * sizeof(int));
771 if (!socks) {
772 syslog(LOG_ERR, "couldn't allocate memory for sockets");
773 mcleanup(0);
774 }
775
776 for (r = res; r; r = r->ai_next) {
777 s = socket(r->ai_family, r->ai_socktype,
778 r->ai_protocol);
779 if (s < 0) {
780 syslog(LOG_DEBUG, "socket(): %m");
781 continue;
782 }
783 if (options & SO_DEBUG)
784 if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
785 &on, sizeof(on)) < 0) {
786 syslog(LOG_ERR,
787 "setsockopt (SO_DEBUG): %m");
788 close(s);
789 continue;
790 }
791 if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &on,
792 sizeof(on)) < 0) {
793 syslog(LOG_ERR,
794 "setsockopt (SO_REUSEPORT): %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