xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision 77013d11e6483b970af25e13c9b892075742f7e5)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1988, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 /*-
32  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
33  *
34  * Copyright (c) 2018 Prodrive Technologies, https://prodrive-technologies.com/
35  * Author: Ed Schouten <ed@FreeBSD.org>
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  */
58 
59 #ifndef lint
60 static const char copyright[] =
61 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
62 	The Regents of the University of California.  All rights reserved.\n";
63 #endif /* not lint */
64 
65 #ifndef lint
66 #if 0
67 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
68 #endif
69 #endif /* not lint */
70 
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
73 
74 /*
75  *  syslogd -- log system messages
76  *
77  * This program implements a system log. It takes a series of lines.
78  * Each line may have a priority, signified as "<n>" as
79  * the first characters of the line.  If this is
80  * not present, a default priority is used.
81  *
82  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
83  * cause it to reread its configuration file.
84  *
85  * Defined Constants:
86  *
87  * MAXLINE -- the maximum line length that can be handled.
88  * DEFUPRI -- the default priority for user messages
89  * DEFSPRI -- the default priority for kernel messages
90  *
91  * Author: Eric Allman
92  * extensive changes by Ralph Campbell
93  * more extensive changes by Eric Allman (again)
94  * Extension to log by program name as well as facility and priority
95  *   by Peter da Silva.
96  * -u and -v by Harlan Stenn.
97  * Priority comparison code by Harlan Stenn.
98  */
99 
100 #define	MAXLINE		8192		/* maximum line length */
101 #define	MAXSVLINE	MAXLINE		/* maximum saved line length */
102 #define	DEFUPRI		(LOG_USER|LOG_NOTICE)
103 #define	DEFSPRI		(LOG_KERN|LOG_CRIT)
104 #define	TIMERINTVL	30		/* interval for checking flush, mark */
105 #define	TTYMSGTIME	1		/* timeout passed to ttymsg */
106 #define	RCVBUF_MINSIZE	(80 * 1024)	/* minimum size of dgram rcv buffer */
107 
108 #include <sys/param.h>
109 #include <sys/ioctl.h>
110 #include <sys/mman.h>
111 #include <sys/queue.h>
112 #include <sys/resource.h>
113 #include <sys/socket.h>
114 #include <sys/stat.h>
115 #include <sys/syslimits.h>
116 #include <sys/time.h>
117 #include <sys/uio.h>
118 #include <sys/un.h>
119 #include <sys/wait.h>
120 
121 #if defined(INET) || defined(INET6)
122 #include <netinet/in.h>
123 #include <arpa/inet.h>
124 #endif
125 
126 #include <assert.h>
127 #include <ctype.h>
128 #include <dirent.h>
129 #include <err.h>
130 #include <errno.h>
131 #include <fcntl.h>
132 #include <fnmatch.h>
133 #include <libutil.h>
134 #include <limits.h>
135 #include <netdb.h>
136 #include <paths.h>
137 #include <signal.h>
138 #include <stdbool.h>
139 #include <stddef.h>
140 #include <stdio.h>
141 #include <stdlib.h>
142 #include <string.h>
143 #include <sysexits.h>
144 #include <unistd.h>
145 #include <utmpx.h>
146 #include <regex.h>
147 
148 #include "pathnames.h"
149 #include "ttymsg.h"
150 
151 #define SYSLOG_NAMES
152 #include <sys/syslog.h>
153 
154 static const char *ConfFile = _PATH_LOGCONF;
155 static const char *PidFile = _PATH_LOGPID;
156 static const char ctty[] = _PATH_CONSOLE;
157 static const char include_str[] = "include";
158 static const char include_ext[] = ".conf";
159 
160 #define	dprintf		if (Debug) printf
161 
162 #define	MAXUNAMES	20	/* maximum number of user names */
163 
164 #define	sstosa(ss)	((struct sockaddr *)(ss))
165 #ifdef INET
166 #define	sstosin(ss)	((struct sockaddr_in *)(void *)(ss))
167 #define	satosin(sa)	((struct sockaddr_in *)(void *)(sa))
168 #endif
169 #ifdef INET6
170 #define	sstosin6(ss)	((struct sockaddr_in6 *)(void *)(ss))
171 #define	satosin6(sa)	((struct sockaddr_in6 *)(void *)(sa))
172 #define	s6_addr32	__u6_addr.__u6_addr32
173 #define	IN6_ARE_MASKED_ADDR_EQUAL(d, a, m)	(	\
174 	(((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
175 	(((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
176 	(((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
177 	(((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
178 #endif
179 /*
180  * List of peers and sockets for binding.
181  */
182 struct peer {
183 	const char	*pe_name;
184 	const char	*pe_serv;
185 	mode_t		pe_mode;
186 	STAILQ_ENTRY(peer)	next;
187 };
188 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
189 
190 struct socklist {
191 	struct addrinfo		sl_ai;
192 #define	sl_sa		sl_ai.ai_addr
193 #define	sl_salen	sl_ai.ai_addrlen
194 #define	sl_family	sl_ai.ai_family
195 	int			sl_socket;
196 	struct peer		*sl_peer;
197 	int			(*sl_recv)(struct socklist *);
198 	STAILQ_ENTRY(socklist)	next;
199 };
200 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
201 
202 /*
203  * Flags to logmsg().
204  */
205 
206 #define	IGN_CONS	0x001	/* don't print on console */
207 #define	SYNC_FILE	0x002	/* do fsync on file after printing */
208 #define	MARK		0x008	/* this message is a mark */
209 #define	ISKERNEL	0x010	/* kernel generated message */
210 
211 /* Timestamps of log entries. */
212 struct logtime {
213 	struct tm	tm;
214 	suseconds_t	usec;
215 };
216 
217 /* Traditional syslog timestamp format. */
218 #define	RFC3164_DATELEN	15
219 #define	RFC3164_DATEFMT	"%b %e %H:%M:%S"
220 
221 /*
222  * This structure holds a property-based filter
223  */
224 
225 struct prop_filter {
226 	uint8_t	prop_type;
227 #define	PROP_TYPE_NOOP		0
228 #define	PROP_TYPE_MSG		1
229 #define	PROP_TYPE_HOSTNAME	2
230 #define	PROP_TYPE_PROGNAME	3
231 
232 	uint8_t	cmp_type;
233 #define	PROP_CMP_CONTAINS	1
234 #define	PROP_CMP_EQUAL		2
235 #define	PROP_CMP_STARTS		3
236 #define	PROP_CMP_REGEX		4
237 
238 	uint16_t cmp_flags;
239 #define	PROP_FLAG_EXCLUDE	(1 << 0)
240 #define	PROP_FLAG_ICASE		(1 << 1)
241 
242 	union {
243 		char *p_strval;
244 		regex_t *p_re;
245 	} pflt_uniptr;
246 #define	pflt_strval	pflt_uniptr.p_strval
247 #define	pflt_re		pflt_uniptr.p_re
248 
249 	size_t	pflt_strlen;
250 };
251 
252 /*
253  * This structure represents the files that will have log
254  * copies printed.
255  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
256  * or if f_type is F_PIPE and f_pid > 0.
257  */
258 
259 struct filed {
260 	STAILQ_ENTRY(filed)	next;	/* next in linked list */
261 	short	f_type;			/* entry type, see below */
262 	short	f_file;			/* file descriptor */
263 	time_t	f_time;			/* time this was last written */
264 	char	*f_host;		/* host from which to recd. */
265 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
266 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
267 #define PRI_LT	0x1
268 #define PRI_EQ	0x2
269 #define PRI_GT	0x4
270 	char	*f_program;		/* program this applies to */
271 	struct prop_filter *f_prop_filter; /* property-based filter */
272 	union {
273 		char	f_uname[MAXUNAMES][MAXLOGNAME];
274 		struct {
275 			char	f_hname[MAXHOSTNAMELEN];
276 			struct addrinfo *f_addr;
277 
278 		} f_forw;		/* forwarding address */
279 		char	f_fname[MAXPATHLEN];
280 		struct {
281 			char	f_pname[MAXPATHLEN];
282 			pid_t	f_pid;
283 		} f_pipe;
284 	} f_un;
285 #define	fu_uname	f_un.f_uname
286 #define	fu_forw_hname	f_un.f_forw.f_hname
287 #define	fu_forw_addr	f_un.f_forw.f_addr
288 #define	fu_fname	f_un.f_fname
289 #define	fu_pipe_pname	f_un.f_pipe.f_pname
290 #define	fu_pipe_pid	f_un.f_pipe.f_pid
291 	char	f_prevline[MAXSVLINE];		/* last message logged */
292 	struct logtime f_lasttime;		/* time of last occurrence */
293 	int	f_prevpri;			/* pri of f_prevline */
294 	size_t	f_prevlen;			/* length of f_prevline */
295 	int	f_prevcount;			/* repetition cnt of prevline */
296 	u_int	f_repeatcount;			/* number of "repeated" msgs */
297 	int	f_flags;			/* file-specific flags */
298 #define	FFLAG_SYNC 0x01
299 #define	FFLAG_NEEDSYNC	0x02
300 };
301 
302 /*
303  * Queue of about-to-be dead processes we should watch out for.
304  */
305 struct deadq_entry {
306 	pid_t				dq_pid;
307 	int				dq_timeout;
308 	TAILQ_ENTRY(deadq_entry)	dq_entries;
309 };
310 static TAILQ_HEAD(, deadq_entry) deadq_head =
311     TAILQ_HEAD_INITIALIZER(deadq_head);
312 
313 /*
314  * The timeout to apply to processes waiting on the dead queue.  Unit
315  * of measure is `mark intervals', i.e. 20 minutes by default.
316  * Processes on the dead queue will be terminated after that time.
317  */
318 
319 #define	 DQ_TIMO_INIT	2
320 
321 /*
322  * Struct to hold records of network addresses that are allowed to log
323  * to us.
324  */
325 struct allowedpeer {
326 	int isnumeric;
327 	u_short port;
328 	union {
329 		struct {
330 			struct sockaddr_storage addr;
331 			struct sockaddr_storage mask;
332 		} numeric;
333 		char *name;
334 	} u;
335 #define a_addr u.numeric.addr
336 #define a_mask u.numeric.mask
337 #define a_name u.name
338 	STAILQ_ENTRY(allowedpeer)	next;
339 };
340 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
341 
342 
343 /*
344  * Intervals at which we flush out "message repeated" messages,
345  * in seconds after previous message is logged.  After each flush,
346  * we move to the next interval until we reach the largest.
347  */
348 static int repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
349 #define	MAXREPEAT	(nitems(repeatinterval) - 1)
350 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
351 #define	BACKOFF(f)	do {						\
352 				if (++(f)->f_repeatcount > MAXREPEAT)	\
353 					(f)->f_repeatcount = MAXREPEAT;	\
354 			} while (0)
355 
356 /* values for f_type */
357 #define F_UNUSED	0		/* unused entry */
358 #define F_FILE		1		/* regular file */
359 #define F_TTY		2		/* terminal */
360 #define F_CONSOLE	3		/* console terminal */
361 #define F_FORW		4		/* remote machine */
362 #define F_USERS		5		/* list of users */
363 #define F_WALL		6		/* everyone logged on */
364 #define F_PIPE		7		/* pipe to program */
365 
366 static const char *TypeNames[] = {
367 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
368 	"FORW",		"USERS",	"WALL",		"PIPE"
369 };
370 
371 static STAILQ_HEAD(, filed) fhead =
372     STAILQ_HEAD_INITIALIZER(fhead);	/* Log files that we write to */
373 static struct filed consfile;	/* Console */
374 
375 static int	Debug;		/* debug flag */
376 static int	Foreground = 0;	/* Run in foreground, instead of daemonizing */
377 static int	resolve = 1;	/* resolve hostname */
378 static char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
379 static const char *LocalDomain;	/* our local domain name */
380 static int	Initialized;	/* set when we have initialized ourselves */
381 static int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
382 static int	MarkSeq;	/* mark sequence number */
383 static int	NoBind;		/* don't bind() as suggested by RFC 3164 */
384 static int	SecureMode;	/* when true, receive only unix domain socks */
385 static int	MaxForwardLen = 1024;	/* max length of forwared message */
386 #ifdef INET6
387 static int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
388 #else
389 static int	family = PF_INET; /* protocol family (IPv4 only) */
390 #endif
391 static int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
392 static int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
393 static int	use_bootfile;	/* log entire bootfile for every kern msg */
394 static int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
395 static int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
396 
397 static char	bootfile[MAXPATHLEN]; /* booted kernel file */
398 
399 static int	RemoteAddDate;	/* Always set the date on remote messages */
400 static int	RemoteHostname;	/* Log remote hostname from the message */
401 
402 static int	UniquePriority;	/* Only log specified priority? */
403 static int	LogFacPri;	/* Put facility and priority in log message: */
404 				/* 0=no, 1=numeric, 2=names */
405 static int	KeepKernFac;	/* Keep remotely logged kernel facility */
406 static int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
407 static struct pidfh *pfh;
408 static int	sigpipe[2];	/* Pipe to catch a signal during select(). */
409 static bool	RFC3164OutputFormat = true; /* Use legacy format by default. */
410 
411 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
412 
413 struct iovlist;
414 
415 static int	allowaddr(char *);
416 static int	addfile(struct filed *);
417 static int	addpeer(struct peer *);
418 static int	addsock(struct addrinfo *, struct socklist *);
419 static struct filed *cfline(const char *, const char *, const char *,
420     const char *);
421 static const char *cvthname(struct sockaddr *);
422 static void	deadq_enter(pid_t, const char *);
423 static int	deadq_remove(struct deadq_entry *);
424 static int	deadq_removebypid(pid_t);
425 static int	decode(const char *, const CODE *);
426 static void	die(int) __dead2;
427 static void	dodie(int);
428 static void	dofsync(void);
429 static void	domark(int);
430 static void	fprintlog_first(struct filed *, const char *, const char *,
431     const char *, const char *, const char *, const char *, int);
432 static void	fprintlog_write(struct filed *, struct iovlist *, int);
433 static void	fprintlog_successive(struct filed *, int);
434 static void	init(int);
435 static void	logerror(const char *);
436 static void	logmsg(int, const struct logtime *, const char *, const char *,
437     const char *, const char *, const char *, const char *, int);
438 static void	log_deadchild(pid_t, int, const char *);
439 static void	markit(void);
440 static int	socksetup(struct peer *);
441 static int	socklist_recv_file(struct socklist *);
442 static int	socklist_recv_sock(struct socklist *);
443 static int	socklist_recv_signal(struct socklist *);
444 static void	sighandler(int);
445 static int	skip_message(const char *, const char *, int);
446 static int	evaluate_prop_filter(const struct prop_filter *filter,
447     const char *value);
448 static int	prop_filter_compile(struct prop_filter *pfilter,
449     char *filterstr);
450 static void	parsemsg(const char *, char *);
451 static void	printsys(char *);
452 static int	p_open(const char *, pid_t *);
453 static void	reapchild(int);
454 static const char *ttymsg_check(struct iovec *, int, char *, int);
455 static void	usage(void);
456 static int	validate(struct sockaddr *, const char *);
457 static void	unmapped(struct sockaddr *);
458 static void	wallmsg(struct filed *, struct iovec *, const int iovlen);
459 static int	waitdaemon(int);
460 static void	timedout(int);
461 static void	increase_rcvbuf(int);
462 
463 static void
464 close_filed(struct filed *f)
465 {
466 
467 	if (f == NULL || f->f_file == -1)
468 		return;
469 
470 	switch (f->f_type) {
471 	case F_FORW:
472 		if (f->fu_forw_addr != NULL) {
473 			freeaddrinfo(f->fu_forw_addr);
474 			f->fu_forw_addr = NULL;
475 		}
476 		/* FALLTHROUGH */
477 
478 	case F_FILE:
479 	case F_TTY:
480 	case F_CONSOLE:
481 		f->f_type = F_UNUSED;
482 		break;
483 	case F_PIPE:
484 		f->fu_pipe_pid = 0;
485 		break;
486 	}
487 	(void)close(f->f_file);
488 	f->f_file = -1;
489 }
490 
491 static int
492 addfile(struct filed *f0)
493 {
494 	struct filed *f;
495 
496 	f = calloc(1, sizeof(*f));
497 	if (f == NULL)
498 		err(1, "malloc failed");
499 	*f = *f0;
500 	STAILQ_INSERT_TAIL(&fhead, f, next);
501 
502 	return (0);
503 }
504 
505 static int
506 addpeer(struct peer *pe0)
507 {
508 	struct peer *pe;
509 
510 	pe = calloc(1, sizeof(*pe));
511 	if (pe == NULL)
512 		err(1, "malloc failed");
513 	*pe = *pe0;
514 	STAILQ_INSERT_TAIL(&pqueue, pe, next);
515 
516 	return (0);
517 }
518 
519 static int
520 addsock(struct addrinfo *ai, struct socklist *sl0)
521 {
522 	struct socklist *sl;
523 
524 	/* Copy *ai->ai_addr to the tail of struct socklist if any. */
525 	sl = calloc(1, sizeof(*sl) + ((ai != NULL) ? ai->ai_addrlen : 0));
526 	if (sl == NULL)
527 		err(1, "malloc failed");
528 	*sl = *sl0;
529 	if (ai != NULL) {
530 		memcpy(&sl->sl_ai, ai, sizeof(*ai));
531 		if (ai->ai_addrlen > 0) {
532 			memcpy((sl + 1), ai->ai_addr, ai->ai_addrlen);
533 			sl->sl_sa = (struct sockaddr *)(sl + 1);
534 		} else
535 			sl->sl_sa = NULL;
536 	}
537 	STAILQ_INSERT_TAIL(&shead, sl, next);
538 
539 	return (0);
540 }
541 
542 int
543 main(int argc, char *argv[])
544 {
545 	int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
546 	fd_set *fdsr = NULL;
547 	struct timeval tv, *tvp;
548 	struct peer *pe;
549 	struct socklist *sl;
550 	pid_t ppid = 1, spid;
551 	char *p;
552 
553 	if (madvise(NULL, 0, MADV_PROTECT) != 0)
554 		dprintf("madvise() failed: %s\n", strerror(errno));
555 
556 	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:M:m:nNoO:p:P:sS:Tuv"))
557 	    != -1)
558 		switch (ch) {
559 #ifdef INET
560 		case '4':
561 			family = PF_INET;
562 			break;
563 #endif
564 #ifdef INET6
565 		case '6':
566 			family = PF_INET6;
567 			break;
568 #endif
569 		case '8':
570 			mask_C1 = 0;
571 			break;
572 		case 'A':
573 			send_to_all++;
574 			break;
575 		case 'a':		/* allow specific network addresses only */
576 			if (allowaddr(optarg) == -1)
577 				usage();
578 			break;
579 		case 'b':
580 			bflag = 1;
581 			p = strchr(optarg, ']');
582 			if (p != NULL)
583 				p = strchr(p + 1, ':');
584 			else {
585 				p = strchr(optarg, ':');
586 				if (p != NULL && strchr(p + 1, ':') != NULL)
587 					p = NULL; /* backward compatibility */
588 			}
589 			if (p == NULL) {
590 				/* A hostname or filename only. */
591 				addpeer(&(struct peer){
592 					.pe_name = optarg,
593 					.pe_serv = "syslog"
594 				});
595 			} else {
596 				/* The case of "name:service". */
597 				*p++ = '\0';
598 				addpeer(&(struct peer){
599 					.pe_serv = p,
600 					.pe_name = (strlen(optarg) == 0) ?
601 					    NULL : optarg,
602 				});
603 			}
604 			break;
605 		case 'c':
606 			no_compress++;
607 			break;
608 		case 'C':
609 			logflags |= O_CREAT;
610 			break;
611 		case 'd':		/* debug */
612 			Debug++;
613 			break;
614 		case 'f':		/* configuration file */
615 			ConfFile = optarg;
616 			break;
617 		case 'F':		/* run in foreground instead of daemon */
618 			Foreground++;
619 			break;
620 		case 'H':
621 			RemoteHostname = 1;
622 			break;
623 		case 'k':		/* keep remote kern fac */
624 			KeepKernFac = 1;
625 			break;
626 		case 'l':
627 		case 'p':
628 		case 'S':
629 		    {
630 			long	perml;
631 			mode_t	mode;
632 			char	*name, *ep;
633 
634 			if (ch == 'l')
635 				mode = DEFFILEMODE;
636 			else if (ch == 'p') {
637 				mode = DEFFILEMODE;
638 				pflag = 1;
639 			} else {
640 				mode = S_IRUSR | S_IWUSR;
641 				Sflag = 1;
642 			}
643 			if (optarg[0] == '/')
644 				name = optarg;
645 			else if ((name = strchr(optarg, ':')) != NULL) {
646 				*name++ = '\0';
647 				if (name[0] != '/')
648 					errx(1, "socket name must be absolute "
649 					    "path");
650 				if (isdigit(*optarg)) {
651 					perml = strtol(optarg, &ep, 8);
652 				    if (*ep || perml < 0 ||
653 					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
654 					    errx(1, "invalid mode %s, exiting",
655 						optarg);
656 				    mode = (mode_t )perml;
657 				} else
658 					errx(1, "invalid mode %s, exiting",
659 					    optarg);
660 			} else
661 				errx(1, "invalid filename %s, exiting",
662 				    optarg);
663 			addpeer(&(struct peer){
664 				.pe_name = name,
665 				.pe_mode = mode
666 			});
667 			break;
668 		   }
669 		case 'M':		/* max length of forwarded message */
670 			MaxForwardLen = atoi(optarg);
671 			if (MaxForwardLen < 480)
672 				errx(1, "minimum length limit of forwarded "
673 				        "messages is 480 bytes");
674 			break;
675 		case 'm':		/* mark interval */
676 			MarkInterval = atoi(optarg) * 60;
677 			break;
678 		case 'N':
679 			NoBind = 1;
680 			SecureMode = 1;
681 			break;
682 		case 'n':
683 			resolve = 0;
684 			break;
685 		case 'O':
686 			if (strcmp(optarg, "bsd") == 0 ||
687 			    strcmp(optarg, "rfc3164") == 0)
688 				RFC3164OutputFormat = true;
689 			else if (strcmp(optarg, "syslog") == 0 ||
690 			    strcmp(optarg, "rfc5424") == 0)
691 				RFC3164OutputFormat = false;
692 			else
693 				usage();
694 			break;
695 		case 'o':
696 			use_bootfile = 1;
697 			break;
698 		case 'P':		/* path for alt. PID */
699 			PidFile = optarg;
700 			break;
701 		case 's':		/* no network mode */
702 			SecureMode++;
703 			break;
704 		case 'T':
705 			RemoteAddDate = 1;
706 			break;
707 		case 'u':		/* only log specified priority */
708 			UniquePriority++;
709 			break;
710 		case 'v':		/* log facility and priority */
711 		  	LogFacPri++;
712 			break;
713 		default:
714 			usage();
715 		}
716 	if ((argc -= optind) != 0)
717 		usage();
718 
719 	if (RFC3164OutputFormat && MaxForwardLen > 1024)
720 		errx(1, "RFC 3164 messages may not exceed 1024 bytes");
721 
722 	/* Pipe to catch a signal during select(). */
723 	s = pipe2(sigpipe, O_CLOEXEC);
724 	if (s < 0) {
725 		err(1, "cannot open a pipe for signals");
726 	} else {
727 		addsock(NULL, &(struct socklist){
728 		    .sl_socket = sigpipe[0],
729 		    .sl_recv = socklist_recv_signal
730 		});
731 	}
732 
733 	/* Listen by default: /dev/klog. */
734 	s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
735 	if (s < 0) {
736 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
737 	} else {
738 		addsock(NULL, &(struct socklist){
739 			.sl_socket = s,
740 			.sl_recv = socklist_recv_file,
741 		});
742 	}
743 	/* Listen by default: *:514 if no -b flag. */
744 	if (bflag == 0)
745 		addpeer(&(struct peer){
746 			.pe_serv = "syslog"
747 		});
748 	/* Listen by default: /var/run/log if no -p flag. */
749 	if (pflag == 0)
750 		addpeer(&(struct peer){
751 			.pe_name = _PATH_LOG,
752 			.pe_mode = DEFFILEMODE,
753 		});
754 	/* Listen by default: /var/run/logpriv if no -S flag. */
755 	if (Sflag == 0)
756 		addpeer(&(struct peer){
757 			.pe_name = _PATH_LOG_PRIV,
758 			.pe_mode = S_IRUSR | S_IWUSR,
759 		});
760 	STAILQ_FOREACH(pe, &pqueue, next)
761 		socksetup(pe);
762 
763 	pfh = pidfile_open(PidFile, 0600, &spid);
764 	if (pfh == NULL) {
765 		if (errno == EEXIST)
766 			errx(1, "syslogd already running, pid: %d", spid);
767 		warn("cannot open pid file");
768 	}
769 
770 	if ((!Foreground) && (!Debug)) {
771 		ppid = waitdaemon(30);
772 		if (ppid < 0) {
773 			warn("could not become daemon");
774 			pidfile_remove(pfh);
775 			exit(1);
776 		}
777 	} else if (Debug)
778 		setlinebuf(stdout);
779 
780 	consfile.f_type = F_CONSOLE;
781 	(void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
782 	    sizeof(consfile.fu_fname));
783 	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
784 	(void)signal(SIGTERM, dodie);
785 	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
786 	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
787 	(void)signal(SIGHUP, sighandler);
788 	(void)signal(SIGCHLD, sighandler);
789 	(void)signal(SIGALRM, domark);
790 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
791 	(void)alarm(TIMERINTVL);
792 
793 	/* tuck my process id away */
794 	pidfile_write(pfh);
795 
796 	dprintf("off & running....\n");
797 
798 	tvp = &tv;
799 	tv.tv_sec = tv.tv_usec = 0;
800 
801 	STAILQ_FOREACH(sl, &shead, next) {
802 		if (sl->sl_socket > fdsrmax)
803 			fdsrmax = sl->sl_socket;
804 	}
805 	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
806 	    sizeof(*fdsr));
807 	if (fdsr == NULL)
808 		errx(1, "calloc fd_set");
809 
810 	for (;;) {
811 		if (Initialized == 0)
812 			init(0);
813 		else if (WantInitialize)
814 			init(WantInitialize);
815 		if (WantReapchild)
816 			reapchild(WantReapchild);
817 		if (MarkSet)
818 			markit();
819 		if (WantDie) {
820 			free(fdsr);
821 			die(WantDie);
822 		}
823 
824 		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
825 		    sizeof(*fdsr));
826 
827 		STAILQ_FOREACH(sl, &shead, next) {
828 			if (sl->sl_socket != -1 && sl->sl_recv != NULL)
829 				FD_SET(sl->sl_socket, fdsr);
830 		}
831 		i = select(fdsrmax + 1, fdsr, NULL, NULL,
832 		    needdofsync ? &tv : tvp);
833 		switch (i) {
834 		case 0:
835 			dofsync();
836 			needdofsync = 0;
837 			if (tvp) {
838 				tvp = NULL;
839 				if (ppid != 1)
840 					kill(ppid, SIGALRM);
841 			}
842 			continue;
843 		case -1:
844 			if (errno != EINTR)
845 				logerror("select");
846 			continue;
847 		}
848 		STAILQ_FOREACH(sl, &shead, next) {
849 			if (FD_ISSET(sl->sl_socket, fdsr))
850 				(*sl->sl_recv)(sl);
851 		}
852 	}
853 	free(fdsr);
854 }
855 
856 static int
857 socklist_recv_signal(struct socklist *sl __unused)
858 {
859 	ssize_t len;
860 	int i, nsig, signo;
861 
862 	if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
863 		logerror("ioctl(FIONREAD)");
864 		err(1, "signal pipe read failed");
865 	}
866 	nsig = i / sizeof(signo);
867 	dprintf("# of received signals = %d\n", nsig);
868 	for (i = 0; i < nsig; i++) {
869 		len = read(sigpipe[0], &signo, sizeof(signo));
870 		if (len != sizeof(signo)) {
871 			logerror("signal pipe read failed");
872 			err(1, "signal pipe read failed");
873 		}
874 		dprintf("Received signal: %d from fd=%d\n", signo,
875 		    sigpipe[0]);
876 		switch (signo) {
877 		case SIGHUP:
878 			WantInitialize = 1;
879 			break;
880 		case SIGCHLD:
881 			WantReapchild = 1;
882 			break;
883 		}
884 	}
885 	return (0);
886 }
887 
888 static int
889 socklist_recv_sock(struct socklist *sl)
890 {
891 	struct sockaddr_storage ss;
892 	struct sockaddr *sa = (struct sockaddr *)&ss;
893 	socklen_t sslen;
894 	const char *hname;
895 	char line[MAXLINE + 1];
896 	int len;
897 
898 	sslen = sizeof(ss);
899 	len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
900 	dprintf("received sa_len = %d\n", sslen);
901 	if (len == 0)
902 		return (-1);
903 	if (len < 0) {
904 		if (errno != EINTR)
905 			logerror("recvfrom");
906 		return (-1);
907 	}
908 	/* Received valid data. */
909 	line[len] = '\0';
910 	if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
911 		hname = LocalHostName;
912 	else {
913 		hname = cvthname(sa);
914 		unmapped(sa);
915 		if (validate(sa, hname) == 0) {
916 			dprintf("Message from %s was ignored.", hname);
917 			return (-1);
918 		}
919 	}
920 	parsemsg(hname, line);
921 
922 	return (0);
923 }
924 
925 static void
926 unmapped(struct sockaddr *sa)
927 {
928 #if defined(INET) && defined(INET6)
929 	struct sockaddr_in6 *sin6;
930 	struct sockaddr_in sin;
931 
932 	if (sa == NULL ||
933 	    sa->sa_family != AF_INET6 ||
934 	    sa->sa_len != sizeof(*sin6))
935 		return;
936 	sin6 = satosin6(sa);
937 	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
938 		return;
939 	sin = (struct sockaddr_in){
940 		.sin_family = AF_INET,
941 		.sin_len = sizeof(sin),
942 		.sin_port = sin6->sin6_port
943 	};
944 	memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
945 	    sizeof(sin.sin_addr));
946 	memcpy(sa, &sin, sizeof(sin));
947 #else
948 	if (sa == NULL)
949 		return;
950 #endif
951 }
952 
953 static void
954 usage(void)
955 {
956 
957 	fprintf(stderr,
958 		"usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]\n"
959 		"               [-b bind_address] [-f config_file]\n"
960 		"               [-l [mode:]path] [-M fwd_length]\n"
961 		"               [-m mark_interval] [-O format] [-P pid_file]\n"
962 		"               [-p log_socket] [-S logpriv_socket]\n");
963 	exit(1);
964 }
965 
966 /*
967  * Removes characters from log messages that are unsafe to display.
968  * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
969  */
970 static void
971 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
972 {
973 	char *q;
974 	int c;
975 
976 	q = out;
977 	while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
978 		if (mask_C1 && (c & 0x80) && c < 0xA0) {
979 			c &= 0x7F;
980 			*q++ = 'M';
981 			*q++ = '-';
982 		}
983 		if (isascii(c) && iscntrl(c)) {
984 			if (c == '\n') {
985 				*q++ = ' ';
986 			} else if (c == '\t') {
987 				*q++ = '\t';
988 			} else {
989 				*q++ = '^';
990 				*q++ = c ^ 0100;
991 			}
992 		} else {
993 			*q++ = c;
994 		}
995 	}
996 	*q = '\0';
997 }
998 
999 /*
1000  * Parses a syslog message according to RFC 5424, assuming that PRI and
1001  * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
1002  * parsed result is passed to logmsg().
1003  */
1004 static void
1005 parsemsg_rfc5424(const char *from, int pri, char *msg)
1006 {
1007 	const struct logtime *timestamp;
1008 	struct logtime timestamp_remote;
1009 	const char *omsg, *hostname, *app_name, *procid, *msgid,
1010 	    *structured_data;
1011 	char line[MAXLINE + 1];
1012 
1013 #define	FAIL_IF(field, expr) do {					\
1014 	if (expr) {							\
1015 		dprintf("Failed to parse " field " from %s: %s\n",	\
1016 		    from, omsg);					\
1017 		return;							\
1018 	}								\
1019 } while (0)
1020 #define	PARSE_CHAR(field, sep) do {					\
1021 	FAIL_IF(field, *msg != sep);					\
1022 	++msg;								\
1023 } while (0)
1024 #define	IF_NOT_NILVALUE(var)						\
1025 	if (msg[0] == '-' && msg[1] == ' ') {				\
1026 		msg += 2;						\
1027 		var = NULL;						\
1028 	} else if (msg[0] == '-' && msg[1] == '\0') {			\
1029 		++msg;							\
1030 		var = NULL;						\
1031 	} else
1032 
1033 	omsg = msg;
1034 	IF_NOT_NILVALUE(timestamp) {
1035 		/* Parse RFC 3339-like timestamp. */
1036 #define	PARSE_NUMBER(dest, length, min, max) do {			\
1037 	int i, v;							\
1038 									\
1039 	v = 0;								\
1040 	for (i = 0; i < length; ++i) {					\
1041 		FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9');		\
1042 		v = v * 10 + *msg++ - '0';				\
1043 	}								\
1044 	FAIL_IF("TIMESTAMP", v < min || v > max);			\
1045 	dest = v;							\
1046 } while (0)
1047 		/* Date and time. */
1048 		memset(&timestamp_remote, 0, sizeof(timestamp_remote));
1049 		PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
1050 		timestamp_remote.tm.tm_year -= 1900;
1051 		PARSE_CHAR("TIMESTAMP", '-');
1052 		PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
1053 		--timestamp_remote.tm.tm_mon;
1054 		PARSE_CHAR("TIMESTAMP", '-');
1055 		PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
1056 		PARSE_CHAR("TIMESTAMP", 'T');
1057 		PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
1058 		PARSE_CHAR("TIMESTAMP", ':');
1059 		PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
1060 		PARSE_CHAR("TIMESTAMP", ':');
1061 		PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
1062 		/* Perform normalization. */
1063 		timegm(&timestamp_remote.tm);
1064 		/* Optional: fractional seconds. */
1065 		if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
1066 			int i;
1067 
1068 			++msg;
1069 			for (i = 100000; i != 0; i /= 10) {
1070 				if (*msg < '0' || *msg > '9')
1071 					break;
1072 				timestamp_remote.usec += (*msg++ - '0') * i;
1073 			}
1074 		}
1075 		/* Timezone. */
1076 		if (*msg == 'Z') {
1077 			/* UTC. */
1078 			++msg;
1079 		} else {
1080 			int sign, tz_hour, tz_min;
1081 
1082 			/* Local time zone offset. */
1083 			FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1084 			sign = *msg++ == '-' ? -1 : 1;
1085 			PARSE_NUMBER(tz_hour, 2, 0, 23);
1086 			PARSE_CHAR("TIMESTAMP", ':');
1087 			PARSE_NUMBER(tz_min, 2, 0, 59);
1088 			timestamp_remote.tm.tm_gmtoff =
1089 			    sign * (tz_hour * 3600 + tz_min * 60);
1090 		}
1091 #undef PARSE_NUMBER
1092 		PARSE_CHAR("TIMESTAMP", ' ');
1093 		timestamp = RemoteAddDate ? NULL : &timestamp_remote;
1094 	}
1095 
1096 	/* String fields part of the HEADER. */
1097 #define	PARSE_STRING(field, var)					\
1098 	IF_NOT_NILVALUE(var) {						\
1099 		var = msg;						\
1100 		while (*msg >= '!' && *msg <= '~')			\
1101 			++msg;						\
1102 		FAIL_IF(field, var == msg);				\
1103 		PARSE_CHAR(field, ' ');					\
1104 		msg[-1] = '\0';						\
1105 	}
1106 	PARSE_STRING("HOSTNAME", hostname);
1107 	if (hostname == NULL || !RemoteHostname)
1108 		hostname = from;
1109 	PARSE_STRING("APP-NAME", app_name);
1110 	PARSE_STRING("PROCID", procid);
1111 	PARSE_STRING("MSGID", msgid);
1112 #undef PARSE_STRING
1113 
1114 	/* Structured data. */
1115 #define	PARSE_SD_NAME() do {						\
1116 	const char *start;						\
1117 									\
1118 	start = msg;							\
1119 	while (*msg >= '!' && *msg <= '~' && *msg != '=' &&		\
1120 	    *msg != ']' && *msg != '"')					\
1121 		++msg;							\
1122 	FAIL_IF("STRUCTURED-NAME", start == msg);			\
1123 } while (0)
1124 	IF_NOT_NILVALUE(structured_data) {
1125 		/* SD-ELEMENT. */
1126 		while (*msg == '[') {
1127 			++msg;
1128 			/* SD-ID. */
1129 			PARSE_SD_NAME();
1130 			/* SD-PARAM. */
1131 			while (*msg == ' ') {
1132 				++msg;
1133 				/* PARAM-NAME. */
1134 				PARSE_SD_NAME();
1135 				PARSE_CHAR("STRUCTURED-NAME", '=');
1136 				PARSE_CHAR("STRUCTURED-NAME", '"');
1137 				while (*msg != '"') {
1138 					FAIL_IF("STRUCTURED-NAME",
1139 					    *msg == '\0');
1140 					if (*msg++ == '\\') {
1141 						FAIL_IF("STRUCTURED-NAME",
1142 						    *msg == '\0');
1143 						++msg;
1144 					}
1145 				}
1146 				++msg;
1147 			}
1148 			PARSE_CHAR("STRUCTURED-NAME", ']');
1149 		}
1150 		PARSE_CHAR("STRUCTURED-NAME", ' ');
1151 		msg[-1] = '\0';
1152 	}
1153 #undef PARSE_SD_NAME
1154 
1155 #undef FAIL_IF
1156 #undef PARSE_CHAR
1157 #undef IF_NOT_NILVALUE
1158 
1159 	parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1160 	logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1161 	    structured_data, line, 0);
1162 }
1163 
1164 /*
1165  * Returns the length of the application name ("TAG" in RFC 3164
1166  * terminology) and process ID from a message if present.
1167  */
1168 static void
1169 parsemsg_rfc3164_get_app_name_procid(const char *msg, size_t *app_name_length_p,
1170     ptrdiff_t *procid_begin_offset_p, size_t *procid_length_p)
1171 {
1172 	const char *m, *procid_begin;
1173 	size_t app_name_length, procid_length;
1174 
1175 	m = msg;
1176 
1177 	/* Application name. */
1178 	app_name_length = strspn(m,
1179 	    "abcdefghijklmnopqrstuvwxyz"
1180 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1181 	    "0123456789"
1182 	    "_-/");
1183 	if (app_name_length == 0)
1184 		goto bad;
1185 	m += app_name_length;
1186 
1187 	/* Process identifier (optional). */
1188 	if (*m == '[') {
1189 		procid_begin = ++m;
1190 		procid_length = strspn(m, "0123456789");
1191 		if (procid_length == 0)
1192 			goto bad;
1193 		m += procid_length;
1194 		if (*m++ != ']')
1195 			goto bad;
1196 	} else {
1197 		procid_begin = NULL;
1198 		procid_length = 0;
1199 	}
1200 
1201 	/* Separator. */
1202 	if (m[0] != ':' || m[1] != ' ')
1203 		goto bad;
1204 
1205 	*app_name_length_p = app_name_length;
1206 	if (procid_begin_offset_p != NULL)
1207 		*procid_begin_offset_p =
1208 		    procid_begin == NULL ? 0 : procid_begin - msg;
1209 	if (procid_length_p != NULL)
1210 		*procid_length_p = procid_length;
1211 	return;
1212 bad:
1213 	*app_name_length_p = 0;
1214 	if (procid_begin_offset_p != NULL)
1215 		*procid_begin_offset_p = 0;
1216 	if (procid_length_p != NULL)
1217 		*procid_length_p = 0;
1218 }
1219 
1220 /*
1221  * Trims the application name ("TAG" in RFC 3164 terminology) and
1222  * process ID from a message if present.
1223  */
1224 static void
1225 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1226     const char **procid)
1227 {
1228 	char *m, *app_name_begin, *procid_begin;
1229 	size_t app_name_length, procid_length;
1230 	ptrdiff_t procid_begin_offset;
1231 
1232 	m = *msg;
1233 	app_name_begin = m;
1234 
1235 	parsemsg_rfc3164_get_app_name_procid(app_name_begin, &app_name_length,
1236 	    &procid_begin_offset, &procid_length);
1237 	if (app_name_length == 0)
1238 		goto bad;
1239 	procid_begin = procid_begin_offset == 0 ? NULL :
1240 	    app_name_begin + procid_begin_offset;
1241 
1242 	/* Split strings from input. */
1243 	app_name_begin[app_name_length] = '\0';
1244 	m += app_name_length + 1;
1245 	if (procid_begin != NULL) {
1246 		procid_begin[procid_length] = '\0';
1247 		m += procid_length + 2;
1248 	}
1249 
1250 	*msg = m + 1;
1251 	*app_name = app_name_begin;
1252 	*procid = procid_begin;
1253 	return;
1254 bad:
1255 	*app_name = NULL;
1256 	*procid = NULL;
1257 }
1258 
1259 /*
1260  * Parses a syslog message according to RFC 3164, assuming that PRI
1261  * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1262  * result is passed to logmsg().
1263  */
1264 static void
1265 parsemsg_rfc3164(const char *from, int pri, char *msg)
1266 {
1267 	struct tm tm_parsed;
1268 	const struct logtime *timestamp;
1269 	struct logtime timestamp_remote;
1270 	const char *app_name, *procid;
1271 	size_t i, msglen;
1272 	char line[MAXLINE + 1];
1273 
1274 	/*
1275 	 * Parse the TIMESTAMP provided by the remote side. If none is
1276 	 * found, assume this is not an RFC 3164 formatted message,
1277 	 * only containing a TAG and a MSG.
1278 	 */
1279 	timestamp = NULL;
1280 	if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) ==
1281 	    msg + RFC3164_DATELEN && msg[RFC3164_DATELEN] == ' ') {
1282 		msg += RFC3164_DATELEN + 1;
1283 		if (!RemoteAddDate) {
1284 			struct tm tm_now;
1285 			time_t t_now;
1286 			int year;
1287 
1288 			/*
1289 			 * As the timestamp does not contain the year
1290 			 * number, daylight saving time information, nor
1291 			 * a time zone, attempt to infer it. Due to
1292 			 * clock skews, the timestamp may even be part
1293 			 * of the next year. Use the last year for which
1294 			 * the timestamp is at most one week in the
1295 			 * future.
1296 			 *
1297 			 * This loop can only run for at most three
1298 			 * iterations before terminating.
1299 			 */
1300 			t_now = time(NULL);
1301 			localtime_r(&t_now, &tm_now);
1302 			for (year = tm_now.tm_year + 1;; --year) {
1303 				assert(year >= tm_now.tm_year - 1);
1304 				timestamp_remote.tm = tm_parsed;
1305 				timestamp_remote.tm.tm_year = year;
1306 				timestamp_remote.tm.tm_isdst = -1;
1307 				timestamp_remote.usec = 0;
1308 				if (mktime(&timestamp_remote.tm) <
1309 				    t_now + 7 * 24 * 60 * 60)
1310 					break;
1311 			}
1312 			timestamp = &timestamp_remote;
1313 		}
1314 
1315 		/*
1316 		 * A single space character MUST also follow the HOSTNAME field.
1317 		 */
1318 		msglen = strlen(msg);
1319 		for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1320 			if (msg[i] == ' ') {
1321 				if (RemoteHostname) {
1322 					msg[i] = '\0';
1323 					from = msg;
1324 				}
1325 				msg += i + 1;
1326 				break;
1327 			}
1328 			/*
1329 			 * Support non RFC compliant messages, without hostname.
1330 			 */
1331 			if (msg[i] == ':')
1332 				break;
1333 		}
1334 		if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1335 			dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1336 			return;
1337 		}
1338 	}
1339 
1340 	/* Remove the TAG, if present. */
1341 	parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1342 	parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1343 	logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1344 }
1345 
1346 /*
1347  * Takes a raw input line, extracts PRI and determines whether the
1348  * message is formatted according to RFC 3164 or RFC 5424. Continues
1349  * parsing of addition fields in the message according to those
1350  * standards and prints the message on the appropriate log files.
1351  */
1352 static void
1353 parsemsg(const char *from, char *msg)
1354 {
1355 	char *q;
1356 	long n;
1357 	size_t i;
1358 	int pri;
1359 
1360 	/* Parse PRI. */
1361 	if (msg[0] != '<' || !isdigit(msg[1])) {
1362 		dprintf("Invalid PRI from %s\n", from);
1363 		return;
1364 	}
1365 	for (i = 2; i <= 4; i++) {
1366 		if (msg[i] == '>')
1367 			break;
1368 		if (!isdigit(msg[i])) {
1369 			dprintf("Invalid PRI header from %s\n", from);
1370 			return;
1371 		}
1372 	}
1373 	if (msg[i] != '>') {
1374 		dprintf("Invalid PRI header from %s\n", from);
1375 		return;
1376 	}
1377 	errno = 0;
1378 	n = strtol(msg + 1, &q, 10);
1379 	if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
1380 		dprintf("Invalid PRI %ld from %s: %s\n",
1381 		    n, from, strerror(errno));
1382 		return;
1383 	}
1384 	pri = n;
1385 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1386 		pri = DEFUPRI;
1387 
1388 	/*
1389 	 * Don't allow users to log kernel messages.
1390 	 * NOTE: since LOG_KERN == 0 this will also match
1391 	 *       messages with no facility specified.
1392 	 */
1393 	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1394 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1395 
1396 	/* Parse VERSION. */
1397 	msg += i + 1;
1398 	if (msg[0] == '1' && msg[1] == ' ')
1399 		parsemsg_rfc5424(from, pri, msg + 2);
1400 	else
1401 		parsemsg_rfc3164(from, pri, msg);
1402 }
1403 
1404 /*
1405  * Read /dev/klog while data are available, split into lines.
1406  */
1407 static int
1408 socklist_recv_file(struct socklist *sl)
1409 {
1410 	char *p, *q, line[MAXLINE + 1];
1411 	int len, i;
1412 
1413 	len = 0;
1414 	for (;;) {
1415 		i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1416 		if (i > 0) {
1417 			line[i + len] = '\0';
1418 		} else {
1419 			if (i < 0 && errno != EINTR && errno != EAGAIN) {
1420 				logerror("klog");
1421 				close(sl->sl_socket);
1422 				sl->sl_socket = -1;
1423 			}
1424 			break;
1425 		}
1426 
1427 		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1428 			*q = '\0';
1429 			printsys(p);
1430 		}
1431 		len = strlen(p);
1432 		if (len >= MAXLINE - 1) {
1433 			printsys(p);
1434 			len = 0;
1435 		}
1436 		if (len > 0)
1437 			memmove(line, p, len + 1);
1438 	}
1439 	if (len > 0)
1440 		printsys(line);
1441 
1442 	return (len);
1443 }
1444 
1445 /*
1446  * Take a raw input line from /dev/klog, format similar to syslog().
1447  */
1448 static void
1449 printsys(char *msg)
1450 {
1451 	char *p, *q;
1452 	long n;
1453 	int flags, isprintf, pri;
1454 
1455 	flags = ISKERNEL | SYNC_FILE;	/* fsync after write */
1456 	p = msg;
1457 	pri = DEFSPRI;
1458 	isprintf = 1;
1459 	if (*p == '<') {
1460 		errno = 0;
1461 		n = strtol(p + 1, &q, 10);
1462 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1463 			p = q + 1;
1464 			pri = n;
1465 			isprintf = 0;
1466 		}
1467 	}
1468 	/*
1469 	 * Kernel printf's and LOG_CONSOLE messages have been displayed
1470 	 * on the console already.
1471 	 */
1472 	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1473 		flags |= IGN_CONS;
1474 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1475 		pri = DEFSPRI;
1476 	logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1477 }
1478 
1479 static time_t	now;
1480 
1481 /*
1482  * Match a program or host name against a specification.
1483  * Return a non-0 value if the message must be ignored
1484  * based on the specification.
1485  */
1486 static int
1487 skip_message(const char *name, const char *spec, int checkcase)
1488 {
1489 	const char *s;
1490 	char prev, next;
1491 	int exclude = 0;
1492 	/* Behaviour on explicit match */
1493 
1494 	if (spec == NULL)
1495 		return 0;
1496 	switch (*spec) {
1497 	case '-':
1498 		exclude = 1;
1499 		/*FALLTHROUGH*/
1500 	case '+':
1501 		spec++;
1502 		break;
1503 	default:
1504 		break;
1505 	}
1506 	if (checkcase)
1507 		s = strstr (spec, name);
1508 	else
1509 		s = strcasestr (spec, name);
1510 
1511 	if (s != NULL) {
1512 		prev = (s == spec ? ',' : *(s - 1));
1513 		next = *(s + strlen (name));
1514 
1515 		if (prev == ',' && (next == '\0' || next == ','))
1516 			/* Explicit match: skip iff the spec is an
1517 			   exclusive one. */
1518 			return exclude;
1519 	}
1520 
1521 	/* No explicit match for this name: skip the message iff
1522 	   the spec is an inclusive one. */
1523 	return !exclude;
1524 }
1525 
1526 /*
1527  * Match some property of the message against a filter.
1528  * Return a non-0 value if the message must be ignored
1529  * based on the filter.
1530  */
1531 static int
1532 evaluate_prop_filter(const struct prop_filter *filter, const char *value)
1533 {
1534 	const char *s = NULL;
1535 	const int exclude = ((filter->cmp_flags & PROP_FLAG_EXCLUDE) > 0);
1536 	size_t valuelen;
1537 
1538 	if (value == NULL)
1539 		return (-1);
1540 
1541 	if (filter->cmp_type == PROP_CMP_REGEX) {
1542 		if (regexec(filter->pflt_re, value, 0, NULL, 0) == 0)
1543 			return (exclude);
1544 		else
1545 			return (!exclude);
1546 	}
1547 
1548 	valuelen = strlen(value);
1549 
1550 	/* a shortcut for equal with different length is always false */
1551 	if (filter->cmp_type == PROP_CMP_EQUAL &&
1552 	    valuelen != filter->pflt_strlen)
1553 		return (!exclude);
1554 
1555 	if (filter->cmp_flags & PROP_FLAG_ICASE)
1556 		s = strcasestr(value, filter->pflt_strval);
1557 	else
1558 		s = strstr(value, filter->pflt_strval);
1559 
1560 	/*
1561 	 * PROP_CMP_CONTAINS	true if s
1562 	 * PROP_CMP_STARTS	true if s && s == value
1563 	 * PROP_CMP_EQUAL	true if s && s == value &&
1564 	 *			    valuelen == filter->pflt_strlen
1565 	 *			    (and length match is checked
1566 	 *			     already)
1567 	 */
1568 
1569 	switch (filter->cmp_type) {
1570 	case PROP_CMP_STARTS:
1571 	case PROP_CMP_EQUAL:
1572 		if (s != value)
1573 			return (!exclude);
1574 	/* FALLTHROUGH */
1575 	case PROP_CMP_CONTAINS:
1576 		if (s)
1577 			return (exclude);
1578 		else
1579 			return (!exclude);
1580 		break;
1581 	default:
1582 		/* unknown cmp_type */
1583 		break;
1584 	}
1585 
1586 	return (-1);
1587 }
1588 
1589 /*
1590  * Logs a message to the appropriate log files, users, etc. based on the
1591  * priority. Log messages are always formatted according to RFC 3164,
1592  * even if they were in RFC 5424 format originally, The MSGID and
1593  * STRUCTURED-DATA fields are thus discarded for the time being.
1594  */
1595 static void
1596 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1597     const char *app_name, const char *procid, const char *msgid,
1598     const char *structured_data, const char *msg, int flags)
1599 {
1600 	struct timeval tv;
1601 	struct logtime timestamp_now;
1602 	struct filed *f;
1603 	size_t savedlen;
1604 	int fac, prilev;
1605 	char saved[MAXSVLINE], kernel_app_name[100];
1606 
1607 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1608 	    pri, flags, hostname, msg);
1609 
1610 	(void)gettimeofday(&tv, NULL);
1611 	now = tv.tv_sec;
1612 	if (timestamp == NULL) {
1613 		localtime_r(&now, &timestamp_now.tm);
1614 		timestamp_now.usec = tv.tv_usec;
1615 		timestamp = &timestamp_now;
1616 	}
1617 
1618 	/* extract facility and priority level */
1619 	if (flags & MARK)
1620 		fac = LOG_NFACILITIES;
1621 	else
1622 		fac = LOG_FAC(pri);
1623 
1624 	/* Check maximum facility number. */
1625 	if (fac > LOG_NFACILITIES)
1626 		return;
1627 
1628 	prilev = LOG_PRI(pri);
1629 
1630 	/*
1631 	 * Lookup kernel app name from log prefix if present.
1632 	 * This is only used for local program specification matching.
1633 	 */
1634 	if (flags & ISKERNEL) {
1635 		size_t kernel_app_name_length;
1636 
1637 		parsemsg_rfc3164_get_app_name_procid(msg,
1638 		    &kernel_app_name_length, NULL, NULL);
1639 		if (kernel_app_name_length != 0) {
1640 			strlcpy(kernel_app_name, msg,
1641 			    MIN(sizeof(kernel_app_name),
1642 			    kernel_app_name_length + 1));
1643 		} else
1644 			kernel_app_name[0] = '\0';
1645 	}
1646 
1647 	/* log the message to the particular outputs */
1648 	if (!Initialized) {
1649 		f = &consfile;
1650 		/*
1651 		 * Open in non-blocking mode to avoid hangs during open
1652 		 * and close(waiting for the port to drain).
1653 		 */
1654 		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1655 
1656 		if (f->f_file >= 0) {
1657 			f->f_lasttime = *timestamp;
1658 			fprintlog_first(f, hostname, app_name, procid, msgid,
1659 			    structured_data, msg, flags);
1660 			close(f->f_file);
1661 			f->f_file = -1;
1662 		}
1663 		return;
1664 	}
1665 
1666 	/*
1667 	 * Store all of the fields of the message, except the timestamp,
1668 	 * in a single string. This string is used to detect duplicate
1669 	 * messages.
1670 	 */
1671 	assert(hostname != NULL);
1672 	assert(msg != NULL);
1673 	savedlen = snprintf(saved, sizeof(saved),
1674 	    "%d %s %s %s %s %s %s", pri, hostname,
1675 	    app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1676 	    msgid == NULL ? "-" : msgid,
1677 	    structured_data == NULL ? "-" : structured_data, msg);
1678 
1679 	STAILQ_FOREACH(f, &fhead, next) {
1680 		/* skip messages that are incorrect priority */
1681 		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1682 		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1683 		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1684 		     )
1685 		    || f->f_pmask[fac] == INTERNAL_NOPRI)
1686 			continue;
1687 
1688 		/* skip messages with the incorrect hostname */
1689 		if (skip_message(hostname, f->f_host, 0))
1690 			continue;
1691 
1692 		/* skip messages with the incorrect program name */
1693 		if (flags & ISKERNEL && kernel_app_name[0] != '\0') {
1694 			if (skip_message(kernel_app_name, f->f_program, 1))
1695 				continue;
1696 		} else if (skip_message(app_name == NULL ? "" : app_name,
1697 		    f->f_program, 1))
1698 			continue;
1699 
1700 		/* skip messages if a property does not match filter */
1701 		if (f->f_prop_filter != NULL &&
1702 		    f->f_prop_filter->prop_type != PROP_TYPE_NOOP) {
1703 			switch (f->f_prop_filter->prop_type) {
1704 			case PROP_TYPE_MSG:
1705 				if (evaluate_prop_filter(f->f_prop_filter,
1706 				    msg))
1707 					continue;
1708 				break;
1709 			case PROP_TYPE_HOSTNAME:
1710 				if (evaluate_prop_filter(f->f_prop_filter,
1711 				    hostname))
1712 					continue;
1713 				break;
1714 			case PROP_TYPE_PROGNAME:
1715 				if (evaluate_prop_filter(f->f_prop_filter,
1716 				    app_name == NULL ? "" : app_name))
1717 					continue;
1718 				break;
1719 			default:
1720 				continue;
1721 			}
1722 		}
1723 
1724 		/* skip message to console if it has already been printed */
1725 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1726 			continue;
1727 
1728 		/* don't output marks to recently written files */
1729 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1730 			continue;
1731 
1732 		/*
1733 		 * suppress duplicate lines to this file
1734 		 */
1735 		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1736 		    (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1737 		    strcmp(saved, f->f_prevline) == 0) {
1738 			f->f_lasttime = *timestamp;
1739 			f->f_prevcount++;
1740 			dprintf("msg repeated %d times, %ld sec of %d\n",
1741 			    f->f_prevcount, (long)(now - f->f_time),
1742 			    repeatinterval[f->f_repeatcount]);
1743 			/*
1744 			 * If domark would have logged this by now,
1745 			 * flush it now (so we don't hold isolated messages),
1746 			 * but back off so we'll flush less often
1747 			 * in the future.
1748 			 */
1749 			if (now > REPEATTIME(f)) {
1750 				fprintlog_successive(f, flags);
1751 				BACKOFF(f);
1752 			}
1753 		} else {
1754 			/* new line, save it */
1755 			if (f->f_prevcount)
1756 				fprintlog_successive(f, 0);
1757 			f->f_repeatcount = 0;
1758 			f->f_prevpri = pri;
1759 			f->f_lasttime = *timestamp;
1760 			static_assert(sizeof(f->f_prevline) == sizeof(saved),
1761 			    "Space to store saved line incorrect");
1762 			(void)strcpy(f->f_prevline, saved);
1763 			f->f_prevlen = savedlen;
1764 			fprintlog_first(f, hostname, app_name, procid, msgid,
1765 			    structured_data, msg, flags);
1766 		}
1767 	}
1768 }
1769 
1770 static void
1771 dofsync(void)
1772 {
1773 	struct filed *f;
1774 
1775 	STAILQ_FOREACH(f, &fhead, next) {
1776 		if ((f->f_type == F_FILE) &&
1777 		    (f->f_flags & FFLAG_NEEDSYNC)) {
1778 			f->f_flags &= ~FFLAG_NEEDSYNC;
1779 			(void)fsync(f->f_file);
1780 		}
1781 	}
1782 }
1783 
1784 /*
1785  * List of iovecs to which entries can be appended.
1786  * Used for constructing the message to be logged.
1787  */
1788 struct iovlist {
1789 	struct iovec	iov[TTYMSG_IOV_MAX];
1790 	size_t		iovcnt;
1791 	size_t		totalsize;
1792 };
1793 
1794 static void
1795 iovlist_init(struct iovlist *il)
1796 {
1797 
1798 	il->iovcnt = 0;
1799 	il->totalsize = 0;
1800 }
1801 
1802 static void
1803 iovlist_append(struct iovlist *il, const char *str)
1804 {
1805 	size_t size;
1806 
1807 	/* Discard components if we've run out of iovecs. */
1808 	if (il->iovcnt < nitems(il->iov)) {
1809 		size = strlen(str);
1810 		il->iov[il->iovcnt++] = (struct iovec){
1811 			.iov_base	= __DECONST(char *, str),
1812 			.iov_len	= size,
1813 		};
1814 		il->totalsize += size;
1815 	}
1816 }
1817 
1818 #if defined(INET) || defined(INET6)
1819 static void
1820 iovlist_truncate(struct iovlist *il, size_t size)
1821 {
1822 	struct iovec *last;
1823 	size_t diff;
1824 
1825 	while (il->totalsize > size) {
1826 		diff = il->totalsize - size;
1827 		last = &il->iov[il->iovcnt - 1];
1828 		if (diff >= last->iov_len) {
1829 			/* Remove the last iovec entirely. */
1830 			--il->iovcnt;
1831 			il->totalsize -= last->iov_len;
1832 		} else {
1833 			/* Remove the last iovec partially. */
1834 			last->iov_len -= diff;
1835 			il->totalsize -= diff;
1836 		}
1837 	}
1838 }
1839 #endif
1840 
1841 static void
1842 fprintlog_write(struct filed *f, struct iovlist *il, int flags)
1843 {
1844 	struct msghdr msghdr;
1845 	struct addrinfo *r;
1846 	struct socklist *sl;
1847 	const char *msgret;
1848 	ssize_t lsent;
1849 
1850 	switch (f->f_type) {
1851 	case F_FORW:
1852 		dprintf(" %s", f->fu_forw_hname);
1853 		switch (f->fu_forw_addr->ai_family) {
1854 #ifdef INET
1855 		case AF_INET:
1856 			dprintf(":%d\n",
1857 			    ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1858 			break;
1859 #endif
1860 #ifdef INET6
1861 		case AF_INET6:
1862 			dprintf(":%d\n",
1863 			    ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1864 			break;
1865 #endif
1866 		default:
1867 			dprintf("\n");
1868 		}
1869 
1870 #if defined(INET) || defined(INET6)
1871 		/* Truncate messages to maximum forward length. */
1872 		iovlist_truncate(il, MaxForwardLen);
1873 #endif
1874 
1875 		lsent = 0;
1876 		for (r = f->fu_forw_addr; r; r = r->ai_next) {
1877 			memset(&msghdr, 0, sizeof(msghdr));
1878 			msghdr.msg_name = r->ai_addr;
1879 			msghdr.msg_namelen = r->ai_addrlen;
1880 			msghdr.msg_iov = il->iov;
1881 			msghdr.msg_iovlen = il->iovcnt;
1882 			STAILQ_FOREACH(sl, &shead, next) {
1883 				if (sl->sl_socket < 0)
1884 					continue;
1885 				if (sl->sl_sa == NULL ||
1886 				    sl->sl_family == AF_UNSPEC ||
1887 				    sl->sl_family == AF_LOCAL)
1888 					continue;
1889 				lsent = sendmsg(sl->sl_socket, &msghdr, 0);
1890 				if (lsent == (ssize_t)il->totalsize)
1891 					break;
1892 			}
1893 			if (lsent == (ssize_t)il->totalsize && !send_to_all)
1894 				break;
1895 		}
1896 		dprintf("lsent/totalsize: %zd/%zu\n", lsent, il->totalsize);
1897 		if (lsent != (ssize_t)il->totalsize) {
1898 			int e = errno;
1899 			logerror("sendto");
1900 			errno = e;
1901 			switch (errno) {
1902 			case ENOBUFS:
1903 			case ENETDOWN:
1904 			case ENETUNREACH:
1905 			case EHOSTUNREACH:
1906 			case EHOSTDOWN:
1907 			case EADDRNOTAVAIL:
1908 				break;
1909 			/* case EBADF: */
1910 			/* case EACCES: */
1911 			/* case ENOTSOCK: */
1912 			/* case EFAULT: */
1913 			/* case EMSGSIZE: */
1914 			/* case EAGAIN: */
1915 			/* case ENOBUFS: */
1916 			/* case ECONNREFUSED: */
1917 			default:
1918 				dprintf("removing entry: errno=%d\n", e);
1919 				f->f_type = F_UNUSED;
1920 				break;
1921 			}
1922 		}
1923 		break;
1924 
1925 	case F_FILE:
1926 		dprintf(" %s\n", f->fu_fname);
1927 		iovlist_append(il, "\n");
1928 		if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1929 			/*
1930 			 * If writev(2) fails for potentially transient errors
1931 			 * like the filesystem being full, ignore it.
1932 			 * Otherwise remove this logfile from the list.
1933 			 */
1934 			if (errno != ENOSPC) {
1935 				int e = errno;
1936 				close_filed(f);
1937 				errno = e;
1938 				logerror(f->fu_fname);
1939 			}
1940 		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1941 			f->f_flags |= FFLAG_NEEDSYNC;
1942 			needdofsync = 1;
1943 		}
1944 		break;
1945 
1946 	case F_PIPE:
1947 		dprintf(" %s\n", f->fu_pipe_pname);
1948 		iovlist_append(il, "\n");
1949 		if (f->fu_pipe_pid == 0) {
1950 			if ((f->f_file = p_open(f->fu_pipe_pname,
1951 						&f->fu_pipe_pid)) < 0) {
1952 				logerror(f->fu_pipe_pname);
1953 				break;
1954 			}
1955 		}
1956 		if (writev(f->f_file, il->iov, il->iovcnt) < 0) {
1957 			int e = errno;
1958 
1959 			deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1960 			close_filed(f);
1961 			errno = e;
1962 			logerror(f->fu_pipe_pname);
1963 		}
1964 		break;
1965 
1966 	case F_CONSOLE:
1967 		if (flags & IGN_CONS) {
1968 			dprintf(" (ignored)\n");
1969 			break;
1970 		}
1971 		/* FALLTHROUGH */
1972 
1973 	case F_TTY:
1974 		dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1975 		iovlist_append(il, "\r\n");
1976 		errno = 0;	/* ttymsg() only sometimes returns an errno */
1977 		if ((msgret = ttymsg(il->iov, il->iovcnt, f->fu_fname, 10))) {
1978 			f->f_type = F_UNUSED;
1979 			logerror(msgret);
1980 		}
1981 		break;
1982 
1983 	case F_USERS:
1984 	case F_WALL:
1985 		dprintf("\n");
1986 		iovlist_append(il, "\r\n");
1987 		wallmsg(f, il->iov, il->iovcnt);
1988 		break;
1989 	}
1990 }
1991 
1992 static void
1993 fprintlog_rfc5424(struct filed *f, const char *hostname, const char *app_name,
1994     const char *procid, const char *msgid, const char *structured_data,
1995     const char *msg, int flags)
1996 {
1997 	struct iovlist il;
1998 	suseconds_t usec;
1999 	int i;
2000 	char timebuf[33], priority_number[5];
2001 
2002 	iovlist_init(&il);
2003 	if (f->f_type == F_WALL)
2004 		iovlist_append(&il, "\r\n\aMessage from syslogd ...\r\n");
2005 	iovlist_append(&il, "<");
2006 	snprintf(priority_number, sizeof(priority_number), "%d", f->f_prevpri);
2007 	iovlist_append(&il, priority_number);
2008 	iovlist_append(&il, ">1 ");
2009 	if (strftime(timebuf, sizeof(timebuf), "%FT%T.______%z",
2010 	    &f->f_lasttime.tm) == sizeof(timebuf) - 2) {
2011 		/* Add colon to the time zone offset, which %z doesn't do. */
2012 		timebuf[32] = '\0';
2013 		timebuf[31] = timebuf[30];
2014 		timebuf[30] = timebuf[29];
2015 		timebuf[29] = ':';
2016 
2017 		/* Overwrite space for microseconds with actual value. */
2018 		usec = f->f_lasttime.usec;
2019 		for (i = 25; i >= 20; --i) {
2020 			timebuf[i] = usec % 10 + '0';
2021 			usec /= 10;
2022 		}
2023 		iovlist_append(&il, timebuf);
2024 	} else
2025 		iovlist_append(&il, "-");
2026 	iovlist_append(&il, " ");
2027 	iovlist_append(&il, hostname);
2028 	iovlist_append(&il, " ");
2029 	iovlist_append(&il, app_name == NULL ? "-" : app_name);
2030 	iovlist_append(&il, " ");
2031 	iovlist_append(&il, procid == NULL ? "-" : procid);
2032 	iovlist_append(&il, " ");
2033 	iovlist_append(&il, msgid == NULL ? "-" : msgid);
2034 	iovlist_append(&il, " ");
2035 	iovlist_append(&il, structured_data == NULL ? "-" : structured_data);
2036 	iovlist_append(&il, " ");
2037 	iovlist_append(&il, msg);
2038 
2039 	fprintlog_write(f, &il, flags);
2040 }
2041 
2042 static void
2043 fprintlog_rfc3164(struct filed *f, const char *hostname, const char *app_name,
2044     const char *procid, const char *msg, int flags)
2045 {
2046 	struct iovlist il;
2047 	const CODE *c;
2048 	int facility, priority;
2049 	char timebuf[RFC3164_DATELEN + 1], facility_number[5],
2050 	    priority_number[5];
2051 	bool facility_found, priority_found;
2052 
2053 	if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
2054 	    &f->f_lasttime.tm) == 0)
2055 		timebuf[0] = '\0';
2056 
2057 	iovlist_init(&il);
2058 	switch (f->f_type) {
2059 	case F_FORW:
2060 		/* Message forwarded over the network. */
2061 		iovlist_append(&il, "<");
2062 		snprintf(priority_number, sizeof(priority_number), "%d",
2063 		    f->f_prevpri);
2064 		iovlist_append(&il, priority_number);
2065 		iovlist_append(&il, ">");
2066 		iovlist_append(&il, timebuf);
2067 		if (strcasecmp(hostname, LocalHostName) != 0) {
2068 			iovlist_append(&il, " Forwarded from ");
2069 			iovlist_append(&il, hostname);
2070 			iovlist_append(&il, ":");
2071 		}
2072 		iovlist_append(&il, " ");
2073 		break;
2074 
2075 	case F_WALL:
2076 		/* Message written to terminals. */
2077 		iovlist_append(&il, "\r\n\aMessage from syslogd@");
2078 		iovlist_append(&il, hostname);
2079 		iovlist_append(&il, " at ");
2080 		iovlist_append(&il, timebuf);
2081 		iovlist_append(&il, " ...\r\n");
2082 		break;
2083 
2084 	default:
2085 		/* Message written to files. */
2086 		iovlist_append(&il, timebuf);
2087 		iovlist_append(&il, " ");
2088 
2089 		if (LogFacPri) {
2090 			iovlist_append(&il, "<");
2091 
2092 			facility = f->f_prevpri & LOG_FACMASK;
2093 			facility_found = false;
2094 			if (LogFacPri > 1) {
2095 				for (c = facilitynames; c->c_name; c++) {
2096 					if (c->c_val == facility) {
2097 						iovlist_append(&il, c->c_name);
2098 						facility_found = true;
2099 						break;
2100 					}
2101 				}
2102 			}
2103 			if (!facility_found) {
2104 				snprintf(facility_number,
2105 				    sizeof(facility_number), "%d",
2106 				    LOG_FAC(facility));
2107 				iovlist_append(&il, facility_number);
2108 			}
2109 
2110 			iovlist_append(&il, ".");
2111 
2112 			priority = LOG_PRI(f->f_prevpri);
2113 			priority_found = false;
2114 			if (LogFacPri > 1) {
2115 				for (c = prioritynames; c->c_name; c++) {
2116 					if (c->c_val == priority) {
2117 						iovlist_append(&il, c->c_name);
2118 						priority_found = true;
2119 						break;
2120 					}
2121 				}
2122 			}
2123 			if (!priority_found) {
2124 				snprintf(priority_number,
2125 				    sizeof(priority_number), "%d", priority);
2126 				iovlist_append(&il, priority_number);
2127 			}
2128 
2129 			iovlist_append(&il, "> ");
2130 		}
2131 
2132 		iovlist_append(&il, hostname);
2133 		iovlist_append(&il, " ");
2134 		break;
2135 	}
2136 
2137 	/* Message body with application name and process ID prefixed. */
2138 	if (app_name != NULL) {
2139 		iovlist_append(&il, app_name);
2140 		if (procid != NULL) {
2141 			iovlist_append(&il, "[");
2142 			iovlist_append(&il, procid);
2143 			iovlist_append(&il, "]");
2144 		}
2145 		iovlist_append(&il, ": ");
2146 	}
2147 	iovlist_append(&il, msg);
2148 
2149 	fprintlog_write(f, &il, flags);
2150 }
2151 
2152 static void
2153 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
2154     const char *procid, const char *msgid __unused,
2155     const char *structured_data __unused, const char *msg, int flags)
2156 {
2157 
2158 	dprintf("Logging to %s", TypeNames[f->f_type]);
2159 	f->f_time = now;
2160 	f->f_prevcount = 0;
2161 	if (f->f_type == F_UNUSED) {
2162 		dprintf("\n");
2163 		return;
2164 	}
2165 
2166 	if (RFC3164OutputFormat)
2167 		fprintlog_rfc3164(f, hostname, app_name, procid, msg, flags);
2168 	else
2169 		fprintlog_rfc5424(f, hostname, app_name, procid, msgid,
2170 		    structured_data, msg, flags);
2171 }
2172 
2173 /*
2174  * Prints a message to a log file that the previously logged message was
2175  * received multiple times.
2176  */
2177 static void
2178 fprintlog_successive(struct filed *f, int flags)
2179 {
2180 	char msg[100];
2181 
2182 	assert(f->f_prevcount > 0);
2183 	snprintf(msg, sizeof(msg), "last message repeated %d times",
2184 	    f->f_prevcount);
2185 	fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
2186 	    flags);
2187 }
2188 
2189 /*
2190  *  WALLMSG -- Write a message to the world at large
2191  *
2192  *	Write the specified message to either the entire
2193  *	world, or a list of approved users.
2194  */
2195 static void
2196 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
2197 {
2198 	static int reenter;			/* avoid calling ourselves */
2199 	struct utmpx *ut;
2200 	int i;
2201 	const char *p;
2202 
2203 	if (reenter++)
2204 		return;
2205 	setutxent();
2206 	/* NOSTRICT */
2207 	while ((ut = getutxent()) != NULL) {
2208 		if (ut->ut_type != USER_PROCESS)
2209 			continue;
2210 		if (f->f_type == F_WALL) {
2211 			if ((p = ttymsg(iov, iovlen, ut->ut_line,
2212 			    TTYMSGTIME)) != NULL) {
2213 				errno = 0;	/* already in msg */
2214 				logerror(p);
2215 			}
2216 			continue;
2217 		}
2218 		/* should we send the message to this user? */
2219 		for (i = 0; i < MAXUNAMES; i++) {
2220 			if (!f->fu_uname[i][0])
2221 				break;
2222 			if (!strcmp(f->fu_uname[i], ut->ut_user)) {
2223 				if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
2224 				    TTYMSGTIME)) != NULL) {
2225 					errno = 0;	/* already in msg */
2226 					logerror(p);
2227 				}
2228 				break;
2229 			}
2230 		}
2231 	}
2232 	endutxent();
2233 	reenter = 0;
2234 }
2235 
2236 /*
2237  * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
2238  */
2239 static const char *
2240 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
2241 {
2242 	static char device[1024];
2243 	static char errbuf[1024];
2244 	struct stat sb;
2245 
2246 	(void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
2247 
2248 	if (stat(device, &sb) < 0) {
2249 		(void) snprintf(errbuf, sizeof(errbuf),
2250 		    "%s: %s", device, strerror(errno));
2251 		return (errbuf);
2252 	}
2253 	if ((sb.st_mode & S_IWGRP) == 0)
2254 		/* Messages disabled. */
2255 		return (NULL);
2256 	return ttymsg(iov, iovcnt, line, tmout);
2257 }
2258 
2259 static void
2260 reapchild(int signo __unused)
2261 {
2262 	int status;
2263 	pid_t pid;
2264 	struct filed *f;
2265 
2266 	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
2267 		/* First, look if it's a process from the dead queue. */
2268 		if (deadq_removebypid(pid))
2269 			continue;
2270 
2271 		/* Now, look in list of active processes. */
2272 		STAILQ_FOREACH(f, &fhead, next) {
2273 			if (f->f_type == F_PIPE &&
2274 			    f->fu_pipe_pid == pid) {
2275 				close_filed(f);
2276 				log_deadchild(pid, status, f->fu_pipe_pname);
2277 				break;
2278 			}
2279 		}
2280 	}
2281 	WantReapchild = 0;
2282 }
2283 
2284 /*
2285  * Return a printable representation of a host address.
2286  */
2287 static const char *
2288 cvthname(struct sockaddr *f)
2289 {
2290 	int error, hl;
2291 	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
2292 
2293 	dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
2294 	error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
2295 		    NI_NUMERICHOST);
2296 	if (error) {
2297 		dprintf("Malformed from address %s\n", gai_strerror(error));
2298 		return ("???");
2299 	}
2300 	dprintf("cvthname(%s)\n", ip);
2301 
2302 	if (!resolve)
2303 		return (ip);
2304 
2305 	error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
2306 		    NULL, 0, NI_NAMEREQD);
2307 	if (error) {
2308 		dprintf("Host name for your address (%s) unknown\n", ip);
2309 		return (ip);
2310 	}
2311 	hl = strlen(hname);
2312 	if (hl > 0 && hname[hl-1] == '.')
2313 		hname[--hl] = '\0';
2314 	/* RFC 5424 prefers logging FQDNs. */
2315 	if (RFC3164OutputFormat)
2316 		trimdomain(hname, hl);
2317 	return (hname);
2318 }
2319 
2320 static void
2321 dodie(int signo)
2322 {
2323 
2324 	WantDie = signo;
2325 }
2326 
2327 static void
2328 domark(int signo __unused)
2329 {
2330 
2331 	MarkSet = 1;
2332 }
2333 
2334 /*
2335  * Print syslogd errors some place.
2336  */
2337 static void
2338 logerror(const char *msg)
2339 {
2340 	char buf[512];
2341 	static int recursed = 0;
2342 
2343 	/* If there's an error while trying to log an error, give up. */
2344 	if (recursed)
2345 		return;
2346 	recursed++;
2347 	if (errno != 0) {
2348 		(void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2349 		    strerror(errno));
2350 		msg = buf;
2351 	}
2352 	errno = 0;
2353 	dprintf("%s\n", buf);
2354 	logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2355 	    NULL, msg, 0);
2356 	recursed--;
2357 }
2358 
2359 static void
2360 die(int signo)
2361 {
2362 	struct filed *f;
2363 	struct socklist *sl;
2364 	char buf[100];
2365 
2366 	STAILQ_FOREACH(f, &fhead, next) {
2367 		/* flush any pending output */
2368 		if (f->f_prevcount)
2369 			fprintlog_successive(f, 0);
2370 		if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2371 			close_filed(f);
2372 	}
2373 	if (signo) {
2374 		dprintf("syslogd: exiting on signal %d\n", signo);
2375 		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2376 		errno = 0;
2377 		logerror(buf);
2378 	}
2379 	STAILQ_FOREACH(sl, &shead, next) {
2380 		if (sl->sl_sa != NULL && sl->sl_family == AF_LOCAL)
2381 			unlink(sl->sl_peer->pe_name);
2382 	}
2383 	pidfile_remove(pfh);
2384 
2385 	exit(1);
2386 }
2387 
2388 static int
2389 configfiles(const struct dirent *dp)
2390 {
2391 	const char *p;
2392 	size_t ext_len;
2393 
2394 	if (dp->d_name[0] == '.')
2395 		return (0);
2396 
2397 	ext_len = sizeof(include_ext) -1;
2398 
2399 	if (dp->d_namlen <= ext_len)
2400 		return (0);
2401 
2402 	p = &dp->d_name[dp->d_namlen - ext_len];
2403 	if (strcmp(p, include_ext) != 0)
2404 		return (0);
2405 
2406 	return (1);
2407 }
2408 
2409 static void
2410 readconfigfile(FILE *cf, int allow_includes)
2411 {
2412 	FILE *cf2;
2413 	struct filed *f;
2414 	struct dirent **ent;
2415 	char cline[LINE_MAX];
2416 	char host[MAXHOSTNAMELEN];
2417 	char prog[LINE_MAX];
2418 	char file[MAXPATHLEN];
2419 	char pfilter[LINE_MAX];
2420 	char *p, *tmp;
2421 	int i, nents;
2422 	size_t include_len;
2423 
2424 	/*
2425 	 *  Foreach line in the conf table, open that file.
2426 	 */
2427 	include_len = sizeof(include_str) -1;
2428 	(void)strlcpy(host, "*", sizeof(host));
2429 	(void)strlcpy(prog, "*", sizeof(prog));
2430 	(void)strlcpy(pfilter, "*", sizeof(pfilter));
2431 	while (fgets(cline, sizeof(cline), cf) != NULL) {
2432 		/*
2433 		 * check for end-of-section, comments, strip off trailing
2434 		 * spaces and newline character. #!prog is treated specially:
2435 		 * following lines apply only to that program.
2436 		 */
2437 		for (p = cline; isspace(*p); ++p)
2438 			continue;
2439 		if (*p == 0)
2440 			continue;
2441 		if (allow_includes &&
2442 		    strncmp(p, include_str, include_len) == 0 &&
2443 		    isspace(p[include_len])) {
2444 			p += include_len;
2445 			while (isspace(*p))
2446 				p++;
2447 			tmp = p;
2448 			while (*tmp != '\0' && !isspace(*tmp))
2449 				tmp++;
2450 			*tmp = '\0';
2451 			dprintf("Trying to include files in '%s'\n", p);
2452 			nents = scandir(p, &ent, configfiles, alphasort);
2453 			if (nents == -1) {
2454 				dprintf("Unable to open '%s': %s\n", p,
2455 				    strerror(errno));
2456 				continue;
2457 			}
2458 			for (i = 0; i < nents; i++) {
2459 				if (snprintf(file, sizeof(file), "%s/%s", p,
2460 				    ent[i]->d_name) >= (int)sizeof(file)) {
2461 					dprintf("ignoring path too long: "
2462 					    "'%s/%s'\n", p, ent[i]->d_name);
2463 					free(ent[i]);
2464 					continue;
2465 				}
2466 				free(ent[i]);
2467 				cf2 = fopen(file, "r");
2468 				if (cf2 == NULL)
2469 					continue;
2470 				dprintf("reading %s\n", file);
2471 				readconfigfile(cf2, 0);
2472 				fclose(cf2);
2473 			}
2474 			free(ent);
2475 			continue;
2476 		}
2477 		if (*p == '#') {
2478 			p++;
2479 			if (*p == '\0' || strchr("!+-:", *p) == NULL)
2480 				continue;
2481 		}
2482 		if (*p == '+' || *p == '-') {
2483 			host[0] = *p++;
2484 			while (isspace(*p))
2485 				p++;
2486 			if ((!*p) || (*p == '*')) {
2487 				(void)strlcpy(host, "*", sizeof(host));
2488 				continue;
2489 			}
2490 			if (*p == '@')
2491 				p = LocalHostName;
2492 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2493 				if (!isalnum(*p) && *p != '.' && *p != '-'
2494 				    && *p != ',' && *p != ':' && *p != '%')
2495 					break;
2496 				host[i] = *p++;
2497 			}
2498 			host[i] = '\0';
2499 			continue;
2500 		}
2501 		if (*p == '!') {
2502 			p++;
2503 			while (isspace(*p)) p++;
2504 			if ((!*p) || (*p == '*')) {
2505 				(void)strlcpy(prog, "*", sizeof(prog));
2506 				continue;
2507 			}
2508 			for (i = 0; i < LINE_MAX - 1; i++) {
2509 				if (!isprint(p[i]) || isspace(p[i]))
2510 					break;
2511 				prog[i] = p[i];
2512 			}
2513 			prog[i] = 0;
2514 			continue;
2515 		}
2516 		if (*p == ':') {
2517 			p++;
2518 			while (isspace(*p))
2519 				p++;
2520 			if ((!*p) || (*p == '*')) {
2521 				(void)strlcpy(pfilter, "*", sizeof(pfilter));
2522 				continue;
2523 			}
2524 			(void)strlcpy(pfilter, p, sizeof(pfilter));
2525 			continue;
2526 		}
2527 		for (p = cline + 1; *p != '\0'; p++) {
2528 			if (*p != '#')
2529 				continue;
2530 			if (*(p - 1) == '\\') {
2531 				strcpy(p - 1, p);
2532 				p--;
2533 				continue;
2534 			}
2535 			*p = '\0';
2536 			break;
2537 		}
2538 		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2539 			cline[i] = '\0';
2540 		f = cfline(cline, prog, host, pfilter);
2541 		if (f != NULL)
2542 			addfile(f);
2543 		free(f);
2544 	}
2545 }
2546 
2547 static void
2548 sighandler(int signo)
2549 {
2550 
2551 	/* Send an wake-up signal to the select() loop. */
2552 	write(sigpipe[1], &signo, sizeof(signo));
2553 }
2554 
2555 /*
2556  *  INIT -- Initialize syslogd from configuration table
2557  */
2558 static void
2559 init(int signo)
2560 {
2561 	int i;
2562 	FILE *cf;
2563 	struct filed *f;
2564 	char *p;
2565 	char oldLocalHostName[MAXHOSTNAMELEN];
2566 	char hostMsg[2*MAXHOSTNAMELEN+40];
2567 	char bootfileMsg[MAXLINE + 1];
2568 
2569 	dprintf("init\n");
2570 	WantInitialize = 0;
2571 
2572 	/*
2573 	 * Load hostname (may have changed).
2574 	 */
2575 	if (signo != 0)
2576 		(void)strlcpy(oldLocalHostName, LocalHostName,
2577 		    sizeof(oldLocalHostName));
2578 	if (gethostname(LocalHostName, sizeof(LocalHostName)))
2579 		err(EX_OSERR, "gethostname() failed");
2580 	if ((p = strchr(LocalHostName, '.')) != NULL) {
2581 		/* RFC 5424 prefers logging FQDNs. */
2582 		if (RFC3164OutputFormat)
2583 			*p = '\0';
2584 		LocalDomain = p + 1;
2585 	} else {
2586 		LocalDomain = "";
2587 	}
2588 
2589 	/*
2590 	 * Load / reload timezone data (in case it changed).
2591 	 *
2592 	 * Just calling tzset() again does not work, the timezone code
2593 	 * caches the result.  However, by setting the TZ variable, one
2594 	 * can defeat the caching and have the timezone code really
2595 	 * reload the timezone data.  Respect any initial setting of
2596 	 * TZ, in case the system is configured specially.
2597 	 */
2598 	dprintf("loading timezone data via tzset()\n");
2599 	if (getenv("TZ")) {
2600 		tzset();
2601 	} else {
2602 		setenv("TZ", ":/etc/localtime", 1);
2603 		tzset();
2604 		unsetenv("TZ");
2605 	}
2606 
2607 	/*
2608 	 *  Close all open log files.
2609 	 */
2610 	Initialized = 0;
2611 	STAILQ_FOREACH(f, &fhead, next) {
2612 		/* flush any pending output */
2613 		if (f->f_prevcount)
2614 			fprintlog_successive(f, 0);
2615 
2616 		switch (f->f_type) {
2617 		case F_FILE:
2618 		case F_FORW:
2619 		case F_CONSOLE:
2620 		case F_TTY:
2621 			close_filed(f);
2622 			break;
2623 		case F_PIPE:
2624 			deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2625 			close_filed(f);
2626 			break;
2627 		}
2628 	}
2629 	while(!STAILQ_EMPTY(&fhead)) {
2630 		f = STAILQ_FIRST(&fhead);
2631 		STAILQ_REMOVE_HEAD(&fhead, next);
2632 		free(f->f_program);
2633 		free(f->f_host);
2634 		if (f->f_prop_filter) {
2635 			switch (f->f_prop_filter->cmp_type) {
2636 			case PROP_CMP_REGEX:
2637 				regfree(f->f_prop_filter->pflt_re);
2638 				free(f->f_prop_filter->pflt_re);
2639 				break;
2640 			case PROP_CMP_CONTAINS:
2641 			case PROP_CMP_EQUAL:
2642 			case PROP_CMP_STARTS:
2643 				free(f->f_prop_filter->pflt_strval);
2644 				break;
2645 			}
2646 			free(f->f_prop_filter);
2647 		}
2648 		free(f);
2649 	}
2650 
2651 	/* open the configuration file */
2652 	if ((cf = fopen(ConfFile, "r")) == NULL) {
2653 		dprintf("cannot open %s\n", ConfFile);
2654 		f = cfline("*.ERR\t/dev/console", "*", "*", "*");
2655 		if (f != NULL)
2656 			addfile(f);
2657 		free(f);
2658 		f = cfline("*.PANIC\t*", "*", "*", "*");
2659 		if (f != NULL)
2660 			addfile(f);
2661 		free(f);
2662 		Initialized = 1;
2663 
2664 		return;
2665 	}
2666 
2667 	readconfigfile(cf, 1);
2668 
2669 	/* close the configuration file */
2670 	(void)fclose(cf);
2671 
2672 	Initialized = 1;
2673 
2674 	if (Debug) {
2675 		int port;
2676 		STAILQ_FOREACH(f, &fhead, next) {
2677 			for (i = 0; i <= LOG_NFACILITIES; i++)
2678 				if (f->f_pmask[i] == INTERNAL_NOPRI)
2679 					printf("X ");
2680 				else
2681 					printf("%d ", f->f_pmask[i]);
2682 			printf("%s: ", TypeNames[f->f_type]);
2683 			switch (f->f_type) {
2684 			case F_FILE:
2685 				printf("%s", f->fu_fname);
2686 				break;
2687 
2688 			case F_CONSOLE:
2689 			case F_TTY:
2690 				printf("%s%s", _PATH_DEV, f->fu_fname);
2691 				break;
2692 
2693 			case F_FORW:
2694 				switch (f->fu_forw_addr->ai_family) {
2695 #ifdef INET
2696 				case AF_INET:
2697 					port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2698 					break;
2699 #endif
2700 #ifdef INET6
2701 				case AF_INET6:
2702 					port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2703 					break;
2704 #endif
2705 				default:
2706 					port = 0;
2707 				}
2708 				if (port != 514) {
2709 					printf("%s:%d",
2710 						f->fu_forw_hname, port);
2711 				} else {
2712 					printf("%s", f->fu_forw_hname);
2713 				}
2714 				break;
2715 
2716 			case F_PIPE:
2717 				printf("%s", f->fu_pipe_pname);
2718 				break;
2719 
2720 			case F_USERS:
2721 				for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2722 					printf("%s, ", f->fu_uname[i]);
2723 				break;
2724 			}
2725 			if (f->f_program)
2726 				printf(" (%s)", f->f_program);
2727 			printf("\n");
2728 		}
2729 	}
2730 
2731 	logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2732 	    NULL, NULL, "restart", 0);
2733 	dprintf("syslogd: restarted\n");
2734 	/*
2735 	 * Log a change in hostname, but only on a restart.
2736 	 */
2737 	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2738 		(void)snprintf(hostMsg, sizeof(hostMsg),
2739 		    "hostname changed, \"%s\" to \"%s\"",
2740 		    oldLocalHostName, LocalHostName);
2741 		logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2742 		    NULL, NULL, NULL, hostMsg, 0);
2743 		dprintf("%s\n", hostMsg);
2744 	}
2745 	/*
2746 	 * Log the kernel boot file if we aren't going to use it as
2747 	 * the prefix, and if this is *not* a restart.
2748 	 */
2749 	if (signo == 0 && !use_bootfile) {
2750 		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2751 		    "kernel boot file is %s", bootfile);
2752 		logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2753 		    NULL, NULL, NULL, bootfileMsg, 0);
2754 		dprintf("%s\n", bootfileMsg);
2755 	}
2756 }
2757 
2758 /*
2759  * Compile property-based filter.
2760  * Returns 0 on success, -1 otherwise.
2761  */
2762 static int
2763 prop_filter_compile(struct prop_filter *pfilter, char *filter)
2764 {
2765 	char *filter_endpos, *p;
2766 	char **ap, *argv[2] = {NULL, NULL};
2767 	int re_flags = REG_NOSUB;
2768 	int escaped;
2769 
2770 	bzero(pfilter, sizeof(struct prop_filter));
2771 
2772 	/*
2773 	 * Here's some filter examples mentioned in syslog.conf(5)
2774 	 * 'msg, contains, ".*Deny.*"'
2775 	 * 'programname, regex, "^bird6?$"'
2776 	 * 'hostname, icase_ereregex, "^server-(dcA|podB)-rack1[0-9]{2}\\..*"'
2777 	 */
2778 
2779 	/*
2780 	 * Split filter into 3 parts: property name (argv[0]),
2781 	 * cmp type (argv[1]) and lvalue for comparison (filter).
2782 	 */
2783 	for (ap = argv; (*ap = strsep(&filter, ", \t\n")) != NULL;) {
2784 		if (**ap != '\0')
2785 			if (++ap >= &argv[2])
2786 				break;
2787 	}
2788 
2789 	if (argv[0] == NULL || argv[1] == NULL) {
2790 		logerror("filter parse error");
2791 		return (-1);
2792 	}
2793 
2794 	/* fill in prop_type */
2795 	if (strcasecmp(argv[0], "msg") == 0)
2796 		pfilter->prop_type = PROP_TYPE_MSG;
2797 	else if(strcasecmp(argv[0], "hostname") == 0)
2798 		pfilter->prop_type = PROP_TYPE_HOSTNAME;
2799 	else if(strcasecmp(argv[0], "source") == 0)
2800 		pfilter->prop_type = PROP_TYPE_HOSTNAME;
2801 	else if(strcasecmp(argv[0], "programname") == 0)
2802 		pfilter->prop_type = PROP_TYPE_PROGNAME;
2803 	else {
2804 		logerror("unknown property");
2805 		return (-1);
2806 	}
2807 
2808 	/* full in cmp_flags (i.e. !contains, icase_regex, etc.) */
2809 	if (*argv[1] == '!') {
2810 		pfilter->cmp_flags |= PROP_FLAG_EXCLUDE;
2811 		argv[1]++;
2812 	}
2813 	if (strncasecmp(argv[1], "icase_", (sizeof("icase_") - 1)) == 0) {
2814 		pfilter->cmp_flags |= PROP_FLAG_ICASE;
2815 		argv[1] += sizeof("icase_") - 1;
2816 	}
2817 
2818 	/* fill in cmp_type */
2819 	if (strcasecmp(argv[1], "contains") == 0)
2820 		pfilter->cmp_type = PROP_CMP_CONTAINS;
2821 	else if (strcasecmp(argv[1], "isequal") == 0)
2822 		pfilter->cmp_type = PROP_CMP_EQUAL;
2823 	else if (strcasecmp(argv[1], "startswith") == 0)
2824 		pfilter->cmp_type = PROP_CMP_STARTS;
2825 	else if (strcasecmp(argv[1], "regex") == 0)
2826 		pfilter->cmp_type = PROP_CMP_REGEX;
2827 	else if (strcasecmp(argv[1], "ereregex") == 0) {
2828 		pfilter->cmp_type = PROP_CMP_REGEX;
2829 		re_flags |= REG_EXTENDED;
2830 	} else {
2831 		logerror("unknown cmp function");
2832 		return (-1);
2833 	}
2834 
2835 	/*
2836 	 * Handle filter value
2837 	 */
2838 
2839 	/* ' ".*Deny.*"' */
2840 	/* remove leading whitespace and check for '"' next character  */
2841 	filter += strspn(filter, ", \t\n");
2842 	if (*filter != '"' || strlen(filter) < 3) {
2843 		logerror("property value parse error");
2844 		return (-1);
2845 	}
2846 	filter++;
2847 
2848 	/* '.*Deny.*"' */
2849 	/* process possible backslash (\") escaping */
2850 	escaped = 0;
2851 	filter_endpos = filter;
2852 	for (p = filter; *p != '\0'; p++) {
2853 		if (*p == '\\' && !escaped) {
2854 			escaped = 1;
2855 			/* do not shift filter_endpos */
2856 			continue;
2857 		}
2858 		if (*p == '"' && !escaped) {
2859 			p++;
2860 			break;
2861 		}
2862 		/* we've seen some esc symbols, need to compress the line */
2863 		if (filter_endpos != p)
2864 			*filter_endpos = *p;
2865 
2866 		filter_endpos++;
2867 		escaped = 0;
2868 	}
2869 
2870 	*filter_endpos = '\0';
2871 	/* '.*Deny.*' */
2872 
2873 	/* We should not have anything but whitespace left after closing '"' */
2874 	if (*p != '\0' && strspn(p, " \t\n") != strlen(p)) {
2875 		logerror("property value parse error");
2876 		return (-1);
2877 	}
2878 
2879 	if (pfilter->cmp_type == PROP_CMP_REGEX) {
2880 		pfilter->pflt_re = calloc(1, sizeof(*pfilter->pflt_re));
2881 		if (pfilter->pflt_re == NULL) {
2882 			logerror("RE calloc() error");
2883 			free(pfilter->pflt_re);
2884 			return (-1);
2885 		}
2886 		if (pfilter->cmp_flags & PROP_FLAG_ICASE)
2887 			re_flags |= REG_ICASE;
2888 		if (regcomp(pfilter->pflt_re, filter, re_flags) != 0) {
2889 			logerror("RE compilation error");
2890 			free(pfilter->pflt_re);
2891 			return (-1);
2892 		}
2893 	} else {
2894 		pfilter->pflt_strval = strdup(filter);
2895 		pfilter->pflt_strlen = strlen(filter);
2896 	}
2897 
2898 	return (0);
2899 
2900 }
2901 
2902 /*
2903  * Crack a configuration file line
2904  */
2905 static struct filed *
2906 cfline(const char *line, const char *prog, const char *host,
2907     const char *pfilter)
2908 {
2909 	struct filed *f;
2910 	struct addrinfo hints, *res;
2911 	int error, i, pri, syncfile;
2912 	const char *p, *q;
2913 	char *bp, *pfilter_dup;
2914 	char buf[LINE_MAX], ebuf[100];
2915 
2916 	dprintf("cfline(\"%s\", f, \"%s\", \"%s\", \"%s\")\n", line, prog,
2917 	    host, pfilter);
2918 
2919 	f = calloc(1, sizeof(*f));
2920 	if (f == NULL) {
2921 		logerror("malloc");
2922 		exit(1);
2923 	}
2924 	errno = 0;	/* keep strerror() stuff out of logerror messages */
2925 
2926 	for (i = 0; i <= LOG_NFACILITIES; i++)
2927 		f->f_pmask[i] = INTERNAL_NOPRI;
2928 
2929 	/* save hostname if any */
2930 	if (host && *host == '*')
2931 		host = NULL;
2932 	if (host) {
2933 		int hl;
2934 
2935 		f->f_host = strdup(host);
2936 		if (f->f_host == NULL) {
2937 			logerror("strdup");
2938 			exit(1);
2939 		}
2940 		hl = strlen(f->f_host);
2941 		if (hl > 0 && f->f_host[hl-1] == '.')
2942 			f->f_host[--hl] = '\0';
2943 		/* RFC 5424 prefers logging FQDNs. */
2944 		if (RFC3164OutputFormat)
2945 			trimdomain(f->f_host, hl);
2946 	}
2947 
2948 	/* save program name if any */
2949 	if (prog && *prog == '*')
2950 		prog = NULL;
2951 	if (prog) {
2952 		f->f_program = strdup(prog);
2953 		if (f->f_program == NULL) {
2954 			logerror("strdup");
2955 			exit(1);
2956 		}
2957 	}
2958 
2959 	if (pfilter) {
2960 		f->f_prop_filter = calloc(1, sizeof(*(f->f_prop_filter)));
2961 		if (f->f_prop_filter == NULL) {
2962 			logerror("pfilter calloc");
2963 			exit(1);
2964 		}
2965 		if (*pfilter == '*')
2966 			f->f_prop_filter->prop_type = PROP_TYPE_NOOP;
2967 		else {
2968 			pfilter_dup = strdup(pfilter);
2969 			if (pfilter_dup == NULL) {
2970 				logerror("strdup");
2971 				exit(1);
2972 			}
2973 			if (prop_filter_compile(f->f_prop_filter, pfilter_dup)) {
2974 				logerror("filter compile error");
2975 				exit(1);
2976 			}
2977 		}
2978 	}
2979 
2980 	/* scan through the list of selectors */
2981 	for (p = line; *p && *p != '\t' && *p != ' ';) {
2982 		int pri_done;
2983 		int pri_cmp;
2984 		int pri_invert;
2985 
2986 		/* find the end of this facility name list */
2987 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2988 			continue;
2989 
2990 		/* get the priority comparison */
2991 		pri_cmp = 0;
2992 		pri_done = 0;
2993 		pri_invert = 0;
2994 		if (*q == '!') {
2995 			pri_invert = 1;
2996 			q++;
2997 		}
2998 		while (!pri_done) {
2999 			switch (*q) {
3000 			case '<':
3001 				pri_cmp |= PRI_LT;
3002 				q++;
3003 				break;
3004 			case '=':
3005 				pri_cmp |= PRI_EQ;
3006 				q++;
3007 				break;
3008 			case '>':
3009 				pri_cmp |= PRI_GT;
3010 				q++;
3011 				break;
3012 			default:
3013 				pri_done++;
3014 				break;
3015 			}
3016 		}
3017 
3018 		/* collect priority name */
3019 		for (bp = buf; *q && !strchr("\t,; ", *q); )
3020 			*bp++ = *q++;
3021 		*bp = '\0';
3022 
3023 		/* skip cruft */
3024 		while (strchr(",;", *q))
3025 			q++;
3026 
3027 		/* decode priority name */
3028 		if (*buf == '*') {
3029 			pri = LOG_PRIMASK;
3030 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3031 		} else {
3032 			/* Ignore trailing spaces. */
3033 			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
3034 				buf[i] = '\0';
3035 
3036 			pri = decode(buf, prioritynames);
3037 			if (pri < 0) {
3038 				errno = 0;
3039 				(void)snprintf(ebuf, sizeof ebuf,
3040 				    "unknown priority name \"%s\"", buf);
3041 				logerror(ebuf);
3042 				free(f);
3043 				return (NULL);
3044 			}
3045 		}
3046 		if (!pri_cmp)
3047 			pri_cmp = (UniquePriority)
3048 				  ? (PRI_EQ)
3049 				  : (PRI_EQ | PRI_GT)
3050 				  ;
3051 		if (pri_invert)
3052 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3053 
3054 		/* scan facilities */
3055 		while (*p && !strchr("\t.; ", *p)) {
3056 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
3057 				*bp++ = *p++;
3058 			*bp = '\0';
3059 
3060 			if (*buf == '*') {
3061 				for (i = 0; i < LOG_NFACILITIES; i++) {
3062 					f->f_pmask[i] = pri;
3063 					f->f_pcmp[i] = pri_cmp;
3064 				}
3065 			} else {
3066 				i = decode(buf, facilitynames);
3067 				if (i < 0) {
3068 					errno = 0;
3069 					(void)snprintf(ebuf, sizeof ebuf,
3070 					    "unknown facility name \"%s\"",
3071 					    buf);
3072 					logerror(ebuf);
3073 					free(f);
3074 					return (NULL);
3075 				}
3076 				f->f_pmask[i >> 3] = pri;
3077 				f->f_pcmp[i >> 3] = pri_cmp;
3078 			}
3079 			while (*p == ',' || *p == ' ')
3080 				p++;
3081 		}
3082 
3083 		p = q;
3084 	}
3085 
3086 	/* skip to action part */
3087 	while (*p == '\t' || *p == ' ')
3088 		p++;
3089 
3090 	if (*p == '-') {
3091 		syncfile = 0;
3092 		p++;
3093 	} else
3094 		syncfile = 1;
3095 
3096 	switch (*p) {
3097 	case '@':
3098 		{
3099 			char *tp;
3100 			char endkey = ':';
3101 			/*
3102 			 * scan forward to see if there is a port defined.
3103 			 * so we can't use strlcpy..
3104 			 */
3105 			i = sizeof(f->fu_forw_hname);
3106 			tp = f->fu_forw_hname;
3107 			p++;
3108 
3109 			/*
3110 			 * an ipv6 address should start with a '[' in that case
3111 			 * we should scan for a ']'
3112 			 */
3113 			if (*p == '[') {
3114 				p++;
3115 				endkey = ']';
3116 			}
3117 			while (*p && (*p != endkey) && (i-- > 0)) {
3118 				*tp++ = *p++;
3119 			}
3120 			if (endkey == ']' && *p == endkey)
3121 				p++;
3122 			*tp = '\0';
3123 		}
3124 		/* See if we copied a domain and have a port */
3125 		if (*p == ':')
3126 			p++;
3127 		else
3128 			p = NULL;
3129 
3130 		hints = (struct addrinfo){
3131 			.ai_family = family,
3132 			.ai_socktype = SOCK_DGRAM
3133 		};
3134 		error = getaddrinfo(f->fu_forw_hname,
3135 				p ? p : "syslog", &hints, &res);
3136 		if (error) {
3137 			logerror(gai_strerror(error));
3138 			break;
3139 		}
3140 		f->fu_forw_addr = res;
3141 		f->f_type = F_FORW;
3142 		break;
3143 
3144 	case '/':
3145 		if ((f->f_file = open(p, logflags, 0600)) < 0) {
3146 			f->f_type = F_UNUSED;
3147 			logerror(p);
3148 			break;
3149 		}
3150 		if (syncfile)
3151 			f->f_flags |= FFLAG_SYNC;
3152 		if (isatty(f->f_file)) {
3153 			if (strcmp(p, ctty) == 0)
3154 				f->f_type = F_CONSOLE;
3155 			else
3156 				f->f_type = F_TTY;
3157 			(void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
3158 			    sizeof(f->fu_fname));
3159 		} else {
3160 			(void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
3161 			f->f_type = F_FILE;
3162 		}
3163 		break;
3164 
3165 	case '|':
3166 		f->fu_pipe_pid = 0;
3167 		(void)strlcpy(f->fu_pipe_pname, p + 1,
3168 		    sizeof(f->fu_pipe_pname));
3169 		f->f_type = F_PIPE;
3170 		break;
3171 
3172 	case '*':
3173 		f->f_type = F_WALL;
3174 		break;
3175 
3176 	default:
3177 		for (i = 0; i < MAXUNAMES && *p; i++) {
3178 			for (q = p; *q && *q != ','; )
3179 				q++;
3180 			(void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
3181 			if ((q - p) >= MAXLOGNAME)
3182 				f->fu_uname[i][MAXLOGNAME - 1] = '\0';
3183 			else
3184 				f->fu_uname[i][q - p] = '\0';
3185 			while (*q == ',' || *q == ' ')
3186 				q++;
3187 			p = q;
3188 		}
3189 		f->f_type = F_USERS;
3190 		break;
3191 	}
3192 	return (f);
3193 }
3194 
3195 
3196 /*
3197  *  Decode a symbolic name to a numeric value
3198  */
3199 static int
3200 decode(const char *name, const CODE *codetab)
3201 {
3202 	const CODE *c;
3203 	char *p, buf[40];
3204 
3205 	if (isdigit(*name))
3206 		return (atoi(name));
3207 
3208 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3209 		if (isupper(*name))
3210 			*p = tolower(*name);
3211 		else
3212 			*p = *name;
3213 	}
3214 	*p = '\0';
3215 	for (c = codetab; c->c_name; c++)
3216 		if (!strcmp(buf, c->c_name))
3217 			return (c->c_val);
3218 
3219 	return (-1);
3220 }
3221 
3222 static void
3223 markit(void)
3224 {
3225 	struct filed *f;
3226 	struct deadq_entry *dq, *dq0;
3227 
3228 	now = time((time_t *)NULL);
3229 	MarkSeq += TIMERINTVL;
3230 	if (MarkSeq >= MarkInterval) {
3231 		logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
3232 		    "-- MARK --", MARK);
3233 		MarkSeq = 0;
3234 	}
3235 
3236 	STAILQ_FOREACH(f, &fhead, next) {
3237 		if (f->f_prevcount && now >= REPEATTIME(f)) {
3238 			dprintf("flush %s: repeated %d times, %d sec.\n",
3239 			    TypeNames[f->f_type], f->f_prevcount,
3240 			    repeatinterval[f->f_repeatcount]);
3241 			fprintlog_successive(f, 0);
3242 			BACKOFF(f);
3243 		}
3244 	}
3245 
3246 	/* Walk the dead queue, and see if we should signal somebody. */
3247 	TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
3248 		switch (dq->dq_timeout) {
3249 		case 0:
3250 			/* Already signalled once, try harder now. */
3251 			if (kill(dq->dq_pid, SIGKILL) != 0)
3252 				(void)deadq_remove(dq);
3253 			break;
3254 
3255 		case 1:
3256 			/*
3257 			 * Timed out on dead queue, send terminate
3258 			 * signal.  Note that we leave the removal
3259 			 * from the dead queue to reapchild(), which
3260 			 * will also log the event (unless the process
3261 			 * didn't even really exist, in case we simply
3262 			 * drop it from the dead queue).
3263 			 */
3264 			if (kill(dq->dq_pid, SIGTERM) != 0)
3265 				(void)deadq_remove(dq);
3266 			else
3267 				dq->dq_timeout--;
3268 			break;
3269 		default:
3270 			dq->dq_timeout--;
3271 		}
3272 	}
3273 	MarkSet = 0;
3274 	(void)alarm(TIMERINTVL);
3275 }
3276 
3277 /*
3278  * fork off and become a daemon, but wait for the child to come online
3279  * before returning to the parent, or we get disk thrashing at boot etc.
3280  * Set a timer so we don't hang forever if it wedges.
3281  */
3282 static int
3283 waitdaemon(int maxwait)
3284 {
3285 	int fd;
3286 	int status;
3287 	pid_t pid, childpid;
3288 
3289 	switch (childpid = fork()) {
3290 	case -1:
3291 		return (-1);
3292 	case 0:
3293 		break;
3294 	default:
3295 		signal(SIGALRM, timedout);
3296 		alarm(maxwait);
3297 		while ((pid = wait3(&status, 0, NULL)) != -1) {
3298 			if (WIFEXITED(status))
3299 				errx(1, "child pid %d exited with return code %d",
3300 					pid, WEXITSTATUS(status));
3301 			if (WIFSIGNALED(status))
3302 				errx(1, "child pid %d exited on signal %d%s",
3303 					pid, WTERMSIG(status),
3304 					WCOREDUMP(status) ? " (core dumped)" :
3305 					"");
3306 			if (pid == childpid)	/* it's gone... */
3307 				break;
3308 		}
3309 		exit(0);
3310 	}
3311 
3312 	if (setsid() == -1)
3313 		return (-1);
3314 
3315 	(void)chdir("/");
3316 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
3317 		(void)dup2(fd, STDIN_FILENO);
3318 		(void)dup2(fd, STDOUT_FILENO);
3319 		(void)dup2(fd, STDERR_FILENO);
3320 		if (fd > STDERR_FILENO)
3321 			(void)close(fd);
3322 	}
3323 	return (getppid());
3324 }
3325 
3326 /*
3327  * We get a SIGALRM from the child when it's running and finished doing it's
3328  * fsync()'s or O_SYNC writes for all the boot messages.
3329  *
3330  * We also get a signal from the kernel if the timer expires, so check to
3331  * see what happened.
3332  */
3333 static void
3334 timedout(int sig __unused)
3335 {
3336 	int left;
3337 	left = alarm(0);
3338 	signal(SIGALRM, SIG_DFL);
3339 	if (left == 0)
3340 		errx(1, "timed out waiting for child");
3341 	else
3342 		_exit(0);
3343 }
3344 
3345 /*
3346  * Add `s' to the list of allowable peer addresses to accept messages
3347  * from.
3348  *
3349  * `s' is a string in the form:
3350  *
3351  *    [*]domainname[:{servicename|portnumber|*}]
3352  *
3353  * or
3354  *
3355  *    netaddr/maskbits[:{servicename|portnumber|*}]
3356  *
3357  * Returns -1 on error, 0 if the argument was valid.
3358  */
3359 static int
3360 #if defined(INET) || defined(INET6)
3361 allowaddr(char *s)
3362 #else
3363 allowaddr(char *s __unused)
3364 #endif
3365 {
3366 #if defined(INET) || defined(INET6)
3367 	char *cp1, *cp2;
3368 	struct allowedpeer *ap;
3369 	struct servent *se;
3370 	int masklen = -1;
3371 	struct addrinfo hints, *res = NULL;
3372 #ifdef INET
3373 	in_addr_t *addrp, *maskp;
3374 #endif
3375 #ifdef INET6
3376 	uint32_t *addr6p, *mask6p;
3377 #endif
3378 	char ip[NI_MAXHOST];
3379 
3380 	ap = calloc(1, sizeof(*ap));
3381 	if (ap == NULL)
3382 		err(1, "malloc failed");
3383 
3384 #ifdef INET6
3385 	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
3386 #endif
3387 		cp1 = s;
3388 	if ((cp1 = strrchr(cp1, ':'))) {
3389 		/* service/port provided */
3390 		*cp1++ = '\0';
3391 		if (strlen(cp1) == 1 && *cp1 == '*')
3392 			/* any port allowed */
3393 			ap->port = 0;
3394 		else if ((se = getservbyname(cp1, "udp"))) {
3395 			ap->port = ntohs(se->s_port);
3396 		} else {
3397 			ap->port = strtol(cp1, &cp2, 0);
3398 			/* port not numeric */
3399 			if (*cp2 != '\0')
3400 				goto err;
3401 		}
3402 	} else {
3403 		if ((se = getservbyname("syslog", "udp")))
3404 			ap->port = ntohs(se->s_port);
3405 		else
3406 			/* sanity, should not happen */
3407 			ap->port = 514;
3408 	}
3409 
3410 	if ((cp1 = strchr(s, '/')) != NULL &&
3411 	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
3412 		*cp1 = '\0';
3413 		if ((masklen = atoi(cp1 + 1)) < 0)
3414 			goto err;
3415 	}
3416 #ifdef INET6
3417 	if (*s == '[') {
3418 		cp2 = s + strlen(s) - 1;
3419 		if (*cp2 == ']') {
3420 			++s;
3421 			*cp2 = '\0';
3422 		} else {
3423 			cp2 = NULL;
3424 		}
3425 	} else {
3426 		cp2 = NULL;
3427 	}
3428 #endif
3429 	hints = (struct addrinfo){
3430 		.ai_family = PF_UNSPEC,
3431 		.ai_socktype = SOCK_DGRAM,
3432 		.ai_flags = AI_PASSIVE | AI_NUMERICHOST
3433 	};
3434 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
3435 		ap->isnumeric = 1;
3436 		memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
3437 		ap->a_mask = (struct sockaddr_storage){
3438 			.ss_family = res->ai_family,
3439 			.ss_len = res->ai_addrlen
3440 		};
3441 		switch (res->ai_family) {
3442 #ifdef INET
3443 		case AF_INET:
3444 			maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
3445 			addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
3446 			if (masklen < 0) {
3447 				/* use default netmask */
3448 				if (IN_CLASSA(ntohl(*addrp)))
3449 					*maskp = htonl(IN_CLASSA_NET);
3450 				else if (IN_CLASSB(ntohl(*addrp)))
3451 					*maskp = htonl(IN_CLASSB_NET);
3452 				else
3453 					*maskp = htonl(IN_CLASSC_NET);
3454 			} else if (masklen == 0) {
3455 				*maskp = 0;
3456 			} else if (masklen <= 32) {
3457 				/* convert masklen to netmask */
3458 				*maskp = htonl(~((1 << (32 - masklen)) - 1));
3459 			} else {
3460 				goto err;
3461 			}
3462 			/* Lose any host bits in the network number. */
3463 			*addrp &= *maskp;
3464 			break;
3465 #endif
3466 #ifdef INET6
3467 		case AF_INET6:
3468 			if (masklen > 128)
3469 				goto err;
3470 
3471 			if (masklen < 0)
3472 				masklen = 128;
3473 			mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
3474 			addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
3475 			/* convert masklen to netmask */
3476 			while (masklen > 0) {
3477 				if (masklen < 32) {
3478 					*mask6p =
3479 					    htonl(~(0xffffffff >> masklen));
3480 					*addr6p &= *mask6p;
3481 					break;
3482 				} else {
3483 					*mask6p++ = 0xffffffff;
3484 					addr6p++;
3485 					masklen -= 32;
3486 				}
3487 			}
3488 			break;
3489 #endif
3490 		default:
3491 			goto err;
3492 		}
3493 		freeaddrinfo(res);
3494 	} else {
3495 		/* arg `s' is domain name */
3496 		ap->isnumeric = 0;
3497 		ap->a_name = s;
3498 		if (cp1)
3499 			*cp1 = '/';
3500 #ifdef INET6
3501 		if (cp2) {
3502 			*cp2 = ']';
3503 			--s;
3504 		}
3505 #endif
3506 	}
3507 	STAILQ_INSERT_TAIL(&aphead, ap, next);
3508 
3509 	if (Debug) {
3510 		printf("allowaddr: rule ");
3511 		if (ap->isnumeric) {
3512 			printf("numeric, ");
3513 			getnameinfo(sstosa(&ap->a_addr),
3514 				    (sstosa(&ap->a_addr))->sa_len,
3515 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3516 			printf("addr = %s, ", ip);
3517 			getnameinfo(sstosa(&ap->a_mask),
3518 				    (sstosa(&ap->a_mask))->sa_len,
3519 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
3520 			printf("mask = %s; ", ip);
3521 		} else {
3522 			printf("domainname = %s; ", ap->a_name);
3523 		}
3524 		printf("port = %d\n", ap->port);
3525 	}
3526 
3527 	return (0);
3528 err:
3529 	if (res != NULL)
3530 		freeaddrinfo(res);
3531 	free(ap);
3532 #endif
3533 	return (-1);
3534 }
3535 
3536 /*
3537  * Validate that the remote peer has permission to log to us.
3538  */
3539 static int
3540 validate(struct sockaddr *sa, const char *hname)
3541 {
3542 	int i;
3543 	char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3544 	struct allowedpeer *ap;
3545 #ifdef INET
3546 	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3547 #endif
3548 #ifdef INET6
3549 	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3550 #endif
3551 	struct addrinfo hints, *res;
3552 	u_short sport;
3553 	int num = 0;
3554 
3555 	STAILQ_FOREACH(ap, &aphead, next) {
3556 		num++;
3557 	}
3558 	dprintf("# of validation rule: %d\n", num);
3559 	if (num == 0)
3560 		/* traditional behaviour, allow everything */
3561 		return (1);
3562 
3563 	(void)strlcpy(name, hname, sizeof(name));
3564 	hints = (struct addrinfo){
3565 		.ai_family = PF_UNSPEC,
3566 		.ai_socktype = SOCK_DGRAM,
3567 		.ai_flags = AI_PASSIVE | AI_NUMERICHOST
3568 	};
3569 	if (getaddrinfo(name, NULL, &hints, &res) == 0)
3570 		freeaddrinfo(res);
3571 	else if (strchr(name, '.') == NULL) {
3572 		strlcat(name, ".", sizeof name);
3573 		strlcat(name, LocalDomain, sizeof name);
3574 	}
3575 	if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3576 			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3577 		return (0);	/* for safety, should not occur */
3578 	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3579 		ip, port, name);
3580 	sport = atoi(port);
3581 
3582 	/* now, walk down the list */
3583 	i = 0;
3584 	STAILQ_FOREACH(ap, &aphead, next) {
3585 		i++;
3586 		if (ap->port != 0 && ap->port != sport) {
3587 			dprintf("rejected in rule %d due to port mismatch.\n",
3588 			    i);
3589 			continue;
3590 		}
3591 
3592 		if (ap->isnumeric) {
3593 			if (ap->a_addr.ss_family != sa->sa_family) {
3594 				dprintf("rejected in rule %d due to address family mismatch.\n", i);
3595 				continue;
3596 			}
3597 #ifdef INET
3598 			else if (ap->a_addr.ss_family == AF_INET) {
3599 				sin4 = satosin(sa);
3600 				a4p = satosin(&ap->a_addr);
3601 				m4p = satosin(&ap->a_mask);
3602 				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3603 				    != a4p->sin_addr.s_addr) {
3604 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
3605 					continue;
3606 				}
3607 			}
3608 #endif
3609 #ifdef INET6
3610 			else if (ap->a_addr.ss_family == AF_INET6) {
3611 				sin6 = satosin6(sa);
3612 				a6p = satosin6(&ap->a_addr);
3613 				m6p = satosin6(&ap->a_mask);
3614 				if (a6p->sin6_scope_id != 0 &&
3615 				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
3616 					dprintf("rejected in rule %d due to scope mismatch.\n", i);
3617 					continue;
3618 				}
3619 				if (!IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3620 				    &a6p->sin6_addr, &m6p->sin6_addr)) {
3621 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
3622 					continue;
3623 				}
3624 			}
3625 #endif
3626 			else
3627 				continue;
3628 		} else {
3629 			if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3630 			    FNM_NOMATCH) {
3631 				dprintf("rejected in rule %d due to name "
3632 				    "mismatch.\n", i);
3633 				continue;
3634 			}
3635 		}
3636 		dprintf("accepted in rule %d.\n", i);
3637 		return (1);	/* hooray! */
3638 	}
3639 	return (0);
3640 }
3641 
3642 /*
3643  * Fairly similar to popen(3), but returns an open descriptor, as
3644  * opposed to a FILE *.
3645  */
3646 static int
3647 p_open(const char *prog, pid_t *rpid)
3648 {
3649 	int pfd[2], nulldesc;
3650 	pid_t pid;
3651 	char *argv[4]; /* sh -c cmd NULL */
3652 	char errmsg[200];
3653 
3654 	if (pipe(pfd) == -1)
3655 		return (-1);
3656 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3657 		/* we are royally screwed anyway */
3658 		return (-1);
3659 
3660 	switch ((pid = fork())) {
3661 	case -1:
3662 		close(nulldesc);
3663 		return (-1);
3664 
3665 	case 0:
3666 		(void)setsid();	/* Avoid catching SIGHUPs. */
3667 		argv[0] = strdup("sh");
3668 		argv[1] = strdup("-c");
3669 		argv[2] = strdup(prog);
3670 		argv[3] = NULL;
3671 		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3672 			logerror("strdup");
3673 			exit(1);
3674 		}
3675 
3676 		alarm(0);
3677 
3678 		/* Restore signals marked as SIG_IGN. */
3679 		(void)signal(SIGINT, SIG_DFL);
3680 		(void)signal(SIGQUIT, SIG_DFL);
3681 		(void)signal(SIGPIPE, SIG_DFL);
3682 
3683 		dup2(pfd[0], STDIN_FILENO);
3684 		dup2(nulldesc, STDOUT_FILENO);
3685 		dup2(nulldesc, STDERR_FILENO);
3686 		closefrom(STDERR_FILENO + 1);
3687 
3688 		(void)execvp(_PATH_BSHELL, argv);
3689 		_exit(255);
3690 	}
3691 	close(nulldesc);
3692 	close(pfd[0]);
3693 	/*
3694 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
3695 	 * supposed to get an EWOULDBLOCK on writev(2), which is
3696 	 * caught by the logic above anyway, which will in turn close
3697 	 * the pipe, and fork a new logging subprocess if necessary.
3698 	 * The stale subprocess will be killed some time later unless
3699 	 * it terminated itself due to closing its input pipe (so we
3700 	 * get rid of really dead puppies).
3701 	 */
3702 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3703 		/* This is bad. */
3704 		(void)snprintf(errmsg, sizeof errmsg,
3705 			       "Warning: cannot change pipe to PID %d to "
3706 			       "non-blocking behaviour.",
3707 			       (int)pid);
3708 		logerror(errmsg);
3709 	}
3710 	*rpid = pid;
3711 	return (pfd[1]);
3712 }
3713 
3714 static void
3715 deadq_enter(pid_t pid, const char *name)
3716 {
3717 	struct deadq_entry *dq;
3718 	int status;
3719 
3720 	if (pid == 0)
3721 		return;
3722 	/*
3723 	 * Be paranoid, if we can't signal the process, don't enter it
3724 	 * into the dead queue (perhaps it's already dead).  If possible,
3725 	 * we try to fetch and log the child's status.
3726 	 */
3727 	if (kill(pid, 0) != 0) {
3728 		if (waitpid(pid, &status, WNOHANG) > 0)
3729 			log_deadchild(pid, status, name);
3730 		return;
3731 	}
3732 
3733 	dq = malloc(sizeof(*dq));
3734 	if (dq == NULL) {
3735 		logerror("malloc");
3736 		exit(1);
3737 	}
3738 	*dq = (struct deadq_entry){
3739 		.dq_pid = pid,
3740 		.dq_timeout = DQ_TIMO_INIT
3741 	};
3742 	TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3743 }
3744 
3745 static int
3746 deadq_remove(struct deadq_entry *dq)
3747 {
3748 	if (dq != NULL) {
3749 		TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3750 		free(dq);
3751 		return (1);
3752 	}
3753 
3754 	return (0);
3755 }
3756 
3757 static int
3758 deadq_removebypid(pid_t pid)
3759 {
3760 	struct deadq_entry *dq;
3761 
3762 	TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3763 		if (dq->dq_pid == pid)
3764 			break;
3765 	}
3766 	return (deadq_remove(dq));
3767 }
3768 
3769 static void
3770 log_deadchild(pid_t pid, int status, const char *name)
3771 {
3772 	int code;
3773 	char buf[256];
3774 	const char *reason;
3775 
3776 	errno = 0; /* Keep strerror() stuff out of logerror messages. */
3777 	if (WIFSIGNALED(status)) {
3778 		reason = "due to signal";
3779 		code = WTERMSIG(status);
3780 	} else {
3781 		reason = "with status";
3782 		code = WEXITSTATUS(status);
3783 		if (code == 0)
3784 			return;
3785 	}
3786 	(void)snprintf(buf, sizeof buf,
3787 		       "Logging subprocess %d (%s) exited %s %d.",
3788 		       pid, name, reason, code);
3789 	logerror(buf);
3790 }
3791 
3792 static int
3793 socksetup(struct peer *pe)
3794 {
3795 	struct addrinfo hints, *res, *res0;
3796 	int error;
3797 	char *cp;
3798 	int (*sl_recv)(struct socklist *);
3799 	/*
3800 	 * We have to handle this case for backwards compatibility:
3801 	 * If there are two (or more) colons but no '[' and ']',
3802 	 * assume this is an inet6 address without a service.
3803 	 */
3804 	if (pe->pe_name != NULL) {
3805 #ifdef INET6
3806 		if (pe->pe_name[0] == '[' &&
3807 		    (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3808 			pe->pe_name = &pe->pe_name[1];
3809 			*cp = '\0';
3810 			if (cp[1] == ':' && cp[2] != '\0')
3811 				pe->pe_serv = cp + 2;
3812 		} else {
3813 #endif
3814 			cp = strchr(pe->pe_name, ':');
3815 			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3816 				*cp = '\0';
3817 				if (cp[1] != '\0')
3818 					pe->pe_serv = cp + 1;
3819 				if (cp == pe->pe_name)
3820 					pe->pe_name = NULL;
3821 			}
3822 #ifdef INET6
3823 		}
3824 #endif
3825 	}
3826 	hints = (struct addrinfo){
3827 		.ai_family = AF_UNSPEC,
3828 		.ai_socktype = SOCK_DGRAM,
3829 		.ai_flags = AI_PASSIVE
3830 	};
3831 	if (pe->pe_name != NULL)
3832 		dprintf("Trying peer: %s\n", pe->pe_name);
3833 	if (pe->pe_serv == NULL)
3834 		pe->pe_serv = "syslog";
3835 	error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3836 	if (error) {
3837 		char *msgbuf;
3838 
3839 		asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3840 		    pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3841 		    gai_strerror(error));
3842 		errno = 0;
3843 		if (msgbuf == NULL)
3844 			logerror(gai_strerror(error));
3845 		else
3846 			logerror(msgbuf);
3847 		free(msgbuf);
3848 		die(0);
3849 	}
3850 	for (res = res0; res != NULL; res = res->ai_next) {
3851 		int s;
3852 
3853 		if (res->ai_family != AF_LOCAL &&
3854 		    SecureMode > 1) {
3855 			/* Only AF_LOCAL in secure mode. */
3856 			continue;
3857 		}
3858 		if (family != AF_UNSPEC &&
3859 		    res->ai_family != AF_LOCAL && res->ai_family != family)
3860 			continue;
3861 
3862 		s = socket(res->ai_family, res->ai_socktype,
3863 		    res->ai_protocol);
3864 		if (s < 0) {
3865 			logerror("socket");
3866 			error++;
3867 			continue;
3868 		}
3869 #ifdef INET6
3870 		if (res->ai_family == AF_INET6) {
3871 			if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3872 			       &(int){1}, sizeof(int)) < 0) {
3873 				logerror("setsockopt(IPV6_V6ONLY)");
3874 				close(s);
3875 				error++;
3876 				continue;
3877 			}
3878 		}
3879 #endif
3880 		if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3881 		    &(int){1}, sizeof(int)) < 0) {
3882 			logerror("setsockopt(SO_REUSEADDR)");
3883 			close(s);
3884 			error++;
3885 			continue;
3886 		}
3887 
3888 		/*
3889 		 * Bind INET and UNIX-domain sockets.
3890 		 *
3891 		 * A UNIX-domain socket is always bound to a pathname
3892 		 * regardless of -N flag.
3893 		 *
3894 		 * For INET sockets, RFC 3164 recommends that client
3895 		 * side message should come from the privileged syslogd port.
3896 		 *
3897 		 * If the system administrator chooses not to obey
3898 		 * this, we can skip the bind() step so that the
3899 		 * system will choose a port for us.
3900 		 */
3901 		if (res->ai_family == AF_LOCAL)
3902 			unlink(pe->pe_name);
3903 		if (res->ai_family == AF_LOCAL ||
3904 		    NoBind == 0 || pe->pe_name != NULL) {
3905 			if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3906 				logerror("bind");
3907 				close(s);
3908 				error++;
3909 				continue;
3910 			}
3911 			if (res->ai_family == AF_LOCAL ||
3912 			    SecureMode == 0)
3913 				increase_rcvbuf(s);
3914 		}
3915 		if (res->ai_family == AF_LOCAL &&
3916 		    chmod(pe->pe_name, pe->pe_mode) < 0) {
3917 			dprintf("chmod %s: %s\n", pe->pe_name,
3918 			    strerror(errno));
3919 			close(s);
3920 			error++;
3921 			continue;
3922 		}
3923 		dprintf("new socket fd is %d\n", s);
3924 		if (res->ai_socktype != SOCK_DGRAM) {
3925 			listen(s, 5);
3926 		}
3927 		sl_recv = socklist_recv_sock;
3928 #if defined(INET) || defined(INET6)
3929 		if (SecureMode && (res->ai_family == AF_INET ||
3930 		    res->ai_family == AF_INET6)) {
3931 			dprintf("shutdown\n");
3932 			/* Forbid communication in secure mode. */
3933 			if (shutdown(s, SHUT_RD) < 0 &&
3934 			    errno != ENOTCONN) {
3935 				logerror("shutdown");
3936 				if (!Debug)
3937 					die(0);
3938 			}
3939 			sl_recv = NULL;
3940 		} else
3941 #endif
3942 			dprintf("listening on socket\n");
3943 		dprintf("sending on socket\n");
3944 		addsock(res, &(struct socklist){
3945 			.sl_socket = s,
3946 			.sl_peer = pe,
3947 			.sl_recv = sl_recv
3948 		});
3949 	}
3950 	freeaddrinfo(res0);
3951 
3952 	return(error);
3953 }
3954 
3955 static void
3956 increase_rcvbuf(int fd)
3957 {
3958 	socklen_t len;
3959 
3960 	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3961 	    &(socklen_t){sizeof(len)}) == 0) {
3962 		if (len < RCVBUF_MINSIZE) {
3963 			len = RCVBUF_MINSIZE;
3964 			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
3965 		}
3966 	}
3967 }
3968