xref: /minix/usr.sbin/syslogd/syslogd.c (revision 686761db)
1 /*	$NetBSD: syslogd.c,v 1.122 2015/09/05 20:19:43 dholland Exp $	*/
2 
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 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\
35 	The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
41 #else
42 __RCSID("$NetBSD: syslogd.c,v 1.122 2015/09/05 20:19:43 dholland Exp $");
43 #endif
44 #endif /* not lint */
45 
46 /*
47  *  syslogd -- log system messages
48  *
49  * This program implements a system log. It takes a series of lines.
50  * Each line may have a priority, signified as "<n>" as
51  * the first characters of the line.  If this is
52  * not present, a default priority is used.
53  *
54  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
55  * cause it to reread its configuration file.
56  *
57  * Defined Constants:
58  *
59  * MAXLINE -- the maximimum line length that can be handled.
60  * DEFUPRI -- the default priority for user messages
61  * DEFSPRI -- the default priority for kernel messages
62  *
63  * Author: Eric Allman
64  * extensive changes by Ralph Campbell
65  * more extensive changes by Eric Allman (again)
66  * Extension to log by program name as well as facility and priority
67  *   by Peter da Silva.
68  * -U and -v by Harlan Stenn.
69  * Priority comparison code by Harlan Stenn.
70  * TLS, syslog-protocol, and syslog-sign code by Martin Schuette.
71  */
72 #define SYSLOG_NAMES
73 #include <sys/stat.h>
74 #include <poll.h>
75 #include "syslogd.h"
76 #include "extern.h"
77 
78 #ifndef DISABLE_SIGN
79 #include "sign.h"
80 struct sign_global_t GlobalSign = {
81 	.rsid = 0,
82 	.sig2_delims = STAILQ_HEAD_INITIALIZER(GlobalSign.sig2_delims)
83 };
84 #endif /* !DISABLE_SIGN */
85 
86 #ifndef DISABLE_TLS
87 #include "tls.h"
88 #endif /* !DISABLE_TLS */
89 
90 #ifdef LIBWRAP
91 int allow_severity = LOG_AUTH|LOG_INFO;
92 int deny_severity = LOG_AUTH|LOG_WARNING;
93 #endif
94 
95 const char	*ConfFile = _PATH_LOGCONF;
96 char	ctty[] = _PATH_CONSOLE;
97 
98 /*
99  * Queue of about-to-be-dead processes we should watch out for.
100  */
101 TAILQ_HEAD(, deadq_entry) deadq_head = TAILQ_HEAD_INITIALIZER(deadq_head);
102 
103 typedef struct deadq_entry {
104 	pid_t				dq_pid;
105 	int				dq_timeout;
106 	TAILQ_ENTRY(deadq_entry)	dq_entries;
107 } *dq_t;
108 
109 /*
110  * The timeout to apply to processes waiting on the dead queue.	 Unit
111  * of measure is "mark intervals", i.e. 20 minutes by default.
112  * Processes on the dead queue will be terminated after that time.
113  */
114 #define DQ_TIMO_INIT	2
115 
116 /*
117  * Intervals at which we flush out "message repeated" messages,
118  * in seconds after previous message is logged.	 After each flush,
119  * we move to the next interval until we reach the largest.
120  */
121 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
122 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
123 #define REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
124 #define BACKOFF(f)	{ if ((size_t)(++(f)->f_repeatcount) > MAXREPEAT) \
125 				 (f)->f_repeatcount = MAXREPEAT; \
126 			}
127 
128 /* values for f_type */
129 #define F_UNUSED	0		/* unused entry */
130 #define F_FILE		1		/* regular file */
131 #define F_TTY		2		/* terminal */
132 #define F_CONSOLE	3		/* console terminal */
133 #define F_FORW		4		/* remote machine */
134 #define F_USERS		5		/* list of users */
135 #define F_WALL		6		/* everyone logged on */
136 #define F_PIPE		7		/* pipe to program */
137 #define F_FIFO		8		/* mkfifo(2) file */
138 #define F_TLS		9
139 
140 struct TypeInfo {
141 	const char *name;
142 	char	   *queue_length_string;
143 	const char *default_length_string;
144 	char	   *queue_size_string;
145 	const char *default_size_string;
146 	int64_t	    queue_length;
147 	int64_t	    queue_size;
148 	int   max_msg_length;
149 } TypeInfo[] = {
150 	/* numeric values are set in init()
151 	 * -1 in length/size or max_msg_length means infinite */
152 	{"UNUSED",  NULL,    "0", NULL,	  "0", 0, 0,	 0},
153 	{"FILE",    NULL, "1024", NULL,	 "1M", 0, 0, 16384},
154 	{"TTY",	    NULL,    "0", NULL,	  "0", 0, 0,  1024},
155 	{"CONSOLE", NULL,    "0", NULL,	  "0", 0, 0,  1024},
156 	{"FORW",    NULL,    "0", NULL,	 "1M", 0, 0, 16384},
157 	{"USERS",   NULL,    "0", NULL,	  "0", 0, 0,  1024},
158 	{"WALL",    NULL,    "0", NULL,	  "0", 0, 0,  1024},
159 	{"PIPE",    NULL, "1024", NULL,	 "1M", 0, 0, 16384},
160 	{"FIFO",    NULL, "1024", NULL,	 "1M", 0, 0, 16384},
161 #ifndef DISABLE_TLS
162 	{"TLS",	    NULL,   "-1", NULL, "16M", 0, 0, 16384}
163 #endif /* !DISABLE_TLS */
164 };
165 
166 struct	filed *Files = NULL;
167 struct	filed consfile;
168 
169 time_t	now;
170 int	Debug = D_NONE;		/* debug flag */
171 int	daemonized = 0;		/* we are not daemonized yet */
172 char	*LocalFQDN = NULL;	       /* our FQDN */
173 char	*oldLocalFQDN = NULL;	       /* our previous FQDN */
174 char	LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
175 struct socketEvent *finet;	/* Internet datagram sockets and events */
176 int   *funix;			/* Unix domain datagram sockets */
177 #ifndef DISABLE_TLS
178 struct socketEvent *TLS_Listen_Set; /* TLS/TCP sockets and events */
179 #endif /* !DISABLE_TLS */
180 int	Initialized = 0;	/* set when we have initialized ourselves */
181 int	ShuttingDown;		/* set when we die() */
182 int	MarkInterval = 20 * 60; /* interval between marks in seconds */
183 int	MarkSeq = 0;		/* mark sequence number */
184 int	SecureMode = 0;		/* listen only on unix domain socks */
185 int	UseNameService = 1;	/* make domain name queries */
186 int	NumForwards = 0;	/* number of forwarding actions in conf file */
187 char	**LogPaths;		/* array of pathnames to read messages from */
188 int	NoRepeat = 0;		/* disable "repeated"; log always */
189 int	RemoteAddDate = 0;	/* always add date to messages from network */
190 int	SyncKernel = 0;		/* write kernel messages synchronously */
191 int	UniquePriority = 0;	/* only log specified priority */
192 int	LogFacPri = 0;		/* put facility and priority in log messages: */
193 				/* 0=no, 1=numeric, 2=names */
194 bool	BSDOutputFormat = true;	/* if true emit traditional BSD Syslog lines,
195 				 * otherwise new syslog-protocol lines
196 				 *
197 				 * Open Issue: having a global flag is the
198 				 * easiest solution. If we get a more detailed
199 				 * config file this could/should be changed
200 				 * into a destination-specific flag.
201 				 * Most output code should be ready to handle
202 				 * this, it will only break some syslog-sign
203 				 * configurations (e.g. with SG="0").
204 				 */
205 char	appname[]   = "syslogd";/* the APPNAME for own messages */
206 char   *include_pid = NULL;	/* include PID in own messages */
207 
208 
209 /* init and setup */
210 void		usage(void) __attribute__((__noreturn__));
211 void		logpath_add(char ***, int *, int *, const char *);
212 void		logpath_fileadd(char ***, int *, int *, const char *);
213 void		init(int fd, short event, void *ev);  /* SIGHUP kevent dispatch routine */
214 struct socketEvent*
215 		socksetup(int, const char *);
216 int		getmsgbufsize(void);
217 char	       *getLocalFQDN(void);
218 void		trim_anydomain(char *);
219 /* pipe & subprocess handling */
220 int		p_open(char *, pid_t *);
221 void		deadq_enter(pid_t, const char *);
222 int		deadq_remove(pid_t);
223 void		log_deadchild(pid_t, int, const char *);
224 void		reapchild(int fd, short event, void *ev); /* SIGCHLD kevent dispatch routine */
225 /* input message parsing & formatting */
226 const char     *cvthname(struct sockaddr_storage *);
227 void		printsys(char *);
228 struct buf_msg *printline_syslogprotocol(const char*, char*, int, int);
229 struct buf_msg *printline_bsdsyslog(const char*, char*, int, int);
230 struct buf_msg *printline_kernelprintf(const char*, char*, int, int);
231 size_t		check_timestamp(unsigned char *, char **, bool, bool);
232 char	       *copy_utf8_ascii(char*, size_t);
233 uint_fast32_t	get_utf8_value(const char*);
234 unsigned	valid_utf8(const char *);
235 static unsigned check_sd(char*);
236 static unsigned check_msgid(char *);
237 /* event handling */
238 static void	dispatch_read_klog(int fd, short event, void *ev);
239 static void	dispatch_read_finet(int fd, short event, void *ev);
240 static void	dispatch_read_funix(int fd, short event, void *ev);
241 static void	domark(int fd, short event, void *ev); /* timer kevent dispatch routine */
242 /* log messages */
243 void		logmsg_async(int, const char *, const char *, int);
244 void		logmsg(struct buf_msg *);
245 int		matches_spec(const char *, const char *,
246 		char *(*)(const char *, const char *));
247 void		udp_send(struct filed *, char *, size_t);
248 void		wallmsg(struct filed *, struct iovec *, size_t);
249 /* buffer & queue functions */
250 size_t		message_queue_purge(struct filed *f, size_t, int);
251 size_t		message_allqueues_check(void);
252 static struct buf_queue *
253 		find_qentry_to_delete(const struct buf_queue_head *, int, bool);
254 struct buf_queue *
255 		message_queue_add(struct filed *, struct buf_msg *);
256 size_t		buf_queue_obj_size(struct buf_queue*);
257 /* configuration & parsing */
258 void		cfline(size_t, const char *, struct filed *, const char *,
259     const char *);
260 void		read_config_file(FILE*, struct filed**);
261 void		store_sign_delim_sg2(char*);
262 int		decode(const char *, CODE *);
263 bool		copy_config_value(const char *, char **, const char **,
264     const char *, int);
265 bool		copy_config_value_word(char **, const char **);
266 
267 /* config parsing */
268 #ifndef DISABLE_TLS
269 void		free_cred_SLIST(struct peer_cred_head *);
270 static inline void
271 		free_incoming_tls_sockets(void);
272 #endif /* !DISABLE_TLS */
273 static int writev1(int, struct iovec *, size_t);
274 
275 /* for make_timestamp() */
276 char	timestamp[MAX_TIMESTAMPLEN + 1];
277 /*
278  * Global line buffer.	Since we only process one event at a time,
279  * a global one will do.  But for klog, we use own buffer so that
280  * partial line at the end of buffer can be deferred.
281  */
282 char *linebuf, *klog_linebuf;
283 size_t linebufsize, klog_linebufoff;
284 
285 static const char *bindhostname = NULL;
286 
287 #ifndef DISABLE_TLS
288 struct TLS_Incoming TLS_Incoming_Head = \
289 	SLIST_HEAD_INITIALIZER(TLS_Incoming_Head);
290 extern char *SSL_ERRCODE[];
291 struct tls_global_options_t tls_opt;
292 #endif /* !DISABLE_TLS */
293 
294 int
main(int argc,char * argv[])295 main(int argc, char *argv[])
296 {
297 	int ch, j, fklog;
298 	int funixsize = 0, funixmaxsize = 0;
299 	struct sockaddr_un sunx;
300 	char **pp;
301 	struct event *ev;
302 	uid_t uid = 0;
303 	gid_t gid = 0;
304 	char *user = NULL;
305 	char *group = NULL;
306 	const char *root = "/";
307 	char *endp;
308 	struct group   *gr;
309 	struct passwd  *pw;
310 	unsigned long l;
311 
312 	/* should we set LC_TIME="C" to ensure correct timestamps&parsing? */
313 	(void)setlocale(LC_ALL, "");
314 
315 	while ((ch = getopt(argc, argv, "b:dnsSf:m:o:p:P:ru:g:t:TUv")) != -1)
316 		switch(ch) {
317 		case 'b':
318 			bindhostname = optarg;
319 			break;
320 		case 'd':		/* debug */
321 			Debug = D_DEFAULT;
322 			/* is there a way to read the integer value
323 			 * for Debug as an optional argument? */
324 			break;
325 		case 'f':		/* configuration file */
326 			ConfFile = optarg;
327 			break;
328 		case 'g':
329 			group = optarg;
330 			if (*group == '\0')
331 				usage();
332 			break;
333 		case 'm':		/* mark interval */
334 			MarkInterval = atoi(optarg) * 60;
335 			break;
336 		case 'n':		/* turn off DNS queries */
337 			UseNameService = 0;
338 			break;
339 		case 'o':		/* message format */
340 #define EQ(a)		(strncmp(optarg, # a, sizeof(# a) - 1) == 0)
341 			if (EQ(bsd) || EQ(rfc3264))
342 				BSDOutputFormat = true;
343 			else if (EQ(syslog) || EQ(rfc5424))
344 				BSDOutputFormat = false;
345 			else
346 				usage();
347 			/* TODO: implement additional output option "osyslog"
348 			 *	 for old syslogd behaviour as introduced after
349 			 *	 FreeBSD PR#bin/7055.
350 			 */
351 			break;
352 		case 'p':		/* path */
353 			logpath_add(&LogPaths, &funixsize,
354 			    &funixmaxsize, optarg);
355 			break;
356 		case 'P':		/* file of paths */
357 			logpath_fileadd(&LogPaths, &funixsize,
358 			    &funixmaxsize, optarg);
359 			break;
360 		case 'r':		/* disable "repeated" compression */
361 			NoRepeat++;
362 			break;
363 		case 's':		/* no network listen mode */
364 			SecureMode++;
365 			break;
366 		case 'S':
367 			SyncKernel = 1;
368 			break;
369 		case 't':
370 			root = optarg;
371 			if (*root == '\0')
372 				usage();
373 			break;
374 		case 'T':
375 			RemoteAddDate = 1;
376 			break;
377 		case 'u':
378 			user = optarg;
379 			if (*user == '\0')
380 				usage();
381 			break;
382 		case 'U':		/* only log specified priority */
383 			UniquePriority = 1;
384 			break;
385 		case 'v':		/* log facility and priority */
386 			if (LogFacPri < 2)
387 				LogFacPri++;
388 			break;
389 		default:
390 			usage();
391 		}
392 	if ((argc -= optind) != 0)
393 		usage();
394 
395 	setlinebuf(stdout);
396 	tzset(); /* init TZ information for localtime. */
397 
398 	if (user != NULL) {
399 		if (isdigit((unsigned char)*user)) {
400 			errno = 0;
401 			endp = NULL;
402 			l = strtoul(user, &endp, 0);
403 			if (errno || *endp != '\0')
404 				goto getuser;
405 			uid = (uid_t)l;
406 			if (uid != l) {/* TODO: never executed */
407 				errno = 0;
408 				logerror("UID out of range");
409 				die(0, 0, NULL);
410 			}
411 		} else {
412 getuser:
413 			if ((pw = getpwnam(user)) != NULL) {
414 				uid = pw->pw_uid;
415 			} else {
416 				errno = 0;
417 				logerror("Cannot find user `%s'", user);
418 				die(0, 0, NULL);
419 			}
420 		}
421 	}
422 
423 	if (group != NULL) {
424 		if (isdigit((unsigned char)*group)) {
425 			errno = 0;
426 			endp = NULL;
427 			l = strtoul(group, &endp, 0);
428 			if (errno || *endp != '\0')
429 				goto getgroup;
430 			gid = (gid_t)l;
431 			if (gid != l) {/* TODO: never executed */
432 				errno = 0;
433 				logerror("GID out of range");
434 				die(0, 0, NULL);
435 			}
436 		} else {
437 getgroup:
438 			if ((gr = getgrnam(group)) != NULL) {
439 				gid = gr->gr_gid;
440 			} else {
441 				errno = 0;
442 				logerror("Cannot find group `%s'", group);
443 				die(0, 0, NULL);
444 			}
445 		}
446 	}
447 
448 	if (access(root, F_OK | R_OK)) {
449 		logerror("Cannot access `%s'", root);
450 		die(0, 0, NULL);
451 	}
452 
453 	consfile.f_type = F_CONSOLE;
454 	(void)strlcpy(consfile.f_un.f_fname, ctty,
455 	    sizeof(consfile.f_un.f_fname));
456 	linebufsize = getmsgbufsize();
457 	if (linebufsize < MAXLINE)
458 		linebufsize = MAXLINE;
459 	linebufsize++;
460 
461 	if (!(linebuf = malloc(linebufsize))) {
462 		logerror("Couldn't allocate buffer");
463 		die(0, 0, NULL);
464 	}
465 	if (!(klog_linebuf = malloc(linebufsize))) {
466 		logerror("Couldn't allocate buffer for klog");
467 		die(0, 0, NULL);
468 	}
469 
470 
471 #ifndef SUN_LEN
472 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
473 #endif
474 	if (funixsize == 0)
475 		logpath_add(&LogPaths, &funixsize,
476 		    &funixmaxsize, _PATH_LOG);
477 	funix = malloc(sizeof(*funix) * funixsize);
478 	if (funix == NULL) {
479 		logerror("Couldn't allocate funix descriptors");
480 		die(0, 0, NULL);
481 	}
482 	for (j = 0, pp = LogPaths; *pp; pp++, j++) {
483 		DPRINTF(D_NET, "Making unix dgram socket `%s'\n", *pp);
484 		unlink(*pp);
485 		memset(&sunx, 0, sizeof(sunx));
486 		sunx.sun_family = AF_LOCAL;
487 		(void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
488 		funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
489 		if (funix[j] < 0 || bind(funix[j],
490 		    (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
491 		    chmod(*pp, 0666) < 0) {
492 			logerror("Cannot create `%s'", *pp);
493 			die(0, 0, NULL);
494 		}
495 		DPRINTF(D_NET, "Listening on unix dgram socket `%s'\n", *pp);
496 	}
497 
498 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
499 		DPRINTF(D_FILE, "Can't open `%s' (%d)\n", _PATH_KLOG, errno);
500 	} else {
501 		DPRINTF(D_FILE, "Listening on kernel log `%s' with fd %d\n",
502 		    _PATH_KLOG, fklog);
503 	}
504 
505 #if (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN))
506 	/* basic OpenSSL init */
507 	SSL_load_error_strings();
508 	(void) SSL_library_init();
509 	OpenSSL_add_all_digests();
510 	/* OpenSSL PRNG needs /dev/urandom, thus initialize before chroot() */
511 	if (!RAND_status()) {
512 		errno = 0;
513 		logerror("Unable to initialize OpenSSL PRNG");
514 	} else {
515 		DPRINTF(D_TLS, "Initializing PRNG\n");
516 	}
517 #endif /* (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN)) */
518 #ifndef DISABLE_SIGN
519 	/* initialize rsid -- we will use that later to determine
520 	 * whether sign_global_init() was already called */
521 	GlobalSign.rsid = 0;
522 #endif /* !DISABLE_SIGN */
523 #if (IETF_NUM_PRIVALUES != (LOG_NFACILITIES<<3))
524 	logerror("Warning: system defines %d priority values, but "
525 	    "syslog-protocol/syslog-sign specify %d values",
526 	    LOG_NFACILITIES, SIGN_NUM_PRIVALS);
527 #endif
528 
529 	/*
530 	 * All files are open, we can drop privileges and chroot
531 	 */
532 	DPRINTF(D_MISC, "Attempt to chroot to `%s'\n", root);
533 	if (chroot(root) == -1) {
534 		logerror("Failed to chroot to `%s'", root);
535 		die(0, 0, NULL);
536 	}
537 	DPRINTF(D_MISC, "Attempt to set GID/EGID to `%d'\n", gid);
538 	if (setgid(gid) || setegid(gid)) {
539 		logerror("Failed to set gid to `%d'", gid);
540 		die(0, 0, NULL);
541 	}
542 	DPRINTF(D_MISC, "Attempt to set UID/EUID to `%d'\n", uid);
543 	if (setuid(uid) || seteuid(uid)) {
544 		logerror("Failed to set uid to `%d'", uid);
545 		die(0, 0, NULL);
546 	}
547 	/*
548 	 * We cannot detach from the terminal before we are sure we won't
549 	 * have a fatal error, because error message would not go to the
550 	 * terminal and would not be logged because syslogd dies.
551 	 * All die() calls are behind us, we can call daemon()
552 	 */
553 	if (!Debug) {
554 		(void)daemon(0, 0);
555 		daemonized = 1;
556 		/* tuck my process id away, if i'm not in debug mode */
557 #ifdef __NetBSD_Version__
558 		pidfile(NULL);
559 #endif /* __NetBSD_Version__ */
560 	}
561 
562 #define MAX_PID_LEN 5
563 	include_pid = malloc(MAX_PID_LEN+1);
564 	snprintf(include_pid, MAX_PID_LEN+1, "%d", getpid());
565 
566 	/*
567 	 * Create the global kernel event descriptor.
568 	 *
569 	 * NOTE: We MUST do this after daemon(), bacause the kqueue()
570 	 * API dictates that kqueue descriptors are not inherited
571 	 * across forks (lame!).
572 	 */
573 	(void)event_init();
574 
575 	/*
576 	 * We must read the configuration file for the first time
577 	 * after the kqueue descriptor is created, because we install
578 	 * events during this process.
579 	 */
580 	init(0, 0, NULL);
581 
582 	/*
583 	 * Always exit on SIGTERM.  Also exit on SIGINT and SIGQUIT
584 	 * if we're debugging.
585 	 */
586 	(void)signal(SIGTERM, SIG_IGN);
587 	(void)signal(SIGINT, SIG_IGN);
588 	(void)signal(SIGQUIT, SIG_IGN);
589 
590 	ev = allocev();
591 	signal_set(ev, SIGTERM, die, ev);
592 	EVENT_ADD(ev);
593 
594 	if (Debug) {
595 		ev = allocev();
596 		signal_set(ev, SIGINT, die, ev);
597 		EVENT_ADD(ev);
598 		ev = allocev();
599 		signal_set(ev, SIGQUIT, die, ev);
600 		EVENT_ADD(ev);
601 	}
602 
603 	ev = allocev();
604 	signal_set(ev, SIGCHLD, reapchild, ev);
605 	EVENT_ADD(ev);
606 
607 	ev = allocev();
608 	schedule_event(&ev,
609 		&((struct timeval){TIMERINTVL, 0}),
610 		domark, ev);
611 
612 	(void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
613 
614 	/* Re-read configuration on SIGHUP. */
615 	(void) signal(SIGHUP, SIG_IGN);
616 	ev = allocev();
617 	signal_set(ev, SIGHUP, init, ev);
618 	EVENT_ADD(ev);
619 
620 #ifndef DISABLE_TLS
621 	ev = allocev();
622 	signal_set(ev, SIGUSR1, dispatch_force_tls_reconnect, ev);
623 	EVENT_ADD(ev);
624 #endif /* !DISABLE_TLS */
625 
626 	if (fklog >= 0) {
627 		ev = allocev();
628 		DPRINTF(D_EVENT,
629 			"register klog for fd %d with ev@%p\n", fklog, ev);
630 		event_set(ev, fklog, EV_READ | EV_PERSIST,
631 			dispatch_read_klog, ev);
632 		EVENT_ADD(ev);
633 	}
634 	for (j = 0, pp = LogPaths; *pp; pp++, j++) {
635 		ev = allocev();
636 		event_set(ev, funix[j], EV_READ | EV_PERSIST,
637 			dispatch_read_funix, ev);
638 		EVENT_ADD(ev);
639 	}
640 
641 	DPRINTF(D_MISC, "Off & running....\n");
642 
643 	j = event_dispatch();
644 	/* normal termination via die(), reaching this is an error */
645 	DPRINTF(D_MISC, "event_dispatch() returned %d\n", j);
646 	die(0, 0, NULL);
647 	/*NOTREACHED*/
648 	return 0;
649 }
650 
651 void
usage(void)652 usage(void)
653 {
654 
655 	(void)fprintf(stderr,
656 	    "usage: %s [-dnrSsTUv] [-b bind_address] [-f config_file] [-g group]\n"
657 	    "\t[-m mark_interval] [-P file_list] [-p log_socket\n"
658 	    "\t[-p log_socket2 ...]] [-t chroot_dir] [-u user]\n",
659 	    getprogname());
660 	exit(1);
661 }
662 
663 /*
664  * Dispatch routine for reading /dev/klog
665  *
666  * Note: slightly different semantic in dispatch_read functions:
667  *	 - read_klog() might give multiple messages in linebuf and
668  *	   leaves the task of splitting them to printsys()
669  *	 - all other read functions receive one message and
670  *	   then call printline() with one buffer.
671  */
672 static void
dispatch_read_klog(int fd,short event,void * ev)673 dispatch_read_klog(int fd, short event, void *ev)
674 {
675 	ssize_t rv;
676 	size_t resid = linebufsize - klog_linebufoff;
677 
678 	DPRINTF((D_CALL|D_EVENT), "Kernel log active (%d, %d, %p)"
679 		" with linebuf@%p, length %zu)\n", fd, event, ev,
680 		klog_linebuf, linebufsize);
681 
682 	rv = read(fd, &klog_linebuf[klog_linebufoff], resid - 1);
683 	if (rv > 0) {
684 		klog_linebuf[klog_linebufoff + rv] = '\0';
685 		printsys(klog_linebuf);
686 	} else if (rv < 0 && errno != EINTR) {
687 		/*
688 		 * /dev/klog has croaked.  Disable the event
689 		 * so it won't bother us again.
690 		 */
691 		logerror("klog failed");
692 		event_del(ev);
693 	}
694 }
695 
696 /*
697  * Dispatch routine for reading Unix domain sockets.
698  */
699 static void
dispatch_read_funix(int fd,short event,void * ev)700 dispatch_read_funix(int fd, short event, void *ev)
701 {
702 	struct sockaddr_un myname, fromunix;
703 	ssize_t rv;
704 	socklen_t sunlen;
705 
706 	sunlen = sizeof(myname);
707 	if (getsockname(fd, (struct sockaddr *)&myname, &sunlen) != 0) {
708 		/*
709 		 * This should never happen, so ensure that it doesn't
710 		 * happen again.
711 		 */
712 		logerror("getsockname() unix failed");
713 		event_del(ev);
714 		return;
715 	}
716 
717 #define SUN_PATHLEN(su) \
718 	((su)->sun_len - (sizeof(*(su)) - sizeof((su)->sun_path)))
719 
720 	DPRINTF((D_CALL|D_EVENT|D_NET), "Unix socket (%.*s) active (%d, %d %p)"
721 		" with linebuf@%p, size %zu)\n", (int)SUN_PATHLEN(&myname),
722 		myname.sun_path, fd, event, ev, linebuf, linebufsize-1);
723 
724 	sunlen = sizeof(fromunix);
725 	rv = recvfrom(fd, linebuf, linebufsize-1, 0,
726 	    (struct sockaddr *)&fromunix, &sunlen);
727 	if (rv > 0) {
728 		linebuf[rv] = '\0';
729 		printline(LocalFQDN, linebuf, 0);
730 	} else if (rv < 0 && errno != EINTR) {
731 		logerror("recvfrom() unix `%.*s'",
732 			(int)SUN_PATHLEN(&myname), myname.sun_path);
733 	}
734 }
735 
736 /*
737  * Dispatch routine for reading Internet sockets.
738  */
739 static void
dispatch_read_finet(int fd,short event,void * ev)740 dispatch_read_finet(int fd, short event, void *ev)
741 {
742 #ifdef LIBWRAP
743 	struct request_info req;
744 #endif
745 	struct sockaddr_storage frominet;
746 	ssize_t rv;
747 	socklen_t len;
748 	int reject = 0;
749 
750 	DPRINTF((D_CALL|D_EVENT|D_NET), "inet socket active (%d, %d %p) "
751 		" with linebuf@%p, size %zu)\n",
752 		fd, event, ev, linebuf, linebufsize-1);
753 
754 #ifdef LIBWRAP
755 	request_init(&req, RQ_DAEMON, appname, RQ_FILE, fd, NULL);
756 	fromhost(&req);
757 	reject = !hosts_access(&req);
758 	if (reject)
759 		DPRINTF(D_NET, "access denied\n");
760 #endif
761 
762 	len = sizeof(frominet);
763 	rv = recvfrom(fd, linebuf, linebufsize-1, 0,
764 	    (struct sockaddr *)&frominet, &len);
765 	if (rv == 0 || (rv < 0 && errno == EINTR))
766 		return;
767 	else if (rv < 0) {
768 		logerror("recvfrom inet");
769 		return;
770 	}
771 
772 	linebuf[rv] = '\0';
773 	if (!reject)
774 		printline(cvthname(&frominet), linebuf,
775 		    RemoteAddDate ? ADDDATE : 0);
776 }
777 
778 /*
779  * given a pointer to an array of char *'s, a pointer to its current
780  * size and current allocated max size, and a new char * to add, add
781  * it, update everything as necessary, possibly allocating a new array
782  */
783 void
logpath_add(char *** lp,int * szp,int * maxszp,const char * new)784 logpath_add(char ***lp, int *szp, int *maxszp, const char *new)
785 {
786 	char **nlp;
787 	int newmaxsz;
788 
789 	DPRINTF(D_FILE, "Adding `%s' to the %p logpath list\n", new, *lp);
790 	if (*szp == *maxszp) {
791 		if (*maxszp == 0) {
792 			newmaxsz = 4;	/* start of with enough for now */
793 			*lp = NULL;
794 		} else
795 			newmaxsz = *maxszp * 2;
796 		nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
797 		if (nlp == NULL) {
798 			logerror("Couldn't allocate line buffer");
799 			die(0, 0, NULL);
800 		}
801 		*lp = nlp;
802 		*maxszp = newmaxsz;
803 	}
804 	if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
805 		logerror("Couldn't allocate logpath");
806 		die(0, 0, NULL);
807 	}
808 	(*lp)[(*szp)] = NULL;		/* always keep it NULL terminated */
809 }
810 
811 /* do a file of log sockets */
812 void
logpath_fileadd(char *** lp,int * szp,int * maxszp,const char * file)813 logpath_fileadd(char ***lp, int *szp, int *maxszp, const char *file)
814 {
815 	FILE *fp;
816 	char *line;
817 	size_t len;
818 
819 	fp = fopen(file, "r");
820 	if (fp == NULL) {
821 		logerror("Could not open socket file list `%s'", file);
822 		die(0, 0, NULL);
823 	}
824 
825 	while ((line = fgetln(fp, &len)) != NULL) {
826 		line[len - 1] = 0;
827 		logpath_add(lp, szp, maxszp, line);
828 	}
829 	fclose(fp);
830 }
831 
832 /*
833  * checks UTF-8 codepoint
834  * returns either its length in bytes or 0 if *input is invalid
835 */
836 unsigned
valid_utf8(const char * c)837 valid_utf8(const char *c) {
838 	unsigned rc, nb;
839 
840 	/* first byte gives sequence length */
841 	     if ((*c & 0x80) == 0x00) return 1; /* 0bbbbbbb -- ASCII */
842 	else if ((*c & 0xc0) == 0x80) return 0; /* 10bbbbbb -- trailing byte */
843 	else if ((*c & 0xe0) == 0xc0) nb = 2;	/* 110bbbbb */
844 	else if ((*c & 0xf0) == 0xe0) nb = 3;	/* 1110bbbb */
845 	else if ((*c & 0xf8) == 0xf0) nb = 4;	/* 11110bbb */
846 	else return 0; /* UTF-8 allows only up to 4 bytes */
847 
848 	/* catch overlong encodings */
849 	if ((*c & 0xfe) == 0xc0)
850 		return 0; /* 1100000b ... */
851 	else if (((*c & 0xff) == 0xe0) && ((*(c+1) & 0xe0) == 0x80))
852 		return 0; /* 11100000 100bbbbb ... */
853 	else if (((*c & 0xff) == 0xf0) && ((*(c+1) & 0xf0) == 0x80))
854 		return 0; /* 11110000 1000bbbb ... ... */
855 
856 	/* and also filter UTF-16 surrogates (=invalid in UTF-8) */
857 	if (((*c & 0xff) == 0xed) && ((*(c+1) & 0xe0) == 0xa0))
858 		return 0; /* 11101101 101bbbbb ... */
859 
860 	rc = nb;
861 	/* check trailing bytes */
862 	switch (nb) {
863 	default: return 0;
864 	case 4: if ((*(c+3) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
865 	case 3: if ((*(c+2) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
866 	case 2: if ((*(c+1) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
867 	}
868 	return rc;
869 }
870 #define UTF8CHARMAX 4
871 
872 /*
873  * read UTF-8 value
874  * returns a the codepoint number
875  */
876 uint_fast32_t
get_utf8_value(const char * c)877 get_utf8_value(const char *c) {
878 	uint_fast32_t sum;
879 	unsigned nb, i;
880 
881 	/* first byte gives sequence length */
882 	     if ((*c & 0x80) == 0x00) return *c;/* 0bbbbbbb -- ASCII */
883 	else if ((*c & 0xc0) == 0x80) return 0; /* 10bbbbbb -- trailing byte */
884 	else if ((*c & 0xe0) == 0xc0) {		/* 110bbbbb */
885 		nb = 2;
886 		sum = (*c & ~0xe0) & 0xff;
887 	} else if ((*c & 0xf0) == 0xe0) {	/* 1110bbbb */
888 		nb = 3;
889 		sum = (*c & ~0xf0) & 0xff;
890 	} else if ((*c & 0xf8) == 0xf0) {	/* 11110bbb */
891 		nb = 4;
892 		sum = (*c & ~0xf8) & 0xff;
893 	} else return 0; /* UTF-8 allows only up to 4 bytes */
894 
895 	/* check trailing bytes -- 10bbbbbb */
896 	i = 1;
897 	while (i < nb) {
898 		sum <<= 6;
899 		sum |= ((*(c+i) & ~0xc0) & 0xff);
900 		i++;
901 	}
902 	return sum;
903 }
904 
905 /* note previous versions transscribe
906  * control characters, e.g. \007 --> "^G"
907  * did anyone rely on that?
908  *
909  * this new version works on only one buffer and
910  * replaces control characters with a space
911  */
912 #define NEXTFIELD(ptr) if (*(p) == ' ') (p)++; /* SP */			\
913 		       else {						\
914 				DPRINTF(D_DATA, "format error\n");	\
915 				if (*(p) == '\0') start = (p);		\
916 				goto all_syslog_msg;			\
917 		       }
918 #define FORCE2ASCII(c) ((iscntrl((unsigned char)(c)) && (c) != '\t')	\
919 			? ((c) == '\n' ? ' ' : '?')			\
920 			: (c) & 0177)
921 
922 /* following syslog-protocol */
923 #define printusascii(ch) (ch >= 33 && ch <= 126)
924 #define sdname(ch) (ch != '=' && ch != ' ' \
925 		 && ch != ']' && ch != '"' \
926 		 && printusascii(ch))
927 
928 /* checks whether the first word of string p can be interpreted as
929  * a syslog-protocol MSGID and if so returns its length.
930  *
931  * otherwise returns 0
932  */
933 static unsigned
check_msgid(char * p)934 check_msgid(char *p)
935 {
936 	char *q = p;
937 
938 	/* consider the NILVALUE to be valid */
939 	if (*q == '-' && *(q+1) == ' ')
940 		return 1;
941 
942 	for (;;) {
943 		if (*q == ' ')
944 			return q - p;
945 		else if (*q == '\0' || !printusascii(*q) || q - p >= MSGID_MAX)
946 			return 0;
947 		else
948 			q++;
949 	}
950 }
951 
952 /*
953  * returns number of chars found in SD at beginning of string p
954  * thus returns 0 if no valid SD is found
955  *
956  * if ascii == true then substitute all non-ASCII chars
957  * otherwise use syslog-protocol rules to allow UTF-8 in values
958  * note: one pass for filtering and scanning, so a found SD
959  * is always filtered, but an invalid one could be partially
960  * filtered up to the format error.
961  */
962 static unsigned
check_sd(char * p)963 check_sd(char* p)
964 {
965 	char *q = p;
966 	bool esc = false;
967 
968 	/* consider the NILVALUE to be valid */
969 	if (*q == '-' && (*(q+1) == ' ' || *(q+1) == '\0'))
970 		return 1;
971 
972 	for(;;) { /* SD-ELEMENT */
973 		if (*q++ != '[') return 0;
974 		/* SD-ID */
975 		if (!sdname(*q)) return 0;
976 		while (sdname(*q)) {
977 			*q = FORCE2ASCII(*q);
978 			q++;
979 		}
980 		for(;;) { /* SD-PARAM */
981 			if (*q == ']') {
982 				q++;
983 				if (*q == ' ' || *q == '\0') return q - p;
984 				else if (*q == '[') break;
985 			} else if (*q++ != ' ') return 0;
986 
987 			/* PARAM-NAME */
988 			if (!sdname(*q)) return 0;
989 			while (sdname(*q)) {
990 				*q = FORCE2ASCII(*q);
991 				q++;
992 			}
993 
994 			if (*q++ != '=') return 0;
995 			if (*q++ != '"') return 0;
996 
997 			for(;;) { /* PARAM-VALUE */
998 				if (esc) {
999 					esc = false;
1000 					if (*q == '\\' || *q == '"' ||
1001 					    *q == ']') {
1002 						q++;
1003 						continue;
1004 					}
1005 					/* no else because invalid
1006 					 * escape sequences are accepted */
1007 				}
1008 				else if (*q == '"') break;
1009 				else if (*q == '\0' || *q == ']') return 0;
1010 				else if (*q == '\\') esc = true;
1011 				else {
1012 					int i;
1013 					i = valid_utf8(q);
1014 					if (i == 0)
1015 						*q = '?';
1016 					else if (i == 1)
1017 						*q = FORCE2ASCII(*q);
1018 					else /* multi byte char */
1019 						q += (i-1);
1020 				}
1021 				q++;
1022 			}
1023 			q++;
1024 		}
1025 	}
1026 }
1027 
1028 struct buf_msg *
printline_syslogprotocol(const char * hname,char * msg,int flags,int pri)1029 printline_syslogprotocol(const char *hname, char *msg,
1030 	int flags, int pri)
1031 {
1032 	struct buf_msg *buffer;
1033 	char *p, *start;
1034 	unsigned sdlen = 0, i = 0;
1035 	bool utf8allowed = false; /* for some fields */
1036 
1037 	DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_syslogprotocol("
1038 	    "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1039 
1040 	buffer = buf_msg_new(0);
1041 	p = msg;
1042 	p += check_timestamp((unsigned char*) p,
1043 		&buffer->timestamp, true, !BSDOutputFormat);
1044 	DPRINTF(D_DATA, "Got timestamp \"%s\"\n", buffer->timestamp);
1045 
1046 	if (flags & ADDDATE) {
1047 		FREEPTR(buffer->timestamp);
1048 		buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1049 	}
1050 
1051 	start = p;
1052 	NEXTFIELD(p);
1053 	/* extract host */
1054 	for (start = p;; p++) {
1055 		if ((*p == ' ' || *p == '\0')
1056 		    && start == p-1 && *(p-1) == '-') {
1057 			/* NILVALUE */
1058 			break;
1059 		} else if ((*p == ' ' || *p == '\0')
1060 		    && (start != p-1 || *(p-1) != '-')) {
1061 			buffer->host = strndup(start, p - start);
1062 			break;
1063 		} else {
1064 			*p = FORCE2ASCII(*p);
1065 		}
1066 	}
1067 	/* p @ SP after host */
1068 	DPRINTF(D_DATA, "Got host \"%s\"\n", buffer->host);
1069 
1070 	/* extract app-name */
1071 	NEXTFIELD(p);
1072 	for (start = p;; p++) {
1073 		if ((*p == ' ' || *p == '\0')
1074 		    && start == p-1 && *(p-1) == '-') {
1075 			/* NILVALUE */
1076 			break;
1077 		} else if ((*p == ' ' || *p == '\0')
1078 		    && (start != p-1 || *(p-1) != '-')) {
1079 			buffer->prog = strndup(start, p - start);
1080 			break;
1081 		} else {
1082 			*p = FORCE2ASCII(*p);
1083 		}
1084 	}
1085 	DPRINTF(D_DATA, "Got prog \"%s\"\n", buffer->prog);
1086 
1087 	/* extract procid */
1088 	NEXTFIELD(p);
1089 	for (start = p;; p++) {
1090 		if ((*p == ' ' || *p == '\0')
1091 		    && start == p-1 && *(p-1) == '-') {
1092 			/* NILVALUE */
1093 			break;
1094 		} else if ((*p == ' ' || *p == '\0')
1095 		    && (start != p-1 || *(p-1) != '-')) {
1096 			buffer->pid = strndup(start, p - start);
1097 			start = p;
1098 			break;
1099 		} else {
1100 			*p = FORCE2ASCII(*p);
1101 		}
1102 	}
1103 	DPRINTF(D_DATA, "Got pid \"%s\"\n", buffer->pid);
1104 
1105 	/* extract msgid */
1106 	NEXTFIELD(p);
1107 	for (start = p;; p++) {
1108 		if ((*p == ' ' || *p == '\0')
1109 		    && start == p-1 && *(p-1) == '-') {
1110 			/* NILVALUE */
1111 			start = p+1;
1112 			break;
1113 		} else if ((*p == ' ' || *p == '\0')
1114 		    && (start != p-1 || *(p-1) != '-')) {
1115 			buffer->msgid = strndup(start, p - start);
1116 			start = p+1;
1117 			break;
1118 		} else {
1119 			*p = FORCE2ASCII(*p);
1120 		}
1121 	}
1122 	DPRINTF(D_DATA, "Got msgid \"%s\"\n", buffer->msgid);
1123 
1124 	/* extract SD */
1125 	NEXTFIELD(p);
1126 	start = p;
1127 	sdlen = check_sd(p);
1128 	DPRINTF(D_DATA, "check_sd(\"%s\") returned %d\n", p, sdlen);
1129 
1130 	if (sdlen == 1 && *p == '-') {
1131 		/* NILVALUE */
1132 		p++;
1133 	} else if (sdlen > 1) {
1134 		buffer->sd = strndup(p, sdlen);
1135 		p += sdlen;
1136 	} else {
1137 		DPRINTF(D_DATA, "format error\n");
1138 	}
1139 	if	(*p == '\0') start = p;
1140 	else if (*p == ' ')  start = ++p; /* SP */
1141 	DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1142 
1143 	/* and now the message itself
1144 	 * note: move back to last start to check for BOM
1145 	 */
1146 all_syslog_msg:
1147 	p = start;
1148 
1149 	/* check for UTF-8-BOM */
1150 	if (IS_BOM(p)) {
1151 		DPRINTF(D_DATA, "UTF-8 BOM\n");
1152 		utf8allowed = true;
1153 		p += 3;
1154 	}
1155 
1156 	if (*p != '\0' && !utf8allowed) {
1157 		size_t msglen;
1158 
1159 		msglen = strlen(p);
1160 		assert(!buffer->msg);
1161 		buffer->msg = copy_utf8_ascii(p, msglen);
1162 		buffer->msgorig = buffer->msg;
1163 		buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1164 	} else if (*p != '\0' && utf8allowed) {
1165 		while (*p != '\0') {
1166 			i = valid_utf8(p);
1167 			if (i == 0)
1168 				*p++ = '?';
1169 			else if (i == 1)
1170 				*p = FORCE2ASCII(*p);
1171 			p += i;
1172 		}
1173 		assert(p != start);
1174 		assert(!buffer->msg);
1175 		buffer->msg = strndup(start, p - start);
1176 		buffer->msgorig = buffer->msg;
1177 		buffer->msglen = buffer->msgsize = 1 + p - start;
1178 	}
1179 	DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1180 
1181 	buffer->recvhost = strdup(hname);
1182 	buffer->pri = pri;
1183 	buffer->flags = flags;
1184 
1185 	return buffer;
1186 }
1187 
1188 /* copies an input into a new ASCII buffer
1189  * ASCII controls are converted to format "^X"
1190  * multi-byte UTF-8 chars are converted to format "<ab><cd>"
1191  */
1192 #define INIT_BUFSIZE 512
1193 char *
copy_utf8_ascii(char * p,size_t p_len)1194 copy_utf8_ascii(char *p, size_t p_len)
1195 {
1196 	size_t idst = 0, isrc = 0, dstsize = INIT_BUFSIZE, i;
1197 	char *dst, *tmp_dst;
1198 
1199 	MALLOC(dst, dstsize);
1200 	while (isrc < p_len) {
1201 		if (dstsize < idst + 10) {
1202 			/* check for enough space for \0 and a UTF-8
1203 			 * conversion; longest possible is <U+123456> */
1204 			tmp_dst = realloc(dst, dstsize + INIT_BUFSIZE);
1205 			if (!tmp_dst)
1206 				break;
1207 			dst = tmp_dst;
1208 			dstsize += INIT_BUFSIZE;
1209 		}
1210 
1211 		i = valid_utf8(&p[isrc]);
1212 		if (i == 0) { /* invalid encoding */
1213 			dst[idst++] = '?';
1214 			isrc++;
1215 		} else if (i == 1) { /* check printable */
1216 			if (iscntrl((unsigned char)p[isrc])
1217 			 && p[isrc] != '\t') {
1218 				if (p[isrc] == '\n') {
1219 					dst[idst++] = ' ';
1220 					isrc++;
1221 				} else {
1222 					dst[idst++] = '^';
1223 					dst[idst++] = p[isrc++] ^ 0100;
1224 				}
1225 			} else
1226 				dst[idst++] = p[isrc++];
1227 		} else {  /* convert UTF-8 to ASCII */
1228 			dst[idst++] = '<';
1229 			idst += snprintf(&dst[idst], dstsize - idst, "U+%x",
1230 			    get_utf8_value(&p[isrc]));
1231 			isrc += i;
1232 			dst[idst++] = '>';
1233 		}
1234 	}
1235 	dst[idst] = '\0';
1236 
1237 	/* shrink buffer to right size */
1238 	tmp_dst = realloc(dst, idst+1);
1239 	if (tmp_dst)
1240 		return tmp_dst;
1241 	else
1242 		return dst;
1243 }
1244 
1245 struct buf_msg *
printline_bsdsyslog(const char * hname,char * msg,int flags,int pri)1246 printline_bsdsyslog(const char *hname, char *msg,
1247 	int flags, int pri)
1248 {
1249 	struct buf_msg *buffer;
1250 	char *p, *start;
1251 	unsigned msgidlen = 0, sdlen = 0;
1252 
1253 	DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_bsdsyslog("
1254 		"\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1255 
1256 	buffer = buf_msg_new(0);
1257 	p = msg;
1258 	p += check_timestamp((unsigned char*) p,
1259 		&buffer->timestamp, false, !BSDOutputFormat);
1260 	DPRINTF(D_DATA, "Got timestamp \"%s\"\n", buffer->timestamp);
1261 
1262 	if (flags & ADDDATE || !buffer->timestamp) {
1263 		FREEPTR(buffer->timestamp);
1264 		buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1265 	}
1266 
1267 	if (*p == ' ') p++; /* SP */
1268 	else goto all_bsd_msg;
1269 	/* in any error case we skip header parsing and
1270 	 * treat all following data as message content */
1271 
1272 	/* extract host */
1273 	for (start = p;; p++) {
1274 		if (*p == ' ' || *p == '\0') {
1275 			buffer->host = strndup(start, p - start);
1276 			break;
1277 		} else if (*p == '[' || (*p == ':'
1278 			&& (*(p+1) == ' ' || *(p+1) == '\0'))) {
1279 			/* no host in message */
1280 			buffer->host = LocalFQDN;
1281 			buffer->prog = strndup(start, p - start);
1282 			break;
1283 		} else {
1284 			*p = FORCE2ASCII(*p);
1285 		}
1286 	}
1287 	DPRINTF(D_DATA, "Got host \"%s\"\n", buffer->host);
1288 	/* p @ SP after host, or @ :/[ after prog */
1289 
1290 	/* extract program */
1291 	if (!buffer->prog) {
1292 		if (*p == ' ') p++; /* SP */
1293 		else goto all_bsd_msg;
1294 
1295 		for (start = p;; p++) {
1296 			if (*p == ' ' || *p == '\0') { /* error */
1297 				goto all_bsd_msg;
1298 			} else if (*p == '[' || (*p == ':'
1299 				&& (*(p+1) == ' ' || *(p+1) == '\0'))) {
1300 				buffer->prog = strndup(start, p - start);
1301 				break;
1302 			} else {
1303 				*p = FORCE2ASCII(*p);
1304 			}
1305 		}
1306 	}
1307 	DPRINTF(D_DATA, "Got prog \"%s\"\n", buffer->prog);
1308 	start = p;
1309 
1310 	/* p @ :/[ after prog */
1311 	if (*p == '[') {
1312 		p++;
1313 		if (*p == ' ') p++; /* SP */
1314 		for (start = p;; p++) {
1315 			if (*p == ' ' || *p == '\0') { /* error */
1316 				goto all_bsd_msg;
1317 			} else if (*p == ']') {
1318 				buffer->pid = strndup(start, p - start);
1319 				break;
1320 			} else {
1321 				*p = FORCE2ASCII(*p);
1322 			}
1323 		}
1324 	}
1325 	DPRINTF(D_DATA, "Got pid \"%s\"\n", buffer->pid);
1326 
1327 	if (*p == ']') p++;
1328 	if (*p == ':') p++;
1329 	if (*p == ' ') p++;
1330 
1331 	/* p @ msgid, @ opening [ of SD or @ first byte of message
1332 	 * accept either case and try to detect MSGID and SD fields
1333 	 *
1334 	 * only limitation: we do not accept UTF-8 data in
1335 	 * BSD Syslog messages -- so all SD values are ASCII-filtered
1336 	 *
1337 	 * I have found one scenario with 'unexpected' behaviour:
1338 	 * if there is only a SD intended, but a) it is short enough
1339 	 * to be a MSGID and b) the first word of the message can also
1340 	 * be parsed as an SD.
1341 	 * example:
1342 	 * "<35>Jul  6 12:39:08 tag[123]: [exampleSDID@0] - hello"
1343 	 * --> parsed as
1344 	 *     MSGID = "[exampleSDID@0]"
1345 	 *     SD    = "-"
1346 	 *     MSG   = "hello"
1347 	 */
1348 	start = p;
1349 	msgidlen = check_msgid(p);
1350 	if (msgidlen) /* check for SD in 2nd field */
1351 		sdlen = check_sd(p+msgidlen+1);
1352 
1353 	if (msgidlen && sdlen) {
1354 		/* MSGID in 1st and SD in 2nd field
1355 		 * now check for NILVALUEs and copy */
1356 		if (msgidlen == 1 && *p == '-') {
1357 			p++; /* - */
1358 			p++; /* SP */
1359 			DPRINTF(D_DATA, "Got MSGID \"-\"\n");
1360 		} else {
1361 			/* only has ASCII chars after check_msgid() */
1362 			buffer->msgid = strndup(p, msgidlen);
1363 			p += msgidlen;
1364 			p++; /* SP */
1365 			DPRINTF(D_DATA, "Got MSGID \"%s\"\n",
1366 				buffer->msgid);
1367 		}
1368 	} else {
1369 		/* either no msgid or no SD in 2nd field
1370 		 * --> check 1st field for SD */
1371 		DPRINTF(D_DATA, "No MSGID\n");
1372 		sdlen = check_sd(p);
1373 	}
1374 
1375 	if (sdlen == 0) {
1376 		DPRINTF(D_DATA, "No SD\n");
1377 	} else if (sdlen > 1) {
1378 		buffer->sd = copy_utf8_ascii(p, sdlen);
1379 		DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1380 	} else if (sdlen == 1 && *p == '-') {
1381 		p++;
1382 		DPRINTF(D_DATA, "Got SD \"-\"\n");
1383 	} else {
1384 		DPRINTF(D_DATA, "Error\n");
1385 	}
1386 
1387 	if (*p == ' ') p++;
1388 	start = p;
1389 	/* and now the message itself
1390 	 * note: do not reset start, because we might come here
1391 	 * by goto and want to have the incomplete field as part
1392 	 * of the msg
1393 	 */
1394 all_bsd_msg:
1395 	if (*p != '\0') {
1396 		size_t msglen = strlen(p);
1397 		buffer->msg = copy_utf8_ascii(p, msglen);
1398 		buffer->msgorig = buffer->msg;
1399 		buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1400 	}
1401 	DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1402 
1403 	buffer->recvhost = strdup(hname);
1404 	buffer->pri = pri;
1405 	buffer->flags = flags | BSDSYSLOG;
1406 
1407 	return buffer;
1408 }
1409 
1410 struct buf_msg *
printline_kernelprintf(const char * hname,char * msg,int flags,int pri)1411 printline_kernelprintf(const char *hname, char *msg,
1412 	int flags, int pri)
1413 {
1414 	struct buf_msg *buffer;
1415 	char *p;
1416 	unsigned sdlen = 0;
1417 
1418 	DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_kernelprintf("
1419 		"\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1420 
1421 	buffer = buf_msg_new(0);
1422 	buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1423 	buffer->pri = pri;
1424 	buffer->flags = flags;
1425 
1426 	/* assume there is no MSGID but there might be SD */
1427 	p = msg;
1428 	sdlen = check_sd(p);
1429 
1430 	if (sdlen == 0) {
1431 		DPRINTF(D_DATA, "No SD\n");
1432 	} else if (sdlen > 1) {
1433 		buffer->sd = copy_utf8_ascii(p, sdlen);
1434 		DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1435 	} else if (sdlen == 1 && *p == '-') {
1436 		p++;
1437 		DPRINTF(D_DATA, "Got SD \"-\"\n");
1438 	} else {
1439 		DPRINTF(D_DATA, "Error\n");
1440 	}
1441 
1442 	if (*p == ' ') p++;
1443 	if (*p != '\0') {
1444 		size_t msglen = strlen(p);
1445 		buffer->msg = copy_utf8_ascii(p, msglen);
1446 		buffer->msgorig = buffer->msg;
1447 		buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1448 	}
1449 	DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1450 
1451 	return buffer;
1452 }
1453 
1454 /*
1455  * Take a raw input line, read priority and version, call the
1456  * right message parsing function, then call logmsg().
1457  */
1458 void
printline(const char * hname,char * msg,int flags)1459 printline(const char *hname, char *msg, int flags)
1460 {
1461 	struct buf_msg *buffer;
1462 	int pri;
1463 	char *p, *q;
1464 	long n;
1465 	bool bsdsyslog = true;
1466 
1467 	DPRINTF((D_CALL|D_BUFFER|D_DATA),
1468 		"printline(\"%s\", \"%s\", %d)\n", hname, msg, flags);
1469 
1470 	/* test for special codes */
1471 	pri = DEFUPRI;
1472 	p = msg;
1473 	if (*p == '<') {
1474 		errno = 0;
1475 		n = strtol(p + 1, &q, 10);
1476 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1477 			p = q + 1;
1478 			pri = (int)n;
1479 			/* check for syslog-protocol version */
1480 			if (*p == '1' && p[1] == ' ') {
1481 				p += 2;	 /* skip version and space */
1482 				bsdsyslog = false;
1483 			} else {
1484 				bsdsyslog = true;
1485 			}
1486 		}
1487 	}
1488 	if (pri & ~(LOG_FACMASK|LOG_PRIMASK))
1489 		pri = DEFUPRI;
1490 
1491 	/*
1492 	 * Don't allow users to log kernel messages.
1493 	 * NOTE: Since LOG_KERN == 0, this will also match
1494 	 *	 messages with no facility specified.
1495 	 */
1496 	if ((pri & LOG_FACMASK) == LOG_KERN)
1497 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1498 
1499 	if (bsdsyslog) {
1500 		buffer = printline_bsdsyslog(hname, p, flags, pri);
1501 	} else {
1502 		buffer = printline_syslogprotocol(hname, p, flags, pri);
1503 	}
1504 	logmsg(buffer);
1505 	DELREF(buffer);
1506 }
1507 
1508 /*
1509  * Take a raw input line from /dev/klog, split and format similar to syslog().
1510  */
1511 void
printsys(char * msg)1512 printsys(char *msg)
1513 {
1514 	int n, is_printf, pri, flags;
1515 	char *p, *q;
1516 	struct buf_msg *buffer;
1517 
1518 	klog_linebufoff = 0;
1519 	for (p = msg; *p != '\0'; ) {
1520 		bool bsdsyslog = true;
1521 
1522 		is_printf = 1;
1523 		flags = ISKERNEL | ADDDATE | BSDSYSLOG;
1524 		if (SyncKernel)
1525 			flags |= SYNC_FILE;
1526 		if (is_printf) /* kernel printf's come out on console */
1527 			flags |= IGN_CONS;
1528 		pri = DEFSPRI;
1529 
1530 		if (*p == '<') {
1531 			errno = 0;
1532 			n = (int)strtol(p + 1, &q, 10);
1533 			if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1534 				p = q + 1;
1535 				is_printf = 0;
1536 				pri = n;
1537 				if (*p == '1') { /* syslog-protocol version */
1538 					p += 2;	 /* skip version and space */
1539 					bsdsyslog = false;
1540 				} else {
1541 					bsdsyslog = true;
1542 				}
1543 			}
1544 		}
1545 		for (q = p; *q != '\0' && *q != '\n'; q++)
1546 			/* look for end of line; no further checks.
1547 			 * trust the kernel to send ASCII only */;
1548 		if (*q != '\0')
1549 			*q++ = '\0';
1550 		else {
1551 			memcpy(linebuf, p, klog_linebufoff = q - p);
1552 			break;
1553 		}
1554 
1555 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1556 			pri = DEFSPRI;
1557 
1558 		/* allow all kinds of input from kernel */
1559 		if (is_printf)
1560 			buffer = printline_kernelprintf(
1561 			    LocalFQDN, p, flags, pri);
1562 		else {
1563 			if (bsdsyslog)
1564 				buffer = printline_bsdsyslog(
1565 				    LocalFQDN, p, flags, pri);
1566 			else
1567 				buffer = printline_syslogprotocol(
1568 				    LocalFQDN, p, flags, pri);
1569 		}
1570 
1571 		/* set fields left open */
1572 		if (!buffer->prog)
1573 			buffer->prog = strdup(_PATH_UNIX);
1574 		if (!buffer->host)
1575 			buffer->host = LocalFQDN;
1576 		if (!buffer->recvhost)
1577 			buffer->recvhost = LocalFQDN;
1578 
1579 		logmsg(buffer);
1580 		DELREF(buffer);
1581 		p = q;
1582 	}
1583 }
1584 
1585 /*
1586  * Check to see if `name' matches the provided specification, using the
1587  * specified strstr function.
1588  */
1589 int
matches_spec(const char * name,const char * spec,char * (* check)(const char *,const char *))1590 matches_spec(const char *name, const char *spec,
1591     char *(*check)(const char *, const char *))
1592 {
1593 	const char *s;
1594 	const char *cursor;
1595 	char prev, next;
1596 	size_t len;
1597 
1598 	if (name[0] == '\0')
1599 		return 0;
1600 
1601 	if (strchr(name, ',')) /* sanity */
1602 		return 0;
1603 
1604 	len = strlen(name);
1605 	cursor = spec;
1606 	while ((s = (*check)(cursor, name)) != NULL) {
1607 		prev = s == spec ? ',' : *(s - 1);
1608 		cursor = s + len;
1609 		next = *cursor;
1610 
1611 		if (prev == ',' && (next == '\0' || next == ','))
1612 			return 1;
1613 	}
1614 
1615 	return 0;
1616 }
1617 
1618 /*
1619  * wrapper with old function signature,
1620  * keeps calling code shorter and hides buffer allocation
1621  */
1622 void
logmsg_async(int pri,const char * sd,const char * msg,int flags)1623 logmsg_async(int pri, const char *sd, const char *msg, int flags)
1624 {
1625 	struct buf_msg *buffer;
1626 	size_t msglen;
1627 
1628 	DPRINTF((D_CALL|D_DATA), "logmsg_async(%d, \"%s\", \"%s\", %d)\n",
1629 	    pri, sd, msg, flags);
1630 
1631 	if (msg) {
1632 		msglen = strlen(msg);
1633 		msglen++;		/* adds \0 */
1634 		buffer = buf_msg_new(msglen);
1635 		buffer->msglen = strlcpy(buffer->msg, msg, msglen) + 1;
1636 	} else {
1637 		buffer = buf_msg_new(0);
1638 	}
1639 	if (sd) buffer->sd = strdup(sd);
1640 	buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
1641 	buffer->prog = appname;
1642 	buffer->pid = include_pid;
1643 	buffer->recvhost = buffer->host = LocalFQDN;
1644 	buffer->pri = pri;
1645 	buffer->flags = flags;
1646 
1647 	logmsg(buffer);
1648 	DELREF(buffer);
1649 }
1650 
1651 /* read timestamp in from_buf, convert into a timestamp in to_buf
1652  *
1653  * returns length of timestamp found in from_buf (= number of bytes consumed)
1654  */
1655 size_t
check_timestamp(unsigned char * from_buf,char ** to_buf,bool from_iso,bool to_iso)1656 check_timestamp(unsigned char *from_buf, char **to_buf,
1657 	bool from_iso, bool to_iso)
1658 {
1659 	unsigned char *q;
1660 	int p;
1661 	bool found_ts = false;
1662 
1663 	DPRINTF((D_CALL|D_DATA), "check_timestamp(%p = \"%s\", from_iso=%d, "
1664 	    "to_iso=%d)\n", from_buf, from_buf, from_iso, to_iso);
1665 
1666 	if (!from_buf) return 0;
1667 	/*
1668 	 * Check to see if msg looks non-standard.
1669 	 * looks at every char because we do not have a msg length yet
1670 	 */
1671 	/* detailed checking adapted from Albert Mietus' sl_timestamp.c */
1672 	if (from_iso) {
1673 		if (from_buf[4] == '-' && from_buf[7] == '-'
1674 		    && from_buf[10] == 'T' && from_buf[13] == ':'
1675 		    && from_buf[16] == ':'
1676 		    && isdigit(from_buf[0]) && isdigit(from_buf[1])
1677 		    && isdigit(from_buf[2]) && isdigit(from_buf[3])  /* YYYY */
1678 		    && isdigit(from_buf[5]) && isdigit(from_buf[6])
1679 		    && isdigit(from_buf[8]) && isdigit(from_buf[9])  /* mm dd */
1680 		    && isdigit(from_buf[11]) && isdigit(from_buf[12]) /* HH */
1681 		    && isdigit(from_buf[14]) && isdigit(from_buf[15]) /* MM */
1682 		    && isdigit(from_buf[17]) && isdigit(from_buf[18]) /* SS */
1683 		    )  {
1684 			/* time-secfrac */
1685 			if (from_buf[19] == '.')
1686 				for (p=20; isdigit(from_buf[p]); p++) /* NOP*/;
1687 			else
1688 				p = 19;
1689 			/* time-offset */
1690 			if (from_buf[p] == 'Z'
1691 			 || ((from_buf[p] == '+' || from_buf[p] == '-')
1692 			    && from_buf[p+3] == ':'
1693 			    && isdigit(from_buf[p+1]) && isdigit(from_buf[p+2])
1694 			    && isdigit(from_buf[p+4]) && isdigit(from_buf[p+5])
1695 			 ))
1696 				found_ts = true;
1697 		}
1698 	} else {
1699 		if (from_buf[3] == ' ' && from_buf[6] == ' '
1700 		    && from_buf[9] == ':' && from_buf[12] == ':'
1701 		    && (from_buf[4] == ' ' || isdigit(from_buf[4]))
1702 		    && isdigit(from_buf[5]) /* dd */
1703 		    && isdigit(from_buf[7])  && isdigit(from_buf[8])   /* HH */
1704 		    && isdigit(from_buf[10]) && isdigit(from_buf[11])  /* MM */
1705 		    && isdigit(from_buf[13]) && isdigit(from_buf[14])  /* SS */
1706 		    && isupper(from_buf[0]) && islower(from_buf[1]) /* month */
1707 		    && islower(from_buf[2]))
1708 			found_ts = true;
1709 	}
1710 	if (!found_ts) {
1711 		if (from_buf[0] == '-' && from_buf[1] == ' ') {
1712 			/* NILVALUE */
1713 			if (to_iso) {
1714 				/* with ISO = syslog-protocol output leave
1715 			 	 * it as is, because it is better to have
1716 			 	 * no timestamp than a wrong one.
1717 			 	 */
1718 				*to_buf = strdup("-");
1719 			} else {
1720 				/* with BSD Syslog the field is reqired
1721 				 * so replace it with current time
1722 				 */
1723 				*to_buf = make_timestamp(NULL, false, 0);
1724 			}
1725 			return 2;
1726 		}
1727 		*to_buf = make_timestamp(NULL, false, 0);
1728 		return 0;
1729 	}
1730 
1731 	if (!from_iso && !to_iso) {
1732 		/* copy BSD timestamp */
1733 		DPRINTF(D_CALL, "check_timestamp(): copy BSD timestamp\n");
1734 		*to_buf = strndup((char *)from_buf, BSD_TIMESTAMPLEN);
1735 		return BSD_TIMESTAMPLEN;
1736 	} else if (from_iso && to_iso) {
1737 		/* copy ISO timestamp */
1738 		DPRINTF(D_CALL, "check_timestamp(): copy ISO timestamp\n");
1739 		if (!(q = (unsigned char *) strchr((char *)from_buf, ' ')))
1740 			q = from_buf + strlen((char *)from_buf);
1741 		*to_buf = strndup((char *)from_buf, q - from_buf);
1742 		return q - from_buf;
1743 	} else if (from_iso && !to_iso) {
1744 		/* convert ISO->BSD */
1745 		struct tm parsed;
1746 		time_t timeval;
1747 		char tsbuf[MAX_TIMESTAMPLEN];
1748 		int i = 0;
1749 
1750 		DPRINTF(D_CALL, "check_timestamp(): convert ISO->BSD\n");
1751 		for(i = 0; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1752 		    && from_buf[i] != '.' && from_buf[i] != ' '; i++)
1753 			tsbuf[i] = from_buf[i]; /* copy date & time */
1754 		for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1755 		    && from_buf[i] != '+' && from_buf[i] != '-'
1756 		    && from_buf[i] != 'Z' && from_buf[i] != ' '; i++)
1757 			;			   /* skip fraction digits */
1758 		for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1759 		    && from_buf[i] != ':' && from_buf[i] != ' ' ; i++)
1760 			tsbuf[i] = from_buf[i]; /* copy TZ */
1761 		if (from_buf[i] == ':') i++;	/* skip colon */
1762 		for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1763 		    && from_buf[i] != ' ' ; i++)
1764 			tsbuf[i] = from_buf[i]; /* copy TZ */
1765 
1766 		(void)memset(&parsed, 0, sizeof(parsed));
1767 		parsed.tm_isdst = -1;
1768 		(void)strptime(tsbuf, "%FT%T%z", &parsed);
1769 		timeval = mktime(&parsed);
1770 
1771 		*to_buf = make_timestamp(&timeval, false, BSD_TIMESTAMPLEN);
1772 		return i;
1773 	} else if (!from_iso && to_iso) {
1774 		/* convert BSD->ISO */
1775 		struct tm parsed;
1776 		struct tm *current;
1777 		time_t timeval;
1778 
1779 		(void)memset(&parsed, 0, sizeof(parsed));
1780 		parsed.tm_isdst = -1;
1781 		DPRINTF(D_CALL, "check_timestamp(): convert BSD->ISO\n");
1782 		strptime((char *)from_buf, "%b %d %T", &parsed);
1783 		current = gmtime(&now);
1784 
1785 		/* use current year and timezone */
1786 		parsed.tm_isdst = current->tm_isdst;
1787 		parsed.tm_gmtoff = current->tm_gmtoff;
1788 		parsed.tm_year = current->tm_year;
1789 		if (current->tm_mon == 0 && parsed.tm_mon == 11)
1790 			parsed.tm_year--;
1791 
1792 		timeval = mktime(&parsed);
1793 		*to_buf = make_timestamp(&timeval, true, MAX_TIMESTAMPLEN - 1);
1794 
1795 		return BSD_TIMESTAMPLEN;
1796 	} else {
1797 		DPRINTF(D_MISC,
1798 			"Executing unreachable code in check_timestamp()\n");
1799 		return 0;
1800 	}
1801 }
1802 
1803 /*
1804  * Log a message to the appropriate log files, users, etc. based on
1805  * the priority.
1806  */
1807 void
logmsg(struct buf_msg * buffer)1808 logmsg(struct buf_msg *buffer)
1809 {
1810 	struct filed *f;
1811 	int fac, omask, prilev;
1812 
1813 	DPRINTF((D_CALL|D_BUFFER), "logmsg: buffer@%p, pri 0%o/%d, flags 0x%x,"
1814 	    " timestamp \"%s\", from \"%s\", sd \"%s\", msg \"%s\"\n",
1815 	    buffer, buffer->pri, buffer->pri, buffer->flags,
1816 	    buffer->timestamp, buffer->recvhost, buffer->sd, buffer->msg);
1817 
1818 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
1819 
1820 	/* sanity check */
1821 	assert(buffer->refcount == 1);
1822 	assert(buffer->msglen <= buffer->msgsize);
1823 	assert(buffer->msgorig <= buffer->msg);
1824 	assert((buffer->msg && buffer->msglen == strlen(buffer->msg)+1)
1825 	      || (!buffer->msg && !buffer->msglen));
1826 	if (!buffer->msg && !buffer->sd && !buffer->msgid)
1827 		DPRINTF(D_BUFFER, "Empty message?\n");
1828 
1829 	/* extract facility and priority level */
1830 	if (buffer->flags & MARK)
1831 		fac = LOG_NFACILITIES;
1832 	else
1833 		fac = LOG_FAC(buffer->pri);
1834 	prilev = LOG_PRI(buffer->pri);
1835 
1836 	/* log the message to the particular outputs */
1837 	if (!Initialized) {
1838 		f = &consfile;
1839 		f->f_file = open(ctty, O_WRONLY | O_NDELAY, 0);
1840 
1841 		if (f->f_file >= 0) {
1842 			DELREF(f->f_prevmsg);
1843 			f->f_prevmsg = NEWREF(buffer);
1844 			fprintlog(f, NEWREF(buffer), NULL);
1845 			DELREF(buffer);
1846 			(void)close(f->f_file);
1847 		}
1848 		(void)sigsetmask(omask);
1849 		return;
1850 	}
1851 
1852 	for (f = Files; f; f = f->f_next) {
1853 		char *h;	/* host to use for comparing */
1854 
1855 		/* skip messages that are incorrect priority */
1856 		if (!MATCH_PRI(f, fac, prilev)
1857 		    || f->f_pmask[fac] == INTERNAL_NOPRI)
1858 			continue;
1859 
1860 		/* skip messages with the incorrect host name */
1861 		/* compare with host (which is supposedly more correct), */
1862 		/* but fallback to recvhost if host is NULL */
1863 		h = (buffer->host != NULL) ? buffer->host : buffer->recvhost;
1864 		if (f->f_host != NULL && h != NULL) {
1865 			char shost[MAXHOSTNAMELEN + 1];
1866 
1867 			if (BSDOutputFormat) {
1868 				(void)strlcpy(shost, h, sizeof(shost));
1869 				trim_anydomain(shost);
1870 				h = shost;
1871 			}
1872 			switch (f->f_host[0]) {
1873 			case '+':
1874 				if (! matches_spec(h, f->f_host + 1,
1875 				    strcasestr))
1876 					continue;
1877 				break;
1878 			case '-':
1879 				if (matches_spec(h, f->f_host + 1,
1880 				    strcasestr))
1881 					continue;
1882 				break;
1883 			}
1884 		}
1885 
1886 		/* skip messages with the incorrect program name */
1887 		if (f->f_program != NULL && buffer->prog != NULL) {
1888 			switch (f->f_program[0]) {
1889 			case '+':
1890 				if (!matches_spec(buffer->prog,
1891 				    f->f_program + 1, strstr))
1892 					continue;
1893 				break;
1894 			case '-':
1895 				if (matches_spec(buffer->prog,
1896 				    f->f_program + 1, strstr))
1897 					continue;
1898 				break;
1899 			default:
1900 				if (!matches_spec(buffer->prog,
1901 				    f->f_program, strstr))
1902 					continue;
1903 				break;
1904 			}
1905 		}
1906 
1907 		if (f->f_type == F_CONSOLE && (buffer->flags & IGN_CONS))
1908 			continue;
1909 
1910 		/* don't output marks to recently written files */
1911 		if ((buffer->flags & MARK)
1912 		 && (now - f->f_time) < MarkInterval / 2)
1913 			continue;
1914 
1915 		/*
1916 		 * suppress duplicate lines to this file unless NoRepeat
1917 		 */
1918 #define MSG_FIELD_EQ(x) ((!buffer->x && !f->f_prevmsg->x) ||	\
1919     (buffer->x && f->f_prevmsg->x && !strcmp(buffer->x, f->f_prevmsg->x)))
1920 
1921 		if ((buffer->flags & MARK) == 0 &&
1922 		    f->f_prevmsg &&
1923 		    buffer->msglen == f->f_prevmsg->msglen &&
1924 		    !NoRepeat &&
1925 		    MSG_FIELD_EQ(host) &&
1926 		    MSG_FIELD_EQ(sd) &&
1927 		    MSG_FIELD_EQ(msg)
1928 		    ) {
1929 			f->f_prevcount++;
1930 			DPRINTF(D_DATA, "Msg repeated %d times, %ld sec of %d\n",
1931 			    f->f_prevcount, (long)(now - f->f_time),
1932 			    repeatinterval[f->f_repeatcount]);
1933 			/*
1934 			 * If domark would have logged this by now,
1935 			 * flush it now (so we don't hold isolated messages),
1936 			 * but back off so we'll flush less often
1937 			 * in the future.
1938 			 */
1939 			if (now > REPEATTIME(f)) {
1940 				fprintlog(f, NEWREF(buffer), NULL);
1941 				DELREF(buffer);
1942 				BACKOFF(f);
1943 			}
1944 		} else {
1945 			/* new line, save it */
1946 			if (f->f_prevcount)
1947 				fprintlog(f, NULL, NULL);
1948 			f->f_repeatcount = 0;
1949 			DELREF(f->f_prevmsg);
1950 			f->f_prevmsg = NEWREF(buffer);
1951 			fprintlog(f, NEWREF(buffer), NULL);
1952 			DELREF(buffer);
1953 		}
1954 	}
1955 	(void)sigsetmask(omask);
1956 }
1957 
1958 /*
1959  * format one buffer into output format given by flag BSDOutputFormat
1960  * line is allocated and has to be free()d by caller
1961  * size_t pointers are optional, if not NULL then they will return
1962  *   different lenghts used for formatting and output
1963  */
1964 #define OUT(x) ((x)?(x):"-")
1965 bool
format_buffer(struct buf_msg * buffer,char ** line,size_t * ptr_linelen,size_t * ptr_msglen,size_t * ptr_tlsprefixlen,size_t * ptr_prilen)1966 format_buffer(struct buf_msg *buffer, char **line, size_t *ptr_linelen,
1967 	size_t *ptr_msglen, size_t *ptr_tlsprefixlen, size_t *ptr_prilen)
1968 {
1969 #define FPBUFSIZE 30
1970 	static char ascii_empty[] = "";
1971 	char fp_buf[FPBUFSIZE] = "\0";
1972 	char *hostname, *shorthostname = NULL;
1973 	char *ascii_sd = ascii_empty;
1974 	char *ascii_msg = ascii_empty;
1975 	size_t linelen, msglen, tlsprefixlen, prilen, j;
1976 
1977 	DPRINTF(D_CALL, "format_buffer(%p)\n", buffer);
1978 	if (!buffer) return false;
1979 
1980 	/* All buffer fields are set with strdup(). To avoid problems
1981 	 * on memory exhaustion we allow them to be empty and replace
1982 	 * the essential fields with already allocated generic values.
1983 	 */
1984 	if (!buffer->timestamp)
1985 		buffer->timestamp = timestamp;
1986 	if (!buffer->host && !buffer->recvhost)
1987 		buffer->host = LocalFQDN;
1988 
1989 	if (LogFacPri) {
1990 		const char *f_s = NULL, *p_s = NULL;
1991 		int fac = buffer->pri & LOG_FACMASK;
1992 		int pri = LOG_PRI(buffer->pri);
1993 		char f_n[5], p_n[5];
1994 
1995 		if (LogFacPri > 1) {
1996 			CODE *c;
1997 
1998 			for (c = facilitynames; c->c_name != NULL; c++) {
1999 				if (c->c_val == fac) {
2000 					f_s = c->c_name;
2001 					break;
2002 				}
2003 			}
2004 			for (c = prioritynames; c->c_name != NULL; c++) {
2005 				if (c->c_val == pri) {
2006 					p_s = c->c_name;
2007 					break;
2008 				}
2009 			}
2010 		}
2011 		if (f_s == NULL) {
2012 			snprintf(f_n, sizeof(f_n), "%d", LOG_FAC(fac));
2013 			f_s = f_n;
2014 		}
2015 		if (p_s == NULL) {
2016 			snprintf(p_n, sizeof(p_n), "%d", pri);
2017 			p_s = p_n;
2018 		}
2019 		snprintf(fp_buf, sizeof(fp_buf), "<%s.%s>", f_s, p_s);
2020 	}
2021 
2022 	/* hostname or FQDN */
2023 	hostname = (buffer->host ? buffer->host : buffer->recvhost);
2024 	if (BSDOutputFormat
2025 	 && (shorthostname = strdup(hostname))) {
2026 		/* if the previous BSD output format with "host [recvhost]:"
2027 		 * gets implemented, this is the right place to distinguish
2028 		 * between buffer->host and buffer->recvhost
2029 		 */
2030 		trim_anydomain(shorthostname);
2031 		hostname = shorthostname;
2032 	}
2033 
2034 	/* new message formatting:
2035 	 * instead of using iov always assemble one complete TLS-ready line
2036 	 * with length and priority (depending on BSDOutputFormat either in
2037 	 * BSD Syslog or syslog-protocol format)
2038 	 *
2039 	 * additionally save the length of the prefixes,
2040 	 * so UDP destinations can skip the length prefix and
2041 	 * file/pipe/wall destinations can omit length and priority
2042 	 */
2043 	/* first determine required space */
2044 	if (BSDOutputFormat) {
2045 		/* only output ASCII chars */
2046 		if (buffer->sd)
2047 			ascii_sd = copy_utf8_ascii(buffer->sd,
2048 				strlen(buffer->sd));
2049 		if (buffer->msg) {
2050 			if (IS_BOM(buffer->msg))
2051 				ascii_msg = copy_utf8_ascii(buffer->msg,
2052 					buffer->msglen - 1);
2053 			else /* assume already converted at input */
2054 				ascii_msg = buffer->msg;
2055 		}
2056 		msglen = snprintf(NULL, 0, "<%d>%s%.15s %s %s%s%s%s: %s%s%s",
2057 			     buffer->pri, fp_buf, buffer->timestamp,
2058 			     hostname, OUT(buffer->prog),
2059 			     buffer->pid ? "[" : "",
2060 			     buffer->pid ? buffer->pid : "",
2061 			     buffer->pid ? "]" : "", ascii_sd,
2062 			     (buffer->sd && buffer->msg ? " ": ""), ascii_msg);
2063 	} else
2064 		msglen = snprintf(NULL, 0, "<%d>1 %s%s %s %s %s %s %s%s%s",
2065 			     buffer->pri, fp_buf, buffer->timestamp,
2066 			     hostname, OUT(buffer->prog), OUT(buffer->pid),
2067 			     OUT(buffer->msgid), OUT(buffer->sd),
2068 			     (buffer->msg ? " ": ""),
2069 			     (buffer->msg ? buffer->msg: ""));
2070 	/* add space for length prefix */
2071 	tlsprefixlen = 0;
2072 	for (j = msglen; j; j /= 10)
2073 		tlsprefixlen++;
2074 	/* one more for the space */
2075 	tlsprefixlen++;
2076 
2077 	prilen = snprintf(NULL, 0, "<%d>", buffer->pri);
2078 	if (!BSDOutputFormat)
2079 		prilen += 2; /* version char and space */
2080 	MALLOC(*line, msglen + tlsprefixlen + 1);
2081 	if (BSDOutputFormat)
2082 		linelen = snprintf(*line,
2083 		     msglen + tlsprefixlen + 1,
2084 		     "%zu <%d>%s%.15s %s %s%s%s%s: %s%s%s",
2085 		     msglen, buffer->pri, fp_buf, buffer->timestamp,
2086 		     hostname, OUT(buffer->prog),
2087 		     (buffer->pid ? "[" : ""),
2088 		     (buffer->pid ? buffer->pid : ""),
2089 		     (buffer->pid ? "]" : ""), ascii_sd,
2090 		     (buffer->sd && buffer->msg ? " ": ""), ascii_msg);
2091 	else
2092 		linelen = snprintf(*line,
2093 		     msglen + tlsprefixlen + 1,
2094 		     "%zu <%d>1 %s%s %s %s %s %s %s%s%s",
2095 		     msglen, buffer->pri, fp_buf, buffer->timestamp,
2096 		     hostname, OUT(buffer->prog), OUT(buffer->pid),
2097 		     OUT(buffer->msgid), OUT(buffer->sd),
2098 		     (buffer->msg ? " ": ""),
2099 		     (buffer->msg ? buffer->msg: ""));
2100 	DPRINTF(D_DATA, "formatted %zu octets to: '%.*s' (linelen %zu, "
2101 	    "msglen %zu, tlsprefixlen %zu, prilen %zu)\n", linelen,
2102 	    (int)linelen, *line, linelen, msglen, tlsprefixlen, prilen);
2103 
2104 	FREEPTR(shorthostname);
2105 	if (ascii_sd != ascii_empty)
2106 		FREEPTR(ascii_sd);
2107 	if (ascii_msg != ascii_empty && ascii_msg != buffer->msg)
2108 		FREEPTR(ascii_msg);
2109 
2110 	if (ptr_linelen)      *ptr_linelen	= linelen;
2111 	if (ptr_msglen)	      *ptr_msglen	= msglen;
2112 	if (ptr_tlsprefixlen) *ptr_tlsprefixlen = tlsprefixlen;
2113 	if (ptr_prilen)	      *ptr_prilen	= prilen;
2114 	return true;
2115 }
2116 
2117 /*
2118  * if qentry == NULL: new message, if temporarily undeliverable it will be enqueued
2119  * if qentry != NULL: a temporarily undeliverable message will not be enqueued,
2120  *		    but after delivery be removed from the queue
2121  */
2122 void
fprintlog(struct filed * f,struct buf_msg * passedbuffer,struct buf_queue * qentry)2123 fprintlog(struct filed *f, struct buf_msg *passedbuffer, struct buf_queue *qentry)
2124 {
2125 	static char crnl[] = "\r\n";
2126 	struct buf_msg *buffer = passedbuffer;
2127 	struct iovec iov[4];
2128 	struct iovec *v = iov;
2129 	bool error = false;
2130 	int e = 0, len = 0;
2131 	size_t msglen, linelen, tlsprefixlen, prilen;
2132 	char *p, *line = NULL, *lineptr = NULL;
2133 #ifndef DISABLE_SIGN
2134 	bool newhash = false;
2135 #endif
2136 #define REPBUFSIZE 80
2137 	char greetings[200];
2138 #define ADDEV() do { v++; assert((size_t)(v - iov) < A_CNT(iov)); } while(/*CONSTCOND*/0)
2139 
2140 	DPRINTF(D_CALL, "fprintlog(%p, %p, %p)\n", f, buffer, qentry);
2141 
2142 	f->f_time = now;
2143 
2144 	/* increase refcount here and lower again at return.
2145 	 * this enables the buffer in the else branch to be freed
2146 	 * --> every branch needs one NEWREF() or buf_msg_new()! */
2147 	if (buffer) {
2148 		(void)NEWREF(buffer);
2149 	} else {
2150 		if (f->f_prevcount > 1) {
2151 			/* possible syslog-sign incompatibility:
2152 			 * assume destinations f1 and f2 share one SG and
2153 			 * get the same message sequence.
2154 			 *
2155 			 * now both f1 and f2 generate "repeated" messages
2156 			 * "repeated" messages are different due to different
2157 			 * timestamps
2158 			 * the SG will get hashes for the two "repeated" messages
2159 			 *
2160 			 * now both f1 and f2 are just fine, but a verification
2161 			 * will report that each 'lost' a message, i.e. the
2162 			 * other's "repeated" message
2163 			 *
2164 			 * conditions for 'safe configurations':
2165 			 * - use NoRepeat option,
2166 			 * - use SG 3, or
2167 			 * - have exactly one destination for every PRI
2168 			 */
2169 			buffer = buf_msg_new(REPBUFSIZE);
2170 			buffer->msglen = snprintf(buffer->msg, REPBUFSIZE,
2171 			    "last message repeated %d times", f->f_prevcount);
2172 			buffer->timestamp = make_timestamp(NULL,
2173 			    !BSDOutputFormat, 0);
2174 			buffer->pri = f->f_prevmsg->pri;
2175 			buffer->host = LocalFQDN;
2176 			buffer->prog = appname;
2177 			buffer->pid = include_pid;
2178 
2179 		} else {
2180 			buffer = NEWREF(f->f_prevmsg);
2181 		}
2182 	}
2183 
2184 	/* no syslog-sign messages to tty/console/... */
2185 	if ((buffer->flags & SIGN_MSG)
2186 	    && ((f->f_type == F_UNUSED)
2187 	    || (f->f_type == F_TTY)
2188 	    || (f->f_type == F_CONSOLE)
2189 	    || (f->f_type == F_USERS)
2190 	    || (f->f_type == F_WALL)
2191 	    || (f->f_type == F_FIFO))) {
2192 		DELREF(buffer);
2193 		return;
2194 	}
2195 
2196 	/* buffering works only for few types */
2197 	if (qentry
2198 	    && (f->f_type != F_TLS)
2199 	    && (f->f_type != F_PIPE)
2200 	    && (f->f_type != F_FILE)
2201 	    && (f->f_type != F_FIFO)) {
2202 		errno = 0;
2203 		logerror("Warning: unexpected message type %d in buffer",
2204 		    f->f_type);
2205 		DELREF(buffer);
2206 		return;
2207 	}
2208 
2209 	if (!format_buffer(buffer, &line,
2210 	    &linelen, &msglen, &tlsprefixlen, &prilen)) {
2211 		DPRINTF(D_CALL, "format_buffer() failed, skip message\n");
2212 		DELREF(buffer);
2213 		return;
2214 	}
2215 	/* assert maximum message length */
2216 	if (TypeInfo[f->f_type].max_msg_length != -1
2217 	    && (size_t)TypeInfo[f->f_type].max_msg_length
2218 	    < linelen - tlsprefixlen - prilen) {
2219 		linelen = TypeInfo[f->f_type].max_msg_length
2220 		    + tlsprefixlen + prilen;
2221 		DPRINTF(D_DATA, "truncating oversized message to %zu octets\n",
2222 		    linelen);
2223 	}
2224 
2225 #ifndef DISABLE_SIGN
2226 	/* keep state between appending the hash (before buffer is sent)
2227 	 * and possibly sending a SB (after buffer is sent): */
2228 	/* get hash */
2229 	if (!(buffer->flags & SIGN_MSG) && !qentry) {
2230 		char *hash = NULL;
2231 		struct signature_group_t *sg;
2232 
2233 		if ((sg = sign_get_sg(buffer->pri, f)) != NULL) {
2234 			if (sign_msg_hash(line + tlsprefixlen, &hash))
2235 				newhash = sign_append_hash(hash, sg);
2236 			else
2237 				DPRINTF(D_SIGN,
2238 					"Unable to hash line \"%s\"\n", line);
2239 		}
2240 	}
2241 #endif /* !DISABLE_SIGN */
2242 
2243 	/* set start and length of buffer and/or fill iovec */
2244 	switch (f->f_type) {
2245 	case F_UNUSED:
2246 		/* nothing */
2247 		break;
2248 	case F_TLS:
2249 		/* nothing, as TLS uses whole buffer to send */
2250 		lineptr = line;
2251 		len = linelen;
2252 		break;
2253 	case F_FORW:
2254 		lineptr = line + tlsprefixlen;
2255 		len = linelen - tlsprefixlen;
2256 		break;
2257 	case F_PIPE:
2258 	case F_FIFO:
2259 	case F_FILE:  /* fallthrough */
2260 		if (f->f_flags & FFLAG_FULL) {
2261 			v->iov_base = line + tlsprefixlen;
2262 			v->iov_len = linelen - tlsprefixlen;
2263 		} else {
2264 			v->iov_base = line + tlsprefixlen + prilen;
2265 			v->iov_len = linelen - tlsprefixlen - prilen;
2266 		}
2267 		ADDEV();
2268 		v->iov_base = &crnl[1];
2269 		v->iov_len = 1;
2270 		ADDEV();
2271 		break;
2272 	case F_CONSOLE:
2273 	case F_TTY:
2274 		/* filter non-ASCII */
2275 		p = line;
2276 		while (*p) {
2277 			*p = FORCE2ASCII(*p);
2278 			p++;
2279 		}
2280 		v->iov_base = line + tlsprefixlen + prilen;
2281 		v->iov_len = linelen - tlsprefixlen - prilen;
2282 		ADDEV();
2283 		v->iov_base = crnl;
2284 		v->iov_len = 2;
2285 		ADDEV();
2286 		break;
2287 	case F_WALL:
2288 		v->iov_base = greetings;
2289 		v->iov_len = snprintf(greetings, sizeof(greetings),
2290 		    "\r\n\7Message from syslogd@%s at %s ...\r\n",
2291 		    (buffer->host ? buffer->host : buffer->recvhost),
2292 		    buffer->timestamp);
2293 		ADDEV();
2294 	case F_USERS: /* fallthrough */
2295 		/* filter non-ASCII */
2296 		p = line;
2297 		while (*p) {
2298 			*p = FORCE2ASCII(*p);
2299 			p++;
2300 		}
2301 		v->iov_base = line + tlsprefixlen + prilen;
2302 		v->iov_len = linelen - tlsprefixlen - prilen;
2303 		ADDEV();
2304 		v->iov_base = &crnl[1];
2305 		v->iov_len = 1;
2306 		ADDEV();
2307 		break;
2308 	}
2309 
2310 	/* send */
2311 	switch (f->f_type) {
2312 	case F_UNUSED:
2313 		DPRINTF(D_MISC, "Logging to %s\n", TypeInfo[f->f_type].name);
2314 		break;
2315 
2316 	case F_FORW:
2317 		DPRINTF(D_MISC, "Logging to %s %s\n",
2318 		    TypeInfo[f->f_type].name, f->f_un.f_forw.f_hname);
2319 		udp_send(f, lineptr, len);
2320 		break;
2321 
2322 #ifndef DISABLE_TLS
2323 	case F_TLS:
2324 		DPRINTF(D_MISC, "Logging to %s %s\n",
2325 		    TypeInfo[f->f_type].name,
2326 		    f->f_un.f_tls.tls_conn->hostname);
2327 		/* make sure every message gets queued once
2328 		 * it will be removed when sendmsg is sent and free()d */
2329 		if (!qentry)
2330 			qentry = message_queue_add(f, NEWREF(buffer));
2331 		(void)tls_send(f, lineptr, len, qentry);
2332 		break;
2333 #endif /* !DISABLE_TLS */
2334 
2335 	case F_PIPE:
2336 		DPRINTF(D_MISC, "Logging to %s %s\n",
2337 		    TypeInfo[f->f_type].name, f->f_un.f_pipe.f_pname);
2338 		if (f->f_un.f_pipe.f_pid == 0) {
2339 			/* (re-)open */
2340 			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
2341 			    &f->f_un.f_pipe.f_pid)) < 0) {
2342 				f->f_type = F_UNUSED;
2343 				logerror("%s", f->f_un.f_pipe.f_pname);
2344 				message_queue_freeall(f);
2345 				break;
2346 			} else if (!qentry) /* prevent recursion */
2347 				SEND_QUEUE(f);
2348 		}
2349 		if (writev(f->f_file, iov, v - iov) < 0) {
2350 			e = errno;
2351 			if (f->f_un.f_pipe.f_pid > 0) {
2352 				(void) close(f->f_file);
2353 				deadq_enter(f->f_un.f_pipe.f_pid,
2354 				    f->f_un.f_pipe.f_pname);
2355 			}
2356 			f->f_un.f_pipe.f_pid = 0;
2357 			/*
2358 			 * If the error was EPIPE, then what is likely
2359 			 * has happened is we have a command that is
2360 			 * designed to take a single message line and
2361 			 * then exit, but we tried to feed it another
2362 			 * one before we reaped the child and thus
2363 			 * reset our state.
2364 			 *
2365 			 * Well, now we've reset our state, so try opening
2366 			 * the pipe and sending the message again if EPIPE
2367 			 * was the error.
2368 			 */
2369 			if (e == EPIPE) {
2370 				if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
2371 				     &f->f_un.f_pipe.f_pid)) < 0) {
2372 					f->f_type = F_UNUSED;
2373 					logerror("%s", f->f_un.f_pipe.f_pname);
2374 					message_queue_freeall(f);
2375 					break;
2376 				}
2377 				if (writev(f->f_file, iov, v - iov) < 0) {
2378 					e = errno;
2379 					if (f->f_un.f_pipe.f_pid > 0) {
2380 					    (void) close(f->f_file);
2381 					    deadq_enter(f->f_un.f_pipe.f_pid,
2382 						f->f_un.f_pipe.f_pname);
2383 					}
2384 					f->f_un.f_pipe.f_pid = 0;
2385 					error = true;	/* enqueue on return */
2386 				} else
2387 					e = 0;
2388 			}
2389 			if (e != 0 && !error) {
2390 				errno = e;
2391 				logerror("%s", f->f_un.f_pipe.f_pname);
2392 			}
2393 		}
2394 		if (e == 0 && qentry) { /* sent buffered msg */
2395 			message_queue_remove(f, qentry);
2396 		}
2397 		break;
2398 
2399 	case F_CONSOLE:
2400 		if (buffer->flags & IGN_CONS) {
2401 			DPRINTF(D_MISC, "Logging to %s (ignored)\n",
2402 				TypeInfo[f->f_type].name);
2403 			break;
2404 		}
2405 		/* FALLTHROUGH */
2406 
2407 	case F_TTY:
2408 	case F_FILE:
2409 		DPRINTF(D_MISC, "Logging to %s %s\n",
2410 			TypeInfo[f->f_type].name, f->f_un.f_fname);
2411 	again:
2412 		if ((f->f_type == F_FILE ? writev(f->f_file, iov, v - iov) :
2413 		    writev1(f->f_file, iov, v - iov)) < 0) {
2414 			e = errno;
2415 			if (f->f_type == F_FILE && e == ENOSPC) {
2416 				int lasterror = f->f_lasterror;
2417 				f->f_lasterror = e;
2418 				if (lasterror != e)
2419 					logerror("%s", f->f_un.f_fname);
2420 				error = true;	/* enqueue on return */
2421 			}
2422 			(void)close(f->f_file);
2423 			/*
2424 			 * Check for errors on TTY's due to loss of tty
2425 			 */
2426 			if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
2427 				f->f_file = open(f->f_un.f_fname,
2428 				    O_WRONLY|O_APPEND|O_NONBLOCK, 0);
2429 				if (f->f_file < 0) {
2430 					f->f_type = F_UNUSED;
2431 					logerror("%s", f->f_un.f_fname);
2432 					message_queue_freeall(f);
2433 				} else
2434 					goto again;
2435 			} else {
2436 				f->f_type = F_UNUSED;
2437 				errno = e;
2438 				f->f_lasterror = e;
2439 				logerror("%s", f->f_un.f_fname);
2440 				message_queue_freeall(f);
2441 			}
2442 		} else {
2443 			f->f_lasterror = 0;
2444 			if ((buffer->flags & SYNC_FILE)
2445 			 && (f->f_flags & FFLAG_SYNC))
2446 				(void)fsync(f->f_file);
2447 			/* Problem with files: We cannot check beforehand if
2448 			 * they would be writeable and call send_queue() first.
2449 			 * So we call send_queue() after a successful write,
2450 			 * which means the first message will be out of order.
2451 			 */
2452 			if (!qentry) /* prevent recursion */
2453 				SEND_QUEUE(f);
2454 			else if (qentry) /* sent buffered msg */
2455 				message_queue_remove(f, qentry);
2456 		}
2457 		break;
2458 
2459 	case F_FIFO:
2460 		DPRINTF(D_MISC, "Logging to %s %s\n",
2461 			TypeInfo[f->f_type].name, f->f_un.f_fname);
2462 		if (f->f_file < 0) {
2463 			f->f_file =
2464 			  open(f->f_un.f_fname, O_WRONLY|O_NONBLOCK, 0);
2465 			e = errno;
2466 			if (f->f_file < 0 && e == ENXIO) {
2467 				/* Drop messages with no reader */
2468 				if (qentry)
2469 					message_queue_remove(f, qentry);
2470 				break;
2471 			}
2472 		}
2473 
2474 		if (f->f_file >= 0 && writev(f->f_file, iov, v - iov) < 0) {
2475 			e = errno;
2476 
2477 			/* Enqueue if the fifo buffer is full */
2478 			if (e == EAGAIN) {
2479 				if (f->f_lasterror != e)
2480 					logerror("%s", f->f_un.f_fname);
2481 				f->f_lasterror = e;
2482 				error = true;	/* enqueue on return */
2483 				break;
2484 			}
2485 
2486 			close(f->f_file);
2487 			f->f_file = -1;
2488 
2489 			/* Drop messages with no reader */
2490 			if (e == EPIPE) {
2491 				if (qentry)
2492 					message_queue_remove(f, qentry);
2493 				break;
2494 			}
2495 		}
2496 
2497 		if (f->f_file < 0) {
2498 			f->f_type = F_UNUSED;
2499 			errno = e;
2500 			f->f_lasterror = e;
2501 			logerror("%s", f->f_un.f_fname);
2502 			message_queue_freeall(f);
2503 			break;
2504 		}
2505 
2506 		f->f_lasterror = 0;
2507 		if (!qentry) /* prevent recursion (see comment for F_FILE) */
2508 			SEND_QUEUE(f);
2509 		if (qentry) /* sent buffered msg */
2510 			message_queue_remove(f, qentry);
2511 		break;
2512 
2513 	case F_USERS:
2514 	case F_WALL:
2515 		DPRINTF(D_MISC, "Logging to %s\n", TypeInfo[f->f_type].name);
2516 		wallmsg(f, iov, v - iov);
2517 		break;
2518 	}
2519 	f->f_prevcount = 0;
2520 
2521 	if (error && !qentry)
2522 		message_queue_add(f, NEWREF(buffer));
2523 #ifndef DISABLE_SIGN
2524 	if (newhash) {
2525 		struct signature_group_t *sg;
2526 		sg = sign_get_sg(buffer->pri, f);
2527 		(void)sign_send_signature_block(sg, false);
2528 	}
2529 #endif /* !DISABLE_SIGN */
2530 	/* this belongs to the ad-hoc buffer at the first if(buffer) */
2531 	DELREF(buffer);
2532 	/* TLS frees on its own */
2533 	if (f->f_type != F_TLS)
2534 		FREEPTR(line);
2535 }
2536 
2537 /* send one line by UDP */
2538 void
udp_send(struct filed * f,char * line,size_t len)2539 udp_send(struct filed *f, char *line, size_t len)
2540 {
2541 	int lsent, fail, retry, j;
2542 	struct addrinfo *r;
2543 
2544 	DPRINTF((D_NET|D_CALL), "udp_send(f=%p, line=\"%s\", "
2545 	    "len=%zu) to dest.\n", f, line, len);
2546 
2547 	if (!finet)
2548 		return;
2549 
2550 	lsent = -1;
2551 	fail = 0;
2552 	assert(f->f_type == F_FORW);
2553 	for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
2554 		retry = 0;
2555 		for (j = 0; j < finet->fd; j++) {
2556 			if (finet[j+1].af != r->ai_family)
2557 				continue;
2558 sendagain:
2559 			lsent = sendto(finet[j+1].fd, line, len, 0,
2560 			    r->ai_addr, r->ai_addrlen);
2561 			if (lsent == -1) {
2562 				switch (errno) {
2563 				case ENOBUFS:
2564 					/* wait/retry/drop */
2565 					if (++retry < 5) {
2566 						usleep(1000);
2567 						goto sendagain;
2568 					}
2569 					break;
2570 				case EHOSTDOWN:
2571 				case EHOSTUNREACH:
2572 				case ENETDOWN:
2573 					/* drop */
2574 					break;
2575 				default:
2576 					/* busted */
2577 					fail++;
2578 					break;
2579 				}
2580 			} else if ((size_t)lsent == len)
2581 				break;
2582 		}
2583 		if ((size_t)lsent != len && fail) {
2584 			f->f_type = F_UNUSED;
2585 			logerror("sendto() failed");
2586 		}
2587 	}
2588 }
2589 
2590 /*
2591  *  WALLMSG -- Write a message to the world at large
2592  *
2593  *	Write the specified message to either the entire
2594  *	world, or a list of approved users.
2595  */
2596 void
wallmsg(struct filed * f,struct iovec * iov,size_t iovcnt)2597 wallmsg(struct filed *f, struct iovec *iov, size_t iovcnt)
2598 {
2599 #ifdef __NetBSD_Version__
2600 	static int reenter;			/* avoid calling ourselves */
2601 	int i;
2602 	char *p;
2603 	struct utmpentry *ep;
2604 
2605 	if (reenter++)
2606 		return;
2607 
2608 	(void)getutentries(NULL, &ep);
2609 	/* NOSTRICT */
2610 	for (; ep; ep = ep->next) {
2611 		if (f->f_type == F_WALL) {
2612 			if ((p = ttymsg(iov, iovcnt, ep->line, TTYMSGTIME))
2613 			    != NULL) {
2614 				errno = 0;	/* already in msg */
2615 				logerror("%s", p);
2616 			}
2617 			continue;
2618 		}
2619 		/* should we send the message to this user? */
2620 		for (i = 0; i < MAXUNAMES; i++) {
2621 			if (!f->f_un.f_uname[i][0])
2622 				break;
2623 			if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
2624 				struct stat st;
2625 				char tty[MAXPATHLEN];
2626 				snprintf(tty, sizeof(tty), "%s/%s", _PATH_DEV,
2627 				    ep->line);
2628 				if (stat(tty, &st) != -1 &&
2629 				    (st.st_mode & S_IWGRP) == 0)
2630 					break;
2631 
2632 				if ((p = ttymsg(iov, iovcnt, ep->line,
2633 				    TTYMSGTIME)) != NULL) {
2634 					errno = 0;	/* already in msg */
2635 					logerror("%s", p);
2636 				}
2637 				break;
2638 			}
2639 		}
2640 	}
2641 	reenter = 0;
2642 #endif /* __NetBSD_Version__ */
2643 }
2644 
2645 void
2646 /*ARGSUSED*/
reapchild(int fd,short event,void * ev)2647 reapchild(int fd, short event, void *ev)
2648 {
2649 	int status;
2650 	pid_t pid;
2651 	struct filed *f;
2652 
2653 	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
2654 		if (!Initialized || ShuttingDown) {
2655 			/*
2656 			 * Be silent while we are initializing or
2657 			 * shutting down.
2658 			 */
2659 			continue;
2660 		}
2661 
2662 		if (deadq_remove(pid))
2663 			continue;
2664 
2665 		/* Now, look in the list of active processes. */
2666 		for (f = Files; f != NULL; f = f->f_next) {
2667 			if (f->f_type == F_PIPE &&
2668 			    f->f_un.f_pipe.f_pid == pid) {
2669 				(void) close(f->f_file);
2670 				f->f_un.f_pipe.f_pid = 0;
2671 				log_deadchild(pid, status,
2672 				    f->f_un.f_pipe.f_pname);
2673 				break;
2674 			}
2675 		}
2676 	}
2677 }
2678 
2679 /*
2680  * Return a printable representation of a host address (FQDN if available)
2681  */
2682 const char *
cvthname(struct sockaddr_storage * f)2683 cvthname(struct sockaddr_storage *f)
2684 {
2685 	int error;
2686 	int niflag = NI_DGRAM;
2687 	static char host[NI_MAXHOST], ip[NI_MAXHOST];
2688 
2689 	error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
2690 	    ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
2691 
2692 	DPRINTF(D_CALL, "cvthname(%s)\n", ip);
2693 
2694 	if (error) {
2695 		DPRINTF(D_NET, "Malformed from address %s\n",
2696 		    gai_strerror(error));
2697 		return "???";
2698 	}
2699 
2700 	if (!UseNameService)
2701 		return ip;
2702 
2703 	error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
2704 	    host, sizeof host, NULL, 0, niflag);
2705 	if (error) {
2706 		DPRINTF(D_NET, "Host name for your address (%s) unknown\n", ip);
2707 		return ip;
2708 	}
2709 
2710 	return host;
2711 }
2712 
2713 void
trim_anydomain(char * host)2714 trim_anydomain(char *host)
2715 {
2716 	bool onlydigits = true;
2717 	int i;
2718 
2719 	if (!BSDOutputFormat)
2720 		return;
2721 
2722 	/* if non-digits found, then assume hostname and cut at first dot (this
2723 	 * case also covers IPv6 addresses which should not contain dots),
2724 	 * if only digits then assume IPv4 address and do not cut at all */
2725 	for (i = 0; host[i]; i++) {
2726 		if (host[i] == '.' && !onlydigits)
2727 			host[i] = '\0';
2728 		else if (!isdigit((unsigned char)host[i]) && host[i] != '.')
2729 			onlydigits = false;
2730 	}
2731 }
2732 
2733 static void
2734 /*ARGSUSED*/
domark(int fd,short event,void * ev)2735 domark(int fd, short event, void *ev)
2736 {
2737 	struct event *ev_pass = (struct event *)ev;
2738 	struct filed *f;
2739 	dq_t q, nextq;
2740 	sigset_t newmask, omask;
2741 
2742 	schedule_event(&ev_pass,
2743 		&((struct timeval){TIMERINTVL, 0}),
2744 		domark, ev_pass);
2745 	DPRINTF((D_CALL|D_EVENT), "domark()\n");
2746 
2747 	BLOCK_SIGNALS(omask, newmask);
2748 	now = time(NULL);
2749 	MarkSeq += TIMERINTVL;
2750 	if (MarkSeq >= MarkInterval) {
2751 		logmsg_async(LOG_INFO, NULL, "-- MARK --", ADDDATE|MARK);
2752 		MarkSeq = 0;
2753 	}
2754 
2755 	for (f = Files; f; f = f->f_next) {
2756 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2757 			DPRINTF(D_DATA, "Flush %s: repeated %d times, %d sec.\n",
2758 			    TypeInfo[f->f_type].name, f->f_prevcount,
2759 			    repeatinterval[f->f_repeatcount]);
2760 			fprintlog(f, NULL, NULL);
2761 			BACKOFF(f);
2762 		}
2763 	}
2764 	message_allqueues_check();
2765 	RESTORE_SIGNALS(omask);
2766 
2767 	/* Walk the dead queue, and see if we should signal somebody. */
2768 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = nextq) {
2769 		nextq = TAILQ_NEXT(q, dq_entries);
2770 		switch (q->dq_timeout) {
2771 		case 0:
2772 			/* Already signalled once, try harder now. */
2773 			if (kill(q->dq_pid, SIGKILL) != 0)
2774 				(void) deadq_remove(q->dq_pid);
2775 			break;
2776 
2777 		case 1:
2778 			/*
2779 			 * Timed out on the dead queue, send terminate
2780 			 * signal.  Note that we leave the removal from
2781 			 * the dead queue to reapchild(), which will
2782 			 * also log the event (unless the process
2783 			 * didn't even really exist, in case we simply
2784 			 * drop it from the dead queue).
2785 			 */
2786 			if (kill(q->dq_pid, SIGTERM) != 0) {
2787 				(void) deadq_remove(q->dq_pid);
2788 				break;
2789 			}
2790 			/* FALLTHROUGH */
2791 
2792 		default:
2793 			q->dq_timeout--;
2794 		}
2795 	}
2796 #ifndef DISABLE_SIGN
2797 	if (GlobalSign.rsid) {	/* check if initialized */
2798 		struct signature_group_t *sg;
2799 		STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
2800 			sign_send_certificate_block(sg);
2801 		}
2802 	}
2803 #endif /* !DISABLE_SIGN */
2804 }
2805 
2806 /*
2807  * Print syslogd errors some place.
2808  */
2809 void
logerror(const char * fmt,...)2810 logerror(const char *fmt, ...)
2811 {
2812 	static int logerror_running;
2813 	va_list ap;
2814 	char tmpbuf[BUFSIZ];
2815 	char buf[BUFSIZ];
2816 	char *outbuf;
2817 
2818 	/* If there's an error while trying to log an error, give up. */
2819 	if (logerror_running)
2820 		return;
2821 	logerror_running = 1;
2822 
2823 	va_start(ap, fmt);
2824 	(void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
2825 	va_end(ap);
2826 
2827 	if (errno) {
2828 		(void)snprintf(buf, sizeof(buf), "%s: %s",
2829 		    tmpbuf, strerror(errno));
2830 		outbuf = buf;
2831 	} else {
2832 		(void)snprintf(buf, sizeof(buf), "%s", tmpbuf);
2833 		outbuf = tmpbuf;
2834 	}
2835 
2836 	if (daemonized)
2837 		logmsg_async(LOG_SYSLOG|LOG_ERR, NULL, outbuf, ADDDATE);
2838 	if (!daemonized && Debug)
2839 		DPRINTF(D_MISC, "%s\n", outbuf);
2840 	if (!daemonized && !Debug)
2841 		printf("%s\n", outbuf);
2842 
2843 	logerror_running = 0;
2844 }
2845 
2846 /*
2847  * Print syslogd info some place.
2848  */
2849 void
loginfo(const char * fmt,...)2850 loginfo(const char *fmt, ...)
2851 {
2852 	va_list ap;
2853 	char buf[BUFSIZ];
2854 
2855 	va_start(ap, fmt);
2856 	(void)vsnprintf(buf, sizeof(buf), fmt, ap);
2857 	va_end(ap);
2858 
2859 	DPRINTF(D_MISC, "%s\n", buf);
2860 	logmsg_async(LOG_SYSLOG|LOG_INFO, NULL, buf, ADDDATE);
2861 }
2862 
2863 #ifndef DISABLE_TLS
2864 static inline void
free_incoming_tls_sockets(void)2865 free_incoming_tls_sockets(void)
2866 {
2867 	struct TLS_Incoming_Conn *tls_in;
2868 	int i;
2869 
2870 	/*
2871 	 * close all listening and connected TLS sockets
2872 	 */
2873 	if (TLS_Listen_Set)
2874 		for (i = 0; i < TLS_Listen_Set->fd; i++) {
2875 			if (close(TLS_Listen_Set[i+1].fd) == -1)
2876 				logerror("close() failed");
2877 			DEL_EVENT(TLS_Listen_Set[i+1].ev);
2878 			FREEPTR(TLS_Listen_Set[i+1].ev);
2879 		}
2880 	FREEPTR(TLS_Listen_Set);
2881 	/* close/free incoming TLS connections */
2882 	while (!SLIST_EMPTY(&TLS_Incoming_Head)) {
2883 		tls_in = SLIST_FIRST(&TLS_Incoming_Head);
2884 		SLIST_REMOVE_HEAD(&TLS_Incoming_Head, entries);
2885 		FREEPTR(tls_in->inbuf);
2886 		free_tls_conn(tls_in->tls_conn);
2887 		free(tls_in);
2888 	}
2889 }
2890 #endif /* !DISABLE_TLS */
2891 
2892 void
2893 /*ARGSUSED*/
die(int fd,short event,void * ev)2894 die(int fd, short event, void *ev)
2895 {
2896 	struct filed *f, *next;
2897 	char **p;
2898 	sigset_t newmask, omask;
2899 	int i;
2900 	size_t j;
2901 
2902 	ShuttingDown = 1;	/* Don't log SIGCHLDs. */
2903 	/* prevent recursive signals */
2904 	BLOCK_SIGNALS(omask, newmask);
2905 
2906 	errno = 0;
2907 	if (ev != NULL)
2908 		logerror("Exiting on signal %d", fd);
2909 	else
2910 		logerror("Fatal error, exiting");
2911 
2912 	/*
2913 	 *  flush any pending output
2914 	 */
2915 	for (f = Files; f != NULL; f = f->f_next) {
2916 		/* flush any pending output */
2917 		if (f->f_prevcount)
2918 			fprintlog(f, NULL, NULL);
2919 		SEND_QUEUE(f);
2920 	}
2921 
2922 #ifndef DISABLE_TLS
2923 	free_incoming_tls_sockets();
2924 #endif /* !DISABLE_TLS */
2925 #ifndef DISABLE_SIGN
2926 	sign_global_free();
2927 #endif /* !DISABLE_SIGN */
2928 
2929 	/*
2930 	 *  Close all open log files.
2931 	 */
2932 	for (f = Files; f != NULL; f = next) {
2933 		message_queue_freeall(f);
2934 
2935 		switch (f->f_type) {
2936 		case F_FILE:
2937 		case F_TTY:
2938 		case F_CONSOLE:
2939 		case F_FIFO:
2940 			if (f->f_file >= 0)
2941 				(void)close(f->f_file);
2942 			break;
2943 		case F_PIPE:
2944 			if (f->f_un.f_pipe.f_pid > 0) {
2945 				(void)close(f->f_file);
2946 			}
2947 			f->f_un.f_pipe.f_pid = 0;
2948 			break;
2949 		case F_FORW:
2950 			if (f->f_un.f_forw.f_addr)
2951 				freeaddrinfo(f->f_un.f_forw.f_addr);
2952 			break;
2953 #ifndef DISABLE_TLS
2954 		case F_TLS:
2955 			free_tls_conn(f->f_un.f_tls.tls_conn);
2956 			break;
2957 #endif /* !DISABLE_TLS */
2958 		}
2959 		next = f->f_next;
2960 		DELREF(f->f_prevmsg);
2961 		FREEPTR(f->f_program);
2962 		FREEPTR(f->f_host);
2963 		DEL_EVENT(f->f_sq_event);
2964 		free((char *)f);
2965 	}
2966 
2967 	/*
2968 	 *  Close all open UDP sockets
2969 	 */
2970 	if (finet) {
2971 		for (i = 0; i < finet->fd; i++) {
2972 			if (close(finet[i+1].fd) < 0) {
2973 				logerror("close() failed");
2974 				die(0, 0, NULL);
2975 			}
2976 			DEL_EVENT(finet[i+1].ev);
2977 			FREEPTR(finet[i+1].ev);
2978 		}
2979 		FREEPTR(finet);
2980 	}
2981 
2982 	/* free config options */
2983 	for (j = 0; j < A_CNT(TypeInfo); j++) {
2984 		FREEPTR(TypeInfo[j].queue_length_string);
2985 		FREEPTR(TypeInfo[j].queue_size_string);
2986 	}
2987 
2988 #ifndef DISABLE_TLS
2989 	FREEPTR(tls_opt.CAdir);
2990 	FREEPTR(tls_opt.CAfile);
2991 	FREEPTR(tls_opt.keyfile);
2992 	FREEPTR(tls_opt.certfile);
2993 	FREEPTR(tls_opt.x509verify);
2994 	FREEPTR(tls_opt.bindhost);
2995 	FREEPTR(tls_opt.bindport);
2996 	FREEPTR(tls_opt.server);
2997 	FREEPTR(tls_opt.gen_cert);
2998 	free_cred_SLIST(&tls_opt.cert_head);
2999 	free_cred_SLIST(&tls_opt.fprint_head);
3000 	FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3001 #endif /* !DISABLE_TLS */
3002 
3003 	FREEPTR(funix);
3004 	for (p = LogPaths; p && *p; p++)
3005 		unlink(*p);
3006 	exit(0);
3007 }
3008 
3009 #ifndef DISABLE_SIGN
3010 /*
3011  * get one "sign_delim_sg2" item, convert and store in ordered queue
3012  */
3013 void
store_sign_delim_sg2(char * tmp_buf)3014 store_sign_delim_sg2(char *tmp_buf)
3015 {
3016 	struct string_queue *sqentry, *sqe1, *sqe2;
3017 
3018 	if(!(sqentry = malloc(sizeof(*sqentry)))) {
3019 		logerror("Unable to allocate memory");
3020 		return;
3021 	}
3022 	/*LINTED constcond/null effect */
3023 	assert(sizeof(int64_t) == sizeof(uint_fast64_t));
3024 	if (dehumanize_number(tmp_buf, (int64_t*) &(sqentry->key)) == -1
3025 	    || sqentry->key > (LOG_NFACILITIES<<3)) {
3026 		DPRINTF(D_PARSE, "invalid sign_delim_sg2: %s\n", tmp_buf);
3027 		free(sqentry);
3028 		FREEPTR(tmp_buf);
3029 		return;
3030 	}
3031 	sqentry->data = tmp_buf;
3032 
3033 	if (STAILQ_EMPTY(&GlobalSign.sig2_delims)) {
3034 		STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
3035 		    sqentry, entries);
3036 		return;
3037 	}
3038 
3039 	/* keep delimiters sorted */
3040 	sqe1 = sqe2 = STAILQ_FIRST(&GlobalSign.sig2_delims);
3041 	if (sqe1->key > sqentry->key) {
3042 		STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
3043 		    sqentry, entries);
3044 		return;
3045 	}
3046 
3047 	while ((sqe1 = sqe2)
3048 	   && (sqe2 = STAILQ_NEXT(sqe1, entries))) {
3049 		if (sqe2->key > sqentry->key) {
3050 			break;
3051 		} else if (sqe2->key == sqentry->key) {
3052 			DPRINTF(D_PARSE, "duplicate sign_delim_sg2: %s\n",
3053 			    tmp_buf);
3054 			FREEPTR(sqentry);
3055 			FREEPTR(tmp_buf);
3056 			return;
3057 		}
3058 	}
3059 	STAILQ_INSERT_AFTER(&GlobalSign.sig2_delims, sqe1, sqentry, entries);
3060 }
3061 #endif /* !DISABLE_SIGN */
3062 
3063 /*
3064  * read syslog.conf
3065  */
3066 void
read_config_file(FILE * cf,struct filed ** f_ptr)3067 read_config_file(FILE *cf, struct filed **f_ptr)
3068 {
3069 	size_t linenum = 0;
3070 	size_t i;
3071 	struct filed *f, **nextp;
3072 	char cline[LINE_MAX];
3073 	char prog[NAME_MAX + 1];
3074 	char host[MAXHOSTNAMELEN];
3075 	const char *p;
3076 	char *q;
3077 	bool found_keyword;
3078 #ifndef DISABLE_TLS
3079 	struct peer_cred *cred = NULL;
3080 	struct peer_cred_head *credhead = NULL;
3081 #endif /* !DISABLE_TLS */
3082 #ifndef DISABLE_SIGN
3083 	char *sign_sg_str = NULL;
3084 #endif /* !DISABLE_SIGN */
3085 #if (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN))
3086 	char *tmp_buf = NULL;
3087 #endif /* (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN)) */
3088 	/* central list of recognized configuration keywords
3089 	 * and an address for their values as strings */
3090 	const struct config_keywords {
3091 		const char *keyword;
3092 		char **variable;
3093 	} config_keywords[] = {
3094 #ifndef DISABLE_TLS
3095 		/* TLS settings */
3096 		{"tls_ca",		  &tls_opt.CAfile},
3097 		{"tls_cadir",		  &tls_opt.CAdir},
3098 		{"tls_cert",		  &tls_opt.certfile},
3099 		{"tls_key",		  &tls_opt.keyfile},
3100 		{"tls_verify",		  &tls_opt.x509verify},
3101 		{"tls_bindport",	  &tls_opt.bindport},
3102 		{"tls_bindhost",	  &tls_opt.bindhost},
3103 		{"tls_server",		  &tls_opt.server},
3104 		{"tls_gen_cert",	  &tls_opt.gen_cert},
3105 		/* special cases in parsing */
3106 		{"tls_allow_fingerprints",&tmp_buf},
3107 		{"tls_allow_clientcerts", &tmp_buf},
3108 		/* buffer settings */
3109 		{"tls_queue_length",	  &TypeInfo[F_TLS].queue_length_string},
3110 		{"tls_queue_size",	  &TypeInfo[F_TLS].queue_size_string},
3111 #endif /* !DISABLE_TLS */
3112 		{"file_queue_length",	  &TypeInfo[F_FILE].queue_length_string},
3113 		{"pipe_queue_length",	  &TypeInfo[F_PIPE].queue_length_string},
3114 		{"fifo_queue_length",	  &TypeInfo[F_FIFO].queue_length_string},
3115 		{"file_queue_size",	  &TypeInfo[F_FILE].queue_size_string},
3116 		{"pipe_queue_size",	  &TypeInfo[F_PIPE].queue_size_string},
3117 		{"fifo_queue_size",	  &TypeInfo[F_FIFO].queue_size_string},
3118 #ifndef DISABLE_SIGN
3119 		/* syslog-sign setting */
3120 		{"sign_sg",		  &sign_sg_str},
3121 		/* also special case in parsing */
3122 		{"sign_delim_sg2",	  &tmp_buf},
3123 #endif /* !DISABLE_SIGN */
3124 	};
3125 
3126 	DPRINTF(D_CALL, "read_config_file()\n");
3127 
3128 	/* free all previous config options */
3129 	for (i = 0; i < A_CNT(TypeInfo); i++) {
3130 		if (TypeInfo[i].queue_length_string
3131 		    && TypeInfo[i].queue_length_string
3132 		    != TypeInfo[i].default_length_string) {
3133 			FREEPTR(TypeInfo[i].queue_length_string);
3134 			TypeInfo[i].queue_length_string =
3135 				strdup(TypeInfo[i].default_length_string);
3136 		 }
3137 		if (TypeInfo[i].queue_size_string
3138 		    && TypeInfo[i].queue_size_string
3139 		    != TypeInfo[i].default_size_string) {
3140 			FREEPTR(TypeInfo[i].queue_size_string);
3141 			TypeInfo[i].queue_size_string =
3142 				strdup(TypeInfo[i].default_size_string);
3143 		 }
3144 	}
3145 	for (i = 0; i < A_CNT(config_keywords); i++)
3146 		FREEPTR(*config_keywords[i].variable);
3147 	/*
3148 	 * global settings
3149 	 */
3150 	while (fgets(cline, sizeof(cline), cf) != NULL) {
3151 		linenum++;
3152 		for (p = cline; isspace((unsigned char)*p); ++p)
3153 			continue;
3154 		if ((*p == '\0') || (*p == '#'))
3155 			continue;
3156 
3157 		for (i = 0; i < A_CNT(config_keywords); i++) {
3158 			if (copy_config_value(config_keywords[i].keyword,
3159 			    config_keywords[i].variable, &p, ConfFile,
3160 			    linenum)) {
3161 				DPRINTF((D_PARSE|D_MEM),
3162 				    "found option %s, saved @%p\n",
3163 				    config_keywords[i].keyword,
3164 				    *config_keywords[i].variable);
3165 #ifndef DISABLE_SIGN
3166 				if (!strcmp("sign_delim_sg2",
3167 				    config_keywords[i].keyword))
3168 					do {
3169 						store_sign_delim_sg2(tmp_buf);
3170 					} while (copy_config_value_word(
3171 					    &tmp_buf, &p));
3172 
3173 #endif /* !DISABLE_SIGN */
3174 
3175 #ifndef DISABLE_TLS
3176 				/* special cases with multiple parameters */
3177 				if (!strcmp("tls_allow_fingerprints",
3178 				    config_keywords[i].keyword))
3179 					credhead = &tls_opt.fprint_head;
3180 				else if (!strcmp("tls_allow_clientcerts",
3181 				    config_keywords[i].keyword))
3182 					credhead = &tls_opt.cert_head;
3183 
3184 				if (credhead) do {
3185 					if(!(cred = malloc(sizeof(*cred)))) {
3186 						logerror("Unable to "
3187 							"allocate memory");
3188 						break;
3189 					}
3190 					cred->data = tmp_buf;
3191 					tmp_buf = NULL;
3192 					SLIST_INSERT_HEAD(credhead,
3193 						cred, entries);
3194 				} while /* additional values? */
3195 					(copy_config_value_word(&tmp_buf, &p));
3196 				credhead = NULL;
3197 				break;
3198 #endif /* !DISABLE_TLS */
3199 			}
3200 		}
3201 	}
3202 	/* convert strings to integer values */
3203 	for (i = 0; i < A_CNT(TypeInfo); i++) {
3204 		if (!TypeInfo[i].queue_length_string
3205 		    || dehumanize_number(TypeInfo[i].queue_length_string,
3206 		    &TypeInfo[i].queue_length) == -1)
3207 			if (dehumanize_number(TypeInfo[i].default_length_string,
3208 			    &TypeInfo[i].queue_length) == -1)
3209 				abort();
3210 		if (!TypeInfo[i].queue_size_string
3211 		    || dehumanize_number(TypeInfo[i].queue_size_string,
3212 		    &TypeInfo[i].queue_size) == -1)
3213 			if (dehumanize_number(TypeInfo[i].default_size_string,
3214 			    &TypeInfo[i].queue_size) == -1)
3215 				abort();
3216 	}
3217 
3218 #ifndef DISABLE_SIGN
3219 	if (sign_sg_str) {
3220 		if (sign_sg_str[1] == '\0'
3221 		    && (sign_sg_str[0] == '0' || sign_sg_str[0] == '1'
3222 		    || sign_sg_str[0] == '2' || sign_sg_str[0] == '3'))
3223 			GlobalSign.sg = sign_sg_str[0] - '0';
3224 		else {
3225 			GlobalSign.sg = SIGN_SG;
3226 			DPRINTF(D_MISC, "Invalid sign_sg value `%s', "
3227 			    "use default value `%d'\n",
3228 			    sign_sg_str, GlobalSign.sg);
3229 		}
3230 	} else	/* disable syslog-sign */
3231 		GlobalSign.sg = -1;
3232 #endif /* !DISABLE_SIGN */
3233 
3234 	rewind(cf);
3235 	linenum = 0;
3236 	/*
3237 	 *  Foreach line in the conf table, open that file.
3238 	 */
3239 	f = NULL;
3240 	nextp = &f;
3241 
3242 	strcpy(prog, "*");
3243 	strcpy(host, "*");
3244 	while (fgets(cline, sizeof(cline), cf) != NULL) {
3245 		linenum++;
3246 		found_keyword = false;
3247 		/*
3248 		 * check for end-of-section, comments, strip off trailing
3249 		 * spaces and newline character.  #!prog is treated specially:
3250 		 * following lines apply only to that program.
3251 		 */
3252 		for (p = cline; isspace((unsigned char)*p); ++p)
3253 			continue;
3254 		if (*p == '\0')
3255 			continue;
3256 		if (*p == '#') {
3257 			p++;
3258 			if (*p != '!' && *p != '+' && *p != '-')
3259 				continue;
3260 		}
3261 
3262 		for (i = 0; i < A_CNT(config_keywords); i++) {
3263 			if (!strncasecmp(p, config_keywords[i].keyword,
3264 				strlen(config_keywords[i].keyword))) {
3265 				DPRINTF(D_PARSE,
3266 				    "skip cline %zu with keyword %s\n",
3267 				    linenum, config_keywords[i].keyword);
3268 				found_keyword = true;
3269 			}
3270 		}
3271 		if (found_keyword)
3272 			continue;
3273 
3274 		if (*p == '+' || *p == '-') {
3275 			host[0] = *p++;
3276 			while (isspace((unsigned char)*p))
3277 				p++;
3278 			if (*p == '\0' || *p == '*') {
3279 				strcpy(host, "*");
3280 				continue;
3281 			}
3282 			/* the +hostname expression will continue
3283 			 * to use the LocalHostName, not the FQDN */
3284 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
3285 				if (*p == '@') {
3286 					(void)strncpy(&host[i], LocalHostName,
3287 					    sizeof(host) - 1 - i);
3288 					host[sizeof(host) - 1] = '\0';
3289 					i = strlen(host) - 1;
3290 					p++;
3291 					continue;
3292 				}
3293 				if (!isalnum((unsigned char)*p) &&
3294 				    *p != '.' && *p != '-' && *p != ',')
3295 					break;
3296 				host[i] = *p++;
3297 			}
3298 			host[i] = '\0';
3299 			continue;
3300 		}
3301 		if (*p == '!') {
3302 			p++;
3303 			while (isspace((unsigned char)*p))
3304 				p++;
3305 			if (*p == '\0' || *p == '*') {
3306 				strcpy(prog, "*");
3307 				continue;
3308 			}
3309 			for (i = 0; i < NAME_MAX; i++) {
3310 				if (!isprint((unsigned char)p[i]))
3311 					break;
3312 				prog[i] = p[i];
3313 			}
3314 			prog[i] = '\0';
3315 			continue;
3316 		}
3317 		for (q = strchr(cline, '\0'); isspace((unsigned char)*--q);)
3318 			continue;
3319 		*++q = '\0';
3320 		if ((f = calloc(1, sizeof(*f))) == NULL) {
3321 			logerror("alloc failed");
3322 			die(0, 0, NULL);
3323 		}
3324 		if (!*f_ptr) *f_ptr = f; /* return first node */
3325 		*nextp = f;
3326 		nextp = &f->f_next;
3327 		cfline(linenum, cline, f, prog, host);
3328 	}
3329 }
3330 
3331 /*
3332  *  INIT -- Initialize syslogd from configuration table
3333  */
3334 void
3335 /*ARGSUSED*/
init(int fd,short event,void * ev)3336 init(int fd, short event, void *ev)
3337 {
3338 	FILE *cf;
3339 	int i;
3340 	struct filed *f, *newf, **nextp, *f2;
3341 	char *p;
3342 	sigset_t newmask, omask;
3343 #ifndef DISABLE_TLS
3344 	char *tls_status_msg = NULL;
3345 	struct peer_cred *cred = NULL;
3346 #endif /* !DISABLE_TLS */
3347 
3348 	/* prevent recursive signals */
3349 	BLOCK_SIGNALS(omask, newmask);
3350 
3351 	DPRINTF((D_EVENT|D_CALL), "init\n");
3352 
3353 	/*
3354 	 * be careful about dependencies and order of actions:
3355 	 * 1. flush buffer queues
3356 	 * 2. flush -sign SBs
3357 	 * 3. flush/delete buffer queue again, in case an SB got there
3358 	 * 4. close files/connections
3359 	 */
3360 
3361 	/*
3362 	 *  flush any pending output
3363 	 */
3364 	for (f = Files; f != NULL; f = f->f_next) {
3365 		/* flush any pending output */
3366 		if (f->f_prevcount)
3367 			fprintlog(f, NULL, NULL);
3368 		SEND_QUEUE(f);
3369 	}
3370 	/* some actions only on SIGHUP and not on first start */
3371 	if (Initialized) {
3372 #ifndef DISABLE_SIGN
3373 		sign_global_free();
3374 #endif /* !DISABLE_SIGN */
3375 #ifndef DISABLE_TLS
3376 		free_incoming_tls_sockets();
3377 #endif /* !DISABLE_TLS */
3378 		Initialized = 0;
3379 	}
3380 	/*
3381 	 *  Close all open log files.
3382 	 */
3383 	for (f = Files; f != NULL; f = f->f_next) {
3384 		switch (f->f_type) {
3385 		case F_FILE:
3386 		case F_TTY:
3387 		case F_CONSOLE:
3388 			(void)close(f->f_file);
3389 			break;
3390 		case F_PIPE:
3391 			if (f->f_un.f_pipe.f_pid > 0) {
3392 				(void)close(f->f_file);
3393 				deadq_enter(f->f_un.f_pipe.f_pid,
3394 				    f->f_un.f_pipe.f_pname);
3395 			}
3396 			f->f_un.f_pipe.f_pid = 0;
3397 			break;
3398 		case F_FORW:
3399 			if (f->f_un.f_forw.f_addr)
3400 				freeaddrinfo(f->f_un.f_forw.f_addr);
3401 			break;
3402 #ifndef DISABLE_TLS
3403 		case F_TLS:
3404 			free_tls_sslptr(f->f_un.f_tls.tls_conn);
3405 			break;
3406 #endif /* !DISABLE_TLS */
3407 		}
3408 	}
3409 
3410 	/*
3411 	 *  Close all open UDP sockets
3412 	 */
3413 	if (finet) {
3414 		for (i = 0; i < finet->fd; i++) {
3415 			if (close(finet[i+1].fd) < 0) {
3416 				logerror("close() failed");
3417 				die(0, 0, NULL);
3418 			}
3419 			DEL_EVENT(finet[i+1].ev);
3420 			FREEPTR(finet[i+1].ev);
3421 		}
3422 		FREEPTR(finet);
3423 	}
3424 
3425 	/* get FQDN and hostname/domain */
3426 	FREEPTR(oldLocalFQDN);
3427 	oldLocalFQDN = LocalFQDN;
3428 	LocalFQDN = getLocalFQDN();
3429 	if ((p = strchr(LocalFQDN, '.')) != NULL)
3430 		(void)strlcpy(LocalHostName, LocalFQDN, 1+p-LocalFQDN);
3431 	else
3432 		(void)strlcpy(LocalHostName, LocalFQDN, sizeof(LocalHostName));
3433 
3434 	/*
3435 	 *  Reset counter of forwarding actions
3436 	 */
3437 
3438 	NumForwards=0;
3439 
3440 	/* new destination list to replace Files */
3441 	newf = NULL;
3442 	nextp = &newf;
3443 
3444 	/* open the configuration file */
3445 	if ((cf = fopen(ConfFile, "r")) == NULL) {
3446 		DPRINTF(D_FILE, "Cannot open `%s'\n", ConfFile);
3447 		*nextp = (struct filed *)calloc(1, sizeof(*f));
3448 		cfline(0, "*.ERR\t/dev/console", *nextp, "*", "*");
3449 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
3450 		cfline(0, "*.PANIC\t*", (*nextp)->f_next, "*", "*");
3451 		Initialized = 1;
3452 		RESTORE_SIGNALS(omask);
3453 		return;
3454 	}
3455 
3456 #ifndef DISABLE_TLS
3457 	/* init with new TLS_CTX
3458 	 * as far as I see one cannot change the cert/key of an existing CTX
3459 	 */
3460 	FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3461 
3462 	free_cred_SLIST(&tls_opt.cert_head);
3463 	free_cred_SLIST(&tls_opt.fprint_head);
3464 #endif /* !DISABLE_TLS */
3465 
3466 	/* read and close configuration file */
3467 	read_config_file(cf, &newf);
3468 	newf = *nextp;
3469 	(void)fclose(cf);
3470 	DPRINTF(D_MISC, "read_config_file() returned newf=%p\n", newf);
3471 
3472 #define MOVE_QUEUE(dst, src) do {				\
3473 	struct buf_queue *buf;					\
3474 	STAILQ_CONCAT(&dst->f_qhead, &src->f_qhead);		\
3475 	STAILQ_FOREACH(buf, &dst->f_qhead, entries) {		\
3476 	      dst->f_qelements++;				\
3477 	      dst->f_qsize += buf_queue_obj_size(buf);		\
3478 	}							\
3479 	src->f_qsize = 0;					\
3480 	src->f_qelements = 0;					\
3481 } while (/*CONSTCOND*/0)
3482 
3483 	/*
3484 	 *  Free old log files.
3485 	 */
3486 	for (f = Files; f != NULL;) {
3487 		struct filed *ftmp;
3488 
3489 		/* check if a new logfile is equal, if so pass the queue */
3490 		for (f2 = newf; f2 != NULL; f2 = f2->f_next) {
3491 			if (f->f_type == f2->f_type
3492 			    && ((f->f_type == F_PIPE
3493 			    && !strcmp(f->f_un.f_pipe.f_pname,
3494 			    f2->f_un.f_pipe.f_pname))
3495 #ifndef DISABLE_TLS
3496 			    || (f->f_type == F_TLS
3497 			    && !strcmp(f->f_un.f_tls.tls_conn->hostname,
3498 			    f2->f_un.f_tls.tls_conn->hostname)
3499 			    && !strcmp(f->f_un.f_tls.tls_conn->port,
3500 			    f2->f_un.f_tls.tls_conn->port))
3501 #endif /* !DISABLE_TLS */
3502 			    || (f->f_type == F_FORW
3503 			    && !strcmp(f->f_un.f_forw.f_hname,
3504 			    f2->f_un.f_forw.f_hname)))) {
3505 				DPRINTF(D_BUFFER, "move queue from f@%p "
3506 				    "to f2@%p\n", f, f2);
3507 				MOVE_QUEUE(f2, f);
3508 			 }
3509 		}
3510 		message_queue_freeall(f);
3511 		DELREF(f->f_prevmsg);
3512 #ifndef DISABLE_TLS
3513 		if (f->f_type == F_TLS)
3514 			free_tls_conn(f->f_un.f_tls.tls_conn);
3515 #endif /* !DISABLE_TLS */
3516 		FREEPTR(f->f_program);
3517 		FREEPTR(f->f_host);
3518 		DEL_EVENT(f->f_sq_event);
3519 
3520 		ftmp = f->f_next;
3521 		free((char *)f);
3522 		f = ftmp;
3523 	}
3524 	Files = newf;
3525 	Initialized = 1;
3526 
3527 	if (Debug) {
3528 		for (f = Files; f; f = f->f_next) {
3529 			for (i = 0; i <= LOG_NFACILITIES; i++)
3530 				if (f->f_pmask[i] == INTERNAL_NOPRI)
3531 					printf("X ");
3532 				else
3533 					printf("%d ", f->f_pmask[i]);
3534 			printf("%s: ", TypeInfo[f->f_type].name);
3535 			switch (f->f_type) {
3536 			case F_FILE:
3537 			case F_TTY:
3538 			case F_CONSOLE:
3539 			case F_FIFO:
3540 				printf("%s", f->f_un.f_fname);
3541 				break;
3542 
3543 			case F_FORW:
3544 				printf("%s", f->f_un.f_forw.f_hname);
3545 				break;
3546 #ifndef DISABLE_TLS
3547 			case F_TLS:
3548 				printf("[%s]", f->f_un.f_tls.tls_conn->hostname);
3549 				break;
3550 #endif /* !DISABLE_TLS */
3551 			case F_PIPE:
3552 				printf("%s", f->f_un.f_pipe.f_pname);
3553 				break;
3554 
3555 			case F_USERS:
3556 				for (i = 0;
3557 				    i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
3558 					printf("%s, ", f->f_un.f_uname[i]);
3559 				break;
3560 			}
3561 			if (f->f_program != NULL)
3562 				printf(" (%s)", f->f_program);
3563 			printf("\n");
3564 		}
3565 	}
3566 
3567 	finet = socksetup(PF_UNSPEC, bindhostname);
3568 	if (finet) {
3569 		if (SecureMode) {
3570 			for (i = 0; i < finet->fd; i++) {
3571 				if (shutdown(finet[i+1].fd, SHUT_RD) < 0) {
3572 					logerror("shutdown() failed");
3573 					die(0, 0, NULL);
3574 				}
3575 			}
3576 		} else
3577 			DPRINTF(D_NET, "Listening on inet and/or inet6 socket\n");
3578 		DPRINTF(D_NET, "Sending on inet and/or inet6 socket\n");
3579 	}
3580 
3581 #ifndef DISABLE_TLS
3582 	/* TLS setup -- after all local destinations opened  */
3583 	DPRINTF(D_PARSE, "Parsed options: tls_ca: %s, tls_cadir: %s, "
3584 	    "tls_cert: %s, tls_key: %s, tls_verify: %s, "
3585 	    "bind: %s:%s, max. queue_lengths: %"
3586 	    PRId64 ", %" PRId64 ", %" PRId64 ", "
3587 	    "max. queue_sizes: %"
3588 	    PRId64 ", %" PRId64 ", %" PRId64 "\n",
3589 	    tls_opt.CAfile, tls_opt.CAdir,
3590 	    tls_opt.certfile, tls_opt.keyfile, tls_opt.x509verify,
3591 	    tls_opt.bindhost, tls_opt.bindport,
3592 	    TypeInfo[F_TLS].queue_length, TypeInfo[F_FILE].queue_length,
3593 	    TypeInfo[F_PIPE].queue_length,
3594 	    TypeInfo[F_TLS].queue_size, TypeInfo[F_FILE].queue_size,
3595 	    TypeInfo[F_PIPE].queue_size);
3596 	SLIST_FOREACH(cred, &tls_opt.cert_head, entries) {
3597 		DPRINTF(D_PARSE, "Accepting peer certificate "
3598 		    "from file: \"%s\"\n", cred->data);
3599 	}
3600 	SLIST_FOREACH(cred, &tls_opt.fprint_head, entries) {
3601 		DPRINTF(D_PARSE, "Accepting peer certificate with "
3602 		    "fingerprint: \"%s\"\n", cred->data);
3603 	}
3604 
3605 	/* Note: The order of initialization is important because syslog-sign
3606 	 * should use the TLS cert for signing. -- So we check first if TLS
3607 	 * will be used and initialize it before starting -sign.
3608 	 *
3609 	 * This means that if we are a client without TLS destinations TLS
3610 	 * will not be initialized and syslog-sign will generate a new key.
3611 	 * -- Even if the user has set a usable tls_cert.
3612 	 * Is this the expected behaviour? The alternative would be to always
3613 	 * initialize the TLS structures, even if they will not be needed
3614 	 * (or only needed to read the DSA key for -sign).
3615 	 */
3616 
3617 	/* Initialize TLS only if used */
3618 	if (tls_opt.server)
3619 		tls_status_msg = init_global_TLS_CTX();
3620 	else
3621 		for (f = Files; f; f = f->f_next) {
3622 			if (f->f_type != F_TLS)
3623 				continue;
3624 			tls_status_msg = init_global_TLS_CTX();
3625 			break;
3626 		}
3627 
3628 #endif /* !DISABLE_TLS */
3629 
3630 #ifndef DISABLE_SIGN
3631 	/* only initialize -sign if actually used */
3632 	if (GlobalSign.sg == 0 || GlobalSign.sg == 1 || GlobalSign.sg == 2)
3633 		(void)sign_global_init(Files);
3634 	else if (GlobalSign.sg == 3)
3635 		for (f = Files; f; f = f->f_next)
3636 			if (f->f_flags & FFLAG_SIGN) {
3637 				(void)sign_global_init(Files);
3638 				break;
3639 			}
3640 #endif /* !DISABLE_SIGN */
3641 
3642 #ifndef DISABLE_TLS
3643 	if (tls_status_msg) {
3644 		loginfo("%s", tls_status_msg);
3645 		free(tls_status_msg);
3646 	}
3647 	DPRINTF((D_NET|D_TLS), "Preparing sockets for TLS\n");
3648 	TLS_Listen_Set =
3649 		socksetup_tls(PF_UNSPEC, tls_opt.bindhost, tls_opt.bindport);
3650 
3651 	for (f = Files; f; f = f->f_next) {
3652 		if (f->f_type != F_TLS)
3653 			continue;
3654 		if (!tls_connect(f->f_un.f_tls.tls_conn)) {
3655 			logerror("Unable to connect to TLS server %s",
3656 			    f->f_un.f_tls.tls_conn->hostname);
3657 			/* Reconnect after x seconds  */
3658 			schedule_event(&f->f_un.f_tls.tls_conn->event,
3659 			    &((struct timeval){TLS_RECONNECT_SEC, 0}),
3660 			    tls_reconnect, f->f_un.f_tls.tls_conn);
3661 		}
3662 	}
3663 #endif /* !DISABLE_TLS */
3664 
3665 	loginfo("restart");
3666 	/*
3667 	 * Log a change in hostname, but only on a restart (we detect this
3668 	 * by checking to see if we're passed a kevent).
3669 	 */
3670 	if (oldLocalFQDN && strcmp(oldLocalFQDN, LocalFQDN) != 0)
3671 		loginfo("host name changed, \"%s\" to \"%s\"",
3672 		    oldLocalFQDN, LocalFQDN);
3673 
3674 	RESTORE_SIGNALS(omask);
3675 }
3676 
3677 /*
3678  * Crack a configuration file line
3679  */
3680 void
cfline(size_t linenum,const char * line,struct filed * f,const char * prog,const char * host)3681 cfline(size_t linenum, const char *line, struct filed *f, const char *prog,
3682     const char *host)
3683 {
3684 	struct addrinfo hints, *res;
3685 	int    error, i, pri, syncfile;
3686 	const char   *p, *q;
3687 	char *bp;
3688 	char   buf[MAXLINE];
3689 	struct stat sb;
3690 
3691 	DPRINTF((D_CALL|D_PARSE),
3692 		"cfline(%zu, \"%s\", f, \"%s\", \"%s\")\n",
3693 		linenum, line, prog, host);
3694 
3695 	errno = 0;	/* keep strerror() stuff out of logerror messages */
3696 
3697 	/* clear out file entry */
3698 	memset(f, 0, sizeof(*f));
3699 	for (i = 0; i <= LOG_NFACILITIES; i++)
3700 		f->f_pmask[i] = INTERNAL_NOPRI;
3701 	STAILQ_INIT(&f->f_qhead);
3702 
3703 	/*
3704 	 * There should not be any space before the log facility.
3705 	 * Check this is okay, complain and fix if it is not.
3706 	 */
3707 	q = line;
3708 	if (isblank((unsigned char)*line)) {
3709 		errno = 0;
3710 		logerror("Warning: `%s' space or tab before the log facility",
3711 		    line);
3712 		/* Fix: strip all spaces/tabs before the log facility */
3713 		while (*q++ && isblank((unsigned char)*q))
3714 			/* skip blanks */;
3715 		line = q;
3716 	}
3717 
3718 	/*
3719 	 * q is now at the first char of the log facility
3720 	 * There should be at least one tab after the log facility
3721 	 * Check this is okay, and complain and fix if it is not.
3722 	 */
3723 	q = line + strlen(line);
3724 	while (!isblank((unsigned char)*q) && (q != line))
3725 		q--;
3726 	if ((q == line) && strlen(line)) {
3727 		/* No tabs or space in a non empty line: complain */
3728 		errno = 0;
3729 		logerror(
3730 		    "Error: `%s' log facility or log target missing",
3731 		    line);
3732 		return;
3733 	}
3734 
3735 	/* save host name, if any */
3736 	if (*host == '*')
3737 		f->f_host = NULL;
3738 	else {
3739 		f->f_host = strdup(host);
3740 		trim_anydomain(&f->f_host[1]);	/* skip +/- at beginning */
3741 	}
3742 
3743 	/* save program name, if any */
3744 	if (*prog == '*')
3745 		f->f_program = NULL;
3746 	else
3747 		f->f_program = strdup(prog);
3748 
3749 	/* scan through the list of selectors */
3750 	for (p = line; *p && !isblank((unsigned char)*p);) {
3751 		int pri_done, pri_cmp, pri_invert;
3752 
3753 		/* find the end of this facility name list */
3754 		for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
3755 			continue;
3756 
3757 		/* get the priority comparison */
3758 		pri_cmp = 0;
3759 		pri_done = 0;
3760 		pri_invert = 0;
3761 		if (*q == '!') {
3762 			pri_invert = 1;
3763 			q++;
3764 		}
3765 		while (! pri_done) {
3766 			switch (*q) {
3767 			case '<':
3768 				pri_cmp = PRI_LT;
3769 				q++;
3770 				break;
3771 			case '=':
3772 				pri_cmp = PRI_EQ;
3773 				q++;
3774 				break;
3775 			case '>':
3776 				pri_cmp = PRI_GT;
3777 				q++;
3778 				break;
3779 			default:
3780 				pri_done = 1;
3781 				break;
3782 			}
3783 		}
3784 
3785 		/* collect priority name */
3786 		for (bp = buf; *q && !strchr("\t ,;", *q); )
3787 			*bp++ = *q++;
3788 		*bp = '\0';
3789 
3790 		/* skip cruft */
3791 		while (strchr(",;", *q))
3792 			q++;
3793 
3794 		/* decode priority name */
3795 		if (*buf == '*') {
3796 			pri = LOG_PRIMASK + 1;
3797 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3798 		} else {
3799 			pri = decode(buf, prioritynames);
3800 			if (pri < 0) {
3801 				errno = 0;
3802 				logerror("Unknown priority name `%s'", buf);
3803 				return;
3804 			}
3805 		}
3806 		if (pri_cmp == 0)
3807 			pri_cmp = UniquePriority ? PRI_EQ
3808 						 : PRI_EQ | PRI_GT;
3809 		if (pri_invert)
3810 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3811 
3812 		/* scan facilities */
3813 		while (*p && !strchr("\t .;", *p)) {
3814 			for (bp = buf; *p && !strchr("\t ,;.", *p); )
3815 				*bp++ = *p++;
3816 			*bp = '\0';
3817 			if (*buf == '*')
3818 				for (i = 0; i < LOG_NFACILITIES; i++) {
3819 					f->f_pmask[i] = pri;
3820 					f->f_pcmp[i] = pri_cmp;
3821 				}
3822 			else {
3823 				i = decode(buf, facilitynames);
3824 				if (i < 0) {
3825 					errno = 0;
3826 					logerror("Unknown facility name `%s'",
3827 					    buf);
3828 					return;
3829 				}
3830 				f->f_pmask[i >> 3] = pri;
3831 				f->f_pcmp[i >> 3] = pri_cmp;
3832 			}
3833 			while (*p == ',' || *p == ' ')
3834 				p++;
3835 		}
3836 
3837 		p = q;
3838 	}
3839 
3840 	/* skip to action part */
3841 	while (isblank((unsigned char)*p))
3842 		p++;
3843 
3844 	/*
3845 	 * should this be "#ifndef DISABLE_SIGN" or is it a general option?
3846 	 * '+' before file destination: write with PRI field for later
3847 	 * verification
3848 	 */
3849 	if (*p == '+') {
3850 		f->f_flags |= FFLAG_FULL;
3851 		p++;
3852 	}
3853 	if (*p == '-') {
3854 		syncfile = 0;
3855 		p++;
3856 	} else
3857 		syncfile = 1;
3858 
3859 	switch (*p) {
3860 	case '@':
3861 #ifndef DISABLE_SIGN
3862 		if (GlobalSign.sg == 3)
3863 			f->f_flags |= FFLAG_SIGN;
3864 #endif /* !DISABLE_SIGN */
3865 #ifndef DISABLE_TLS
3866 		if (*(p+1) == '[') {
3867 			/* TLS destination */
3868 			if (!parse_tls_destination(p, f, linenum)) {
3869 				logerror("Unable to parse action %s", p);
3870 				break;
3871 			}
3872 			f->f_type = F_TLS;
3873 			break;
3874 		}
3875 #endif /* !DISABLE_TLS */
3876 		(void)strlcpy(f->f_un.f_forw.f_hname, ++p,
3877 		    sizeof(f->f_un.f_forw.f_hname));
3878 		memset(&hints, 0, sizeof(hints));
3879 		hints.ai_family = AF_UNSPEC;
3880 		hints.ai_socktype = SOCK_DGRAM;
3881 		hints.ai_protocol = 0;
3882 		error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
3883 		    &res);
3884 		if (error) {
3885 			errno = 0;
3886 			logerror("%s", gai_strerror(error));
3887 			break;
3888 		}
3889 		f->f_un.f_forw.f_addr = res;
3890 		f->f_type = F_FORW;
3891 		NumForwards++;
3892 		break;
3893 
3894 	case '/':
3895 #ifndef DISABLE_SIGN
3896 		if (GlobalSign.sg == 3)
3897 			f->f_flags |= FFLAG_SIGN;
3898 #endif /* !DISABLE_SIGN */
3899 		(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
3900 		if ((f->f_file = open(p, O_WRONLY|O_APPEND|O_NONBLOCK, 0)) < 0)
3901 		{
3902 			f->f_type = F_UNUSED;
3903 			logerror("%s", p);
3904 			break;
3905 		}
3906 		if (!fstat(f->f_file, &sb) && S_ISFIFO(sb.st_mode)) {
3907 			f->f_file = -1;
3908 			f->f_type = F_FIFO;
3909 			break;
3910 		}
3911 
3912 		if (isatty(f->f_file)) {
3913 			f->f_type = F_TTY;
3914 			if (strcmp(p, ctty) == 0)
3915 				f->f_type = F_CONSOLE;
3916 		} else
3917 			f->f_type = F_FILE;
3918 
3919 		if (syncfile)
3920 			f->f_flags |= FFLAG_SYNC;
3921 		break;
3922 
3923 	case '|':
3924 #ifndef DISABLE_SIGN
3925 		if (GlobalSign.sg == 3)
3926 			f->f_flags |= FFLAG_SIGN;
3927 #endif
3928 		f->f_un.f_pipe.f_pid = 0;
3929 		(void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
3930 		    sizeof(f->f_un.f_pipe.f_pname));
3931 		f->f_type = F_PIPE;
3932 		break;
3933 
3934 	case '*':
3935 		f->f_type = F_WALL;
3936 		break;
3937 
3938 	default:
3939 		for (i = 0; i < MAXUNAMES && *p; i++) {
3940 			for (q = p; *q && *q != ','; )
3941 				q++;
3942 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
3943 			if ((q - p) > UT_NAMESIZE)
3944 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
3945 			else
3946 				f->f_un.f_uname[i][q - p] = '\0';
3947 			while (*q == ',' || *q == ' ')
3948 				q++;
3949 			p = q;
3950 		}
3951 		f->f_type = F_USERS;
3952 		break;
3953 	}
3954 }
3955 
3956 
3957 /*
3958  *  Decode a symbolic name to a numeric value
3959  */
3960 int
decode(const char * name,CODE * codetab)3961 decode(const char *name, CODE *codetab)
3962 {
3963 	CODE *c;
3964 	char *p, buf[40];
3965 
3966 	if (isdigit((unsigned char)*name))
3967 		return atoi(name);
3968 
3969 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3970 		if (isupper((unsigned char)*name))
3971 			*p = tolower((unsigned char)*name);
3972 		else
3973 			*p = *name;
3974 	}
3975 	*p = '\0';
3976 	for (c = codetab; c->c_name; c++)
3977 		if (!strcmp(buf, c->c_name))
3978 			return c->c_val;
3979 
3980 	return -1;
3981 }
3982 
3983 /*
3984  * Retrieve the size of the kernel message buffer, via sysctl.
3985  */
3986 int
getmsgbufsize(void)3987 getmsgbufsize(void)
3988 {
3989 #ifdef __NetBSD_Version__
3990 	int msgbufsize, mib[2];
3991 	size_t size;
3992 
3993 	mib[0] = CTL_KERN;
3994 	mib[1] = KERN_MSGBUFSIZE;
3995 	size = sizeof msgbufsize;
3996 	if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
3997 		DPRINTF(D_MISC, "Couldn't get kern.msgbufsize\n");
3998 		return 0;
3999 	}
4000 	return msgbufsize;
4001 #else
4002 	return MAXLINE;
4003 #endif /* __NetBSD_Version__ */
4004 }
4005 
4006 /*
4007  * Retrieve the hostname, via sysctl.
4008  */
4009 char *
getLocalFQDN(void)4010 getLocalFQDN(void)
4011 {
4012 	int mib[2];
4013 	char *hostname;
4014 	size_t len;
4015 
4016 	mib[0] = CTL_KERN;
4017 	mib[1] = KERN_HOSTNAME;
4018 	sysctl(mib, 2, NULL, &len, NULL, 0);
4019 
4020 	if (!(hostname = malloc(len))) {
4021 		logerror("Unable to allocate memory");
4022 		die(0,0,NULL);
4023 	} else if (sysctl(mib, 2, hostname, &len, NULL, 0) == -1) {
4024 		DPRINTF(D_MISC, "Couldn't get kern.hostname\n");
4025 		(void)gethostname(hostname, sizeof(len));
4026 	}
4027 	return hostname;
4028 }
4029 
4030 struct socketEvent *
socksetup(int af,const char * hostname)4031 socksetup(int af, const char *hostname)
4032 {
4033 	struct addrinfo hints, *res, *r;
4034 	int error, maxs;
4035 #ifdef IPV6_V6ONLY
4036 	int on = 1;
4037 #endif /* IPV6_V6ONLY */
4038 	struct socketEvent *s, *socks;
4039 
4040 	if(SecureMode && !NumForwards)
4041 		return NULL;
4042 
4043 	memset(&hints, 0, sizeof(hints));
4044 	hints.ai_flags = AI_PASSIVE;
4045 	hints.ai_family = af;
4046 	hints.ai_socktype = SOCK_DGRAM;
4047 	error = getaddrinfo(hostname, "syslog", &hints, &res);
4048 	if (error) {
4049 		errno = 0;
4050 		logerror("%s", gai_strerror(error));
4051 		die(0, 0, NULL);
4052 	}
4053 
4054 	/* Count max number of sockets we may open */
4055 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
4056 		continue;
4057 	socks = calloc(maxs+1, sizeof(*socks));
4058 	if (!socks) {
4059 		logerror("Couldn't allocate memory for sockets");
4060 		die(0, 0, NULL);
4061 	}
4062 
4063 	socks->fd = 0;	 /* num of sockets counter at start of array */
4064 	s = socks + 1;
4065 	for (r = res; r; r = r->ai_next) {
4066 		s->fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
4067 		if (s->fd < 0) {
4068 			logerror("socket() failed");
4069 			continue;
4070 		}
4071 		s->af = r->ai_family;
4072 #ifdef IPV6_V6ONLY
4073 		if (r->ai_family == AF_INET6 && setsockopt(s->fd, IPPROTO_IPV6,
4074 		    IPV6_V6ONLY, &on, sizeof(on)) < 0) {
4075 			logerror("setsockopt(IPV6_V6ONLY) failed");
4076 			close(s->fd);
4077 			continue;
4078 		}
4079 #endif /* IPV6_V6ONLY */
4080 
4081 		if (!SecureMode) {
4082 			if (bind(s->fd, r->ai_addr, r->ai_addrlen) < 0) {
4083 				logerror("bind() failed");
4084 				close(s->fd);
4085 				continue;
4086 			}
4087 			s->ev = allocev();
4088 			event_set(s->ev, s->fd, EV_READ | EV_PERSIST,
4089 				dispatch_read_finet, s->ev);
4090 			if (event_add(s->ev, NULL) == -1) {
4091 				DPRINTF((D_EVENT|D_NET),
4092 				    "Failure in event_add()\n");
4093 			} else {
4094 				DPRINTF((D_EVENT|D_NET),
4095 				    "Listen on UDP port "
4096 				    "(event@%p)\n", s->ev);
4097 			}
4098 		}
4099 
4100 		socks->fd++;  /* num counter */
4101 		s++;
4102 	}
4103 
4104 	if (res)
4105 		freeaddrinfo(res);
4106 	if (socks->fd == 0) {
4107 		free (socks);
4108 		if(Debug)
4109 			return NULL;
4110 		else
4111 			die(0, 0, NULL);
4112 	}
4113 	return socks;
4114 }
4115 
4116 /*
4117  * Fairly similar to popen(3), but returns an open descriptor, as opposed
4118  * to a FILE *.
4119  */
4120 int
p_open(char * prog,pid_t * rpid)4121 p_open(char *prog, pid_t *rpid)
4122 {
4123 	static char sh[] = "sh", mc[] = "-c";
4124 	int pfd[2], nulldesc, i;
4125 	pid_t pid;
4126 	char *argv[4];	/* sh -c cmd NULL */
4127 
4128 	if (pipe(pfd) == -1)
4129 		return -1;
4130 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
4131 		/* We are royally screwed anyway. */
4132 		return -1;
4133 	}
4134 
4135 	switch ((pid = fork())) {
4136 	case -1:
4137 		(void) close(nulldesc);
4138 		return -1;
4139 
4140 	case 0:
4141 		argv[0] = sh;
4142 		argv[1] = mc;
4143 		argv[2] = prog;
4144 		argv[3] = NULL;
4145 
4146 		(void) setsid();	/* avoid catching SIGHUPs. */
4147 
4148 		/*
4149 		 * Reset ignored signals to their default behavior.
4150 		 */
4151 		(void)signal(SIGTERM, SIG_DFL);
4152 		(void)signal(SIGINT, SIG_DFL);
4153 		(void)signal(SIGQUIT, SIG_DFL);
4154 		(void)signal(SIGPIPE, SIG_DFL);
4155 		(void)signal(SIGHUP, SIG_DFL);
4156 
4157 		dup2(pfd[0], STDIN_FILENO);
4158 		dup2(nulldesc, STDOUT_FILENO);
4159 		dup2(nulldesc, STDERR_FILENO);
4160 		for (i = getdtablesize(); i > 2; i--)
4161 			(void) close(i);
4162 
4163 		(void) execvp(_PATH_BSHELL, argv);
4164 		_exit(255);
4165 	}
4166 
4167 	(void) close(nulldesc);
4168 	(void) close(pfd[0]);
4169 
4170 	/*
4171 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
4172 	 * supposed to get an EWOULDBLOCK on writev(2), which is
4173 	 * caught by the logic above anyway, which will in turn
4174 	 * close the pipe, and fork a new logging subprocess if
4175 	 * necessary.  The stale subprocess will be killed some
4176 	 * time later unless it terminated itself due to closing
4177 	 * its input pipe.
4178 	 */
4179 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
4180 		/* This is bad. */
4181 		logerror("Warning: cannot change pipe to pid %d to "
4182 		    "non-blocking.", (int) pid);
4183 	}
4184 	*rpid = pid;
4185 	return pfd[1];
4186 }
4187 
4188 void
deadq_enter(pid_t pid,const char * name)4189 deadq_enter(pid_t pid, const char *name)
4190 {
4191 	dq_t p;
4192 	int status;
4193 
4194 	/*
4195 	 * Be paranoid: if we can't signal the process, don't enter it
4196 	 * into the dead queue (perhaps it's already dead).  If possible,
4197 	 * we try to fetch and log the child's status.
4198 	 */
4199 	if (kill(pid, 0) != 0) {
4200 		if (waitpid(pid, &status, WNOHANG) > 0)
4201 			log_deadchild(pid, status, name);
4202 		return;
4203 	}
4204 
4205 	p = malloc(sizeof(*p));
4206 	if (p == NULL) {
4207 		logerror("panic: out of memory!");
4208 		exit(1);
4209 	}
4210 
4211 	p->dq_pid = pid;
4212 	p->dq_timeout = DQ_TIMO_INIT;
4213 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
4214 }
4215 
4216 int
deadq_remove(pid_t pid)4217 deadq_remove(pid_t pid)
4218 {
4219 	dq_t q;
4220 
4221 	for (q = TAILQ_FIRST(&deadq_head); q != NULL;
4222 	     q = TAILQ_NEXT(q, dq_entries)) {
4223 		if (q->dq_pid == pid) {
4224 			TAILQ_REMOVE(&deadq_head, q, dq_entries);
4225 			free(q);
4226 			return 1;
4227 		}
4228 	}
4229 	return 0;
4230 }
4231 
4232 void
log_deadchild(pid_t pid,int status,const char * name)4233 log_deadchild(pid_t pid, int status, const char *name)
4234 {
4235 	int code;
4236 	char buf[256];
4237 	const char *reason;
4238 
4239 	/* Keep strerror() struff out of logerror messages. */
4240 	errno = 0;
4241 	if (WIFSIGNALED(status)) {
4242 		reason = "due to signal";
4243 		code = WTERMSIG(status);
4244 	} else {
4245 		reason = "with status";
4246 		code = WEXITSTATUS(status);
4247 		if (code == 0)
4248 			return;
4249 	}
4250 	(void) snprintf(buf, sizeof(buf),
4251 	    "Logging subprocess %d (%s) exited %s %d.",
4252 	    pid, name, reason, code);
4253 	logerror("%s", buf);
4254 }
4255 
4256 struct event *
allocev(void)4257 allocev(void)
4258 {
4259 	struct event *ev;
4260 
4261 	if (!(ev = calloc(1, sizeof(*ev))))
4262 		logerror("Unable to allocate memory");
4263 	return ev;
4264 }
4265 
4266 /* *ev is allocated if necessary */
4267 void
schedule_event(struct event ** ev,struct timeval * tv,void (* cb)(int,short,void *),void * arg)4268 schedule_event(struct event **ev, struct timeval *tv,
4269 	void (*cb)(int, short, void *), void *arg)
4270 {
4271 	if (!*ev && !(*ev = allocev())) {
4272 		return;
4273 	}
4274 	event_set(*ev, 0, 0, cb, arg);
4275 	DPRINTF(D_EVENT, "event_add(%s@%p)\n", "schedule_ev", *ev); \
4276 	if (event_add(*ev, tv) == -1) {
4277 		DPRINTF(D_EVENT, "Failure in event_add()\n");
4278 	}
4279 }
4280 
4281 #ifndef DISABLE_TLS
4282 /* abbreviation for freeing credential lists */
4283 void
free_cred_SLIST(struct peer_cred_head * head)4284 free_cred_SLIST(struct peer_cred_head *head)
4285 {
4286 	struct peer_cred *cred;
4287 
4288 	while (!SLIST_EMPTY(head)) {
4289 		cred = SLIST_FIRST(head);
4290 		SLIST_REMOVE_HEAD(head, entries);
4291 		FREEPTR(cred->data);
4292 		free(cred);
4293 	}
4294 }
4295 #endif /* !DISABLE_TLS */
4296 
4297 /*
4298  * send message queue after reconnect
4299  */
4300 /*ARGSUSED*/
4301 void
send_queue(int fd,short event,void * arg)4302 send_queue(int fd, short event, void *arg)
4303 {
4304 	struct filed *f = (struct filed *) arg;
4305 	struct buf_queue *qentry;
4306 #define SQ_CHUNK_SIZE 250
4307 	size_t cnt = 0;
4308 
4309 #ifndef DISABLE_TLS
4310 	if (f->f_type == F_TLS) {
4311 		/* use a flag to prevent recursive calls to send_queue() */
4312 		if (f->f_un.f_tls.tls_conn->send_queue)
4313 			return;
4314 		else
4315 			f->f_un.f_tls.tls_conn->send_queue = true;
4316 	}
4317 	DPRINTF((D_DATA|D_CALL), "send_queue(f@%p with %zu msgs, "
4318 		"cnt@%p = %zu)\n", f, f->f_qelements, &cnt, cnt);
4319 #endif /* !DISABLE_TLS */
4320 
4321 	while ((qentry = STAILQ_FIRST(&f->f_qhead))) {
4322 #ifndef DISABLE_TLS
4323 		/* send_queue() might be called with an unconnected destination
4324 		 * from init() or die() or one message might take longer,
4325 		 * leaving the connection in state ST_WAITING and thus not
4326 		 * ready for the next message.
4327 		 * this check is a shortcut to skip these unnecessary calls */
4328 		if (f->f_type == F_TLS
4329 		    && f->f_un.f_tls.tls_conn->state != ST_TLS_EST) {
4330 			DPRINTF(D_TLS, "abort send_queue(cnt@%p = %zu) "
4331 			    "on TLS connection in state %d\n",
4332 			    &cnt, cnt, f->f_un.f_tls.tls_conn->state);
4333 			return;
4334 		 }
4335 #endif /* !DISABLE_TLS */
4336 		fprintlog(f, qentry->msg, qentry);
4337 
4338 		/* Sending a long queue can take some time during which
4339 		 * SIGHUP and SIGALRM are blocked and no events are handled.
4340 		 * To avoid that we only send SQ_CHUNK_SIZE messages at once
4341 		 * and then reschedule ourselves to continue. Thus the control
4342 		 * will return first from all signal-protected functions so a
4343 		 * possible SIGHUP/SIGALRM is handled and then back to the
4344 		 * main loop which can handle possible input.
4345 		 */
4346 		if (++cnt >= SQ_CHUNK_SIZE) {
4347 			if (!f->f_sq_event) { /* alloc on demand */
4348 				f->f_sq_event = allocev();
4349 				event_set(f->f_sq_event, 0, 0, send_queue, f);
4350 			}
4351 			if (event_add(f->f_sq_event, &((struct timeval){0, 1})) == -1) {
4352 				DPRINTF(D_EVENT, "Failure in event_add()\n");
4353 			}
4354 			break;
4355 		}
4356 	}
4357 #ifndef DISABLE_TLS
4358 	if (f->f_type == F_TLS)
4359 		f->f_un.f_tls.tls_conn->send_queue = false;
4360 #endif
4361 
4362 }
4363 
4364 /*
4365  * finds the next queue element to delete
4366  *
4367  * has stateful behaviour, before using it call once with reset = true
4368  * after that every call will return one next queue elemen to delete,
4369  * depending on strategy either the oldest or the one with the lowest priority
4370  */
4371 static struct buf_queue *
find_qentry_to_delete(const struct buf_queue_head * head,int strategy,bool reset)4372 find_qentry_to_delete(const struct buf_queue_head *head, int strategy,
4373     bool reset)
4374 {
4375 	static int pri;
4376 	static struct buf_queue *qentry_static;
4377 
4378 	struct buf_queue *qentry_tmp;
4379 
4380 	if (reset || STAILQ_EMPTY(head)) {
4381 		pri = LOG_DEBUG;
4382 		qentry_static = STAILQ_FIRST(head);
4383 		return NULL;
4384 	}
4385 
4386 	/* find elements to delete */
4387 	if (strategy == PURGE_BY_PRIORITY) {
4388 		qentry_tmp = qentry_static;
4389 		if (!qentry_tmp) return NULL;
4390 		while ((qentry_tmp = STAILQ_NEXT(qentry_tmp, entries)) != NULL)
4391 		{
4392 			if (LOG_PRI(qentry_tmp->msg->pri) == pri) {
4393 				/* save the successor, because qentry_tmp
4394 				 * is probably deleted by the caller */
4395 				qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4396 				return qentry_tmp;
4397 			}
4398 		}
4399 		/* nothing found in while loop --> next pri */
4400 		if (--pri)
4401 			return find_qentry_to_delete(head, strategy, false);
4402 		else
4403 			return NULL;
4404 	} else /* strategy == PURGE_OLDEST or other value */ {
4405 		qentry_tmp = qentry_static;
4406 		qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4407 		return qentry_tmp;  /* is NULL on empty queue */
4408 	}
4409 }
4410 
4411 /* note on TAILQ: newest message added at TAIL,
4412  *		  oldest to be removed is FIRST
4413  */
4414 /*
4415  * checks length of a destination's message queue
4416  * if del_entries == 0 then assert queue length is
4417  *   less or equal to configured number of queue elements
4418  * otherwise del_entries tells how many entries to delete
4419  *
4420  * returns the number of removed queue elements
4421  * (which not necessarily means free'd messages)
4422  *
4423  * strategy PURGE_OLDEST to delete oldest entry, e.g. after it was resent
4424  * strategy PURGE_BY_PRIORITY to delete messages with lowest priority first,
4425  *	this is much slower but might be desirable when unsent messages have
4426  *	to be deleted, e.g. in call from domark()
4427  */
4428 size_t
message_queue_purge(struct filed * f,size_t del_entries,int strategy)4429 message_queue_purge(struct filed *f, size_t del_entries, int strategy)
4430 {
4431 	size_t removed = 0;
4432 	struct buf_queue *qentry = NULL;
4433 
4434 	DPRINTF((D_CALL|D_BUFFER), "purge_message_queue(%p, %zu, %d) with "
4435 	    "f_qelements=%zu and f_qsize=%zu\n",
4436 	    f, del_entries, strategy,
4437 	    f->f_qelements, f->f_qsize);
4438 
4439 	/* reset state */
4440 	(void)find_qentry_to_delete(&f->f_qhead, strategy, true);
4441 
4442 	while (removed < del_entries
4443 	    || (TypeInfo[f->f_type].queue_length != -1
4444 	    && (size_t)TypeInfo[f->f_type].queue_length <= f->f_qelements)
4445 	    || (TypeInfo[f->f_type].queue_size != -1
4446 	    && (size_t)TypeInfo[f->f_type].queue_size <= f->f_qsize)) {
4447 		qentry = find_qentry_to_delete(&f->f_qhead, strategy, 0);
4448 		if (message_queue_remove(f, qentry))
4449 			removed++;
4450 		else
4451 			break;
4452 	}
4453 	return removed;
4454 }
4455 
4456 /* run message_queue_purge() for all destinations to free memory */
4457 size_t
message_allqueues_purge(void)4458 message_allqueues_purge(void)
4459 {
4460 	size_t sum = 0;
4461 	struct filed *f;
4462 
4463 	for (f = Files; f; f = f->f_next)
4464 		sum += message_queue_purge(f,
4465 		    f->f_qelements/10, PURGE_BY_PRIORITY);
4466 
4467 	DPRINTF(D_BUFFER,
4468 	    "message_allqueues_purge(): removed %zu buffer entries\n", sum);
4469 	return sum;
4470 }
4471 
4472 /* run message_queue_purge() for all destinations to check limits */
4473 size_t
message_allqueues_check(void)4474 message_allqueues_check(void)
4475 {
4476 	size_t sum = 0;
4477 	struct filed *f;
4478 
4479 	for (f = Files; f; f = f->f_next)
4480 		sum += message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4481 	DPRINTF(D_BUFFER,
4482 	    "message_allqueues_check(): removed %zu buffer entries\n", sum);
4483 	return sum;
4484 }
4485 
4486 struct buf_msg *
buf_msg_new(const size_t len)4487 buf_msg_new(const size_t len)
4488 {
4489 	struct buf_msg *newbuf;
4490 
4491 	CALLOC(newbuf, sizeof(*newbuf));
4492 
4493 	if (len) { /* len = 0 is valid */
4494 		MALLOC(newbuf->msg, len);
4495 		newbuf->msgorig = newbuf->msg;
4496 		newbuf->msgsize = len;
4497 	}
4498 	return NEWREF(newbuf);
4499 }
4500 
4501 void
buf_msg_free(struct buf_msg * buf)4502 buf_msg_free(struct buf_msg *buf)
4503 {
4504 	if (!buf)
4505 		return;
4506 
4507 	buf->refcount--;
4508 	if (buf->refcount == 0) {
4509 		FREEPTR(buf->timestamp);
4510 		/* small optimizations: the host/recvhost may point to the
4511 		 * global HostName/FQDN. of course this must not be free()d
4512 		 * same goes for appname and include_pid
4513 		 */
4514 		if (buf->recvhost != buf->host
4515 		    && buf->recvhost != LocalHostName
4516 		    && buf->recvhost != LocalFQDN
4517 		    && buf->recvhost != oldLocalFQDN)
4518 			FREEPTR(buf->recvhost);
4519 		if (buf->host != LocalHostName
4520 		    && buf->host != LocalFQDN
4521 		    && buf->host != oldLocalFQDN)
4522 			FREEPTR(buf->host);
4523 		if (buf->prog != appname)
4524 			FREEPTR(buf->prog);
4525 		if (buf->pid != include_pid)
4526 			FREEPTR(buf->pid);
4527 		FREEPTR(buf->msgid);
4528 		FREEPTR(buf->sd);
4529 		FREEPTR(buf->msgorig);	/* instead of msg */
4530 		FREEPTR(buf);
4531 	}
4532 }
4533 
4534 size_t
buf_queue_obj_size(struct buf_queue * qentry)4535 buf_queue_obj_size(struct buf_queue *qentry)
4536 {
4537 	size_t sum = 0;
4538 
4539 	if (!qentry)
4540 		return 0;
4541 	sum += sizeof(*qentry)
4542 	    + sizeof(*qentry->msg)
4543 	    + qentry->msg->msgsize
4544 	    + SAFEstrlen(qentry->msg->timestamp)+1
4545 	    + SAFEstrlen(qentry->msg->msgid)+1;
4546 	if (qentry->msg->prog
4547 	    && qentry->msg->prog != include_pid)
4548 		sum += strlen(qentry->msg->prog)+1;
4549 	if (qentry->msg->pid
4550 	    && qentry->msg->pid != appname)
4551 		sum += strlen(qentry->msg->pid)+1;
4552 	if (qentry->msg->recvhost
4553 	    && qentry->msg->recvhost != LocalHostName
4554 	    && qentry->msg->recvhost != LocalFQDN
4555 	    && qentry->msg->recvhost != oldLocalFQDN)
4556 		sum += strlen(qentry->msg->recvhost)+1;
4557 	if (qentry->msg->host
4558 	    && qentry->msg->host != LocalHostName
4559 	    && qentry->msg->host != LocalFQDN
4560 	    && qentry->msg->host != oldLocalFQDN)
4561 		sum += strlen(qentry->msg->host)+1;
4562 
4563 	return sum;
4564 }
4565 
4566 bool
message_queue_remove(struct filed * f,struct buf_queue * qentry)4567 message_queue_remove(struct filed *f, struct buf_queue *qentry)
4568 {
4569 	if (!f || !qentry || !qentry->msg)
4570 		return false;
4571 
4572 	assert(!STAILQ_EMPTY(&f->f_qhead));
4573 	STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4574 	f->f_qelements--;
4575 	f->f_qsize -= buf_queue_obj_size(qentry);
4576 
4577 	DPRINTF(D_BUFFER, "msg @%p removed from queue @%p, new qlen = %zu\n",
4578 	    qentry->msg, f, f->f_qelements);
4579 	DELREF(qentry->msg);
4580 	FREEPTR(qentry);
4581 	return true;
4582 }
4583 
4584 /*
4585  * returns *qentry on success and NULL on error
4586  */
4587 struct buf_queue *
message_queue_add(struct filed * f,struct buf_msg * buffer)4588 message_queue_add(struct filed *f, struct buf_msg *buffer)
4589 {
4590 	struct buf_queue *qentry;
4591 
4592 	/* check on every call or only every n-th time? */
4593 	message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4594 
4595 	while (!(qentry = malloc(sizeof(*qentry)))
4596 	    && message_queue_purge(f, 1, PURGE_OLDEST))
4597 		continue;
4598 	if (!qentry) {
4599 		logerror("Unable to allocate memory");
4600 		DPRINTF(D_BUFFER, "queue empty, no memory, msg dropped\n");
4601 		return NULL;
4602 	} else {
4603 		qentry->msg = buffer;
4604 		f->f_qelements++;
4605 		f->f_qsize += buf_queue_obj_size(qentry);
4606 		STAILQ_INSERT_TAIL(&f->f_qhead, qentry, entries);
4607 
4608 		DPRINTF(D_BUFFER, "msg @%p queued @%p, qlen = %zu\n",
4609 		    buffer, f, f->f_qelements);
4610 		return qentry;
4611 	}
4612 }
4613 
4614 void
message_queue_freeall(struct filed * f)4615 message_queue_freeall(struct filed *f)
4616 {
4617 	struct buf_queue *qentry;
4618 
4619 	if (!f) return;
4620 	DPRINTF(D_MEM, "message_queue_freeall(f@%p) with f_qhead@%p\n", f,
4621 	    &f->f_qhead);
4622 
4623 	while (!STAILQ_EMPTY(&f->f_qhead)) {
4624 		qentry = STAILQ_FIRST(&f->f_qhead);
4625 		STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4626 		DELREF(qentry->msg);
4627 		FREEPTR(qentry);
4628 	}
4629 
4630 	f->f_qelements = 0;
4631 	f->f_qsize = 0;
4632 }
4633 
4634 #ifndef DISABLE_TLS
4635 /* utility function for tls_reconnect() */
4636 struct filed *
get_f_by_conninfo(struct tls_conn_settings * conn_info)4637 get_f_by_conninfo(struct tls_conn_settings *conn_info)
4638 {
4639 	struct filed *f;
4640 
4641 	for (f = Files; f; f = f->f_next) {
4642 		if ((f->f_type == F_TLS) && f->f_un.f_tls.tls_conn == conn_info)
4643 			return f;
4644 	}
4645 	DPRINTF(D_TLS, "get_f_by_conninfo() called on invalid conn_info\n");
4646 	return NULL;
4647 }
4648 
4649 /*
4650  * Called on signal.
4651  * Lets the admin reconnect without waiting for the reconnect timer expires.
4652  */
4653 /*ARGSUSED*/
4654 void
dispatch_force_tls_reconnect(int fd,short event,void * ev)4655 dispatch_force_tls_reconnect(int fd, short event, void *ev)
4656 {
4657 	struct filed *f;
4658 	DPRINTF((D_TLS|D_CALL|D_EVENT), "dispatch_force_tls_reconnect()\n");
4659 	for (f = Files; f; f = f->f_next) {
4660 		if (f->f_type == F_TLS &&
4661 		    f->f_un.f_tls.tls_conn->state == ST_NONE)
4662 			tls_reconnect(fd, event, f->f_un.f_tls.tls_conn);
4663 	}
4664 }
4665 #endif /* !DISABLE_TLS */
4666 
4667 /*
4668  * return a timestamp in a static buffer,
4669  * either format the timestamp given by parameter in_now
4670  * or use the current time if in_now is NULL.
4671  */
4672 char *
make_timestamp(time_t * in_now,bool iso,size_t tlen)4673 make_timestamp(time_t *in_now, bool iso, size_t tlen)
4674 {
4675 	int frac_digits = 6;
4676 	struct timeval tv;
4677 	time_t mytime;
4678 	struct tm ltime;
4679 	int len = 0;
4680 	int tzlen = 0;
4681 	/* uses global var: time_t now; */
4682 
4683 	if (in_now) {
4684 		mytime = *in_now;
4685 	} else {
4686 		gettimeofday(&tv, NULL);
4687 		mytime = now = tv.tv_sec;
4688 	}
4689 
4690 	if (!iso) {
4691 		strlcpy(timestamp, ctime(&mytime) + 4, sizeof(timestamp));
4692 		timestamp[BSD_TIMESTAMPLEN] = '\0';
4693 	} else {
4694 		localtime_r(&mytime, &ltime);
4695 		len += strftime(timestamp, sizeof(timestamp), "%FT%T", &ltime);
4696 		snprintf(&timestamp[len], frac_digits + 2, ".%.*jd",
4697 		    frac_digits, (intmax_t)tv.tv_usec);
4698 		len += frac_digits + 1;
4699 		tzlen = strftime(&timestamp[len], sizeof(timestamp) - len, "%z",
4700 		    &ltime);
4701 		len += tzlen;
4702 
4703 		if (tzlen == 5) {
4704 			/* strftime gives "+0200", but we need "+02:00" */
4705 			timestamp[len + 2] = '\0';
4706 			timestamp[len + 1] = timestamp[len];
4707 			timestamp[len] = timestamp[len - 1];
4708 			timestamp[len - 1] = timestamp[len - 2];
4709 			timestamp[len - 2] = ':';
4710 		}
4711 	}
4712 
4713 	switch (tlen) {
4714 	case (size_t)-1:
4715 		return timestamp;
4716 	case 0:
4717 		return strdup(timestamp);
4718 	default:
4719 		return strndup(timestamp, tlen);
4720 	}
4721 }
4722 
4723 /* auxillary code to allocate memory and copy a string */
4724 bool
copy_string(char ** mem,const char * p,const char * q)4725 copy_string(char **mem, const char *p, const char *q)
4726 {
4727 	const size_t len = 1 + q - p;
4728 	if (!(*mem = malloc(len))) {
4729 		logerror("Unable to allocate memory for config");
4730 		return false;
4731 	}
4732 	strlcpy(*mem, p, len);
4733 	return true;
4734 }
4735 
4736 /* keyword has to end with ",  everything until next " is copied */
4737 bool
copy_config_value_quoted(const char * keyword,char ** mem,const char ** p)4738 copy_config_value_quoted(const char *keyword, char **mem, const char **p)
4739 {
4740 	const char *q;
4741 	if (strncasecmp(*p, keyword, strlen(keyword)))
4742 		return false;
4743 	q = *p += strlen(keyword);
4744 	if (!(q = strchr(*p, '"'))) {
4745 		errno = 0;
4746 		logerror("unterminated \"\n");
4747 		return false;
4748 	}
4749 	if (!(copy_string(mem, *p, q)))
4750 		return false;
4751 	*p = ++q;
4752 	return true;
4753 }
4754 
4755 /* for config file:
4756  * following = required but whitespace allowed, quotes optional
4757  * if numeric, then conversion to integer and no memory allocation
4758  */
4759 bool
copy_config_value(const char * keyword,char ** mem,const char ** p,const char * file,int line)4760 copy_config_value(const char *keyword, char **mem,
4761 	const char **p, const char *file, int line)
4762 {
4763 	if (strncasecmp(*p, keyword, strlen(keyword)))
4764 		return false;
4765 	*p += strlen(keyword);
4766 
4767 	while (isspace((unsigned char)**p))
4768 		*p += 1;
4769 	if (**p != '=') {
4770 		errno = 0;
4771 		logerror("expected \"=\" in file %s, line %d", file, line);
4772 		return false;
4773 	}
4774 	*p += 1;
4775 
4776 	return copy_config_value_word(mem, p);
4777 }
4778 
4779 /* copy next parameter from a config line */
4780 bool
copy_config_value_word(char ** mem,const char ** p)4781 copy_config_value_word(char **mem, const char **p)
4782 {
4783 	const char *q;
4784 	while (isspace((unsigned char)**p))
4785 		*p += 1;
4786 	if (**p == '"')
4787 		return copy_config_value_quoted("\"", mem, p);
4788 
4789 	/* without quotes: find next whitespace or end of line */
4790 	(void)((q = strchr(*p, ' ')) || (q = strchr(*p, '\t'))
4791 	     || (q = strchr(*p, '\n')) || (q = strchr(*p, '\0')));
4792 
4793 	if (q-*p == 0 || !(copy_string(mem, *p, q)))
4794 		return false;
4795 
4796 	*p = ++q;
4797 	return true;
4798 }
4799 
4800 static int
writev1(int fd,struct iovec * iov,size_t count)4801 writev1(int fd, struct iovec *iov, size_t count)
4802 {
4803 	ssize_t nw = 0, tot = 0;
4804 	size_t ntries = 5;
4805 
4806 	if (count == 0)
4807 		return 0;
4808 	while (ntries--) {
4809 		switch ((nw = writev(fd, iov, count))) {
4810 		case -1:
4811 			if (errno == EAGAIN || errno == EWOULDBLOCK) {
4812 				struct pollfd pfd;
4813 				pfd.fd = fd;
4814 				pfd.events = POLLOUT;
4815 				pfd.revents = 0;
4816 				(void)poll(&pfd, 1, 500);
4817 				continue;
4818 			}
4819 			return -1;
4820 		case 0:
4821 			return 0;
4822 		default:
4823 			tot += nw;
4824 			while (nw > 0) {
4825 				if (iov->iov_len > (size_t)nw) {
4826 					iov->iov_len -= nw;
4827 					iov->iov_base =
4828 					    (char *)iov->iov_base + nw;
4829 					break;
4830 				} else {
4831 					if (--count == 0)
4832 						return tot;
4833 					nw -= iov->iov_len;
4834 					iov++;
4835 				}
4836 			}
4837 		}
4838 	}
4839 	return tot == 0 ? nw : tot;
4840 }
4841 
4842 #ifndef NDEBUG
4843 void
dbprintf(const char * fname,const char * funname,size_t lnum,const char * fmt,...)4844 dbprintf(const char *fname, const char *funname,
4845     size_t lnum, const char *fmt, ...)
4846 {
4847 	va_list ap;
4848 	char *ts;
4849 
4850 	ts = make_timestamp(NULL, true, (size_t)-1);
4851 	printf("%s:%s:%s:%.4zu\t", ts, fname, funname, lnum);
4852 
4853 	va_start(ap, fmt);
4854 	vprintf(fmt, ap);
4855 	va_end(ap);
4856 }
4857 #endif
4858