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