xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision 7aa383846770374466b1dcb2cefd71bde9acf463)
1 /*
2  * Copyright (c) 1983, 1988, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
39 #endif
40 #endif /* not lint */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 /*
46  *  syslogd -- log system messages
47  *
48  * This program implements a system log. It takes a series of lines.
49  * Each line may have a priority, signified as "<n>" as
50  * the first characters of the line.  If this is
51  * not present, a default priority is used.
52  *
53  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
54  * cause it to reread its configuration file.
55  *
56  * Defined Constants:
57  *
58  * MAXLINE -- the maximum line length that can be handled.
59  * DEFUPRI -- the default priority for user messages
60  * DEFSPRI -- the default priority for kernel messages
61  *
62  * Author: Eric Allman
63  * extensive changes by Ralph Campbell
64  * more extensive changes by Eric Allman (again)
65  * Extension to log by program name as well as facility and priority
66  *   by Peter da Silva.
67  * -u and -v by Harlan Stenn.
68  * Priority comparison code by Harlan Stenn.
69  */
70 
71 #define	MAXLINE		1024		/* maximum line length */
72 #define	MAXSVLINE	120		/* maximum saved line length */
73 #define	DEFUPRI		(LOG_USER|LOG_NOTICE)
74 #define	DEFSPRI		(LOG_KERN|LOG_CRIT)
75 #define	TIMERINTVL	30		/* interval for checking flush, mark */
76 #define	TTYMSGTIME	1		/* timeout passed to ttymsg */
77 
78 #include <sys/param.h>
79 #include <sys/ioctl.h>
80 #include <sys/mman.h>
81 #include <sys/stat.h>
82 #include <sys/wait.h>
83 #include <sys/socket.h>
84 #include <sys/queue.h>
85 #include <sys/uio.h>
86 #include <sys/un.h>
87 #include <sys/time.h>
88 #include <sys/resource.h>
89 #include <sys/syslimits.h>
90 #include <sys/types.h>
91 
92 #include <netinet/in.h>
93 #include <netdb.h>
94 #include <arpa/inet.h>
95 
96 #include <ctype.h>
97 #include <err.h>
98 #include <errno.h>
99 #include <fcntl.h>
100 #include <libutil.h>
101 #include <limits.h>
102 #include <paths.h>
103 #include <signal.h>
104 #include <stdio.h>
105 #include <stdlib.h>
106 #include <string.h>
107 #include <sysexits.h>
108 #include <unistd.h>
109 #include <utmpx.h>
110 
111 #include "pathnames.h"
112 #include "ttymsg.h"
113 
114 #define SYSLOG_NAMES
115 #include <sys/syslog.h>
116 
117 const char	*ConfFile = _PATH_LOGCONF;
118 const char	*PidFile = _PATH_LOGPID;
119 const char	ctty[] = _PATH_CONSOLE;
120 
121 #define	dprintf		if (Debug) printf
122 
123 #define	MAXUNAMES	20	/* maximum number of user names */
124 
125 /*
126  * Unix sockets.
127  * We have two default sockets, one with 666 permissions,
128  * and one for privileged programs.
129  */
130 struct funix {
131 	int			s;
132 	const char		*name;
133 	mode_t			mode;
134 	STAILQ_ENTRY(funix)	next;
135 };
136 struct funix funix_secure =	{ -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
137 				{ NULL } };
138 struct funix funix_default =	{ -1, _PATH_LOG, DEFFILEMODE,
139 				{ &funix_secure } };
140 
141 STAILQ_HEAD(, funix) funixes =	{ &funix_default,
142 				&(funix_secure.next.stqe_next) };
143 
144 /*
145  * Flags to logmsg().
146  */
147 
148 #define	IGN_CONS	0x001	/* don't print on console */
149 #define	SYNC_FILE	0x002	/* do fsync on file after printing */
150 #define	ADDDATE		0x004	/* add a date to the message */
151 #define	MARK		0x008	/* this message is a mark */
152 #define	ISKERNEL	0x010	/* kernel generated message */
153 
154 /*
155  * This structure represents the files that will have log
156  * copies printed.
157  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
158  * or if f_type if F_PIPE and f_pid > 0.
159  */
160 
161 struct filed {
162 	struct	filed *f_next;		/* next in linked list */
163 	short	f_type;			/* entry type, see below */
164 	short	f_file;			/* file descriptor */
165 	time_t	f_time;			/* time this was last written */
166 	char	*f_host;		/* host from which to recd. */
167 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
168 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
169 #define PRI_LT	0x1
170 #define PRI_EQ	0x2
171 #define PRI_GT	0x4
172 	char	*f_program;		/* program this applies to */
173 	union {
174 		char	f_uname[MAXUNAMES][MAXLOGNAME];
175 		struct {
176 			char	f_hname[MAXHOSTNAMELEN];
177 			struct addrinfo *f_addr;
178 
179 		} f_forw;		/* forwarding address */
180 		char	f_fname[MAXPATHLEN];
181 		struct {
182 			char	f_pname[MAXPATHLEN];
183 			pid_t	f_pid;
184 		} f_pipe;
185 	} f_un;
186 	char	f_prevline[MAXSVLINE];		/* last message logged */
187 	char	f_lasttime[16];			/* time of last occurrence */
188 	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
189 	int	f_prevpri;			/* pri of f_prevline */
190 	int	f_prevlen;			/* length of f_prevline */
191 	int	f_prevcount;			/* repetition cnt of prevline */
192 	u_int	f_repeatcount;			/* number of "repeated" msgs */
193 	int	f_flags;			/* file-specific flags */
194 #define	FFLAG_SYNC 0x01
195 #define	FFLAG_NEEDSYNC	0x02
196 };
197 
198 /*
199  * Queue of about-to-be dead processes we should watch out for.
200  */
201 
202 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
203 struct stailhead *deadq_headp;
204 
205 struct deadq_entry {
206 	pid_t				dq_pid;
207 	int				dq_timeout;
208 	TAILQ_ENTRY(deadq_entry)	dq_entries;
209 };
210 
211 /*
212  * The timeout to apply to processes waiting on the dead queue.  Unit
213  * of measure is `mark intervals', i.e. 20 minutes by default.
214  * Processes on the dead queue will be terminated after that time.
215  */
216 
217 #define	 DQ_TIMO_INIT	2
218 
219 typedef struct deadq_entry *dq_t;
220 
221 
222 /*
223  * Struct to hold records of network addresses that are allowed to log
224  * to us.
225  */
226 struct allowedpeer {
227 	int isnumeric;
228 	u_short port;
229 	union {
230 		struct {
231 			struct sockaddr_storage addr;
232 			struct sockaddr_storage mask;
233 		} numeric;
234 		char *name;
235 	} u;
236 #define a_addr u.numeric.addr
237 #define a_mask u.numeric.mask
238 #define a_name u.name
239 };
240 
241 
242 /*
243  * Intervals at which we flush out "message repeated" messages,
244  * in seconds after previous message is logged.  After each flush,
245  * we move to the next interval until we reach the largest.
246  */
247 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
248 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
249 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
250 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
251 				 (f)->f_repeatcount = MAXREPEAT; \
252 			}
253 
254 /* values for f_type */
255 #define F_UNUSED	0		/* unused entry */
256 #define F_FILE		1		/* regular file */
257 #define F_TTY		2		/* terminal */
258 #define F_CONSOLE	3		/* console terminal */
259 #define F_FORW		4		/* remote machine */
260 #define F_USERS		5		/* list of users */
261 #define F_WALL		6		/* everyone logged on */
262 #define F_PIPE		7		/* pipe to program */
263 
264 const char *TypeNames[8] = {
265 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
266 	"FORW",		"USERS",	"WALL",		"PIPE"
267 };
268 
269 static struct filed *Files;	/* Log files that we write to */
270 static struct filed consfile;	/* Console */
271 
272 static int	Debug;		/* debug flag */
273 static int	resolve = 1;	/* resolve hostname */
274 static char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
275 static const char *LocalDomain;	/* our local domain name */
276 static int	*finet;		/* Internet datagram socket */
277 static int	fklog = -1;	/* /dev/klog */
278 static int	Initialized;	/* set when we have initialized ourselves */
279 static int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
280 static int	MarkSeq;	/* mark sequence number */
281 static int	SecureMode;	/* when true, receive only unix domain socks */
282 #ifdef INET6
283 static int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
284 #else
285 static int	family = PF_INET; /* protocol family (IPv4 only) */
286 #endif
287 static int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
288 static int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
289 static int	use_bootfile;	/* log entire bootfile for every kern msg */
290 static int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
291 static int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
292 
293 static char	bootfile[MAXLINE+1]; /* booted kernel file */
294 
295 struct allowedpeer *AllowedPeers; /* List of allowed peers */
296 static int	NumAllowed;	/* Number of entries in AllowedPeers */
297 static int	RemoteAddDate;	/* Always set the date on remote messages */
298 
299 static int	UniquePriority;	/* Only log specified priority? */
300 static int	LogFacPri;	/* Put facility and priority in log message: */
301 				/* 0=no, 1=numeric, 2=names */
302 static int	KeepKernFac;	/* Keep remotely logged kernel facility */
303 static int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
304 static struct pidfh *pfh;
305 
306 volatile sig_atomic_t MarkSet, WantDie;
307 
308 static int	allowaddr(char *);
309 static void	cfline(const char *, struct filed *,
310 		    const char *, const char *);
311 static const char *cvthname(struct sockaddr *);
312 static void	deadq_enter(pid_t, const char *);
313 static int	deadq_remove(pid_t);
314 static int	decode(const char *, CODE *);
315 static void	die(int);
316 static void	dodie(int);
317 static void	dofsync(void);
318 static void	domark(int);
319 static void	fprintlog(struct filed *, int, const char *);
320 static int	*socksetup(int, const char *);
321 static void	init(int);
322 static void	logerror(const char *);
323 static void	logmsg(int, const char *, const char *, int);
324 static void	log_deadchild(pid_t, int, const char *);
325 static void	markit(void);
326 static int	skip_message(const char *, const char *, int);
327 static void	printline(const char *, char *, int);
328 static void	printsys(char *);
329 static int	p_open(const char *, pid_t *);
330 static void	readklog(void);
331 static void	reapchild(int);
332 static void	usage(void);
333 static int	validate(struct sockaddr *, const char *);
334 static void	unmapped(struct sockaddr *);
335 static void	wallmsg(struct filed *, struct iovec *, const int iovlen);
336 static int	waitdaemon(int, int, int);
337 static void	timedout(int);
338 static void	double_rbuf(int);
339 
340 int
341 main(int argc, char *argv[])
342 {
343 	int ch, i, fdsrmax = 0, l;
344 	struct sockaddr_un sunx, fromunix;
345 	struct sockaddr_storage frominet;
346 	fd_set *fdsr = NULL;
347 	char line[MAXLINE + 1];
348 	const char *bindhostname, *hname;
349 	struct timeval tv, *tvp;
350 	struct sigaction sact;
351 	struct funix *fx, *fx1;
352 	sigset_t mask;
353 	pid_t ppid = 1, spid;
354 	socklen_t len;
355 
356 	if (madvise(NULL, 0, MADV_PROTECT) != 0)
357 		dprintf("madvise() failed: %s\n", strerror(errno));
358 
359 	bindhostname = NULL;
360 	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nop:P:sS:Tuv"))
361 	    != -1)
362 		switch (ch) {
363 		case '4':
364 			family = PF_INET;
365 			break;
366 #ifdef INET6
367 		case '6':
368 			family = PF_INET6;
369 			break;
370 #endif
371 		case '8':
372 			mask_C1 = 0;
373 			break;
374 		case 'A':
375 			send_to_all++;
376 			break;
377 		case 'a':		/* allow specific network addresses only */
378 			if (allowaddr(optarg) == -1)
379 				usage();
380 			break;
381 		case 'b':
382 			bindhostname = optarg;
383 			break;
384 		case 'c':
385 			no_compress++;
386 			break;
387 		case 'C':
388 			logflags |= O_CREAT;
389 			break;
390 		case 'd':		/* debug */
391 			Debug++;
392 			break;
393 		case 'f':		/* configuration file */
394 			ConfFile = optarg;
395 			break;
396 		case 'k':		/* keep remote kern fac */
397 			KeepKernFac = 1;
398 			break;
399 		case 'l':
400 		    {
401 			long	perml;
402 			mode_t	mode;
403 			char	*name, *ep;
404 
405 			if (optarg[0] == '/') {
406 				mode = DEFFILEMODE;
407 				name = optarg;
408 			} else if ((name = strchr(optarg, ':')) != NULL) {
409 				*name++ = '\0';
410 				if (name[0] != '/')
411 					errx(1, "socket name must be absolute "
412 					    "path");
413 				if (isdigit(*optarg)) {
414 					perml = strtol(optarg, &ep, 8);
415 				    if (*ep || perml < 0 ||
416 					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
417 					    errx(1, "invalid mode %s, exiting",
418 						optarg);
419 				    mode = (mode_t )perml;
420 				} else
421 					errx(1, "invalid mode %s, exiting",
422 					    optarg);
423 			} else	/* doesn't begin with '/', and no ':' */
424 				errx(1, "can't parse path %s", optarg);
425 
426 			if (strlen(name) >= sizeof(sunx.sun_path))
427 				errx(1, "%s path too long, exiting", name);
428 			if ((fx = malloc(sizeof(struct funix))) == NULL)
429 				errx(1, "malloc failed");
430 			fx->s = -1;
431 			fx->name = name;
432 			fx->mode = mode;
433 			STAILQ_INSERT_TAIL(&funixes, fx, next);
434 			break;
435 		   }
436 		case 'm':		/* mark interval */
437 			MarkInterval = atoi(optarg) * 60;
438 			break;
439 		case 'n':
440 			resolve = 0;
441 			break;
442 		case 'o':
443 			use_bootfile = 1;
444 			break;
445 		case 'p':		/* path */
446 			if (strlen(optarg) >= sizeof(sunx.sun_path))
447 				errx(1, "%s path too long, exiting", optarg);
448 			funix_default.name = optarg;
449 			break;
450 		case 'P':		/* path for alt. PID */
451 			PidFile = optarg;
452 			break;
453 		case 's':		/* no network mode */
454 			SecureMode++;
455 			break;
456 		case 'S':		/* path for privileged originator */
457 			if (strlen(optarg) >= sizeof(sunx.sun_path))
458 				errx(1, "%s path too long, exiting", optarg);
459 			funix_secure.name = optarg;
460 			break;
461 		case 'T':
462 			RemoteAddDate = 1;
463 			break;
464 		case 'u':		/* only log specified priority */
465 			UniquePriority++;
466 			break;
467 		case 'v':		/* log facility and priority */
468 		  	LogFacPri++;
469 			break;
470 		default:
471 			usage();
472 		}
473 	if ((argc -= optind) != 0)
474 		usage();
475 
476 	pfh = pidfile_open(PidFile, 0600, &spid);
477 	if (pfh == NULL) {
478 		if (errno == EEXIST)
479 			errx(1, "syslogd already running, pid: %d", spid);
480 		warn("cannot open pid file");
481 	}
482 
483 	if (!Debug) {
484 		ppid = waitdaemon(0, 0, 30);
485 		if (ppid < 0) {
486 			warn("could not become daemon");
487 			pidfile_remove(pfh);
488 			exit(1);
489 		}
490 	} else {
491 		setlinebuf(stdout);
492 	}
493 
494 	if (NumAllowed)
495 		endservent();
496 
497 	consfile.f_type = F_CONSOLE;
498 	(void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
499 	    sizeof(consfile.f_un.f_fname));
500 	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
501 	(void)signal(SIGTERM, dodie);
502 	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
503 	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
504 	/*
505 	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
506 	 * with each other; they are likely candidates for being called
507 	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
508 	 * SIGCHLD happens).
509 	 */
510 	sigemptyset(&mask);
511 	sigaddset(&mask, SIGHUP);
512 	sact.sa_handler = reapchild;
513 	sact.sa_mask = mask;
514 	sact.sa_flags = SA_RESTART;
515 	(void)sigaction(SIGCHLD, &sact, NULL);
516 	(void)signal(SIGALRM, domark);
517 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
518 	(void)alarm(TIMERINTVL);
519 
520 	TAILQ_INIT(&deadq_head);
521 
522 #ifndef SUN_LEN
523 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
524 #endif
525 	STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
526 		(void)unlink(fx->name);
527 		memset(&sunx, 0, sizeof(sunx));
528 		sunx.sun_family = AF_LOCAL;
529 		(void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
530 		fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
531 		if (fx->s < 0 ||
532 		    bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
533 		    chmod(fx->name, fx->mode) < 0) {
534 			(void)snprintf(line, sizeof line,
535 					"cannot create %s", fx->name);
536 			logerror(line);
537 			dprintf("cannot create %s (%d)\n", fx->name, errno);
538 			if (fx == &funix_default || fx == &funix_secure)
539 				die(0);
540 			else {
541 				STAILQ_REMOVE(&funixes, fx, funix, next);
542 				continue;
543 			}
544 			double_rbuf(fx->s);
545 		}
546 	}
547 	if (SecureMode <= 1)
548 		finet = socksetup(family, bindhostname);
549 
550 	if (finet) {
551 		if (SecureMode) {
552 			for (i = 0; i < *finet; i++) {
553 				if (shutdown(finet[i+1], SHUT_RD) < 0) {
554 					logerror("shutdown");
555 					if (!Debug)
556 						die(0);
557 				}
558 			}
559 		} else {
560 			dprintf("listening on inet and/or inet6 socket\n");
561 		}
562 		dprintf("sending on inet and/or inet6 socket\n");
563 	}
564 
565 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
566 		if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
567 			fklog = -1;
568 	if (fklog < 0)
569 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
570 
571 	/* tuck my process id away */
572 	pidfile_write(pfh);
573 
574 	dprintf("off & running....\n");
575 
576 	init(0);
577 	/* prevent SIGHUP and SIGCHLD handlers from running in parallel */
578 	sigemptyset(&mask);
579 	sigaddset(&mask, SIGCHLD);
580 	sact.sa_handler = init;
581 	sact.sa_mask = mask;
582 	sact.sa_flags = SA_RESTART;
583 	(void)sigaction(SIGHUP, &sact, NULL);
584 
585 	tvp = &tv;
586 	tv.tv_sec = tv.tv_usec = 0;
587 
588 	if (fklog != -1 && fklog > fdsrmax)
589 		fdsrmax = fklog;
590 	if (finet && !SecureMode) {
591 		for (i = 0; i < *finet; i++) {
592 		    if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
593 			fdsrmax = finet[i+1];
594 		}
595 	}
596 	STAILQ_FOREACH(fx, &funixes, next)
597 		if (fx->s > fdsrmax)
598 			fdsrmax = fx->s;
599 
600 	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
601 	    sizeof(fd_mask));
602 	if (fdsr == NULL)
603 		errx(1, "calloc fd_set");
604 
605 	for (;;) {
606 		if (MarkSet)
607 			markit();
608 		if (WantDie)
609 			die(WantDie);
610 
611 		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
612 		    sizeof(fd_mask));
613 
614 		if (fklog != -1)
615 			FD_SET(fklog, fdsr);
616 		if (finet && !SecureMode) {
617 			for (i = 0; i < *finet; i++) {
618 				if (finet[i+1] != -1)
619 					FD_SET(finet[i+1], fdsr);
620 			}
621 		}
622 		STAILQ_FOREACH(fx, &funixes, next)
623 			FD_SET(fx->s, fdsr);
624 
625 		i = select(fdsrmax+1, fdsr, NULL, NULL,
626 		    needdofsync ? &tv : tvp);
627 		switch (i) {
628 		case 0:
629 			dofsync();
630 			needdofsync = 0;
631 			if (tvp) {
632 				tvp = NULL;
633 				if (ppid != 1)
634 					kill(ppid, SIGALRM);
635 			}
636 			continue;
637 		case -1:
638 			if (errno != EINTR)
639 				logerror("select");
640 			continue;
641 		}
642 		if (fklog != -1 && FD_ISSET(fklog, fdsr))
643 			readklog();
644 		if (finet && !SecureMode) {
645 			for (i = 0; i < *finet; i++) {
646 				if (FD_ISSET(finet[i+1], fdsr)) {
647 					len = sizeof(frominet);
648 					l = recvfrom(finet[i+1], line, MAXLINE,
649 					     0, (struct sockaddr *)&frominet,
650 					     &len);
651 					if (l > 0) {
652 						line[l] = '\0';
653 						hname = cvthname((struct sockaddr *)&frominet);
654 						unmapped((struct sockaddr *)&frominet);
655 						if (validate((struct sockaddr *)&frominet, hname))
656 							printline(hname, line, RemoteAddDate ? ADDDATE : 0);
657 					} else if (l < 0 && errno != EINTR)
658 						logerror("recvfrom inet");
659 				}
660 			}
661 		}
662 		STAILQ_FOREACH(fx, &funixes, next) {
663 			if (FD_ISSET(fx->s, fdsr)) {
664 				len = sizeof(fromunix);
665 				l = recvfrom(fx->s, line, MAXLINE, 0,
666 				    (struct sockaddr *)&fromunix, &len);
667 				if (l > 0) {
668 					line[l] = '\0';
669 					printline(LocalHostName, line, 0);
670 				} else if (l < 0 && errno != EINTR)
671 					logerror("recvfrom unix");
672 			}
673 		}
674 	}
675 	if (fdsr)
676 		free(fdsr);
677 }
678 
679 static void
680 unmapped(struct sockaddr *sa)
681 {
682 	struct sockaddr_in6 *sin6;
683 	struct sockaddr_in sin4;
684 
685 	if (sa->sa_family != AF_INET6)
686 		return;
687 	if (sa->sa_len != sizeof(struct sockaddr_in6) ||
688 	    sizeof(sin4) > sa->sa_len)
689 		return;
690 	sin6 = (struct sockaddr_in6 *)sa;
691 	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
692 		return;
693 
694 	memset(&sin4, 0, sizeof(sin4));
695 	sin4.sin_family = AF_INET;
696 	sin4.sin_len = sizeof(struct sockaddr_in);
697 	memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
698 	       sizeof(sin4.sin_addr));
699 	sin4.sin_port = sin6->sin6_port;
700 
701 	memcpy(sa, &sin4, sin4.sin_len);
702 }
703 
704 static void
705 usage(void)
706 {
707 
708 	fprintf(stderr, "%s\n%s\n%s\n%s\n",
709 		"usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
710 		"               [-b bind_address] [-f config_file]",
711 		"               [-l [mode:]path] [-m mark_interval]",
712 		"               [-P pid_file] [-p log_socket]");
713 	exit(1);
714 }
715 
716 /*
717  * Take a raw input line, decode the message, and print the message
718  * on the appropriate log files.
719  */
720 static void
721 printline(const char *hname, char *msg, int flags)
722 {
723 	char *p, *q;
724 	long n;
725 	int c, pri;
726 	char line[MAXLINE + 1];
727 
728 	/* test for special codes */
729 	p = msg;
730 	pri = DEFUPRI;
731 	if (*p == '<') {
732 		errno = 0;
733 		n = strtol(p + 1, &q, 10);
734 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
735 			p = q + 1;
736 			pri = n;
737 		}
738 	}
739 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
740 		pri = DEFUPRI;
741 
742 	/*
743 	 * Don't allow users to log kernel messages.
744 	 * NOTE: since LOG_KERN == 0 this will also match
745 	 *       messages with no facility specified.
746 	 */
747 	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
748 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
749 
750 	q = line;
751 
752 	while ((c = (unsigned char)*p++) != '\0' &&
753 	    q < &line[sizeof(line) - 4]) {
754 		if (mask_C1 && (c & 0x80) && c < 0xA0) {
755 			c &= 0x7F;
756 			*q++ = 'M';
757 			*q++ = '-';
758 		}
759 		if (isascii(c) && iscntrl(c)) {
760 			if (c == '\n') {
761 				*q++ = ' ';
762 			} else if (c == '\t') {
763 				*q++ = '\t';
764 			} else {
765 				*q++ = '^';
766 				*q++ = c ^ 0100;
767 			}
768 		} else {
769 			*q++ = c;
770 		}
771 	}
772 	*q = '\0';
773 
774 	logmsg(pri, line, hname, flags);
775 }
776 
777 /*
778  * Read /dev/klog while data are available, split into lines.
779  */
780 static void
781 readklog(void)
782 {
783 	char *p, *q, line[MAXLINE + 1];
784 	int len, i;
785 
786 	len = 0;
787 	for (;;) {
788 		i = read(fklog, line + len, MAXLINE - 1 - len);
789 		if (i > 0) {
790 			line[i + len] = '\0';
791 		} else {
792 			if (i < 0 && errno != EINTR && errno != EAGAIN) {
793 				logerror("klog");
794 				fklog = -1;
795 			}
796 			break;
797 		}
798 
799 		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
800 			*q = '\0';
801 			printsys(p);
802 		}
803 		len = strlen(p);
804 		if (len >= MAXLINE - 1) {
805 			printsys(p);
806 			len = 0;
807 		}
808 		if (len > 0)
809 			memmove(line, p, len + 1);
810 	}
811 	if (len > 0)
812 		printsys(line);
813 }
814 
815 /*
816  * Take a raw input line from /dev/klog, format similar to syslog().
817  */
818 static void
819 printsys(char *msg)
820 {
821 	char *p, *q;
822 	long n;
823 	int flags, isprintf, pri;
824 
825 	flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
826 	p = msg;
827 	pri = DEFSPRI;
828 	isprintf = 1;
829 	if (*p == '<') {
830 		errno = 0;
831 		n = strtol(p + 1, &q, 10);
832 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
833 			p = q + 1;
834 			pri = n;
835 			isprintf = 0;
836 		}
837 	}
838 	/*
839 	 * Kernel printf's and LOG_CONSOLE messages have been displayed
840 	 * on the console already.
841 	 */
842 	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
843 		flags |= IGN_CONS;
844 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
845 		pri = DEFSPRI;
846 	logmsg(pri, p, LocalHostName, flags);
847 }
848 
849 static time_t	now;
850 
851 /*
852  * Match a program or host name against a specification.
853  * Return a non-0 value if the message must be ignored
854  * based on the specification.
855  */
856 static int
857 skip_message(const char *name, const char *spec, int checkcase)
858 {
859 	const char *s;
860 	char prev, next;
861 	int exclude = 0;
862 	/* Behaviour on explicit match */
863 
864 	if (spec == NULL)
865 		return 0;
866 	switch (*spec) {
867 	case '-':
868 		exclude = 1;
869 		/*FALLTHROUGH*/
870 	case '+':
871 		spec++;
872 		break;
873 	default:
874 		break;
875 	}
876 	if (checkcase)
877 		s = strstr (spec, name);
878 	else
879 		s = strcasestr (spec, name);
880 
881 	if (s != NULL) {
882 		prev = (s == spec ? ',' : *(s - 1));
883 		next = *(s + strlen (name));
884 
885 		if (prev == ',' && (next == '\0' || next == ','))
886 			/* Explicit match: skip iff the spec is an
887 			   exclusive one. */
888 			return exclude;
889 	}
890 
891 	/* No explicit match for this name: skip the message iff
892 	   the spec is an inclusive one. */
893 	return !exclude;
894 }
895 
896 /*
897  * Log a message to the appropriate log files, users, etc. based on
898  * the priority.
899  */
900 static void
901 logmsg(int pri, const char *msg, const char *from, int flags)
902 {
903 	struct filed *f;
904 	int i, fac, msglen, omask, prilev;
905 	const char *timestamp;
906  	char prog[NAME_MAX+1];
907 	char buf[MAXLINE+1];
908 
909 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
910 	    pri, flags, from, msg);
911 
912 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
913 
914 	/*
915 	 * Check to see if msg looks non-standard.
916 	 */
917 	msglen = strlen(msg);
918 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
919 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
920 		flags |= ADDDATE;
921 
922 	(void)time(&now);
923 	if (flags & ADDDATE) {
924 		timestamp = ctime(&now) + 4;
925 	} else {
926 		timestamp = msg;
927 		msg += 16;
928 		msglen -= 16;
929 	}
930 
931 	/* skip leading blanks */
932 	while (isspace(*msg)) {
933 		msg++;
934 		msglen--;
935 	}
936 
937 	/* extract facility and priority level */
938 	if (flags & MARK)
939 		fac = LOG_NFACILITIES;
940 	else
941 		fac = LOG_FAC(pri);
942 
943 	/* Check maximum facility number. */
944 	if (fac > LOG_NFACILITIES) {
945 		(void)sigsetmask(omask);
946 		return;
947 	}
948 
949 	prilev = LOG_PRI(pri);
950 
951 	/* extract program name */
952 	for (i = 0; i < NAME_MAX; i++) {
953 		if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
954 		    msg[i] == '/' || isspace(msg[i]))
955 			break;
956 		prog[i] = msg[i];
957 	}
958 	prog[i] = 0;
959 
960 	/* add kernel prefix for kernel messages */
961 	if (flags & ISKERNEL) {
962 		snprintf(buf, sizeof(buf), "%s: %s",
963 		    use_bootfile ? bootfile : "kernel", msg);
964 		msg = buf;
965 		msglen = strlen(buf);
966 	}
967 
968 	/* log the message to the particular outputs */
969 	if (!Initialized) {
970 		f = &consfile;
971 		/*
972 		 * Open in non-blocking mode to avoid hangs during open
973 		 * and close(waiting for the port to drain).
974 		 */
975 		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
976 
977 		if (f->f_file >= 0) {
978 			(void)strlcpy(f->f_lasttime, timestamp,
979 				sizeof(f->f_lasttime));
980 			fprintlog(f, flags, msg);
981 			(void)close(f->f_file);
982 		}
983 		(void)sigsetmask(omask);
984 		return;
985 	}
986 	for (f = Files; f; f = f->f_next) {
987 		/* skip messages that are incorrect priority */
988 		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
989 		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
990 		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
991 		     )
992 		    || f->f_pmask[fac] == INTERNAL_NOPRI)
993 			continue;
994 
995 		/* skip messages with the incorrect hostname */
996 		if (skip_message(from, f->f_host, 0))
997 			continue;
998 
999 		/* skip messages with the incorrect program name */
1000 		if (skip_message(prog, f->f_program, 1))
1001 			continue;
1002 
1003 		/* skip message to console if it has already been printed */
1004 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1005 			continue;
1006 
1007 		/* don't output marks to recently written files */
1008 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1009 			continue;
1010 
1011 		/*
1012 		 * suppress duplicate lines to this file
1013 		 */
1014 		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1015 		    (flags & MARK) == 0 && msglen == f->f_prevlen &&
1016 		    f->f_prevline && !strcmp(msg, f->f_prevline) &&
1017 		    !strcasecmp(from, f->f_prevhost)) {
1018 			(void)strlcpy(f->f_lasttime, timestamp,
1019 				sizeof(f->f_lasttime));
1020 			f->f_prevcount++;
1021 			dprintf("msg repeated %d times, %ld sec of %d\n",
1022 			    f->f_prevcount, (long)(now - f->f_time),
1023 			    repeatinterval[f->f_repeatcount]);
1024 			/*
1025 			 * If domark would have logged this by now,
1026 			 * flush it now (so we don't hold isolated messages),
1027 			 * but back off so we'll flush less often
1028 			 * in the future.
1029 			 */
1030 			if (now > REPEATTIME(f)) {
1031 				fprintlog(f, flags, (char *)NULL);
1032 				BACKOFF(f);
1033 			}
1034 		} else {
1035 			/* new line, save it */
1036 			if (f->f_prevcount)
1037 				fprintlog(f, 0, (char *)NULL);
1038 			f->f_repeatcount = 0;
1039 			f->f_prevpri = pri;
1040 			(void)strlcpy(f->f_lasttime, timestamp,
1041 				sizeof(f->f_lasttime));
1042 			(void)strlcpy(f->f_prevhost, from,
1043 			    sizeof(f->f_prevhost));
1044 			if (msglen < MAXSVLINE) {
1045 				f->f_prevlen = msglen;
1046 				(void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1047 				fprintlog(f, flags, (char *)NULL);
1048 			} else {
1049 				f->f_prevline[0] = 0;
1050 				f->f_prevlen = 0;
1051 				fprintlog(f, flags, msg);
1052 			}
1053 		}
1054 	}
1055 	(void)sigsetmask(omask);
1056 }
1057 
1058 static void
1059 dofsync(void)
1060 {
1061 	struct filed *f;
1062 
1063 	for (f = Files; f; f = f->f_next) {
1064 		if ((f->f_type == F_FILE) &&
1065 		    (f->f_flags & FFLAG_NEEDSYNC)) {
1066 			f->f_flags &= ~FFLAG_NEEDSYNC;
1067 			(void)fsync(f->f_file);
1068 		}
1069 	}
1070 }
1071 
1072 #define IOV_SIZE 7
1073 static void
1074 fprintlog(struct filed *f, int flags, const char *msg)
1075 {
1076 	struct iovec iov[IOV_SIZE];
1077 	struct iovec *v;
1078 	struct addrinfo *r;
1079 	int i, l, lsent = 0;
1080 	char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1081 	char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1082 	const char *msgret;
1083 
1084 	v = iov;
1085 	if (f->f_type == F_WALL) {
1086 		v->iov_base = greetings;
1087 		/* The time displayed is not synchornized with the other log
1088 		 * destinations (like messages).  Following fragment was using
1089 		 * ctime(&now), which was updating the time every 30 sec.
1090 		 * With f_lasttime, time is synchronized correctly.
1091 		 */
1092 		v->iov_len = snprintf(greetings, sizeof greetings,
1093 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1094 		    f->f_prevhost, f->f_lasttime);
1095 		if (v->iov_len > 0)
1096 			v++;
1097 		v->iov_base = nul;
1098 		v->iov_len = 0;
1099 		v++;
1100 	} else {
1101 		v->iov_base = f->f_lasttime;
1102 		v->iov_len = strlen(f->f_lasttime);
1103 		v++;
1104 		v->iov_base = space;
1105 		v->iov_len = 1;
1106 		v++;
1107 	}
1108 
1109 	if (LogFacPri) {
1110 	  	static char fp_buf[30];	/* Hollow laugh */
1111 		int fac = f->f_prevpri & LOG_FACMASK;
1112 		int pri = LOG_PRI(f->f_prevpri);
1113 		const char *f_s = NULL;
1114 		char f_n[5];	/* Hollow laugh */
1115 		const char *p_s = NULL;
1116 		char p_n[5];	/* Hollow laugh */
1117 
1118 		if (LogFacPri > 1) {
1119 		  CODE *c;
1120 
1121 		  for (c = facilitynames; c->c_name; c++) {
1122 		    if (c->c_val == fac) {
1123 		      f_s = c->c_name;
1124 		      break;
1125 		    }
1126 		  }
1127 		  for (c = prioritynames; c->c_name; c++) {
1128 		    if (c->c_val == pri) {
1129 		      p_s = c->c_name;
1130 		      break;
1131 		    }
1132 		  }
1133 		}
1134 		if (!f_s) {
1135 		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1136 		  f_s = f_n;
1137 		}
1138 		if (!p_s) {
1139 		  snprintf(p_n, sizeof p_n, "%d", pri);
1140 		  p_s = p_n;
1141 		}
1142 		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1143 		v->iov_base = fp_buf;
1144 		v->iov_len = strlen(fp_buf);
1145 	} else {
1146 		v->iov_base = nul;
1147 		v->iov_len = 0;
1148 	}
1149 	v++;
1150 
1151 	v->iov_base = f->f_prevhost;
1152 	v->iov_len = strlen(v->iov_base);
1153 	v++;
1154 	v->iov_base = space;
1155 	v->iov_len = 1;
1156 	v++;
1157 
1158 	if (msg) {
1159 		wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1160 		if (wmsg == NULL) {
1161 			logerror("strdup");
1162 			exit(1);
1163 		}
1164 		v->iov_base = wmsg;
1165 		v->iov_len = strlen(msg);
1166 	} else if (f->f_prevcount > 1) {
1167 		v->iov_base = repbuf;
1168 		v->iov_len = snprintf(repbuf, sizeof repbuf,
1169 		    "last message repeated %d times", f->f_prevcount);
1170 	} else if (f->f_prevline) {
1171 		v->iov_base = f->f_prevline;
1172 		v->iov_len = f->f_prevlen;
1173 	} else {
1174 		return;
1175 	}
1176 	v++;
1177 
1178 	dprintf("Logging to %s", TypeNames[f->f_type]);
1179 	f->f_time = now;
1180 
1181 	switch (f->f_type) {
1182 		int port;
1183 	case F_UNUSED:
1184 		dprintf("\n");
1185 		break;
1186 
1187 	case F_FORW:
1188 		port = (int)ntohs(((struct sockaddr_in *)
1189 			    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1190 		if (port != 514) {
1191 			dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1192 		} else {
1193 			dprintf(" %s\n", f->f_un.f_forw.f_hname);
1194 		}
1195 		/* check for local vs remote messages */
1196 		if (strcasecmp(f->f_prevhost, LocalHostName))
1197 			l = snprintf(line, sizeof line - 1,
1198 			    "<%d>%.15s Forwarded from %s: %s",
1199 			    f->f_prevpri, (char *)iov[0].iov_base,
1200 			    f->f_prevhost, (char *)iov[5].iov_base);
1201 		else
1202 			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1203 			     f->f_prevpri, (char *)iov[0].iov_base,
1204 			    (char *)iov[5].iov_base);
1205 		if (l < 0)
1206 			l = 0;
1207 		else if (l > MAXLINE)
1208 			l = MAXLINE;
1209 
1210 		if (finet) {
1211 			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1212 				for (i = 0; i < *finet; i++) {
1213 #if 0
1214 					/*
1215 					 * should we check AF first, or just
1216 					 * trial and error? FWD
1217 					 */
1218 					if (r->ai_family ==
1219 					    address_family_of(finet[i+1]))
1220 #endif
1221 					lsent = sendto(finet[i+1], line, l, 0,
1222 					    r->ai_addr, r->ai_addrlen);
1223 					if (lsent == l)
1224 						break;
1225 				}
1226 				if (lsent == l && !send_to_all)
1227 					break;
1228 			}
1229 			dprintf("lsent/l: %d/%d\n", lsent, l);
1230 			if (lsent != l) {
1231 				int e = errno;
1232 				logerror("sendto");
1233 				errno = e;
1234 				switch (errno) {
1235 				case ENOBUFS:
1236 				case ENETDOWN:
1237 				case EHOSTUNREACH:
1238 				case EHOSTDOWN:
1239 					break;
1240 				/* case EBADF: */
1241 				/* case EACCES: */
1242 				/* case ENOTSOCK: */
1243 				/* case EFAULT: */
1244 				/* case EMSGSIZE: */
1245 				/* case EAGAIN: */
1246 				/* case ENOBUFS: */
1247 				/* case ECONNREFUSED: */
1248 				default:
1249 					dprintf("removing entry\n");
1250 					f->f_type = F_UNUSED;
1251 					break;
1252 				}
1253 			}
1254 		}
1255 		break;
1256 
1257 	case F_FILE:
1258 		dprintf(" %s\n", f->f_un.f_fname);
1259 		v->iov_base = lf;
1260 		v->iov_len = 1;
1261 		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1262 			/*
1263 			 * If writev(2) fails for potentially transient errors
1264 			 * like the filesystem being full, ignore it.
1265 			 * Otherwise remove this logfile from the list.
1266 			 */
1267 			if (errno != ENOSPC) {
1268 				int e = errno;
1269 				(void)close(f->f_file);
1270 				f->f_type = F_UNUSED;
1271 				errno = e;
1272 				logerror(f->f_un.f_fname);
1273 			}
1274 		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1275 			f->f_flags |= FFLAG_NEEDSYNC;
1276 			needdofsync = 1;
1277 		}
1278 		break;
1279 
1280 	case F_PIPE:
1281 		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1282 		v->iov_base = lf;
1283 		v->iov_len = 1;
1284 		if (f->f_un.f_pipe.f_pid == 0) {
1285 			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1286 						&f->f_un.f_pipe.f_pid)) < 0) {
1287 				f->f_type = F_UNUSED;
1288 				logerror(f->f_un.f_pipe.f_pname);
1289 				break;
1290 			}
1291 		}
1292 		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1293 			int e = errno;
1294 			(void)close(f->f_file);
1295 			if (f->f_un.f_pipe.f_pid > 0)
1296 				deadq_enter(f->f_un.f_pipe.f_pid,
1297 					    f->f_un.f_pipe.f_pname);
1298 			f->f_un.f_pipe.f_pid = 0;
1299 			errno = e;
1300 			logerror(f->f_un.f_pipe.f_pname);
1301 		}
1302 		break;
1303 
1304 	case F_CONSOLE:
1305 		if (flags & IGN_CONS) {
1306 			dprintf(" (ignored)\n");
1307 			break;
1308 		}
1309 		/* FALLTHROUGH */
1310 
1311 	case F_TTY:
1312 		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1313 		v->iov_base = crlf;
1314 		v->iov_len = 2;
1315 
1316 		errno = 0;	/* ttymsg() only sometimes returns an errno */
1317 		if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1318 			f->f_type = F_UNUSED;
1319 			logerror(msgret);
1320 		}
1321 		break;
1322 
1323 	case F_USERS:
1324 	case F_WALL:
1325 		dprintf("\n");
1326 		v->iov_base = crlf;
1327 		v->iov_len = 2;
1328 		wallmsg(f, iov, IOV_SIZE);
1329 		break;
1330 	}
1331 	f->f_prevcount = 0;
1332 	free(wmsg);
1333 }
1334 
1335 /*
1336  *  WALLMSG -- Write a message to the world at large
1337  *
1338  *	Write the specified message to either the entire
1339  *	world, or a list of approved users.
1340  */
1341 static void
1342 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1343 {
1344 	static int reenter;			/* avoid calling ourselves */
1345 	struct utmpx *ut;
1346 	int i;
1347 	const char *p;
1348 
1349 	if (reenter++)
1350 		return;
1351 	setutxent();
1352 	/* NOSTRICT */
1353 	while ((ut = getutxent()) != NULL) {
1354 		if (ut->ut_type != USER_PROCESS)
1355 			continue;
1356 		if (f->f_type == F_WALL) {
1357 			if ((p = ttymsg(iov, iovlen, ut->ut_line,
1358 			    TTYMSGTIME)) != NULL) {
1359 				errno = 0;	/* already in msg */
1360 				logerror(p);
1361 			}
1362 			continue;
1363 		}
1364 		/* should we send the message to this user? */
1365 		for (i = 0; i < MAXUNAMES; i++) {
1366 			if (!f->f_un.f_uname[i][0])
1367 				break;
1368 			if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1369 				if ((p = ttymsg(iov, iovlen, ut->ut_line,
1370 				    TTYMSGTIME)) != NULL) {
1371 					errno = 0;	/* already in msg */
1372 					logerror(p);
1373 				}
1374 				break;
1375 			}
1376 		}
1377 	}
1378 	endutxent();
1379 	reenter = 0;
1380 }
1381 
1382 static void
1383 reapchild(int signo __unused)
1384 {
1385 	int status;
1386 	pid_t pid;
1387 	struct filed *f;
1388 
1389 	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1390 		if (!Initialized)
1391 			/* Don't tell while we are initting. */
1392 			continue;
1393 
1394 		/* First, look if it's a process from the dead queue. */
1395 		if (deadq_remove(pid))
1396 			goto oncemore;
1397 
1398 		/* Now, look in list of active processes. */
1399 		for (f = Files; f; f = f->f_next)
1400 			if (f->f_type == F_PIPE &&
1401 			    f->f_un.f_pipe.f_pid == pid) {
1402 				(void)close(f->f_file);
1403 				f->f_un.f_pipe.f_pid = 0;
1404 				log_deadchild(pid, status,
1405 					      f->f_un.f_pipe.f_pname);
1406 				break;
1407 			}
1408 	  oncemore:
1409 		continue;
1410 	}
1411 }
1412 
1413 /*
1414  * Return a printable representation of a host address.
1415  */
1416 static const char *
1417 cvthname(struct sockaddr *f)
1418 {
1419 	int error, hl;
1420 	sigset_t omask, nmask;
1421 	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1422 
1423 	error = getnameinfo((struct sockaddr *)f,
1424 			    ((struct sockaddr *)f)->sa_len,
1425 			    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1426 	dprintf("cvthname(%s)\n", ip);
1427 
1428 	if (error) {
1429 		dprintf("Malformed from address %s\n", gai_strerror(error));
1430 		return ("???");
1431 	}
1432 	if (!resolve)
1433 		return (ip);
1434 
1435 	sigemptyset(&nmask);
1436 	sigaddset(&nmask, SIGHUP);
1437 	sigprocmask(SIG_BLOCK, &nmask, &omask);
1438 	error = getnameinfo((struct sockaddr *)f,
1439 			    ((struct sockaddr *)f)->sa_len,
1440 			    hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1441 	sigprocmask(SIG_SETMASK, &omask, NULL);
1442 	if (error) {
1443 		dprintf("Host name for your address (%s) unknown\n", ip);
1444 		return (ip);
1445 	}
1446 	hl = strlen(hname);
1447 	if (hl > 0 && hname[hl-1] == '.')
1448 		hname[--hl] = '\0';
1449 	trimdomain(hname, hl);
1450 	return (hname);
1451 }
1452 
1453 static void
1454 dodie(int signo)
1455 {
1456 
1457 	WantDie = signo;
1458 }
1459 
1460 static void
1461 domark(int signo __unused)
1462 {
1463 
1464 	MarkSet = 1;
1465 }
1466 
1467 /*
1468  * Print syslogd errors some place.
1469  */
1470 static void
1471 logerror(const char *type)
1472 {
1473 	char buf[512];
1474 	static int recursed = 0;
1475 
1476 	/* If there's an error while trying to log an error, give up. */
1477 	if (recursed)
1478 		return;
1479 	recursed++;
1480 	if (errno)
1481 		(void)snprintf(buf,
1482 		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1483 	else
1484 		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1485 	errno = 0;
1486 	dprintf("%s\n", buf);
1487 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1488 	recursed--;
1489 }
1490 
1491 static void
1492 die(int signo)
1493 {
1494 	struct filed *f;
1495 	struct funix *fx;
1496 	int was_initialized;
1497 	char buf[100];
1498 
1499 	was_initialized = Initialized;
1500 	Initialized = 0;	/* Don't log SIGCHLDs. */
1501 	for (f = Files; f != NULL; f = f->f_next) {
1502 		/* flush any pending output */
1503 		if (f->f_prevcount)
1504 			fprintlog(f, 0, (char *)NULL);
1505 		if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1506 			(void)close(f->f_file);
1507 			f->f_un.f_pipe.f_pid = 0;
1508 		}
1509 	}
1510 	Initialized = was_initialized;
1511 	if (signo) {
1512 		dprintf("syslogd: exiting on signal %d\n", signo);
1513 		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1514 		errno = 0;
1515 		logerror(buf);
1516 	}
1517 	STAILQ_FOREACH(fx, &funixes, next)
1518 		(void)unlink(fx->name);
1519 	pidfile_remove(pfh);
1520 
1521 	exit(1);
1522 }
1523 
1524 /*
1525  *  INIT -- Initialize syslogd from configuration table
1526  */
1527 static void
1528 init(int signo)
1529 {
1530 	int i;
1531 	FILE *cf;
1532 	struct filed *f, *next, **nextp;
1533 	char *p;
1534 	char cline[LINE_MAX];
1535  	char prog[NAME_MAX+1];
1536 	char host[MAXHOSTNAMELEN];
1537 	char oldLocalHostName[MAXHOSTNAMELEN];
1538 	char hostMsg[2*MAXHOSTNAMELEN+40];
1539 	char bootfileMsg[LINE_MAX];
1540 
1541 	dprintf("init\n");
1542 
1543 	/*
1544 	 * Load hostname (may have changed).
1545 	 */
1546 	if (signo != 0)
1547 		(void)strlcpy(oldLocalHostName, LocalHostName,
1548 		    sizeof(oldLocalHostName));
1549 	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1550 		err(EX_OSERR, "gethostname() failed");
1551 	if ((p = strchr(LocalHostName, '.')) != NULL) {
1552 		*p++ = '\0';
1553 		LocalDomain = p;
1554 	} else {
1555 		LocalDomain = "";
1556 	}
1557 
1558 	/*
1559 	 *  Close all open log files.
1560 	 */
1561 	Initialized = 0;
1562 	for (f = Files; f != NULL; f = next) {
1563 		/* flush any pending output */
1564 		if (f->f_prevcount)
1565 			fprintlog(f, 0, (char *)NULL);
1566 
1567 		switch (f->f_type) {
1568 		case F_FILE:
1569 		case F_FORW:
1570 		case F_CONSOLE:
1571 		case F_TTY:
1572 			(void)close(f->f_file);
1573 			break;
1574 		case F_PIPE:
1575 			if (f->f_un.f_pipe.f_pid > 0) {
1576 				(void)close(f->f_file);
1577 				deadq_enter(f->f_un.f_pipe.f_pid,
1578 					    f->f_un.f_pipe.f_pname);
1579 			}
1580 			f->f_un.f_pipe.f_pid = 0;
1581 			break;
1582 		}
1583 		next = f->f_next;
1584 		if (f->f_program) free(f->f_program);
1585 		if (f->f_host) free(f->f_host);
1586 		free((char *)f);
1587 	}
1588 	Files = NULL;
1589 	nextp = &Files;
1590 
1591 	/* open the configuration file */
1592 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1593 		dprintf("cannot open %s\n", ConfFile);
1594 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1595 		if (*nextp == NULL) {
1596 			logerror("calloc");
1597 			exit(1);
1598 		}
1599 		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1600 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1601 		if ((*nextp)->f_next == NULL) {
1602 			logerror("calloc");
1603 			exit(1);
1604 		}
1605 		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1606 		Initialized = 1;
1607 		return;
1608 	}
1609 
1610 	/*
1611 	 *  Foreach line in the conf table, open that file.
1612 	 */
1613 	f = NULL;
1614 	(void)strlcpy(host, "*", sizeof(host));
1615 	(void)strlcpy(prog, "*", sizeof(prog));
1616 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1617 		/*
1618 		 * check for end-of-section, comments, strip off trailing
1619 		 * spaces and newline character. #!prog is treated specially:
1620 		 * following lines apply only to that program.
1621 		 */
1622 		for (p = cline; isspace(*p); ++p)
1623 			continue;
1624 		if (*p == 0)
1625 			continue;
1626 		if (*p == '#') {
1627 			p++;
1628 			if (*p != '!' && *p != '+' && *p != '-')
1629 				continue;
1630 		}
1631 		if (*p == '+' || *p == '-') {
1632 			host[0] = *p++;
1633 			while (isspace(*p))
1634 				p++;
1635 			if ((!*p) || (*p == '*')) {
1636 				(void)strlcpy(host, "*", sizeof(host));
1637 				continue;
1638 			}
1639 			if (*p == '@')
1640 				p = LocalHostName;
1641 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1642 				if (!isalnum(*p) && *p != '.' && *p != '-'
1643 				    && *p != ',' && *p != ':' && *p != '%')
1644 					break;
1645 				host[i] = *p++;
1646 			}
1647 			host[i] = '\0';
1648 			continue;
1649 		}
1650 		if (*p == '!') {
1651 			p++;
1652 			while (isspace(*p)) p++;
1653 			if ((!*p) || (*p == '*')) {
1654 				(void)strlcpy(prog, "*", sizeof(prog));
1655 				continue;
1656 			}
1657 			for (i = 0; i < NAME_MAX; i++) {
1658 				if (!isprint(p[i]) || isspace(p[i]))
1659 					break;
1660 				prog[i] = p[i];
1661 			}
1662 			prog[i] = 0;
1663 			continue;
1664 		}
1665 		for (p = cline + 1; *p != '\0'; p++) {
1666 			if (*p != '#')
1667 				continue;
1668 			if (*(p - 1) == '\\') {
1669 				strcpy(p - 1, p);
1670 				p--;
1671 				continue;
1672 			}
1673 			*p = '\0';
1674 			break;
1675 		}
1676 		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1677 			cline[i] = '\0';
1678 		f = (struct filed *)calloc(1, sizeof(*f));
1679 		if (f == NULL) {
1680 			logerror("calloc");
1681 			exit(1);
1682 		}
1683 		*nextp = f;
1684 		nextp = &f->f_next;
1685 		cfline(cline, f, prog, host);
1686 	}
1687 
1688 	/* close the configuration file */
1689 	(void)fclose(cf);
1690 
1691 	Initialized = 1;
1692 
1693 	if (Debug) {
1694 		int port;
1695 		for (f = Files; f; f = f->f_next) {
1696 			for (i = 0; i <= LOG_NFACILITIES; i++)
1697 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1698 					printf("X ");
1699 				else
1700 					printf("%d ", f->f_pmask[i]);
1701 			printf("%s: ", TypeNames[f->f_type]);
1702 			switch (f->f_type) {
1703 			case F_FILE:
1704 				printf("%s", f->f_un.f_fname);
1705 				break;
1706 
1707 			case F_CONSOLE:
1708 			case F_TTY:
1709 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1710 				break;
1711 
1712 			case F_FORW:
1713 				port = (int)ntohs(((struct sockaddr_in *)
1714 				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1715 				if (port != 514) {
1716 					printf("%s:%d",
1717 						f->f_un.f_forw.f_hname, port);
1718 				} else {
1719 					printf("%s", f->f_un.f_forw.f_hname);
1720 				}
1721 				break;
1722 
1723 			case F_PIPE:
1724 				printf("%s", f->f_un.f_pipe.f_pname);
1725 				break;
1726 
1727 			case F_USERS:
1728 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1729 					printf("%s, ", f->f_un.f_uname[i]);
1730 				break;
1731 			}
1732 			if (f->f_program)
1733 				printf(" (%s)", f->f_program);
1734 			printf("\n");
1735 		}
1736 	}
1737 
1738 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1739 	dprintf("syslogd: restarted\n");
1740 	/*
1741 	 * Log a change in hostname, but only on a restart.
1742 	 */
1743 	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1744 		(void)snprintf(hostMsg, sizeof(hostMsg),
1745 		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1746 		    oldLocalHostName, LocalHostName);
1747 		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1748 		dprintf("%s\n", hostMsg);
1749 	}
1750 	/*
1751 	 * Log the kernel boot file if we aren't going to use it as
1752 	 * the prefix, and if this is *not* a restart.
1753 	 */
1754 	if (signo == 0 && !use_bootfile) {
1755 		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1756 		    "syslogd: kernel boot file is %s", bootfile);
1757 		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1758 		dprintf("%s\n", bootfileMsg);
1759 	}
1760 }
1761 
1762 /*
1763  * Crack a configuration file line
1764  */
1765 static void
1766 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1767 {
1768 	struct addrinfo hints, *res;
1769 	int error, i, pri, syncfile;
1770 	const char *p, *q;
1771 	char *bp;
1772 	char buf[MAXLINE], ebuf[100];
1773 
1774 	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1775 
1776 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1777 
1778 	/* clear out file entry */
1779 	memset(f, 0, sizeof(*f));
1780 	for (i = 0; i <= LOG_NFACILITIES; i++)
1781 		f->f_pmask[i] = INTERNAL_NOPRI;
1782 
1783 	/* save hostname if any */
1784 	if (host && *host == '*')
1785 		host = NULL;
1786 	if (host) {
1787 		int hl;
1788 
1789 		f->f_host = strdup(host);
1790 		if (f->f_host == NULL) {
1791 			logerror("strdup");
1792 			exit(1);
1793 		}
1794 		hl = strlen(f->f_host);
1795 		if (hl > 0 && f->f_host[hl-1] == '.')
1796 			f->f_host[--hl] = '\0';
1797 		trimdomain(f->f_host, hl);
1798 	}
1799 
1800 	/* save program name if any */
1801 	if (prog && *prog == '*')
1802 		prog = NULL;
1803 	if (prog) {
1804 		f->f_program = strdup(prog);
1805 		if (f->f_program == NULL) {
1806 			logerror("strdup");
1807 			exit(1);
1808 		}
1809 	}
1810 
1811 	/* scan through the list of selectors */
1812 	for (p = line; *p && *p != '\t' && *p != ' ';) {
1813 		int pri_done;
1814 		int pri_cmp;
1815 		int pri_invert;
1816 
1817 		/* find the end of this facility name list */
1818 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1819 			continue;
1820 
1821 		/* get the priority comparison */
1822 		pri_cmp = 0;
1823 		pri_done = 0;
1824 		pri_invert = 0;
1825 		if (*q == '!') {
1826 			pri_invert = 1;
1827 			q++;
1828 		}
1829 		while (!pri_done) {
1830 			switch (*q) {
1831 			case '<':
1832 				pri_cmp |= PRI_LT;
1833 				q++;
1834 				break;
1835 			case '=':
1836 				pri_cmp |= PRI_EQ;
1837 				q++;
1838 				break;
1839 			case '>':
1840 				pri_cmp |= PRI_GT;
1841 				q++;
1842 				break;
1843 			default:
1844 				pri_done++;
1845 				break;
1846 			}
1847 		}
1848 
1849 		/* collect priority name */
1850 		for (bp = buf; *q && !strchr("\t,; ", *q); )
1851 			*bp++ = *q++;
1852 		*bp = '\0';
1853 
1854 		/* skip cruft */
1855 		while (strchr(",;", *q))
1856 			q++;
1857 
1858 		/* decode priority name */
1859 		if (*buf == '*') {
1860 			pri = LOG_PRIMASK;
1861 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1862 		} else {
1863 			/* Ignore trailing spaces. */
1864 			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1865 				buf[i] = '\0';
1866 
1867 			pri = decode(buf, prioritynames);
1868 			if (pri < 0) {
1869 				(void)snprintf(ebuf, sizeof ebuf,
1870 				    "unknown priority name \"%s\"", buf);
1871 				logerror(ebuf);
1872 				return;
1873 			}
1874 		}
1875 		if (!pri_cmp)
1876 			pri_cmp = (UniquePriority)
1877 				  ? (PRI_EQ)
1878 				  : (PRI_EQ | PRI_GT)
1879 				  ;
1880 		if (pri_invert)
1881 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1882 
1883 		/* scan facilities */
1884 		while (*p && !strchr("\t.; ", *p)) {
1885 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1886 				*bp++ = *p++;
1887 			*bp = '\0';
1888 
1889 			if (*buf == '*') {
1890 				for (i = 0; i < LOG_NFACILITIES; i++) {
1891 					f->f_pmask[i] = pri;
1892 					f->f_pcmp[i] = pri_cmp;
1893 				}
1894 			} else {
1895 				i = decode(buf, facilitynames);
1896 				if (i < 0) {
1897 					(void)snprintf(ebuf, sizeof ebuf,
1898 					    "unknown facility name \"%s\"",
1899 					    buf);
1900 					logerror(ebuf);
1901 					return;
1902 				}
1903 				f->f_pmask[i >> 3] = pri;
1904 				f->f_pcmp[i >> 3] = pri_cmp;
1905 			}
1906 			while (*p == ',' || *p == ' ')
1907 				p++;
1908 		}
1909 
1910 		p = q;
1911 	}
1912 
1913 	/* skip to action part */
1914 	while (*p == '\t' || *p == ' ')
1915 		p++;
1916 
1917 	if (*p == '-') {
1918 		syncfile = 0;
1919 		p++;
1920 	} else
1921 		syncfile = 1;
1922 
1923 	switch (*p) {
1924 	case '@':
1925 		{
1926 			char *tp;
1927 			/*
1928 			 * scan forward to see if there is a port defined.
1929 			 * so we can't use strlcpy..
1930 			 */
1931 			i = sizeof(f->f_un.f_forw.f_hname);
1932 			tp = f->f_un.f_forw.f_hname;
1933 			p++;
1934 
1935 			while (*p && (*p != ':') && (i-- > 0)) {
1936 				*tp++ = *p++;
1937 			}
1938 			*tp = '\0';
1939 		}
1940 		/* See if we copied a domain and have a port */
1941 		if (*p == ':')
1942 			p++;
1943 		else
1944 			p = NULL;
1945 
1946 		memset(&hints, 0, sizeof(hints));
1947 		hints.ai_family = family;
1948 		hints.ai_socktype = SOCK_DGRAM;
1949 		error = getaddrinfo(f->f_un.f_forw.f_hname,
1950 				p ? p : "syslog", &hints, &res);
1951 		if (error) {
1952 			logerror(gai_strerror(error));
1953 			break;
1954 		}
1955 		f->f_un.f_forw.f_addr = res;
1956 		f->f_type = F_FORW;
1957 		break;
1958 
1959 	case '/':
1960 		if ((f->f_file = open(p, logflags, 0600)) < 0) {
1961 			f->f_type = F_UNUSED;
1962 			logerror(p);
1963 			break;
1964 		}
1965 		if (syncfile)
1966 			f->f_flags |= FFLAG_SYNC;
1967 		if (isatty(f->f_file)) {
1968 			if (strcmp(p, ctty) == 0)
1969 				f->f_type = F_CONSOLE;
1970 			else
1971 				f->f_type = F_TTY;
1972 			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1973 			    sizeof(f->f_un.f_fname));
1974 		} else {
1975 			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1976 			f->f_type = F_FILE;
1977 		}
1978 		break;
1979 
1980 	case '|':
1981 		f->f_un.f_pipe.f_pid = 0;
1982 		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1983 		    sizeof(f->f_un.f_pipe.f_pname));
1984 		f->f_type = F_PIPE;
1985 		break;
1986 
1987 	case '*':
1988 		f->f_type = F_WALL;
1989 		break;
1990 
1991 	default:
1992 		for (i = 0; i < MAXUNAMES && *p; i++) {
1993 			for (q = p; *q && *q != ','; )
1994 				q++;
1995 			(void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
1996 			if ((q - p) >= MAXLOGNAME)
1997 				f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
1998 			else
1999 				f->f_un.f_uname[i][q - p] = '\0';
2000 			while (*q == ',' || *q == ' ')
2001 				q++;
2002 			p = q;
2003 		}
2004 		f->f_type = F_USERS;
2005 		break;
2006 	}
2007 }
2008 
2009 
2010 /*
2011  *  Decode a symbolic name to a numeric value
2012  */
2013 static int
2014 decode(const char *name, CODE *codetab)
2015 {
2016 	CODE *c;
2017 	char *p, buf[40];
2018 
2019 	if (isdigit(*name))
2020 		return (atoi(name));
2021 
2022 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2023 		if (isupper(*name))
2024 			*p = tolower(*name);
2025 		else
2026 			*p = *name;
2027 	}
2028 	*p = '\0';
2029 	for (c = codetab; c->c_name; c++)
2030 		if (!strcmp(buf, c->c_name))
2031 			return (c->c_val);
2032 
2033 	return (-1);
2034 }
2035 
2036 static void
2037 markit(void)
2038 {
2039 	struct filed *f;
2040 	dq_t q, next;
2041 
2042 	now = time((time_t *)NULL);
2043 	MarkSeq += TIMERINTVL;
2044 	if (MarkSeq >= MarkInterval) {
2045 		logmsg(LOG_INFO, "-- MARK --",
2046 		    LocalHostName, ADDDATE|MARK);
2047 		MarkSeq = 0;
2048 	}
2049 
2050 	for (f = Files; f; f = f->f_next) {
2051 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2052 			dprintf("flush %s: repeated %d times, %d sec.\n",
2053 			    TypeNames[f->f_type], f->f_prevcount,
2054 			    repeatinterval[f->f_repeatcount]);
2055 			fprintlog(f, 0, (char *)NULL);
2056 			BACKOFF(f);
2057 		}
2058 	}
2059 
2060 	/* Walk the dead queue, and see if we should signal somebody. */
2061 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2062 		next = TAILQ_NEXT(q, dq_entries);
2063 
2064 		switch (q->dq_timeout) {
2065 		case 0:
2066 			/* Already signalled once, try harder now. */
2067 			if (kill(q->dq_pid, SIGKILL) != 0)
2068 				(void)deadq_remove(q->dq_pid);
2069 			break;
2070 
2071 		case 1:
2072 			/*
2073 			 * Timed out on dead queue, send terminate
2074 			 * signal.  Note that we leave the removal
2075 			 * from the dead queue to reapchild(), which
2076 			 * will also log the event (unless the process
2077 			 * didn't even really exist, in case we simply
2078 			 * drop it from the dead queue).
2079 			 */
2080 			if (kill(q->dq_pid, SIGTERM) != 0)
2081 				(void)deadq_remove(q->dq_pid);
2082 			/* FALLTHROUGH */
2083 
2084 		default:
2085 			q->dq_timeout--;
2086 		}
2087 	}
2088 	MarkSet = 0;
2089 	(void)alarm(TIMERINTVL);
2090 }
2091 
2092 /*
2093  * fork off and become a daemon, but wait for the child to come online
2094  * before returing to the parent, or we get disk thrashing at boot etc.
2095  * Set a timer so we don't hang forever if it wedges.
2096  */
2097 static int
2098 waitdaemon(int nochdir, int noclose, int maxwait)
2099 {
2100 	int fd;
2101 	int status;
2102 	pid_t pid, childpid;
2103 
2104 	switch (childpid = fork()) {
2105 	case -1:
2106 		return (-1);
2107 	case 0:
2108 		break;
2109 	default:
2110 		signal(SIGALRM, timedout);
2111 		alarm(maxwait);
2112 		while ((pid = wait3(&status, 0, NULL)) != -1) {
2113 			if (WIFEXITED(status))
2114 				errx(1, "child pid %d exited with return code %d",
2115 					pid, WEXITSTATUS(status));
2116 			if (WIFSIGNALED(status))
2117 				errx(1, "child pid %d exited on signal %d%s",
2118 					pid, WTERMSIG(status),
2119 					WCOREDUMP(status) ? " (core dumped)" :
2120 					"");
2121 			if (pid == childpid)	/* it's gone... */
2122 				break;
2123 		}
2124 		exit(0);
2125 	}
2126 
2127 	if (setsid() == -1)
2128 		return (-1);
2129 
2130 	if (!nochdir)
2131 		(void)chdir("/");
2132 
2133 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2134 		(void)dup2(fd, STDIN_FILENO);
2135 		(void)dup2(fd, STDOUT_FILENO);
2136 		(void)dup2(fd, STDERR_FILENO);
2137 		if (fd > 2)
2138 			(void)close (fd);
2139 	}
2140 	return (getppid());
2141 }
2142 
2143 /*
2144  * We get a SIGALRM from the child when it's running and finished doing it's
2145  * fsync()'s or O_SYNC writes for all the boot messages.
2146  *
2147  * We also get a signal from the kernel if the timer expires, so check to
2148  * see what happened.
2149  */
2150 static void
2151 timedout(int sig __unused)
2152 {
2153 	int left;
2154 	left = alarm(0);
2155 	signal(SIGALRM, SIG_DFL);
2156 	if (left == 0)
2157 		errx(1, "timed out waiting for child");
2158 	else
2159 		_exit(0);
2160 }
2161 
2162 /*
2163  * Add `s' to the list of allowable peer addresses to accept messages
2164  * from.
2165  *
2166  * `s' is a string in the form:
2167  *
2168  *    [*]domainname[:{servicename|portnumber|*}]
2169  *
2170  * or
2171  *
2172  *    netaddr/maskbits[:{servicename|portnumber|*}]
2173  *
2174  * Returns -1 on error, 0 if the argument was valid.
2175  */
2176 static int
2177 allowaddr(char *s)
2178 {
2179 	char *cp1, *cp2;
2180 	struct allowedpeer ap;
2181 	struct servent *se;
2182 	int masklen = -1;
2183 	struct addrinfo hints, *res;
2184 	struct in_addr *addrp, *maskp;
2185 #ifdef INET6
2186 	int i;
2187 	u_int32_t *addr6p, *mask6p;
2188 #endif
2189 	char ip[NI_MAXHOST];
2190 
2191 #ifdef INET6
2192 	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2193 #endif
2194 		cp1 = s;
2195 	if ((cp1 = strrchr(cp1, ':'))) {
2196 		/* service/port provided */
2197 		*cp1++ = '\0';
2198 		if (strlen(cp1) == 1 && *cp1 == '*')
2199 			/* any port allowed */
2200 			ap.port = 0;
2201 		else if ((se = getservbyname(cp1, "udp"))) {
2202 			ap.port = ntohs(se->s_port);
2203 		} else {
2204 			ap.port = strtol(cp1, &cp2, 0);
2205 			if (*cp2 != '\0')
2206 				return (-1); /* port not numeric */
2207 		}
2208 	} else {
2209 		if ((se = getservbyname("syslog", "udp")))
2210 			ap.port = ntohs(se->s_port);
2211 		else
2212 			/* sanity, should not happen */
2213 			ap.port = 514;
2214 	}
2215 
2216 	if ((cp1 = strchr(s, '/')) != NULL &&
2217 	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2218 		*cp1 = '\0';
2219 		if ((masklen = atoi(cp1 + 1)) < 0)
2220 			return (-1);
2221 	}
2222 #ifdef INET6
2223 	if (*s == '[') {
2224 		cp2 = s + strlen(s) - 1;
2225 		if (*cp2 == ']') {
2226 			++s;
2227 			*cp2 = '\0';
2228 		} else {
2229 			cp2 = NULL;
2230 		}
2231 	} else {
2232 		cp2 = NULL;
2233 	}
2234 #endif
2235 	memset(&hints, 0, sizeof(hints));
2236 	hints.ai_family = PF_UNSPEC;
2237 	hints.ai_socktype = SOCK_DGRAM;
2238 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2239 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2240 		ap.isnumeric = 1;
2241 		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2242 		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2243 		ap.a_mask.ss_family = res->ai_family;
2244 		if (res->ai_family == AF_INET) {
2245 			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2246 			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2247 			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2248 			if (masklen < 0) {
2249 				/* use default netmask */
2250 				if (IN_CLASSA(ntohl(addrp->s_addr)))
2251 					maskp->s_addr = htonl(IN_CLASSA_NET);
2252 				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2253 					maskp->s_addr = htonl(IN_CLASSB_NET);
2254 				else
2255 					maskp->s_addr = htonl(IN_CLASSC_NET);
2256 			} else if (masklen <= 32) {
2257 				/* convert masklen to netmask */
2258 				if (masklen == 0)
2259 					maskp->s_addr = 0;
2260 				else
2261 					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2262 			} else {
2263 				freeaddrinfo(res);
2264 				return (-1);
2265 			}
2266 			/* Lose any host bits in the network number. */
2267 			addrp->s_addr &= maskp->s_addr;
2268 		}
2269 #ifdef INET6
2270 		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2271 			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2272 			if (masklen < 0)
2273 				masklen = 128;
2274 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2275 			/* convert masklen to netmask */
2276 			while (masklen > 0) {
2277 				if (masklen < 32) {
2278 					*mask6p = htonl(~(0xffffffff >> masklen));
2279 					break;
2280 				}
2281 				*mask6p++ = 0xffffffff;
2282 				masklen -= 32;
2283 			}
2284 			/* Lose any host bits in the network number. */
2285 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2286 			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2287 			for (i = 0; i < 4; i++)
2288 				addr6p[i] &= mask6p[i];
2289 		}
2290 #endif
2291 		else {
2292 			freeaddrinfo(res);
2293 			return (-1);
2294 		}
2295 		freeaddrinfo(res);
2296 	} else {
2297 		/* arg `s' is domain name */
2298 		ap.isnumeric = 0;
2299 		ap.a_name = s;
2300 		if (cp1)
2301 			*cp1 = '/';
2302 #ifdef INET6
2303 		if (cp2) {
2304 			*cp2 = ']';
2305 			--s;
2306 		}
2307 #endif
2308 	}
2309 
2310 	if (Debug) {
2311 		printf("allowaddr: rule %d: ", NumAllowed);
2312 		if (ap.isnumeric) {
2313 			printf("numeric, ");
2314 			getnameinfo((struct sockaddr *)&ap.a_addr,
2315 				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2316 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2317 			printf("addr = %s, ", ip);
2318 			getnameinfo((struct sockaddr *)&ap.a_mask,
2319 				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2320 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2321 			printf("mask = %s; ", ip);
2322 		} else {
2323 			printf("domainname = %s; ", ap.a_name);
2324 		}
2325 		printf("port = %d\n", ap.port);
2326 	}
2327 
2328 	if ((AllowedPeers = realloc(AllowedPeers,
2329 				    ++NumAllowed * sizeof(struct allowedpeer)))
2330 	    == NULL) {
2331 		logerror("realloc");
2332 		exit(1);
2333 	}
2334 	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2335 	return (0);
2336 }
2337 
2338 /*
2339  * Validate that the remote peer has permission to log to us.
2340  */
2341 static int
2342 validate(struct sockaddr *sa, const char *hname)
2343 {
2344 	int i;
2345 	size_t l1, l2;
2346 	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2347 	struct allowedpeer *ap;
2348 	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2349 #ifdef INET6
2350 	int j, reject;
2351 	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2352 #endif
2353 	struct addrinfo hints, *res;
2354 	u_short sport;
2355 
2356 	if (NumAllowed == 0)
2357 		/* traditional behaviour, allow everything */
2358 		return (1);
2359 
2360 	(void)strlcpy(name, hname, sizeof(name));
2361 	memset(&hints, 0, sizeof(hints));
2362 	hints.ai_family = PF_UNSPEC;
2363 	hints.ai_socktype = SOCK_DGRAM;
2364 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2365 	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2366 		freeaddrinfo(res);
2367 	else if (strchr(name, '.') == NULL) {
2368 		strlcat(name, ".", sizeof name);
2369 		strlcat(name, LocalDomain, sizeof name);
2370 	}
2371 	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2372 			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2373 		return (0);	/* for safety, should not occur */
2374 	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2375 		ip, port, name);
2376 	sport = atoi(port);
2377 
2378 	/* now, walk down the list */
2379 	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2380 		if (ap->port != 0 && ap->port != sport) {
2381 			dprintf("rejected in rule %d due to port mismatch.\n", i);
2382 			continue;
2383 		}
2384 
2385 		if (ap->isnumeric) {
2386 			if (ap->a_addr.ss_family != sa->sa_family) {
2387 				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2388 				continue;
2389 			}
2390 			if (ap->a_addr.ss_family == AF_INET) {
2391 				sin4 = (struct sockaddr_in *)sa;
2392 				a4p = (struct sockaddr_in *)&ap->a_addr;
2393 				m4p = (struct sockaddr_in *)&ap->a_mask;
2394 				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2395 				    != a4p->sin_addr.s_addr) {
2396 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2397 					continue;
2398 				}
2399 			}
2400 #ifdef INET6
2401 			else if (ap->a_addr.ss_family == AF_INET6) {
2402 				sin6 = (struct sockaddr_in6 *)sa;
2403 				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2404 				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2405 				if (a6p->sin6_scope_id != 0 &&
2406 				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2407 					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2408 					continue;
2409 				}
2410 				reject = 0;
2411 				for (j = 0; j < 16; j += 4) {
2412 					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2413 					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2414 						++reject;
2415 						break;
2416 					}
2417 				}
2418 				if (reject) {
2419 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2420 					continue;
2421 				}
2422 			}
2423 #endif
2424 			else
2425 				continue;
2426 		} else {
2427 			cp = ap->a_name;
2428 			l1 = strlen(name);
2429 			if (*cp == '*') {
2430 				/* allow wildmatch */
2431 				cp++;
2432 				l2 = strlen(cp);
2433 				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2434 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2435 					continue;
2436 				}
2437 			} else {
2438 				/* exact match */
2439 				l2 = strlen(cp);
2440 				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2441 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2442 					continue;
2443 				}
2444 			}
2445 		}
2446 		dprintf("accepted in rule %d.\n", i);
2447 		return (1);	/* hooray! */
2448 	}
2449 	return (0);
2450 }
2451 
2452 /*
2453  * Fairly similar to popen(3), but returns an open descriptor, as
2454  * opposed to a FILE *.
2455  */
2456 static int
2457 p_open(const char *prog, pid_t *rpid)
2458 {
2459 	int pfd[2], nulldesc, i;
2460 	pid_t pid;
2461 	sigset_t omask, mask;
2462 	char *argv[4]; /* sh -c cmd NULL */
2463 	char errmsg[200];
2464 
2465 	if (pipe(pfd) == -1)
2466 		return (-1);
2467 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2468 		/* we are royally screwed anyway */
2469 		return (-1);
2470 
2471 	sigemptyset(&mask);
2472 	sigaddset(&mask, SIGALRM);
2473 	sigaddset(&mask, SIGHUP);
2474 	sigprocmask(SIG_BLOCK, &mask, &omask);
2475 	switch ((pid = fork())) {
2476 	case -1:
2477 		sigprocmask(SIG_SETMASK, &omask, 0);
2478 		close(nulldesc);
2479 		return (-1);
2480 
2481 	case 0:
2482 		argv[0] = strdup("sh");
2483 		argv[1] = strdup("-c");
2484 		argv[2] = strdup(prog);
2485 		argv[3] = NULL;
2486 		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2487 			logerror("strdup");
2488 			exit(1);
2489 		}
2490 
2491 		alarm(0);
2492 		(void)setsid();	/* Avoid catching SIGHUPs. */
2493 
2494 		/*
2495 		 * Throw away pending signals, and reset signal
2496 		 * behaviour to standard values.
2497 		 */
2498 		signal(SIGALRM, SIG_IGN);
2499 		signal(SIGHUP, SIG_IGN);
2500 		sigprocmask(SIG_SETMASK, &omask, 0);
2501 		signal(SIGPIPE, SIG_DFL);
2502 		signal(SIGQUIT, SIG_DFL);
2503 		signal(SIGALRM, SIG_DFL);
2504 		signal(SIGHUP, SIG_DFL);
2505 
2506 		dup2(pfd[0], STDIN_FILENO);
2507 		dup2(nulldesc, STDOUT_FILENO);
2508 		dup2(nulldesc, STDERR_FILENO);
2509 		for (i = getdtablesize(); i > 2; i--)
2510 			(void)close(i);
2511 
2512 		(void)execvp(_PATH_BSHELL, argv);
2513 		_exit(255);
2514 	}
2515 
2516 	sigprocmask(SIG_SETMASK, &omask, 0);
2517 	close(nulldesc);
2518 	close(pfd[0]);
2519 	/*
2520 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2521 	 * supposed to get an EWOULDBLOCK on writev(2), which is
2522 	 * caught by the logic above anyway, which will in turn close
2523 	 * the pipe, and fork a new logging subprocess if necessary.
2524 	 * The stale subprocess will be killed some time later unless
2525 	 * it terminated itself due to closing its input pipe (so we
2526 	 * get rid of really dead puppies).
2527 	 */
2528 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2529 		/* This is bad. */
2530 		(void)snprintf(errmsg, sizeof errmsg,
2531 			       "Warning: cannot change pipe to PID %d to "
2532 			       "non-blocking behaviour.",
2533 			       (int)pid);
2534 		logerror(errmsg);
2535 	}
2536 	*rpid = pid;
2537 	return (pfd[1]);
2538 }
2539 
2540 static void
2541 deadq_enter(pid_t pid, const char *name)
2542 {
2543 	dq_t p;
2544 	int status;
2545 
2546 	/*
2547 	 * Be paranoid, if we can't signal the process, don't enter it
2548 	 * into the dead queue (perhaps it's already dead).  If possible,
2549 	 * we try to fetch and log the child's status.
2550 	 */
2551 	if (kill(pid, 0) != 0) {
2552 		if (waitpid(pid, &status, WNOHANG) > 0)
2553 			log_deadchild(pid, status, name);
2554 		return;
2555 	}
2556 
2557 	p = malloc(sizeof(struct deadq_entry));
2558 	if (p == NULL) {
2559 		logerror("malloc");
2560 		exit(1);
2561 	}
2562 
2563 	p->dq_pid = pid;
2564 	p->dq_timeout = DQ_TIMO_INIT;
2565 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2566 }
2567 
2568 static int
2569 deadq_remove(pid_t pid)
2570 {
2571 	dq_t q;
2572 
2573 	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2574 		if (q->dq_pid == pid) {
2575 			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2576 				free(q);
2577 				return (1);
2578 		}
2579 	}
2580 
2581 	return (0);
2582 }
2583 
2584 static void
2585 log_deadchild(pid_t pid, int status, const char *name)
2586 {
2587 	int code;
2588 	char buf[256];
2589 	const char *reason;
2590 
2591 	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2592 	if (WIFSIGNALED(status)) {
2593 		reason = "due to signal";
2594 		code = WTERMSIG(status);
2595 	} else {
2596 		reason = "with status";
2597 		code = WEXITSTATUS(status);
2598 		if (code == 0)
2599 			return;
2600 	}
2601 	(void)snprintf(buf, sizeof buf,
2602 		       "Logging subprocess %d (%s) exited %s %d.",
2603 		       pid, name, reason, code);
2604 	logerror(buf);
2605 }
2606 
2607 static int *
2608 socksetup(int af, const char *bindhostname)
2609 {
2610 	struct addrinfo hints, *res, *r;
2611 	int error, maxs, *s, *socks;
2612 
2613 	memset(&hints, 0, sizeof(hints));
2614 	hints.ai_flags = AI_PASSIVE;
2615 	hints.ai_family = af;
2616 	hints.ai_socktype = SOCK_DGRAM;
2617 	error = getaddrinfo(bindhostname, "syslog", &hints, &res);
2618 	if (error) {
2619 		logerror(gai_strerror(error));
2620 		errno = 0;
2621 		die(0);
2622 	}
2623 
2624 	/* Count max number of sockets we may open */
2625 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2626 	socks = malloc((maxs+1) * sizeof(int));
2627 	if (socks == NULL) {
2628 		logerror("couldn't allocate memory for sockets");
2629 		die(0);
2630 	}
2631 
2632 	*socks = 0;   /* num of sockets counter at start of array */
2633 	s = socks + 1;
2634 	for (r = res; r; r = r->ai_next) {
2635 		int on = 1;
2636 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2637 		if (*s < 0) {
2638 			logerror("socket");
2639 			continue;
2640 		}
2641 		if (r->ai_family == AF_INET6) {
2642 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2643 				       (char *)&on, sizeof (on)) < 0) {
2644 				logerror("setsockopt");
2645 				close(*s);
2646 				continue;
2647 			}
2648 		}
2649 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2650 			       (char *)&on, sizeof (on)) < 0) {
2651 			logerror("setsockopt");
2652 			close(*s);
2653 			continue;
2654 		}
2655 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2656 			close(*s);
2657 			logerror("bind");
2658 			continue;
2659 		}
2660 
2661 		double_rbuf(*s);
2662 
2663 		(*socks)++;
2664 		s++;
2665 	}
2666 
2667 	if (*socks == 0) {
2668 		free(socks);
2669 		if (Debug)
2670 			return (NULL);
2671 		else
2672 			die(0);
2673 	}
2674 	if (res)
2675 		freeaddrinfo(res);
2676 
2677 	return (socks);
2678 }
2679 
2680 static void
2681 double_rbuf(int fd)
2682 {
2683 	socklen_t slen, len;
2684 
2685 	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2686 		len *= 2;
2687 		setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);
2688 	}
2689 }
2690