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