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