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