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