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