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