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