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