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