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