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