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