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