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