xref: /netbsd/usr.sbin/syslogd/syslogd.c (revision 15beba29)
1 /*	$NetBSD: syslogd.c,v 1.133 2020/09/29 14:08:43 gson 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.133 2020/09/29 14:08:43 gson 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 = NULL;	/* include PID in own messages */
210 
211 
212 /* init and setup */
213 void		usage(void) __attribute__((__noreturn__));
214 void		logpath_add(char ***, int *, int *, const char *);
215 void		logpath_fileadd(char ***, int *, int *, const char *);
216 void		init(int fd, short event, void *ev);  /* SIGHUP kevent dispatch routine */
217 struct socketEvent*
218 		socksetup(int, const char *);
219 int		getmsgbufsize(void);
220 char	       *getLocalFQDN(void);
221 void		trim_anydomain(char *);
222 /* pipe & subprocess handling */
223 int		p_open(char *, pid_t *);
224 void		deadq_enter(pid_t, const char *);
225 int		deadq_remove(pid_t);
226 void		log_deadchild(pid_t, int, const char *);
227 void		reapchild(int fd, short event, void *ev); /* SIGCHLD kevent dispatch routine */
228 /* input message parsing & formatting */
229 const char     *cvthname(struct sockaddr_storage *);
230 void		printsys(char *);
231 struct buf_msg *printline_syslogprotocol(const char*, char*, int, int);
232 struct buf_msg *printline_bsdsyslog(const char*, char*, int, int);
233 struct buf_msg *printline_kernelprintf(const char*, char*, int, int);
234 size_t		check_timestamp(unsigned char *, char **, bool, bool);
235 char	       *copy_utf8_ascii(char*, size_t);
236 uint_fast32_t	get_utf8_value(const char*);
237 unsigned	valid_utf8(const char *);
238 static unsigned check_sd(char*);
239 static unsigned check_msgid(char *);
240 /* event handling */
241 static void	dispatch_read_klog(int fd, short event, void *ev);
242 static void	dispatch_read_finet(int fd, short event, void *ev);
243 static void	dispatch_read_funix(int fd, short event, void *ev);
244 static void	domark(int fd, short event, void *ev); /* timer kevent dispatch routine */
245 /* log messages */
246 void		logmsg_async(int, const char *, const char *, int);
247 void		logmsg(struct buf_msg *);
248 int		matches_spec(const char *, const char *,
249 		char *(*)(const char *, const char *));
250 void		udp_send(struct filed *, char *, size_t);
251 void		wallmsg(struct filed *, struct iovec *, size_t);
252 /* buffer & queue functions */
253 size_t		message_queue_purge(struct filed *f, size_t, int);
254 size_t		message_allqueues_check(void);
255 static struct buf_queue *
256 		find_qentry_to_delete(const struct buf_queue_head *, int, bool);
257 struct buf_queue *
258 		message_queue_add(struct filed *, struct buf_msg *);
259 size_t		buf_queue_obj_size(struct buf_queue*);
260 /* configuration & parsing */
261 void		cfline(size_t, const char *, struct filed *, const char *,
262     const char *);
263 void		read_config_file(FILE*, struct filed**);
264 void		store_sign_delim_sg2(char*);
265 int		decode(const char *, CODE *);
266 bool		copy_config_value(const char *, char **, const char **,
267     const char *, int);
268 bool		copy_config_value_word(char **, const char **);
269 
270 /* config parsing */
271 #ifndef DISABLE_TLS
272 void		free_cred_SLIST(struct peer_cred_head *);
273 static inline void
274 		free_incoming_tls_sockets(void);
275 #endif /* !DISABLE_TLS */
276 static int writev1(int, struct iovec *, size_t);
277 
278 static void setsockbuf(int, const char *);
279 
280 /* for make_timestamp() */
281 char	timestamp[MAX_TIMESTAMPLEN + 1];
282 /*
283  * Global line buffer.	Since we only process one event at a time,
284  * a global one will do.  But for klog, we use own buffer so that
285  * partial line at the end of buffer can be deferred.
286  */
287 char *linebuf, *klog_linebuf;
288 size_t linebufsize, klog_linebufoff;
289 
290 static const char *bindhostname = NULL;
291 
292 #ifndef DISABLE_TLS
293 struct TLS_Incoming TLS_Incoming_Head = \
294 	SLIST_HEAD_INITIALIZER(TLS_Incoming_Head);
295 extern char *SSL_ERRCODE[];
296 struct tls_global_options_t tls_opt;
297 #endif /* !DISABLE_TLS */
298 
299 int
300 main(int argc, char *argv[])
301 {
302 	int ch, j, fklog;
303 	int funixsize = 0, funixmaxsize = 0;
304 	struct sockaddr_un sunx;
305 	char **pp;
306 	struct event *ev;
307 	uid_t uid = 0;
308 	gid_t gid = 0;
309 	char *user = NULL;
310 	char *group = NULL;
311 	const char *root = "/";
312 	char *endp;
313 	struct group   *gr;
314 	struct passwd  *pw;
315 	unsigned long l;
316 
317 	/* should we set LC_TIME="C" to ensure correct timestamps&parsing? */
318 	(void)setlocale(LC_ALL, "");
319 
320 	while ((ch = getopt(argc, argv, "b:B:dnsSf:m:o:p:P:ru:g:t:TUvX")) != -1)
321 		switch(ch) {
322 		case 'b':
323 			bindhostname = optarg;
324 			break;
325 		case 'B':
326 			buflen = atoi(optarg);
327 			if (buflen < RCVBUFLEN)
328 				buflen = RCVBUFLEN;
329 			break;
330 		case 'd':		/* debug */
331 			Debug = D_DEFAULT;
332 			/* is there a way to read the integer value
333 			 * for Debug as an optional argument? */
334 			break;
335 		case 'f':		/* configuration file */
336 			ConfFile = optarg;
337 			break;
338 		case 'g':
339 			group = optarg;
340 			if (*group == '\0')
341 				usage();
342 			break;
343 		case 'm':		/* mark interval */
344 			MarkInterval = atoi(optarg) * 60;
345 			break;
346 		case 'n':		/* turn off DNS queries */
347 			UseNameService = 0;
348 			break;
349 		case 'o':		/* message format */
350 #define EQ(a)		(strncmp(optarg, # a, sizeof(# a) - 1) == 0)
351 			if (EQ(bsd) || EQ(rfc3264))
352 				BSDOutputFormat = true;
353 			else if (EQ(syslog) || EQ(rfc5424))
354 				BSDOutputFormat = false;
355 			else
356 				usage();
357 			/* TODO: implement additional output option "osyslog"
358 			 *	 for old syslogd behaviour as introduced after
359 			 *	 FreeBSD PR#bin/7055.
360 			 */
361 			break;
362 		case 'p':		/* path */
363 			logpath_add(&LogPaths, &funixsize,
364 			    &funixmaxsize, optarg);
365 			break;
366 		case 'P':		/* file of paths */
367 			logpath_fileadd(&LogPaths, &funixsize,
368 			    &funixmaxsize, optarg);
369 			break;
370 		case 'r':		/* disable "repeated" compression */
371 			NoRepeat++;
372 			break;
373 		case 's':		/* no network listen mode */
374 			SecureMode++;
375 			break;
376 		case 'S':
377 			SyncKernel = 1;
378 			break;
379 		case 't':
380 			root = optarg;
381 			if (*root == '\0')
382 				usage();
383 			break;
384 		case 'T':
385 			RemoteAddDate = 1;
386 			break;
387 		case 'u':
388 			user = optarg;
389 			if (*user == '\0')
390 				usage();
391 			break;
392 		case 'U':		/* only log specified priority */
393 			UniquePriority = 1;
394 			break;
395 		case 'v':		/* log facility and priority */
396 			if (LogFacPri < 2)
397 				LogFacPri++;
398 			break;
399 		case 'X':
400 			LogOverflow = 0;
401 			break;
402 		default:
403 			usage();
404 		}
405 	if ((argc -= optind) != 0)
406 		usage();
407 
408 	setlinebuf(stdout);
409 	tzset(); /* init TZ information for localtime. */
410 
411 	if (user != NULL) {
412 		if (isdigit((unsigned char)*user)) {
413 			errno = 0;
414 			endp = NULL;
415 			l = strtoul(user, &endp, 0);
416 			if (errno || *endp != '\0')
417 				goto getuser;
418 			uid = (uid_t)l;
419 			if (uid != l) {/* TODO: never executed */
420 				errno = 0;
421 				logerror("UID out of range");
422 				die(0, 0, NULL);
423 			}
424 		} else {
425 getuser:
426 			if ((pw = getpwnam(user)) != NULL) {
427 				uid = pw->pw_uid;
428 			} else {
429 				errno = 0;
430 				logerror("Cannot find user `%s'", user);
431 				die(0, 0, NULL);
432 			}
433 		}
434 	}
435 
436 	if (group != NULL) {
437 		if (isdigit((unsigned char)*group)) {
438 			errno = 0;
439 			endp = NULL;
440 			l = strtoul(group, &endp, 0);
441 			if (errno || *endp != '\0')
442 				goto getgroup;
443 			gid = (gid_t)l;
444 			if (gid != l) {/* TODO: never executed */
445 				errno = 0;
446 				logerror("GID out of range");
447 				die(0, 0, NULL);
448 			}
449 		} else {
450 getgroup:
451 			if ((gr = getgrnam(group)) != NULL) {
452 				gid = gr->gr_gid;
453 			} else {
454 				errno = 0;
455 				logerror("Cannot find group `%s'", group);
456 				die(0, 0, NULL);
457 			}
458 		}
459 	}
460 
461 	if (access(root, F_OK | R_OK)) {
462 		logerror("Cannot access `%s'", root);
463 		die(0, 0, NULL);
464 	}
465 
466 	consfile.f_type = F_CONSOLE;
467 	(void)strlcpy(consfile.f_un.f_fname, ctty,
468 	    sizeof(consfile.f_un.f_fname));
469 	linebufsize = getmsgbufsize();
470 	if (linebufsize < MAXLINE)
471 		linebufsize = MAXLINE;
472 	linebufsize++;
473 
474 	if (!(linebuf = malloc(linebufsize))) {
475 		logerror("Couldn't allocate buffer");
476 		die(0, 0, NULL);
477 	}
478 	if (!(klog_linebuf = malloc(linebufsize))) {
479 		logerror("Couldn't allocate buffer for klog");
480 		die(0, 0, NULL);
481 	}
482 
483 
484 #ifndef SUN_LEN
485 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
486 #endif
487 	if (funixsize == 0)
488 		logpath_add(&LogPaths, &funixsize,
489 		    &funixmaxsize, _PATH_LOG);
490 	funix = malloc(sizeof(*funix) * funixsize);
491 	if (funix == NULL) {
492 		logerror("Couldn't allocate funix descriptors");
493 		die(0, 0, NULL);
494 	}
495 	for (j = 0, pp = LogPaths; *pp; pp++, j++) {
496 		DPRINTF(D_NET, "Making unix dgram socket `%s'\n", *pp);
497 		unlink(*pp);
498 		memset(&sunx, 0, sizeof(sunx));
499 		sunx.sun_family = AF_LOCAL;
500 		(void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
501 		funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
502 		if (funix[j] < 0 || bind(funix[j],
503 		    (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
504 		    chmod(*pp, 0666) < 0) {
505 			logerror("Cannot create `%s'", *pp);
506 			die(0, 0, NULL);
507 		}
508 		setsockbuf(funix[j], *pp);
509 		DPRINTF(D_NET, "Listening on unix dgram socket `%s'\n", *pp);
510 	}
511 
512 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
513 		DPRINTF(D_FILE, "Can't open `%s' (%d)\n", _PATH_KLOG, errno);
514 	} else {
515 		DPRINTF(D_FILE, "Listening on kernel log `%s' with fd %d\n",
516 		    _PATH_KLOG, fklog);
517 	}
518 
519 #if (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN))
520 	/* basic OpenSSL init */
521 	SSL_load_error_strings();
522 	(void) SSL_library_init();
523 	OpenSSL_add_all_digests();
524 	/* OpenSSL PRNG needs /dev/urandom, thus initialize before chroot() */
525 	if (!RAND_status()) {
526 		errno = 0;
527 		logerror("Unable to initialize OpenSSL PRNG");
528 	} else {
529 		DPRINTF(D_TLS, "Initializing PRNG\n");
530 	}
531 #endif /* (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN)) */
532 #ifndef DISABLE_SIGN
533 	/* initialize rsid -- we will use that later to determine
534 	 * whether sign_global_init() was already called */
535 	GlobalSign.rsid = 0;
536 #endif /* !DISABLE_SIGN */
537 #if (IETF_NUM_PRIVALUES != (LOG_NFACILITIES<<3))
538 	logerror("Warning: system defines %d priority values, but "
539 	    "syslog-protocol/syslog-sign specify %d values",
540 	    LOG_NFACILITIES, SIGN_NUM_PRIVALS);
541 #endif
542 
543 	/*
544 	 * All files are open, we can drop privileges and chroot
545 	 */
546 	DPRINTF(D_MISC, "Attempt to chroot to `%s'\n", root);
547 	if (chroot(root) == -1) {
548 		logerror("Failed to chroot to `%s'", root);
549 		die(0, 0, NULL);
550 	}
551 	DPRINTF(D_MISC, "Attempt to set GID/EGID to `%d'\n", gid);
552 	if (setgid(gid) || setegid(gid)) {
553 		logerror("Failed to set gid to `%d'", gid);
554 		die(0, 0, NULL);
555 	}
556 	DPRINTF(D_MISC, "Attempt to set UID/EUID to `%d'\n", uid);
557 	if (setuid(uid) || seteuid(uid)) {
558 		logerror("Failed to set uid to `%d'", uid);
559 		die(0, 0, NULL);
560 	}
561 	/*
562 	 * We cannot detach from the terminal before we are sure we won't
563 	 * have a fatal error, because error message would not go to the
564 	 * terminal and would not be logged because syslogd dies.
565 	 * All die() calls are behind us, we can call daemon()
566 	 */
567 	if (!Debug) {
568 		(void)daemon(0, 0);
569 		daemonized = 1;
570 		/* tuck my process id away, if i'm not in debug mode */
571 #ifdef __NetBSD_Version__
572 		pidfile(NULL);
573 #endif /* __NetBSD_Version__ */
574 	}
575 
576 #define MAX_PID_LEN 5
577 	include_pid = malloc(MAX_PID_LEN+1);
578 	snprintf(include_pid, MAX_PID_LEN+1, "%d", getpid());
579 
580 	/*
581 	 * Create the global kernel event descriptor.
582 	 *
583 	 * NOTE: We MUST do this after daemon(), bacause 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 			if (close(finet[i+1].fd) < 0) {
3016 				logerror("close() failed");
3017 				die(0, 0, NULL);
3018 			}
3019 			DEL_EVENT(finet[i+1].ev);
3020 			FREEPTR(finet[i+1].ev);
3021 		}
3022 		FREEPTR(finet);
3023 	}
3024 
3025 	/* free config options */
3026 	for (j = 0; j < A_CNT(TypeInfo); j++) {
3027 		FREEPTR(TypeInfo[j].queue_length_string);
3028 		FREEPTR(TypeInfo[j].queue_size_string);
3029 	}
3030 
3031 #ifndef DISABLE_TLS
3032 	FREEPTR(tls_opt.CAdir);
3033 	FREEPTR(tls_opt.CAfile);
3034 	FREEPTR(tls_opt.keyfile);
3035 	FREEPTR(tls_opt.certfile);
3036 	FREEPTR(tls_opt.x509verify);
3037 	FREEPTR(tls_opt.bindhost);
3038 	FREEPTR(tls_opt.bindport);
3039 	FREEPTR(tls_opt.server);
3040 	FREEPTR(tls_opt.gen_cert);
3041 	free_cred_SLIST(&tls_opt.cert_head);
3042 	free_cred_SLIST(&tls_opt.fprint_head);
3043 	FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3044 #endif /* !DISABLE_TLS */
3045 
3046 	FREEPTR(funix);
3047 	for (p = LogPaths; p && *p; p++)
3048 		unlink(*p);
3049 	exit(0);
3050 }
3051 
3052 #ifndef DISABLE_SIGN
3053 /*
3054  * get one "sign_delim_sg2" item, convert and store in ordered queue
3055  */
3056 void
3057 store_sign_delim_sg2(char *tmp_buf)
3058 {
3059 	struct string_queue *sqentry, *sqe1, *sqe2;
3060 
3061 	if(!(sqentry = malloc(sizeof(*sqentry)))) {
3062 		logerror("Unable to allocate memory");
3063 		return;
3064 	}
3065 	/*LINTED constcond/null effect */
3066 	assert(sizeof(int64_t) == sizeof(uint_fast64_t));
3067 	if (dehumanize_number(tmp_buf, (int64_t*) &(sqentry->key)) == -1
3068 	    || sqentry->key > (LOG_NFACILITIES<<3)) {
3069 		DPRINTF(D_PARSE, "invalid sign_delim_sg2: %s\n", tmp_buf);
3070 		free(sqentry);
3071 		FREEPTR(tmp_buf);
3072 		return;
3073 	}
3074 	sqentry->data = tmp_buf;
3075 
3076 	if (STAILQ_EMPTY(&GlobalSign.sig2_delims)) {
3077 		STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
3078 		    sqentry, entries);
3079 		return;
3080 	}
3081 
3082 	/* keep delimiters sorted */
3083 	sqe1 = sqe2 = STAILQ_FIRST(&GlobalSign.sig2_delims);
3084 	if (sqe1->key > sqentry->key) {
3085 		STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
3086 		    sqentry, entries);
3087 		return;
3088 	}
3089 
3090 	while ((sqe1 = sqe2)
3091 	   && (sqe2 = STAILQ_NEXT(sqe1, entries))) {
3092 		if (sqe2->key > sqentry->key) {
3093 			break;
3094 		} else if (sqe2->key == sqentry->key) {
3095 			DPRINTF(D_PARSE, "duplicate sign_delim_sg2: %s\n",
3096 			    tmp_buf);
3097 			FREEPTR(sqentry);
3098 			FREEPTR(tmp_buf);
3099 			return;
3100 		}
3101 	}
3102 	STAILQ_INSERT_AFTER(&GlobalSign.sig2_delims, sqe1, sqentry, entries);
3103 }
3104 #endif /* !DISABLE_SIGN */
3105 
3106 /*
3107  * read syslog.conf
3108  */
3109 void
3110 read_config_file(FILE *cf, struct filed **f_ptr)
3111 {
3112 	size_t linenum = 0;
3113 	size_t i;
3114 	struct filed *f, **nextp;
3115 	char cline[LINE_MAX];
3116 	char prog[NAME_MAX + 1];
3117 	char host[MAXHOSTNAMELEN];
3118 	const char *p;
3119 	char *q;
3120 	bool found_keyword;
3121 #ifndef DISABLE_TLS
3122 	struct peer_cred *cred = NULL;
3123 	struct peer_cred_head *credhead = NULL;
3124 #endif /* !DISABLE_TLS */
3125 #ifndef DISABLE_SIGN
3126 	char *sign_sg_str = NULL;
3127 #endif /* !DISABLE_SIGN */
3128 #if (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN))
3129 	char *tmp_buf = NULL;
3130 #endif /* (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN)) */
3131 	/* central list of recognized configuration keywords
3132 	 * and an address for their values as strings */
3133 	const struct config_keywords {
3134 		const char *keyword;
3135 		char **variable;
3136 	} config_keywords[] = {
3137 #ifndef DISABLE_TLS
3138 		/* TLS settings */
3139 		{"tls_ca",		  &tls_opt.CAfile},
3140 		{"tls_cadir",		  &tls_opt.CAdir},
3141 		{"tls_cert",		  &tls_opt.certfile},
3142 		{"tls_key",		  &tls_opt.keyfile},
3143 		{"tls_verify",		  &tls_opt.x509verify},
3144 		{"tls_bindport",	  &tls_opt.bindport},
3145 		{"tls_bindhost",	  &tls_opt.bindhost},
3146 		{"tls_server",		  &tls_opt.server},
3147 		{"tls_gen_cert",	  &tls_opt.gen_cert},
3148 		/* special cases in parsing */
3149 		{"tls_allow_fingerprints",&tmp_buf},
3150 		{"tls_allow_clientcerts", &tmp_buf},
3151 		/* buffer settings */
3152 		{"tls_queue_length",	  &TypeInfo[F_TLS].queue_length_string},
3153 		{"tls_queue_size",	  &TypeInfo[F_TLS].queue_size_string},
3154 #endif /* !DISABLE_TLS */
3155 		{"file_queue_length",	  &TypeInfo[F_FILE].queue_length_string},
3156 		{"pipe_queue_length",	  &TypeInfo[F_PIPE].queue_length_string},
3157 		{"fifo_queue_length",	  &TypeInfo[F_FIFO].queue_length_string},
3158 		{"file_queue_size",	  &TypeInfo[F_FILE].queue_size_string},
3159 		{"pipe_queue_size",	  &TypeInfo[F_PIPE].queue_size_string},
3160 		{"fifo_queue_size",	  &TypeInfo[F_FIFO].queue_size_string},
3161 #ifndef DISABLE_SIGN
3162 		/* syslog-sign setting */
3163 		{"sign_sg",		  &sign_sg_str},
3164 		/* also special case in parsing */
3165 		{"sign_delim_sg2",	  &tmp_buf},
3166 #endif /* !DISABLE_SIGN */
3167 	};
3168 
3169 	DPRINTF(D_CALL, "read_config_file()\n");
3170 
3171 	/* free all previous config options */
3172 	for (i = 0; i < A_CNT(TypeInfo); i++) {
3173 		if (TypeInfo[i].queue_length_string
3174 		    && TypeInfo[i].queue_length_string
3175 		    != TypeInfo[i].default_length_string) {
3176 			FREEPTR(TypeInfo[i].queue_length_string);
3177 			TypeInfo[i].queue_length_string =
3178 				strdup(TypeInfo[i].default_length_string);
3179 		 }
3180 		if (TypeInfo[i].queue_size_string
3181 		    && TypeInfo[i].queue_size_string
3182 		    != TypeInfo[i].default_size_string) {
3183 			FREEPTR(TypeInfo[i].queue_size_string);
3184 			TypeInfo[i].queue_size_string =
3185 				strdup(TypeInfo[i].default_size_string);
3186 		 }
3187 	}
3188 	for (i = 0; i < A_CNT(config_keywords); i++)
3189 		FREEPTR(*config_keywords[i].variable);
3190 	/*
3191 	 * global settings
3192 	 */
3193 	while (fgets(cline, sizeof(cline), cf) != NULL) {
3194 		linenum++;
3195 		for (p = cline; isspace((unsigned char)*p); ++p)
3196 			continue;
3197 		if ((*p == '\0') || (*p == '#'))
3198 			continue;
3199 
3200 		for (i = 0; i < A_CNT(config_keywords); i++) {
3201 			if (copy_config_value(config_keywords[i].keyword,
3202 			    config_keywords[i].variable, &p, ConfFile,
3203 			    linenum)) {
3204 				DPRINTF((D_PARSE|D_MEM),
3205 				    "found option %s, saved @%p\n",
3206 				    config_keywords[i].keyword,
3207 				    *config_keywords[i].variable);
3208 #ifndef DISABLE_SIGN
3209 				if (!strcmp("sign_delim_sg2",
3210 				    config_keywords[i].keyword))
3211 					do {
3212 						store_sign_delim_sg2(tmp_buf);
3213 					} while (copy_config_value_word(
3214 					    &tmp_buf, &p));
3215 
3216 #endif /* !DISABLE_SIGN */
3217 
3218 #ifndef DISABLE_TLS
3219 				/* special cases with multiple parameters */
3220 				if (!strcmp("tls_allow_fingerprints",
3221 				    config_keywords[i].keyword))
3222 					credhead = &tls_opt.fprint_head;
3223 				else if (!strcmp("tls_allow_clientcerts",
3224 				    config_keywords[i].keyword))
3225 					credhead = &tls_opt.cert_head;
3226 
3227 				if (credhead) do {
3228 					if(!(cred = malloc(sizeof(*cred)))) {
3229 						logerror("Unable to "
3230 							"allocate memory");
3231 						break;
3232 					}
3233 					cred->data = tmp_buf;
3234 					tmp_buf = NULL;
3235 					SLIST_INSERT_HEAD(credhead,
3236 						cred, entries);
3237 				} while /* additional values? */
3238 					(copy_config_value_word(&tmp_buf, &p));
3239 				credhead = NULL;
3240 				break;
3241 #endif /* !DISABLE_TLS */
3242 			}
3243 		}
3244 	}
3245 	/* convert strings to integer values */
3246 	for (i = 0; i < A_CNT(TypeInfo); i++) {
3247 		if (!TypeInfo[i].queue_length_string
3248 		    || dehumanize_number(TypeInfo[i].queue_length_string,
3249 		    &TypeInfo[i].queue_length) == -1)
3250 			if (dehumanize_number(TypeInfo[i].default_length_string,
3251 			    &TypeInfo[i].queue_length) == -1)
3252 				abort();
3253 		if (!TypeInfo[i].queue_size_string
3254 		    || dehumanize_number(TypeInfo[i].queue_size_string,
3255 		    &TypeInfo[i].queue_size) == -1)
3256 			if (dehumanize_number(TypeInfo[i].default_size_string,
3257 			    &TypeInfo[i].queue_size) == -1)
3258 				abort();
3259 	}
3260 
3261 #ifndef DISABLE_SIGN
3262 	if (sign_sg_str) {
3263 		if (sign_sg_str[1] == '\0'
3264 		    && (sign_sg_str[0] == '0' || sign_sg_str[0] == '1'
3265 		    || sign_sg_str[0] == '2' || sign_sg_str[0] == '3'))
3266 			GlobalSign.sg = sign_sg_str[0] - '0';
3267 		else {
3268 			GlobalSign.sg = SIGN_SG;
3269 			DPRINTF(D_MISC, "Invalid sign_sg value `%s', "
3270 			    "use default value `%d'\n",
3271 			    sign_sg_str, GlobalSign.sg);
3272 		}
3273 	} else	/* disable syslog-sign */
3274 		GlobalSign.sg = -1;
3275 #endif /* !DISABLE_SIGN */
3276 
3277 	rewind(cf);
3278 	linenum = 0;
3279 	/*
3280 	 *  Foreach line in the conf table, open that file.
3281 	 */
3282 	f = NULL;
3283 	nextp = &f;
3284 
3285 	strcpy(prog, "*");
3286 	strcpy(host, "*");
3287 	while (fgets(cline, sizeof(cline), cf) != NULL) {
3288 		linenum++;
3289 		found_keyword = false;
3290 		/*
3291 		 * check for end-of-section, comments, strip off trailing
3292 		 * spaces and newline character.  #!prog is treated specially:
3293 		 * following lines apply only to that program.
3294 		 */
3295 		for (p = cline; isspace((unsigned char)*p); ++p)
3296 			continue;
3297 		if (*p == '\0')
3298 			continue;
3299 		if (*p == '#') {
3300 			p++;
3301 			if (*p != '!' && *p != '+' && *p != '-')
3302 				continue;
3303 		}
3304 
3305 		for (i = 0; i < A_CNT(config_keywords); i++) {
3306 			if (!strncasecmp(p, config_keywords[i].keyword,
3307 				strlen(config_keywords[i].keyword))) {
3308 				DPRINTF(D_PARSE,
3309 				    "skip cline %zu with keyword %s\n",
3310 				    linenum, config_keywords[i].keyword);
3311 				found_keyword = true;
3312 			}
3313 		}
3314 		if (found_keyword)
3315 			continue;
3316 
3317 		if (*p == '+' || *p == '-') {
3318 			host[0] = *p++;
3319 			while (isspace((unsigned char)*p))
3320 				p++;
3321 			if (*p == '\0' || *p == '*') {
3322 				strcpy(host, "*");
3323 				continue;
3324 			}
3325 			/* the +hostname expression will continue
3326 			 * to use the LocalHostName, not the FQDN */
3327 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
3328 				if (*p == '@') {
3329 					(void)strncpy(&host[i], LocalHostName,
3330 					    sizeof(host) - 1 - i);
3331 					host[sizeof(host) - 1] = '\0';
3332 					i = strlen(host) - 1;
3333 					p++;
3334 					continue;
3335 				}
3336 				if (!isalnum((unsigned char)*p) &&
3337 				    *p != '.' && *p != '-' && *p != ',')
3338 					break;
3339 				host[i] = *p++;
3340 			}
3341 			host[i] = '\0';
3342 			continue;
3343 		}
3344 		if (*p == '!') {
3345 			p++;
3346 			while (isspace((unsigned char)*p))
3347 				p++;
3348 			if (*p == '\0' || *p == '*') {
3349 				strcpy(prog, "*");
3350 				continue;
3351 			}
3352 			for (i = 0; i < NAME_MAX; i++) {
3353 				if (!isprint((unsigned char)p[i]))
3354 					break;
3355 				prog[i] = p[i];
3356 			}
3357 			prog[i] = '\0';
3358 			continue;
3359 		}
3360 		for (q = strchr(cline, '\0'); isspace((unsigned char)*--q);)
3361 			continue;
3362 		*++q = '\0';
3363 		if ((f = calloc(1, sizeof(*f))) == NULL) {
3364 			logerror("alloc failed");
3365 			die(0, 0, NULL);
3366 		}
3367 		if (!*f_ptr) *f_ptr = f; /* return first node */
3368 		*nextp = f;
3369 		nextp = &f->f_next;
3370 		cfline(linenum, cline, f, prog, host);
3371 	}
3372 }
3373 
3374 /*
3375  *  INIT -- Initialize syslogd from configuration table
3376  */
3377 void
3378 /*ARGSUSED*/
3379 init(int fd, short event, void *ev)
3380 {
3381 	FILE *cf;
3382 	int i;
3383 	struct filed *f, *newf, **nextp, *f2;
3384 	char *p;
3385 	sigset_t newmask, omask;
3386 #ifndef DISABLE_TLS
3387 	char *tls_status_msg = NULL;
3388 	struct peer_cred *cred = NULL;
3389 #endif /* !DISABLE_TLS */
3390 
3391 	/* prevent recursive signals */
3392 	BLOCK_SIGNALS(omask, newmask);
3393 
3394 	DPRINTF((D_EVENT|D_CALL), "init\n");
3395 
3396 	/*
3397 	 * be careful about dependencies and order of actions:
3398 	 * 1. flush buffer queues
3399 	 * 2. flush -sign SBs
3400 	 * 3. flush/delete buffer queue again, in case an SB got there
3401 	 * 4. close files/connections
3402 	 */
3403 
3404 	/*
3405 	 *  flush any pending output
3406 	 */
3407 	for (f = Files; f != NULL; f = f->f_next) {
3408 		/* flush any pending output */
3409 		if (f->f_prevcount)
3410 			fprintlog(f, NULL, NULL);
3411 		SEND_QUEUE(f);
3412 	}
3413 	/* some actions only on SIGHUP and not on first start */
3414 	if (Initialized) {
3415 #ifndef DISABLE_SIGN
3416 		sign_global_free();
3417 #endif /* !DISABLE_SIGN */
3418 #ifndef DISABLE_TLS
3419 		free_incoming_tls_sockets();
3420 #endif /* !DISABLE_TLS */
3421 		Initialized = 0;
3422 	}
3423 	/*
3424 	 *  Close all open log files.
3425 	 */
3426 	for (f = Files; f != NULL; f = f->f_next) {
3427 		switch (f->f_type) {
3428 		case F_FILE:
3429 		case F_TTY:
3430 		case F_CONSOLE:
3431 			(void)close(f->f_file);
3432 			break;
3433 		case F_PIPE:
3434 			if (f->f_un.f_pipe.f_pid > 0) {
3435 				(void)close(f->f_file);
3436 				deadq_enter(f->f_un.f_pipe.f_pid,
3437 				    f->f_un.f_pipe.f_pname);
3438 			}
3439 			f->f_un.f_pipe.f_pid = 0;
3440 			break;
3441 		case F_FORW:
3442 			if (f->f_un.f_forw.f_addr)
3443 				freeaddrinfo(f->f_un.f_forw.f_addr);
3444 			break;
3445 #ifndef DISABLE_TLS
3446 		case F_TLS:
3447 			free_tls_sslptr(f->f_un.f_tls.tls_conn);
3448 			break;
3449 #endif /* !DISABLE_TLS */
3450 		}
3451 	}
3452 
3453 	/*
3454 	 *  Close all open UDP sockets
3455 	 */
3456 	if (finet) {
3457 		for (i = 0; i < finet->fd; i++) {
3458 			if (close(finet[i+1].fd) < 0) {
3459 				logerror("close() failed");
3460 				die(0, 0, NULL);
3461 			}
3462 			DEL_EVENT(finet[i+1].ev);
3463 			FREEPTR(finet[i+1].ev);
3464 		}
3465 		FREEPTR(finet);
3466 	}
3467 
3468 	/* get FQDN and hostname/domain */
3469 	FREEPTR(oldLocalFQDN);
3470 	oldLocalFQDN = LocalFQDN;
3471 	LocalFQDN = getLocalFQDN();
3472 	if ((p = strchr(LocalFQDN, '.')) != NULL)
3473 		(void)strlcpy(LocalHostName, LocalFQDN, 1+p-LocalFQDN);
3474 	else
3475 		(void)strlcpy(LocalHostName, LocalFQDN, sizeof(LocalHostName));
3476 
3477 	/*
3478 	 *  Reset counter of forwarding actions
3479 	 */
3480 
3481 	NumForwards=0;
3482 
3483 	/* new destination list to replace Files */
3484 	newf = NULL;
3485 	nextp = &newf;
3486 
3487 	/* open the configuration file */
3488 	if ((cf = fopen(ConfFile, "r")) == NULL) {
3489 		DPRINTF(D_FILE, "Cannot open `%s'\n", ConfFile);
3490 		*nextp = (struct filed *)calloc(1, sizeof(*f));
3491 		cfline(0, "*.ERR\t/dev/console", *nextp, "*", "*");
3492 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
3493 		cfline(0, "*.PANIC\t*", (*nextp)->f_next, "*", "*");
3494 		Initialized = 1;
3495 		RESTORE_SIGNALS(omask);
3496 		return;
3497 	}
3498 
3499 #ifndef DISABLE_TLS
3500 	/* init with new TLS_CTX
3501 	 * as far as I see one cannot change the cert/key of an existing CTX
3502 	 */
3503 	FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3504 
3505 	free_cred_SLIST(&tls_opt.cert_head);
3506 	free_cred_SLIST(&tls_opt.fprint_head);
3507 #endif /* !DISABLE_TLS */
3508 
3509 	/* read and close configuration file */
3510 	read_config_file(cf, &newf);
3511 	newf = *nextp;
3512 	(void)fclose(cf);
3513 	DPRINTF(D_MISC, "read_config_file() returned newf=%p\n", newf);
3514 
3515 #define MOVE_QUEUE(dst, src) do {				\
3516 	struct buf_queue *buf;					\
3517 	STAILQ_CONCAT(&dst->f_qhead, &src->f_qhead);		\
3518 	STAILQ_FOREACH(buf, &dst->f_qhead, entries) {		\
3519 	      dst->f_qelements++;				\
3520 	      dst->f_qsize += buf_queue_obj_size(buf);		\
3521 	}							\
3522 	src->f_qsize = 0;					\
3523 	src->f_qelements = 0;					\
3524 } while (/*CONSTCOND*/0)
3525 
3526 	/*
3527 	 *  Free old log files.
3528 	 */
3529 	for (f = Files; f != NULL;) {
3530 		struct filed *ftmp;
3531 
3532 		/* check if a new logfile is equal, if so pass the queue */
3533 		for (f2 = newf; f2 != NULL; f2 = f2->f_next) {
3534 			if (f->f_type == f2->f_type
3535 			    && ((f->f_type == F_PIPE
3536 			    && !strcmp(f->f_un.f_pipe.f_pname,
3537 			    f2->f_un.f_pipe.f_pname))
3538 #ifndef DISABLE_TLS
3539 			    || (f->f_type == F_TLS
3540 			    && !strcmp(f->f_un.f_tls.tls_conn->hostname,
3541 			    f2->f_un.f_tls.tls_conn->hostname)
3542 			    && !strcmp(f->f_un.f_tls.tls_conn->port,
3543 			    f2->f_un.f_tls.tls_conn->port))
3544 #endif /* !DISABLE_TLS */
3545 			    || (f->f_type == F_FORW
3546 			    && !strcmp(f->f_un.f_forw.f_hname,
3547 			    f2->f_un.f_forw.f_hname)))) {
3548 				DPRINTF(D_BUFFER, "move queue from f@%p "
3549 				    "to f2@%p\n", f, f2);
3550 				MOVE_QUEUE(f2, f);
3551 			 }
3552 		}
3553 		message_queue_freeall(f);
3554 		DELREF(f->f_prevmsg);
3555 #ifndef DISABLE_TLS
3556 		if (f->f_type == F_TLS)
3557 			free_tls_conn(f->f_un.f_tls.tls_conn);
3558 #endif /* !DISABLE_TLS */
3559 		FREEPTR(f->f_program);
3560 		FREEPTR(f->f_host);
3561 		DEL_EVENT(f->f_sq_event);
3562 
3563 		ftmp = f->f_next;
3564 		free((char *)f);
3565 		f = ftmp;
3566 	}
3567 	Files = newf;
3568 	Initialized = 1;
3569 
3570 	if (Debug) {
3571 		for (f = Files; f; f = f->f_next) {
3572 			for (i = 0; i <= LOG_NFACILITIES; i++)
3573 				if (f->f_pmask[i] == INTERNAL_NOPRI)
3574 					printf("X ");
3575 				else
3576 					printf("%d ", f->f_pmask[i]);
3577 			printf("%s: ", TypeInfo[f->f_type].name);
3578 			switch (f->f_type) {
3579 			case F_FILE:
3580 			case F_TTY:
3581 			case F_CONSOLE:
3582 			case F_FIFO:
3583 				printf("%s", f->f_un.f_fname);
3584 				break;
3585 
3586 			case F_FORW:
3587 				printf("%s", f->f_un.f_forw.f_hname);
3588 				break;
3589 #ifndef DISABLE_TLS
3590 			case F_TLS:
3591 				printf("[%s]", f->f_un.f_tls.tls_conn->hostname);
3592 				break;
3593 #endif /* !DISABLE_TLS */
3594 			case F_PIPE:
3595 				printf("%s", f->f_un.f_pipe.f_pname);
3596 				break;
3597 
3598 			case F_USERS:
3599 				for (i = 0;
3600 				    i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
3601 					printf("%s, ", f->f_un.f_uname[i]);
3602 				break;
3603 			}
3604 			if (f->f_program != NULL)
3605 				printf(" (%s)", f->f_program);
3606 			printf("\n");
3607 		}
3608 	}
3609 
3610 	finet = socksetup(PF_UNSPEC, bindhostname);
3611 	if (finet) {
3612 		if (SecureMode) {
3613 			for (i = 0; i < finet->fd; i++) {
3614 				if (shutdown(finet[i+1].fd, SHUT_RD) < 0) {
3615 					logerror("shutdown() failed");
3616 					die(0, 0, NULL);
3617 				}
3618 			}
3619 		} else
3620 			DPRINTF(D_NET, "Listening on inet and/or inet6 socket\n");
3621 		DPRINTF(D_NET, "Sending on inet and/or inet6 socket\n");
3622 	}
3623 
3624 #ifndef DISABLE_TLS
3625 	/* TLS setup -- after all local destinations opened  */
3626 	DPRINTF(D_PARSE, "Parsed options: tls_ca: %s, tls_cadir: %s, "
3627 	    "tls_cert: %s, tls_key: %s, tls_verify: %s, "
3628 	    "bind: %s:%s, max. queue_lengths: %"
3629 	    PRId64 ", %" PRId64 ", %" PRId64 ", "
3630 	    "max. queue_sizes: %"
3631 	    PRId64 ", %" PRId64 ", %" PRId64 "\n",
3632 	    tls_opt.CAfile, tls_opt.CAdir,
3633 	    tls_opt.certfile, tls_opt.keyfile, tls_opt.x509verify,
3634 	    tls_opt.bindhost, tls_opt.bindport,
3635 	    TypeInfo[F_TLS].queue_length, TypeInfo[F_FILE].queue_length,
3636 	    TypeInfo[F_PIPE].queue_length,
3637 	    TypeInfo[F_TLS].queue_size, TypeInfo[F_FILE].queue_size,
3638 	    TypeInfo[F_PIPE].queue_size);
3639 	SLIST_FOREACH(cred, &tls_opt.cert_head, entries) {
3640 		DPRINTF(D_PARSE, "Accepting peer certificate "
3641 		    "from file: \"%s\"\n", cred->data);
3642 	}
3643 	SLIST_FOREACH(cred, &tls_opt.fprint_head, entries) {
3644 		DPRINTF(D_PARSE, "Accepting peer certificate with "
3645 		    "fingerprint: \"%s\"\n", cred->data);
3646 	}
3647 
3648 	/* Note: The order of initialization is important because syslog-sign
3649 	 * should use the TLS cert for signing. -- So we check first if TLS
3650 	 * will be used and initialize it before starting -sign.
3651 	 *
3652 	 * This means that if we are a client without TLS destinations TLS
3653 	 * will not be initialized and syslog-sign will generate a new key.
3654 	 * -- Even if the user has set a usable tls_cert.
3655 	 * Is this the expected behaviour? The alternative would be to always
3656 	 * initialize the TLS structures, even if they will not be needed
3657 	 * (or only needed to read the DSA key for -sign).
3658 	 */
3659 
3660 	/* Initialize TLS only if used */
3661 	if (tls_opt.server)
3662 		tls_status_msg = init_global_TLS_CTX();
3663 	else
3664 		for (f = Files; f; f = f->f_next) {
3665 			if (f->f_type != F_TLS)
3666 				continue;
3667 			tls_status_msg = init_global_TLS_CTX();
3668 			break;
3669 		}
3670 
3671 #endif /* !DISABLE_TLS */
3672 
3673 #ifndef DISABLE_SIGN
3674 	/* only initialize -sign if actually used */
3675 	if (GlobalSign.sg == 0 || GlobalSign.sg == 1 || GlobalSign.sg == 2)
3676 		(void)sign_global_init(Files);
3677 	else if (GlobalSign.sg == 3)
3678 		for (f = Files; f; f = f->f_next)
3679 			if (f->f_flags & FFLAG_SIGN) {
3680 				(void)sign_global_init(Files);
3681 				break;
3682 			}
3683 #endif /* !DISABLE_SIGN */
3684 
3685 #ifndef DISABLE_TLS
3686 	if (tls_status_msg) {
3687 		loginfo("%s", tls_status_msg);
3688 		free(tls_status_msg);
3689 	}
3690 	DPRINTF((D_NET|D_TLS), "Preparing sockets for TLS\n");
3691 	TLS_Listen_Set =
3692 		socksetup_tls(PF_UNSPEC, tls_opt.bindhost, tls_opt.bindport);
3693 
3694 	for (f = Files; f; f = f->f_next) {
3695 		if (f->f_type != F_TLS)
3696 			continue;
3697 		if (!tls_connect(f->f_un.f_tls.tls_conn)) {
3698 			logerror("Unable to connect to TLS server %s",
3699 			    f->f_un.f_tls.tls_conn->hostname);
3700 			/* Reconnect after x seconds  */
3701 			schedule_event(&f->f_un.f_tls.tls_conn->event,
3702 			    &((struct timeval){TLS_RECONNECT_SEC, 0}),
3703 			    tls_reconnect, f->f_un.f_tls.tls_conn);
3704 		}
3705 	}
3706 #endif /* !DISABLE_TLS */
3707 
3708 	loginfo("restart");
3709 	/*
3710 	 * Log a change in hostname, but only on a restart (we detect this
3711 	 * by checking to see if we're passed a kevent).
3712 	 */
3713 	if (oldLocalFQDN && strcmp(oldLocalFQDN, LocalFQDN) != 0)
3714 		loginfo("host name changed, \"%s\" to \"%s\"",
3715 		    oldLocalFQDN, LocalFQDN);
3716 
3717 	RESTORE_SIGNALS(omask);
3718 }
3719 
3720 /*
3721  * Crack a configuration file line
3722  */
3723 void
3724 cfline(size_t linenum, const char *line, struct filed *f, const char *prog,
3725     const char *host)
3726 {
3727 	struct addrinfo hints, *res;
3728 	int    error, i, pri, syncfile;
3729 	const char   *p, *q;
3730 	char *bp;
3731 	char   buf[MAXLINE];
3732 	struct stat sb;
3733 
3734 	DPRINTF((D_CALL|D_PARSE),
3735 		"cfline(%zu, \"%s\", f, \"%s\", \"%s\")\n",
3736 		linenum, line, prog, host);
3737 
3738 	errno = 0;	/* keep strerror() stuff out of logerror messages */
3739 
3740 	/* clear out file entry */
3741 	memset(f, 0, sizeof(*f));
3742 	for (i = 0; i <= LOG_NFACILITIES; i++)
3743 		f->f_pmask[i] = INTERNAL_NOPRI;
3744 	STAILQ_INIT(&f->f_qhead);
3745 
3746 	/*
3747 	 * There should not be any space before the log facility.
3748 	 * Check this is okay, complain and fix if it is not.
3749 	 */
3750 	q = line;
3751 	if (isblank((unsigned char)*line)) {
3752 		errno = 0;
3753 		logerror("Warning: `%s' space or tab before the log facility",
3754 		    line);
3755 		/* Fix: strip all spaces/tabs before the log facility */
3756 		while (*q++ && isblank((unsigned char)*q))
3757 			/* skip blanks */;
3758 		line = q;
3759 	}
3760 
3761 	/*
3762 	 * q is now at the first char of the log facility
3763 	 * There should be at least one tab after the log facility
3764 	 * Check this is okay, and complain and fix if it is not.
3765 	 */
3766 	q = line + strlen(line);
3767 	while (!isblank((unsigned char)*q) && (q != line))
3768 		q--;
3769 	if ((q == line) && strlen(line)) {
3770 		/* No tabs or space in a non empty line: complain */
3771 		errno = 0;
3772 		logerror(
3773 		    "Error: `%s' log facility or log target missing",
3774 		    line);
3775 		return;
3776 	}
3777 
3778 	/* save host name, if any */
3779 	if (*host == '*')
3780 		f->f_host = NULL;
3781 	else {
3782 		f->f_host = strdup(host);
3783 		trim_anydomain(&f->f_host[1]);	/* skip +/- at beginning */
3784 	}
3785 
3786 	/* save program name, if any */
3787 	if (*prog == '*')
3788 		f->f_program = NULL;
3789 	else
3790 		f->f_program = strdup(prog);
3791 
3792 	/* scan through the list of selectors */
3793 	for (p = line; *p && !isblank((unsigned char)*p);) {
3794 		int pri_done, pri_cmp, pri_invert;
3795 
3796 		/* find the end of this facility name list */
3797 		for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
3798 			continue;
3799 
3800 		/* get the priority comparison */
3801 		pri_cmp = 0;
3802 		pri_done = 0;
3803 		pri_invert = 0;
3804 		if (*q == '!') {
3805 			pri_invert = 1;
3806 			q++;
3807 		}
3808 		while (! pri_done) {
3809 			switch (*q) {
3810 			case '<':
3811 				pri_cmp = PRI_LT;
3812 				q++;
3813 				break;
3814 			case '=':
3815 				pri_cmp = PRI_EQ;
3816 				q++;
3817 				break;
3818 			case '>':
3819 				pri_cmp = PRI_GT;
3820 				q++;
3821 				break;
3822 			default:
3823 				pri_done = 1;
3824 				break;
3825 			}
3826 		}
3827 
3828 		/* collect priority name */
3829 		for (bp = buf; *q && !strchr("\t ,;", *q); )
3830 			*bp++ = *q++;
3831 		*bp = '\0';
3832 
3833 		/* skip cruft */
3834 		while (strchr(",;", *q))
3835 			q++;
3836 
3837 		/* decode priority name */
3838 		if (*buf == '*') {
3839 			pri = LOG_PRIMASK + 1;
3840 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3841 		} else {
3842 			pri = decode(buf, prioritynames);
3843 			if (pri < 0) {
3844 				errno = 0;
3845 				logerror("Unknown priority name `%s'", buf);
3846 				return;
3847 			}
3848 		}
3849 		if (pri_cmp == 0)
3850 			pri_cmp = UniquePriority ? PRI_EQ
3851 						 : PRI_EQ | PRI_GT;
3852 		if (pri_invert)
3853 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3854 
3855 		/* scan facilities */
3856 		while (*p && !strchr("\t .;", *p)) {
3857 			for (bp = buf; *p && !strchr("\t ,;.", *p); )
3858 				*bp++ = *p++;
3859 			*bp = '\0';
3860 			if (*buf == '*')
3861 				for (i = 0; i < LOG_NFACILITIES; i++) {
3862 					f->f_pmask[i] = pri;
3863 					f->f_pcmp[i] = pri_cmp;
3864 				}
3865 			else {
3866 				i = decode(buf, facilitynames);
3867 				if (i < 0) {
3868 					errno = 0;
3869 					logerror("Unknown facility name `%s'",
3870 					    buf);
3871 					return;
3872 				}
3873 				f->f_pmask[i >> 3] = pri;
3874 				f->f_pcmp[i >> 3] = pri_cmp;
3875 			}
3876 			while (*p == ',' || *p == ' ')
3877 				p++;
3878 		}
3879 
3880 		p = q;
3881 	}
3882 
3883 	/* skip to action part */
3884 	while (isblank((unsigned char)*p))
3885 		p++;
3886 
3887 	/*
3888 	 * should this be "#ifndef DISABLE_SIGN" or is it a general option?
3889 	 * '+' before file destination: write with PRI field for later
3890 	 * verification
3891 	 */
3892 	if (*p == '+') {
3893 		f->f_flags |= FFLAG_FULL;
3894 		p++;
3895 	}
3896 	if (*p == '-') {
3897 		syncfile = 0;
3898 		p++;
3899 	} else
3900 		syncfile = 1;
3901 
3902 	switch (*p) {
3903 	case '@':
3904 #ifndef DISABLE_SIGN
3905 		if (GlobalSign.sg == 3)
3906 			f->f_flags |= FFLAG_SIGN;
3907 #endif /* !DISABLE_SIGN */
3908 #ifndef DISABLE_TLS
3909 		if (*(p+1) == '[') {
3910 			/* TLS destination */
3911 			if (!parse_tls_destination(p, f, linenum)) {
3912 				logerror("Unable to parse action %s", p);
3913 				break;
3914 			}
3915 			f->f_type = F_TLS;
3916 			break;
3917 		}
3918 #endif /* !DISABLE_TLS */
3919 		(void)strlcpy(f->f_un.f_forw.f_hname, ++p,
3920 		    sizeof(f->f_un.f_forw.f_hname));
3921 		memset(&hints, 0, sizeof(hints));
3922 		hints.ai_family = AF_UNSPEC;
3923 		hints.ai_socktype = SOCK_DGRAM;
3924 		hints.ai_protocol = 0;
3925 		error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
3926 		    &res);
3927 		if (error) {
3928 			errno = 0;
3929 			logerror("%s", gai_strerror(error));
3930 			break;
3931 		}
3932 		f->f_un.f_forw.f_addr = res;
3933 		f->f_type = F_FORW;
3934 		NumForwards++;
3935 		break;
3936 
3937 	case '/':
3938 #ifndef DISABLE_SIGN
3939 		if (GlobalSign.sg == 3)
3940 			f->f_flags |= FFLAG_SIGN;
3941 #endif /* !DISABLE_SIGN */
3942 		(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
3943 		if ((f->f_file = open(p, O_WRONLY|O_APPEND|O_NONBLOCK, 0)) < 0)
3944 		{
3945 			f->f_type = F_UNUSED;
3946 			logerror("%s", p);
3947 			break;
3948 		}
3949 		if (!fstat(f->f_file, &sb) && S_ISFIFO(sb.st_mode)) {
3950 			f->f_file = -1;
3951 			f->f_type = F_FIFO;
3952 			break;
3953 		}
3954 
3955 		if (isatty(f->f_file)) {
3956 			f->f_type = F_TTY;
3957 			if (strcmp(p, ctty) == 0)
3958 				f->f_type = F_CONSOLE;
3959 		} else
3960 			f->f_type = F_FILE;
3961 
3962 		if (syncfile)
3963 			f->f_flags |= FFLAG_SYNC;
3964 		break;
3965 
3966 	case '|':
3967 #ifndef DISABLE_SIGN
3968 		if (GlobalSign.sg == 3)
3969 			f->f_flags |= FFLAG_SIGN;
3970 #endif
3971 		f->f_un.f_pipe.f_pid = 0;
3972 		(void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
3973 		    sizeof(f->f_un.f_pipe.f_pname));
3974 		f->f_type = F_PIPE;
3975 		break;
3976 
3977 	case '*':
3978 		f->f_type = F_WALL;
3979 		break;
3980 
3981 	default:
3982 		for (i = 0; i < MAXUNAMES && *p; i++) {
3983 			for (q = p; *q && *q != ','; )
3984 				q++;
3985 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
3986 			if ((q - p) > UT_NAMESIZE)
3987 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
3988 			else
3989 				f->f_un.f_uname[i][q - p] = '\0';
3990 			while (*q == ',' || *q == ' ')
3991 				q++;
3992 			p = q;
3993 		}
3994 		f->f_type = F_USERS;
3995 		break;
3996 	}
3997 }
3998 
3999 
4000 /*
4001  *  Decode a symbolic name to a numeric value
4002  */
4003 int
4004 decode(const char *name, CODE *codetab)
4005 {
4006 	CODE *c;
4007 	char *p, buf[40];
4008 
4009 	if (isdigit((unsigned char)*name))
4010 		return atoi(name);
4011 
4012 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
4013 		if (isupper((unsigned char)*name))
4014 			*p = tolower((unsigned char)*name);
4015 		else
4016 			*p = *name;
4017 	}
4018 	*p = '\0';
4019 	for (c = codetab; c->c_name; c++)
4020 		if (!strcmp(buf, c->c_name))
4021 			return c->c_val;
4022 
4023 	return -1;
4024 }
4025 
4026 /*
4027  * Retrieve the size of the kernel message buffer, via sysctl.
4028  */
4029 int
4030 getmsgbufsize(void)
4031 {
4032 #ifdef __NetBSD_Version__
4033 	int msgbufsize, mib[2];
4034 	size_t size;
4035 
4036 	mib[0] = CTL_KERN;
4037 	mib[1] = KERN_MSGBUFSIZE;
4038 	size = sizeof msgbufsize;
4039 	if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
4040 		DPRINTF(D_MISC, "Couldn't get kern.msgbufsize\n");
4041 		return 0;
4042 	}
4043 	return msgbufsize;
4044 #else
4045 	return MAXLINE;
4046 #endif /* __NetBSD_Version__ */
4047 }
4048 
4049 /*
4050  * Retrieve the hostname, via sysctl.
4051  */
4052 char *
4053 getLocalFQDN(void)
4054 {
4055 	int mib[2];
4056 	char *hostname;
4057 	size_t len;
4058 
4059 	mib[0] = CTL_KERN;
4060 	mib[1] = KERN_HOSTNAME;
4061 	sysctl(mib, 2, NULL, &len, NULL, 0);
4062 
4063 	if (!(hostname = malloc(len))) {
4064 		logerror("Unable to allocate memory");
4065 		die(0,0,NULL);
4066 	} else if (sysctl(mib, 2, hostname, &len, NULL, 0) == -1) {
4067 		DPRINTF(D_MISC, "Couldn't get kern.hostname\n");
4068 		(void)gethostname(hostname, sizeof(len));
4069 	}
4070 	return hostname;
4071 }
4072 
4073 struct socketEvent *
4074 socksetup(int af, const char *hostname)
4075 {
4076 	struct addrinfo hints, *res, *r;
4077 	int error, maxs;
4078 	int on = 1;
4079 	struct socketEvent *s, *socks;
4080 
4081 	if(SecureMode && !NumForwards)
4082 		return NULL;
4083 
4084 	memset(&hints, 0, sizeof(hints));
4085 	hints.ai_flags = AI_PASSIVE;
4086 	hints.ai_family = af;
4087 	hints.ai_socktype = SOCK_DGRAM;
4088 	error = getaddrinfo(hostname, "syslog", &hints, &res);
4089 	if (error) {
4090 		errno = 0;
4091 		logerror("%s", gai_strerror(error));
4092 		die(0, 0, NULL);
4093 	}
4094 
4095 	/* Count max number of sockets we may open */
4096 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
4097 		continue;
4098 	socks = calloc(maxs+1, sizeof(*socks));
4099 	if (!socks) {
4100 		logerror("Couldn't allocate memory for sockets");
4101 		die(0, 0, NULL);
4102 	}
4103 
4104 	socks->fd = 0;	 /* num of sockets counter at start of array */
4105 	s = socks + 1;
4106 	for (r = res; r; r = r->ai_next) {
4107 		s->fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
4108 		if (s->fd < 0) {
4109 			logerror("socket() failed");
4110 			continue;
4111 		}
4112 		s->af = r->ai_family;
4113 		if (r->ai_family == AF_INET6 && setsockopt(s->fd, IPPROTO_IPV6,
4114 		    IPV6_V6ONLY, &on, sizeof(on)) < 0) {
4115 			logerror("setsockopt(IPV6_V6ONLY) failed");
4116 			close(s->fd);
4117 			continue;
4118 		}
4119 
4120 		if (!SecureMode) {
4121 			if (bind(s->fd, r->ai_addr, r->ai_addrlen) < 0) {
4122 				logerror("bind() failed");
4123 				close(s->fd);
4124 				continue;
4125 			}
4126 			s->ev = allocev();
4127 			event_set(s->ev, s->fd, EV_READ | EV_PERSIST,
4128 				dispatch_read_finet, s->ev);
4129 			if (event_add(s->ev, NULL) == -1) {
4130 				DPRINTF((D_EVENT|D_NET),
4131 				    "Failure in event_add()\n");
4132 			} else {
4133 				DPRINTF((D_EVENT|D_NET),
4134 				    "Listen on UDP port "
4135 				    "(event@%p)\n", s->ev);
4136 			}
4137 		}
4138 
4139 		socks->fd++;  /* num counter */
4140 		s++;
4141 	}
4142 
4143 	if (res)
4144 		freeaddrinfo(res);
4145 	if (socks->fd == 0) {
4146 		free (socks);
4147 		if(Debug)
4148 			return NULL;
4149 		else
4150 			die(0, 0, NULL);
4151 	}
4152 	return socks;
4153 }
4154 
4155 /*
4156  * Fairly similar to popen(3), but returns an open descriptor, as opposed
4157  * to a FILE *.
4158  */
4159 int
4160 p_open(char *prog, pid_t *rpid)
4161 {
4162 	static char sh[] = "sh", mc[] = "-c";
4163 	int pfd[2], nulldesc, i;
4164 	pid_t pid;
4165 	char *argv[4];	/* sh -c cmd NULL */
4166 
4167 	if (pipe(pfd) == -1)
4168 		return -1;
4169 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
4170 		/* We are royally screwed anyway. */
4171 		return -1;
4172 	}
4173 
4174 	switch ((pid = fork())) {
4175 	case -1:
4176 		(void) close(nulldesc);
4177 		return -1;
4178 
4179 	case 0:
4180 		argv[0] = sh;
4181 		argv[1] = mc;
4182 		argv[2] = prog;
4183 		argv[3] = NULL;
4184 
4185 		(void) setsid();	/* avoid catching SIGHUPs. */
4186 
4187 		/*
4188 		 * Reset ignored signals to their default behavior.
4189 		 */
4190 		(void)signal(SIGTERM, SIG_DFL);
4191 		(void)signal(SIGINT, SIG_DFL);
4192 		(void)signal(SIGQUIT, SIG_DFL);
4193 		(void)signal(SIGPIPE, SIG_DFL);
4194 		(void)signal(SIGHUP, SIG_DFL);
4195 
4196 		dup2(pfd[0], STDIN_FILENO);
4197 		dup2(nulldesc, STDOUT_FILENO);
4198 		dup2(nulldesc, STDERR_FILENO);
4199 		for (i = getdtablesize(); i > 2; i--)
4200 			(void) close(i);
4201 
4202 		(void) execvp(_PATH_BSHELL, argv);
4203 		_exit(255);
4204 	}
4205 
4206 	(void) close(nulldesc);
4207 	(void) close(pfd[0]);
4208 
4209 	/*
4210 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
4211 	 * supposed to get an EWOULDBLOCK on writev(2), which is
4212 	 * caught by the logic above anyway, which will in turn
4213 	 * close the pipe, and fork a new logging subprocess if
4214 	 * necessary.  The stale subprocess will be killed some
4215 	 * time later unless it terminated itself due to closing
4216 	 * its input pipe.
4217 	 */
4218 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
4219 		/* This is bad. */
4220 		logerror("Warning: cannot change pipe to pid %d to "
4221 		    "non-blocking.", (int) pid);
4222 	}
4223 	*rpid = pid;
4224 	return pfd[1];
4225 }
4226 
4227 void
4228 deadq_enter(pid_t pid, const char *name)
4229 {
4230 	dq_t p;
4231 	int status;
4232 
4233 	/*
4234 	 * Be paranoid: if we can't signal the process, don't enter it
4235 	 * into the dead queue (perhaps it's already dead).  If possible,
4236 	 * we try to fetch and log the child's status.
4237 	 */
4238 	if (kill(pid, 0) != 0) {
4239 		if (waitpid(pid, &status, WNOHANG) > 0)
4240 			log_deadchild(pid, status, name);
4241 		return;
4242 	}
4243 
4244 	p = malloc(sizeof(*p));
4245 	if (p == NULL) {
4246 		logerror("panic: out of memory!");
4247 		exit(1);
4248 	}
4249 
4250 	p->dq_pid = pid;
4251 	p->dq_timeout = DQ_TIMO_INIT;
4252 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
4253 }
4254 
4255 int
4256 deadq_remove(pid_t pid)
4257 {
4258 	dq_t q;
4259 
4260 	for (q = TAILQ_FIRST(&deadq_head); q != NULL;
4261 	     q = TAILQ_NEXT(q, dq_entries)) {
4262 		if (q->dq_pid == pid) {
4263 			TAILQ_REMOVE(&deadq_head, q, dq_entries);
4264 			free(q);
4265 			return 1;
4266 		}
4267 	}
4268 	return 0;
4269 }
4270 
4271 void
4272 log_deadchild(pid_t pid, int status, const char *name)
4273 {
4274 	int code;
4275 	char buf[256];
4276 	const char *reason;
4277 
4278 	/* Keep strerror() struff out of logerror messages. */
4279 	errno = 0;
4280 	if (WIFSIGNALED(status)) {
4281 		reason = "due to signal";
4282 		code = WTERMSIG(status);
4283 	} else {
4284 		reason = "with status";
4285 		code = WEXITSTATUS(status);
4286 		if (code == 0)
4287 			return;
4288 	}
4289 	(void) snprintf(buf, sizeof(buf),
4290 	    "Logging subprocess %d (%s) exited %s %d.",
4291 	    pid, name, reason, code);
4292 	logerror("%s", buf);
4293 }
4294 
4295 struct event *
4296 allocev(void)
4297 {
4298 	struct event *ev;
4299 
4300 	if (!(ev = calloc(1, sizeof(*ev))))
4301 		logerror("Unable to allocate memory");
4302 	return ev;
4303 }
4304 
4305 /* *ev is allocated if necessary */
4306 void
4307 schedule_event(struct event **ev, struct timeval *tv,
4308 	void (*cb)(int, short, void *), void *arg)
4309 {
4310 	if (!*ev && !(*ev = allocev())) {
4311 		return;
4312 	}
4313 	event_set(*ev, 0, 0, cb, arg);
4314 	DPRINTF(D_EVENT, "event_add(%s@%p)\n", "schedule_ev", *ev); \
4315 	if (event_add(*ev, tv) == -1) {
4316 		DPRINTF(D_EVENT, "Failure in event_add()\n");
4317 	}
4318 }
4319 
4320 #ifndef DISABLE_TLS
4321 /* abbreviation for freeing credential lists */
4322 void
4323 free_cred_SLIST(struct peer_cred_head *head)
4324 {
4325 	struct peer_cred *cred;
4326 
4327 	while (!SLIST_EMPTY(head)) {
4328 		cred = SLIST_FIRST(head);
4329 		SLIST_REMOVE_HEAD(head, entries);
4330 		FREEPTR(cred->data);
4331 		free(cred);
4332 	}
4333 }
4334 #endif /* !DISABLE_TLS */
4335 
4336 /*
4337  * send message queue after reconnect
4338  */
4339 /*ARGSUSED*/
4340 void
4341 send_queue(int fd, short event, void *arg)
4342 {
4343 	struct filed *f = (struct filed *) arg;
4344 	struct buf_queue *qentry;
4345 #define SQ_CHUNK_SIZE 250
4346 	size_t cnt = 0;
4347 
4348 #ifndef DISABLE_TLS
4349 	if (f->f_type == F_TLS) {
4350 		/* use a flag to prevent recursive calls to send_queue() */
4351 		if (f->f_un.f_tls.tls_conn->send_queue)
4352 			return;
4353 		else
4354 			f->f_un.f_tls.tls_conn->send_queue = true;
4355 	}
4356 	DPRINTF((D_DATA|D_CALL), "send_queue(f@%p with %zu msgs, "
4357 		"cnt@%p = %zu)\n", f, f->f_qelements, &cnt, cnt);
4358 #endif /* !DISABLE_TLS */
4359 
4360 	while ((qentry = STAILQ_FIRST(&f->f_qhead))) {
4361 #ifndef DISABLE_TLS
4362 		/* send_queue() might be called with an unconnected destination
4363 		 * from init() or die() or one message might take longer,
4364 		 * leaving the connection in state ST_WAITING and thus not
4365 		 * ready for the next message.
4366 		 * this check is a shortcut to skip these unnecessary calls */
4367 		if (f->f_type == F_TLS
4368 		    && f->f_un.f_tls.tls_conn->state != ST_TLS_EST) {
4369 			DPRINTF(D_TLS, "abort send_queue(cnt@%p = %zu) "
4370 			    "on TLS connection in state %d\n",
4371 			    &cnt, cnt, f->f_un.f_tls.tls_conn->state);
4372 			return;
4373 		 }
4374 #endif /* !DISABLE_TLS */
4375 		fprintlog(f, qentry->msg, qentry);
4376 
4377 		/* Sending a long queue can take some time during which
4378 		 * SIGHUP and SIGALRM are blocked and no events are handled.
4379 		 * To avoid that we only send SQ_CHUNK_SIZE messages at once
4380 		 * and then reschedule ourselves to continue. Thus the control
4381 		 * will return first from all signal-protected functions so a
4382 		 * possible SIGHUP/SIGALRM is handled and then back to the
4383 		 * main loop which can handle possible input.
4384 		 */
4385 		if (++cnt >= SQ_CHUNK_SIZE) {
4386 			if (!f->f_sq_event) { /* alloc on demand */
4387 				f->f_sq_event = allocev();
4388 				event_set(f->f_sq_event, 0, 0, send_queue, f);
4389 			}
4390 			if (event_add(f->f_sq_event, &((struct timeval){0, 1})) == -1) {
4391 				DPRINTF(D_EVENT, "Failure in event_add()\n");
4392 			}
4393 			break;
4394 		}
4395 	}
4396 #ifndef DISABLE_TLS
4397 	if (f->f_type == F_TLS)
4398 		f->f_un.f_tls.tls_conn->send_queue = false;
4399 #endif
4400 
4401 }
4402 
4403 /*
4404  * finds the next queue element to delete
4405  *
4406  * has stateful behaviour, before using it call once with reset = true
4407  * after that every call will return one next queue elemen to delete,
4408  * depending on strategy either the oldest or the one with the lowest priority
4409  */
4410 static struct buf_queue *
4411 find_qentry_to_delete(const struct buf_queue_head *head, int strategy,
4412     bool reset)
4413 {
4414 	static int pri;
4415 	static struct buf_queue *qentry_static;
4416 
4417 	struct buf_queue *qentry_tmp;
4418 
4419 	if (reset || STAILQ_EMPTY(head)) {
4420 		pri = LOG_DEBUG;
4421 		qentry_static = STAILQ_FIRST(head);
4422 		return NULL;
4423 	}
4424 
4425 	/* find elements to delete */
4426 	if (strategy == PURGE_BY_PRIORITY) {
4427 		qentry_tmp = qentry_static;
4428 		if (!qentry_tmp) return NULL;
4429 		while ((qentry_tmp = STAILQ_NEXT(qentry_tmp, entries)) != NULL)
4430 		{
4431 			if (LOG_PRI(qentry_tmp->msg->pri) == pri) {
4432 				/* save the successor, because qentry_tmp
4433 				 * is probably deleted by the caller */
4434 				qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4435 				return qentry_tmp;
4436 			}
4437 		}
4438 		/* nothing found in while loop --> next pri */
4439 		if (--pri)
4440 			return find_qentry_to_delete(head, strategy, false);
4441 		else
4442 			return NULL;
4443 	} else /* strategy == PURGE_OLDEST or other value */ {
4444 		qentry_tmp = qentry_static;
4445 		qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4446 		return qentry_tmp;  /* is NULL on empty queue */
4447 	}
4448 }
4449 
4450 /* note on TAILQ: newest message added at TAIL,
4451  *		  oldest to be removed is FIRST
4452  */
4453 /*
4454  * checks length of a destination's message queue
4455  * if del_entries == 0 then assert queue length is
4456  *   less or equal to configured number of queue elements
4457  * otherwise del_entries tells how many entries to delete
4458  *
4459  * returns the number of removed queue elements
4460  * (which not necessarily means free'd messages)
4461  *
4462  * strategy PURGE_OLDEST to delete oldest entry, e.g. after it was resent
4463  * strategy PURGE_BY_PRIORITY to delete messages with lowest priority first,
4464  *	this is much slower but might be desirable when unsent messages have
4465  *	to be deleted, e.g. in call from domark()
4466  */
4467 size_t
4468 message_queue_purge(struct filed *f, size_t del_entries, int strategy)
4469 {
4470 	size_t removed = 0;
4471 	struct buf_queue *qentry = NULL;
4472 
4473 	DPRINTF((D_CALL|D_BUFFER), "purge_message_queue(%p, %zu, %d) with "
4474 	    "f_qelements=%zu and f_qsize=%zu\n",
4475 	    f, del_entries, strategy,
4476 	    f->f_qelements, f->f_qsize);
4477 
4478 	/* reset state */
4479 	(void)find_qentry_to_delete(&f->f_qhead, strategy, true);
4480 
4481 	while (removed < del_entries
4482 	    || (TypeInfo[f->f_type].queue_length != -1
4483 	    && (size_t)TypeInfo[f->f_type].queue_length <= f->f_qelements)
4484 	    || (TypeInfo[f->f_type].queue_size != -1
4485 	    && (size_t)TypeInfo[f->f_type].queue_size <= f->f_qsize)) {
4486 		qentry = find_qentry_to_delete(&f->f_qhead, strategy, 0);
4487 		if (message_queue_remove(f, qentry))
4488 			removed++;
4489 		else
4490 			break;
4491 	}
4492 	return removed;
4493 }
4494 
4495 /* run message_queue_purge() for all destinations to free memory */
4496 size_t
4497 message_allqueues_purge(void)
4498 {
4499 	size_t sum = 0;
4500 	struct filed *f;
4501 
4502 	for (f = Files; f; f = f->f_next)
4503 		sum += message_queue_purge(f,
4504 		    f->f_qelements/10, PURGE_BY_PRIORITY);
4505 
4506 	DPRINTF(D_BUFFER,
4507 	    "message_allqueues_purge(): removed %zu buffer entries\n", sum);
4508 	return sum;
4509 }
4510 
4511 /* run message_queue_purge() for all destinations to check limits */
4512 size_t
4513 message_allqueues_check(void)
4514 {
4515 	size_t sum = 0;
4516 	struct filed *f;
4517 
4518 	for (f = Files; f; f = f->f_next)
4519 		sum += message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4520 	DPRINTF(D_BUFFER,
4521 	    "message_allqueues_check(): removed %zu buffer entries\n", sum);
4522 	return sum;
4523 }
4524 
4525 struct buf_msg *
4526 buf_msg_new(const size_t len)
4527 {
4528 	struct buf_msg *newbuf;
4529 
4530 	CALLOC(newbuf, sizeof(*newbuf));
4531 
4532 	if (len) { /* len = 0 is valid */
4533 		MALLOC(newbuf->msg, len);
4534 		newbuf->msgorig = newbuf->msg;
4535 		newbuf->msgsize = len;
4536 	}
4537 	return NEWREF(newbuf);
4538 }
4539 
4540 void
4541 buf_msg_free(struct buf_msg *buf)
4542 {
4543 	if (!buf)
4544 		return;
4545 
4546 	buf->refcount--;
4547 	if (buf->refcount == 0) {
4548 		FREEPTR(buf->timestamp);
4549 		/* small optimizations: the host/recvhost may point to the
4550 		 * global HostName/FQDN. of course this must not be free()d
4551 		 * same goes for appname and include_pid
4552 		 */
4553 		if (buf->recvhost != buf->host
4554 		    && buf->recvhost != LocalHostName
4555 		    && buf->recvhost != LocalFQDN
4556 		    && buf->recvhost != oldLocalFQDN)
4557 			FREEPTR(buf->recvhost);
4558 		if (buf->host != LocalHostName
4559 		    && buf->host != LocalFQDN
4560 		    && buf->host != oldLocalFQDN)
4561 			FREEPTR(buf->host);
4562 		if (buf->prog != appname)
4563 			FREEPTR(buf->prog);
4564 		if (buf->pid != include_pid)
4565 			FREEPTR(buf->pid);
4566 		FREEPTR(buf->msgid);
4567 		FREEPTR(buf->sd);
4568 		FREEPTR(buf->msgorig);	/* instead of msg */
4569 		FREEPTR(buf);
4570 	}
4571 }
4572 
4573 size_t
4574 buf_queue_obj_size(struct buf_queue *qentry)
4575 {
4576 	size_t sum = 0;
4577 
4578 	if (!qentry)
4579 		return 0;
4580 	sum += sizeof(*qentry)
4581 	    + sizeof(*qentry->msg)
4582 	    + qentry->msg->msgsize
4583 	    + SAFEstrlen(qentry->msg->timestamp)+1
4584 	    + SAFEstrlen(qentry->msg->msgid)+1;
4585 	if (qentry->msg->prog
4586 	    && qentry->msg->prog != include_pid)
4587 		sum += strlen(qentry->msg->prog)+1;
4588 	if (qentry->msg->pid
4589 	    && qentry->msg->pid != appname)
4590 		sum += strlen(qentry->msg->pid)+1;
4591 	if (qentry->msg->recvhost
4592 	    && qentry->msg->recvhost != LocalHostName
4593 	    && qentry->msg->recvhost != LocalFQDN
4594 	    && qentry->msg->recvhost != oldLocalFQDN)
4595 		sum += strlen(qentry->msg->recvhost)+1;
4596 	if (qentry->msg->host
4597 	    && qentry->msg->host != LocalHostName
4598 	    && qentry->msg->host != LocalFQDN
4599 	    && qentry->msg->host != oldLocalFQDN)
4600 		sum += strlen(qentry->msg->host)+1;
4601 
4602 	return sum;
4603 }
4604 
4605 bool
4606 message_queue_remove(struct filed *f, struct buf_queue *qentry)
4607 {
4608 	if (!f || !qentry || !qentry->msg)
4609 		return false;
4610 
4611 	assert(!STAILQ_EMPTY(&f->f_qhead));
4612 	STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4613 	f->f_qelements--;
4614 	f->f_qsize -= buf_queue_obj_size(qentry);
4615 
4616 	DPRINTF(D_BUFFER, "msg @%p removed from queue @%p, new qlen = %zu\n",
4617 	    qentry->msg, f, f->f_qelements);
4618 	DELREF(qentry->msg);
4619 	FREEPTR(qentry);
4620 	return true;
4621 }
4622 
4623 /*
4624  * returns *qentry on success and NULL on error
4625  */
4626 struct buf_queue *
4627 message_queue_add(struct filed *f, struct buf_msg *buffer)
4628 {
4629 	struct buf_queue *qentry;
4630 
4631 	/* check on every call or only every n-th time? */
4632 	message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4633 
4634 	while (!(qentry = malloc(sizeof(*qentry)))
4635 	    && message_queue_purge(f, 1, PURGE_OLDEST))
4636 		continue;
4637 	if (!qentry) {
4638 		logerror("Unable to allocate memory");
4639 		DPRINTF(D_BUFFER, "queue empty, no memory, msg dropped\n");
4640 		return NULL;
4641 	} else {
4642 		qentry->msg = buffer;
4643 		f->f_qelements++;
4644 		f->f_qsize += buf_queue_obj_size(qentry);
4645 		STAILQ_INSERT_TAIL(&f->f_qhead, qentry, entries);
4646 
4647 		DPRINTF(D_BUFFER, "msg @%p queued @%p, qlen = %zu\n",
4648 		    buffer, f, f->f_qelements);
4649 		return qentry;
4650 	}
4651 }
4652 
4653 void
4654 message_queue_freeall(struct filed *f)
4655 {
4656 	struct buf_queue *qentry;
4657 
4658 	if (!f) return;
4659 	DPRINTF(D_MEM, "message_queue_freeall(f@%p) with f_qhead@%p\n", f,
4660 	    &f->f_qhead);
4661 
4662 	while (!STAILQ_EMPTY(&f->f_qhead)) {
4663 		qentry = STAILQ_FIRST(&f->f_qhead);
4664 		STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4665 		DELREF(qentry->msg);
4666 		FREEPTR(qentry);
4667 	}
4668 
4669 	f->f_qelements = 0;
4670 	f->f_qsize = 0;
4671 }
4672 
4673 #ifndef DISABLE_TLS
4674 /* utility function for tls_reconnect() */
4675 struct filed *
4676 get_f_by_conninfo(struct tls_conn_settings *conn_info)
4677 {
4678 	struct filed *f;
4679 
4680 	for (f = Files; f; f = f->f_next) {
4681 		if ((f->f_type == F_TLS) && f->f_un.f_tls.tls_conn == conn_info)
4682 			return f;
4683 	}
4684 	DPRINTF(D_TLS, "get_f_by_conninfo() called on invalid conn_info\n");
4685 	return NULL;
4686 }
4687 
4688 /*
4689  * Called on signal.
4690  * Lets the admin reconnect without waiting for the reconnect timer expires.
4691  */
4692 /*ARGSUSED*/
4693 void
4694 dispatch_force_tls_reconnect(int fd, short event, void *ev)
4695 {
4696 	struct filed *f;
4697 	DPRINTF((D_TLS|D_CALL|D_EVENT), "dispatch_force_tls_reconnect()\n");
4698 	for (f = Files; f; f = f->f_next) {
4699 		if (f->f_type == F_TLS &&
4700 		    f->f_un.f_tls.tls_conn->state == ST_NONE)
4701 			tls_reconnect(fd, event, f->f_un.f_tls.tls_conn);
4702 	}
4703 }
4704 #endif /* !DISABLE_TLS */
4705 
4706 /*
4707  * return a timestamp in a static buffer,
4708  * either format the timestamp given by parameter in_now
4709  * or use the current time if in_now is NULL.
4710  */
4711 char *
4712 make_timestamp(time_t *in_now, bool iso, size_t tlen)
4713 {
4714 	int frac_digits = 6;
4715 	struct timeval tv;
4716 	time_t mytime;
4717 	struct tm ltime;
4718 	int len = 0;
4719 	int tzlen = 0;
4720 	/* uses global var: time_t now; */
4721 
4722 	if (in_now) {
4723 		mytime = *in_now;
4724 	} else {
4725 		gettimeofday(&tv, NULL);
4726 		mytime = now = tv.tv_sec;
4727 	}
4728 
4729 	if (!iso) {
4730 		strlcpy(timestamp, ctime(&mytime) + 4, sizeof(timestamp));
4731 		timestamp[BSD_TIMESTAMPLEN] = '\0';
4732 	} else {
4733 		localtime_r(&mytime, &ltime);
4734 		len += strftime(timestamp, sizeof(timestamp), "%FT%T", &ltime);
4735 		snprintf(&timestamp[len], frac_digits + 2, ".%.*jd",
4736 		    frac_digits, (intmax_t)tv.tv_usec);
4737 		len += frac_digits + 1;
4738 		tzlen = strftime(&timestamp[len], sizeof(timestamp) - len, "%z",
4739 		    &ltime);
4740 		len += tzlen;
4741 
4742 		if (tzlen == 5) {
4743 			/* strftime gives "+0200", but we need "+02:00" */
4744 			timestamp[len + 2] = '\0';
4745 			timestamp[len + 1] = timestamp[len];
4746 			timestamp[len] = timestamp[len - 1];
4747 			timestamp[len - 1] = timestamp[len - 2];
4748 			timestamp[len - 2] = ':';
4749 		}
4750 	}
4751 
4752 	switch (tlen) {
4753 	case (size_t)-1:
4754 		return timestamp;
4755 	case 0:
4756 		return strdup(timestamp);
4757 	default:
4758 		return strndup(timestamp, tlen);
4759 	}
4760 }
4761 
4762 /* auxillary code to allocate memory and copy a string */
4763 bool
4764 copy_string(char **mem, const char *p, const char *q)
4765 {
4766 	const size_t len = 1 + q - p;
4767 	if (!(*mem = malloc(len))) {
4768 		logerror("Unable to allocate memory for config");
4769 		return false;
4770 	}
4771 	strlcpy(*mem, p, len);
4772 	return true;
4773 }
4774 
4775 /* keyword has to end with ",  everything until next " is copied */
4776 bool
4777 copy_config_value_quoted(const char *keyword, char **mem, const char **p)
4778 {
4779 	const char *q;
4780 	if (strncasecmp(*p, keyword, strlen(keyword)))
4781 		return false;
4782 	q = *p += strlen(keyword);
4783 	if (!(q = strchr(*p, '"'))) {
4784 		errno = 0;
4785 		logerror("unterminated \"\n");
4786 		return false;
4787 	}
4788 	if (!(copy_string(mem, *p, q)))
4789 		return false;
4790 	*p = ++q;
4791 	return true;
4792 }
4793 
4794 /* for config file:
4795  * following = required but whitespace allowed, quotes optional
4796  * if numeric, then conversion to integer and no memory allocation
4797  */
4798 bool
4799 copy_config_value(const char *keyword, char **mem,
4800 	const char **p, const char *file, int line)
4801 {
4802 	if (strncasecmp(*p, keyword, strlen(keyword)))
4803 		return false;
4804 	*p += strlen(keyword);
4805 
4806 	while (isspace((unsigned char)**p))
4807 		*p += 1;
4808 	if (**p != '=') {
4809 		errno = 0;
4810 		logerror("expected \"=\" in file %s, line %d", file, line);
4811 		return false;
4812 	}
4813 	*p += 1;
4814 
4815 	return copy_config_value_word(mem, p);
4816 }
4817 
4818 /* copy next parameter from a config line */
4819 bool
4820 copy_config_value_word(char **mem, const char **p)
4821 {
4822 	const char *q;
4823 	while (isspace((unsigned char)**p))
4824 		*p += 1;
4825 	if (**p == '"')
4826 		return copy_config_value_quoted("\"", mem, p);
4827 
4828 	/* without quotes: find next whitespace or end of line */
4829 	(void)((q = strchr(*p, ' ')) || (q = strchr(*p, '\t'))
4830 	     || (q = strchr(*p, '\n')) || (q = strchr(*p, '\0')));
4831 
4832 	if (q-*p == 0 || !(copy_string(mem, *p, q)))
4833 		return false;
4834 
4835 	*p = ++q;
4836 	return true;
4837 }
4838 
4839 static int
4840 writev1(int fd, struct iovec *iov, size_t count)
4841 {
4842 	ssize_t nw = 0, tot = 0;
4843 	size_t ntries = 5;
4844 
4845 	if (count == 0)
4846 		return 0;
4847 	while (ntries--) {
4848 		switch ((nw = writev(fd, iov, count))) {
4849 		case -1:
4850 			if (errno == EAGAIN || errno == EWOULDBLOCK) {
4851 				struct pollfd pfd;
4852 				pfd.fd = fd;
4853 				pfd.events = POLLOUT;
4854 				pfd.revents = 0;
4855 				(void)poll(&pfd, 1, 500);
4856 				continue;
4857 			}
4858 			return -1;
4859 		case 0:
4860 			return 0;
4861 		default:
4862 			tot += nw;
4863 			while (nw > 0) {
4864 				if (iov->iov_len > (size_t)nw) {
4865 					iov->iov_len -= nw;
4866 					iov->iov_base =
4867 					    (char *)iov->iov_base + nw;
4868 					break;
4869 				} else {
4870 					if (--count == 0)
4871 						return tot;
4872 					nw -= iov->iov_len;
4873 					iov++;
4874 				}
4875 			}
4876 		}
4877 	}
4878 	return tot == 0 ? nw : tot;
4879 }
4880 
4881 #ifndef NDEBUG
4882 void
4883 dbprintf(const char *fname, const char *funname,
4884     size_t lnum, const char *fmt, ...)
4885 {
4886 	va_list ap;
4887 	char *ts;
4888 
4889 	ts = make_timestamp(NULL, true, (size_t)-1);
4890 	printf("%s:%s:%s:%.4zu\t", ts, fname, funname, lnum);
4891 
4892 	va_start(ap, fmt);
4893 	vprintf(fmt, ap);
4894 	va_end(ap);
4895 }
4896 #endif
4897