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