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