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