xref: /openbsd-src/usr.sbin/syslogd/syslogd.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: syslogd.c,v 1.212 2016/08/29 20:31:56 bluhm 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 /*
33  *  syslogd -- log system messages
34  *
35  * This program implements a system log. It takes a series of lines.
36  * Each line may have a priority, signified as "<n>" as
37  * the first characters of the line.  If this is
38  * not present, a default priority is used.
39  *
40  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
41  * cause it to reread its configuration file.
42  *
43  * Defined Constants:
44  *
45  * MAXLINE -- the maximum line length that can be handled.
46  * DEFUPRI -- the default priority for user messages
47  * DEFSPRI -- the default priority for kernel messages
48  *
49  * Author: Eric Allman
50  * extensive changes by Ralph Campbell
51  * more extensive changes by Eric Allman (again)
52  * memory buffer logging by Damien Miller
53  * IPv6, libevent, syslog over TCP and TLS by Alexander Bluhm
54  */
55 
56 #define MAX_UDPMSG	1180		/* maximum UDP send size */
57 #define MIN_MEMBUF	(MAXLINE * 4)	/* Minimum memory buffer size */
58 #define MAX_MEMBUF	(256 * 1024)	/* Maximum memory buffer size */
59 #define MAX_MEMBUF_NAME	64		/* Max length of membuf log name */
60 #define MAX_TCPBUF	(256 * 1024)	/* Maximum tcp event buffer size */
61 #define	MAXSVLINE	120		/* maximum saved line length */
62 #define FD_RESERVE	5		/* file descriptors not accepted */
63 #define DEFUPRI		(LOG_USER|LOG_NOTICE)
64 #define DEFSPRI		(LOG_KERN|LOG_CRIT)
65 #define TIMERINTVL	30		/* interval for checking flush, mark */
66 
67 #include <sys/ioctl.h>
68 #include <sys/stat.h>
69 #include <sys/msgbuf.h>
70 #include <sys/queue.h>
71 #include <sys/sysctl.h>
72 #include <sys/un.h>
73 #include <sys/time.h>
74 #include <sys/resource.h>
75 
76 #include <netinet/in.h>
77 #include <netdb.h>
78 #include <arpa/inet.h>
79 
80 #include <ctype.h>
81 #include <err.h>
82 #include <errno.h>
83 #include <event.h>
84 #include <fcntl.h>
85 #include <limits.h>
86 #include <paths.h>
87 #include <signal.h>
88 #include <stdio.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <tls.h>
92 #include <unistd.h>
93 #include <utmp.h>
94 #include <vis.h>
95 
96 #define MAXIMUM(a, b)	(((a) > (b)) ? (a) : (b))
97 #define MINIMUM(a, b)	(((a) < (b)) ? (a) : (b))
98 
99 #define SYSLOG_NAMES
100 #include <sys/syslog.h>
101 
102 #include "syslogd.h"
103 #include "evbuffer_tls.h"
104 
105 char *ConfFile = _PATH_LOGCONF;
106 const char ctty[] = _PATH_CONSOLE;
107 
108 #define MAXUNAMES	20	/* maximum number of user names */
109 
110 
111 /*
112  * Flags to logmsg().
113  */
114 
115 #define IGN_CONS	0x001	/* don't print on console */
116 #define SYNC_FILE	0x002	/* do fsync on file after printing */
117 #define ADDDATE		0x004	/* add a date to the message */
118 #define MARK		0x008	/* this message is a mark */
119 
120 /*
121  * This structure represents the files that will have log
122  * copies printed.
123  */
124 
125 struct filed {
126 	SIMPLEQ_ENTRY(filed) f_next;	/* next in linked list */
127 	int	f_type;			/* entry type, see below */
128 	int	f_file;			/* file descriptor */
129 	time_t	f_time;			/* time this was last written */
130 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
131 	char	*f_program;		/* program this applies to */
132 	char	*f_hostname;		/* host this applies to */
133 	union {
134 		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
135 		struct {
136 			char	f_loghost[1+4+3+1+NI_MAXHOST+1+NI_MAXSERV];
137 				/* @proto46://[hostname]:servname\0 */
138 			struct sockaddr_storage	 f_addr;
139 			struct buffertls	 f_buftls;
140 			struct bufferevent	*f_bufev;
141 			struct tls		*f_ctx;
142 			char			*f_host;
143 			int			 f_reconnectwait;
144 			int			 f_dropped;
145 		} f_forw;		/* forwarding address */
146 		char	f_fname[PATH_MAX];
147 		struct {
148 			char	f_mname[MAX_MEMBUF_NAME];
149 			struct ringbuf *f_rb;
150 			int	f_overflow;
151 			int	f_attached;
152 			size_t	f_len;
153 		} f_mb;		/* Memory buffer */
154 	} f_un;
155 	char	f_prevline[MAXSVLINE];		/* last message logged */
156 	char	f_lasttime[16];			/* time of last occurrence */
157 	char	f_prevhost[HOST_NAME_MAX+1];	/* host from which recd. */
158 	int	f_prevpri;			/* pri of f_prevline */
159 	int	f_prevlen;			/* length of f_prevline */
160 	int	f_prevcount;			/* repetition cnt of prevline */
161 	unsigned int f_repeatcount;		/* number of "repeated" msgs */
162 	int	f_quick;			/* abort when matched */
163 	time_t	f_lasterrtime;			/* last error was reported */
164 };
165 
166 /*
167  * Intervals at which we flush out "message repeated" messages,
168  * in seconds after previous message is logged.  After each flush,
169  * we move to the next interval until we reach the largest.
170  */
171 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
172 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
173 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
174 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
175 				(f)->f_repeatcount = MAXREPEAT; \
176 			}
177 
178 /* values for f_type */
179 #define F_UNUSED	0		/* unused entry */
180 #define F_FILE		1		/* regular file */
181 #define F_TTY		2		/* terminal */
182 #define F_CONSOLE	3		/* console terminal */
183 #define F_FORWUDP	4		/* remote machine via UDP */
184 #define F_USERS		5		/* list of users */
185 #define F_WALL		6		/* everyone logged on */
186 #define F_MEMBUF	7		/* memory buffer */
187 #define F_PIPE		8		/* pipe to external program */
188 #define F_FORWTCP	9		/* remote machine via TCP */
189 #define F_FORWTLS	10		/* remote machine via TLS */
190 
191 char	*TypeNames[] = {
192 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
193 	"FORWUDP",	"USERS",	"WALL",		"MEMBUF",
194 	"PIPE",		"FORWTCP",	"FORWTLS",
195 };
196 
197 SIMPLEQ_HEAD(filed_list, filed) Files;
198 struct	filed consfile;
199 
200 int	nunix = 1;		/* Number of Unix domain sockets requested */
201 char	*path_unix[MAXUNIX] = { _PATH_LOG }; /* Paths to Unix domain sockets */
202 int	Debug;			/* debug flag */
203 int	Foreground;		/* run in foreground, instead of daemonizing */
204 int	Startup = 1;		/* startup flag */
205 char	LocalHostName[HOST_NAME_MAX+1];	/* our hostname */
206 char	*LocalDomain;		/* our local domain name */
207 int	Initialized = 0;	/* set when we have initialized ourselves */
208 
209 int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
210 int	MarkSeq = 0;		/* mark sequence number */
211 int	SecureMode = 1;		/* when true, speak only unix domain socks */
212 int	NoDNS = 0;		/* when true, will refrain from doing DNS lookups */
213 int	IncludeHostname = 0;	/* include RFC 3164 style hostnames when forwarding */
214 int	Family = PF_UNSPEC;	/* protocol family, may disable IPv4 or IPv6 */
215 char	*bind_host = NULL;	/* bind UDP receive socket */
216 char	*bind_port = NULL;
217 char	*listen_host = NULL;	/* listen on TCP receive socket */
218 char	*listen_port = NULL;
219 char	*tls_hostport = NULL;	/* listen on TLS receive socket */
220 char	*tls_host = NULL;
221 char	*tls_port = NULL;
222 char	*path_ctlsock = NULL;	/* Path to control socket */
223 
224 struct	tls *server_ctx;
225 struct	tls_config *client_config, *server_config;
226 const char *CAfile = "/etc/ssl/cert.pem"; /* file containing CA certificates */
227 int	NoVerify = 0;		/* do not verify TLS server x509 certificate */
228 char	*ClientCertfile = NULL;
229 char	*ClientKeyfile = NULL;
230 int	tcpbuf_dropped = 0;	/* count messages dropped from TCP or TLS */
231 
232 #define CTL_READING_CMD		1
233 #define CTL_WRITING_REPLY	2
234 #define CTL_WRITING_CONT_REPLY	3
235 int	ctl_state = 0;		/* What the control socket is up to */
236 int	membuf_drop = 0;	/* logs were dropped in continuous membuf read */
237 
238 /*
239  * Client protocol NB. all numeric fields in network byte order
240  */
241 #define CTL_VERSION		2
242 
243 /* Request */
244 struct	{
245 	u_int32_t	version;
246 #define CMD_READ	1	/* Read out log */
247 #define CMD_READ_CLEAR	2	/* Read and clear log */
248 #define CMD_CLEAR	3	/* Clear log */
249 #define CMD_LIST	4	/* List available logs */
250 #define CMD_FLAGS	5	/* Query flags only */
251 #define CMD_READ_CONT	6	/* Read out log continuously */
252 	u_int32_t	cmd;
253 	u_int32_t	lines;
254 	char		logname[MAX_MEMBUF_NAME];
255 }	ctl_cmd;
256 
257 size_t	ctl_cmd_bytes = 0;	/* number of bytes of ctl_cmd read */
258 
259 /* Reply */
260 struct ctl_reply_hdr {
261 	u_int32_t	version;
262 #define CTL_HDR_FLAG_OVERFLOW	0x01
263 	u_int32_t	flags;
264 	/* Reply text follows, up to MAX_MEMBUF long */
265 };
266 
267 #define CTL_HDR_LEN		(sizeof(struct ctl_reply_hdr))
268 #define CTL_REPLY_MAXSIZE	(CTL_HDR_LEN + MAX_MEMBUF)
269 #define CTL_REPLY_SIZE		(strlen(reply_text) + CTL_HDR_LEN)
270 
271 char	*ctl_reply = NULL;	/* Buffer for control connection reply */
272 char	*reply_text;		/* Start of reply text in buffer */
273 size_t	ctl_reply_size = 0;	/* Number of bytes used in reply */
274 size_t	ctl_reply_offset = 0;	/* Number of bytes of reply written so far */
275 
276 char	*linebuf;
277 int	 linesize;
278 
279 int		 fd_ctlsock, fd_ctlconn, fd_klog, fd_sendsys, fd_udp, fd_udp6,
280 		 fd_bind, fd_listen, fd_tls, fd_unix[MAXUNIX];
281 struct event	 *ev_ctlaccept, *ev_ctlread, *ev_ctlwrite;
282 
283 struct peer {
284 	struct buffertls	 p_buftls;
285 	struct bufferevent	*p_bufev;
286 	struct tls		*p_ctx;
287 	char			*p_peername;
288 	char			*p_hostname;
289 	int			 p_fd;
290 };
291 char hostname_unknown[] = "???";
292 
293 void	 klog_readcb(int, short, void *);
294 void	 udp_readcb(int, short, void *);
295 void	 unix_readcb(int, short, void *);
296 int	 reserve_accept4(int, int, struct event *,
297     void (*)(int, short, void *), struct sockaddr *, socklen_t *, int);
298 void	 tcp_acceptcb(int, short, void *);
299 int	 octet_counting(struct evbuffer *, char **, int);
300 int	 non_transparent_framing(struct evbuffer *, char **);
301 void	 tcp_readcb(struct bufferevent *, void *);
302 void	 tcp_closecb(struct bufferevent *, short, void *);
303 int	 tcp_socket(struct filed *);
304 void	 tcp_dropcb(struct bufferevent *, void *);
305 void	 tcp_writecb(struct bufferevent *, void *);
306 void	 tcp_errorcb(struct bufferevent *, short, void *);
307 void	 tcp_connectcb(int, short, void *);
308 void	 tcp_connect_retry(struct bufferevent *, struct filed *);
309 int	 tcpbuf_countmsg(struct bufferevent *bufev);
310 void	 die_signalcb(int, short, void *);
311 void	 mark_timercb(int, short, void *);
312 void	 init_signalcb(int, short, void *);
313 void	 ctlsock_acceptcb(int, short, void *);
314 void	 ctlconn_readcb(int, short, void *);
315 void	 ctlconn_writecb(int, short, void *);
316 void	 ctlconn_logto(char *);
317 void	 ctlconn_cleanup(void);
318 
319 struct filed *cfline(char *, char *, char *);
320 void	cvthname(struct sockaddr *, char *, size_t);
321 int	decode(const char *, const CODE *);
322 void	die(int);
323 void	markit(void);
324 void	fprintlog(struct filed *, int, char *);
325 void	init(void);
326 void	logevent(int, const char *);
327 void	logerror(const char *);
328 void	logerrorx(const char *);
329 void	logerrorctx(const char *, struct tls *);
330 void	logerrortlsconf(const char *, struct tls_config *);
331 void	logerror_reason(const char *, const char *);
332 void	logmsg(int, char *, char *, int);
333 struct filed *find_dup(struct filed *);
334 size_t	parsepriority(const char *, int *);
335 void	printline(char *, char *);
336 void	printsys(char *);
337 void	usage(void);
338 void	wallmsg(struct filed *, struct iovec *);
339 int	loghost_parse(char *, char **, char **, char **);
340 int	getmsgbufsize(void);
341 int	socket_bind(const char *, const char *, const char *, int,
342     int *, int *);
343 int	unix_socket(char *, int, mode_t);
344 void	double_sockbuf(int, int);
345 void	tailify_replytext(char *, int);
346 
347 int
348 main(int argc, char *argv[])
349 {
350 	struct timeval	 to;
351 	struct event	*ev_klog, *ev_sendsys, *ev_udp, *ev_udp6,
352 			*ev_bind, *ev_listen, *ev_tls, *ev_unix,
353 			*ev_hup, *ev_int, *ev_quit, *ev_term, *ev_mark;
354 	const char	*errstr;
355 	char		*p;
356 	int		 ch, i;
357 	int		 lockpipe[2] = { -1, -1}, pair[2], nullfd, fd;
358 
359 	while ((ch = getopt(argc, argv, "46a:C:c:dFf:hk:m:np:S:s:T:U:uV"))
360 	    != -1)
361 		switch (ch) {
362 		case '4':		/* disable IPv6 */
363 			Family = PF_INET;
364 			break;
365 		case '6':		/* disable IPv4 */
366 			Family = PF_INET6;
367 			break;
368 		case 'a':
369 			if (nunix >= MAXUNIX)
370 				errx(1, "out of descriptors: %s", optarg);
371 			path_unix[nunix++] = optarg;
372 			break;
373 		case 'C':		/* file containing CA certificates */
374 			CAfile = optarg;
375 			break;
376 		case 'c':		/* file containing client certificate */
377 			ClientCertfile = optarg;
378 			break;
379 		case 'd':		/* debug */
380 			Debug++;
381 			break;
382 		case 'F':		/* foreground */
383 			Foreground = 1;
384 			break;
385 		case 'f':		/* configuration file */
386 			ConfFile = optarg;
387 			break;
388 		case 'h':		/* RFC 3164 hostnames */
389 			IncludeHostname = 1;
390 			break;
391 		case 'k':		/* file containing client key */
392 			ClientKeyfile = optarg;
393 			break;
394 		case 'm':		/* mark interval */
395 			MarkInterval = strtonum(optarg, 0, 365*24*60, &errstr);
396 			if (errstr)
397 				errx(1, "mark_interval %s: %s", errstr, optarg);
398 			MarkInterval *= 60;
399 			break;
400 		case 'n':		/* don't do DNS lookups */
401 			NoDNS = 1;
402 			break;
403 		case 'p':		/* path */
404 			path_unix[0] = optarg;
405 			break;
406 		case 'S':		/* allow tls and listen on address */
407 			tls_hostport = optarg;
408 			if ((p = strdup(optarg)) == NULL)
409 				err(1, "strdup tls address");
410 			if (loghost_parse(p, NULL, &tls_host, &tls_port) == -1)
411 				errx(1, "bad tls address: %s", optarg);
412 			break;
413 		case 's':
414 			path_ctlsock = optarg;
415 			break;
416 		case 'T':		/* allow tcp and listen on address */
417 			if ((p = strdup(optarg)) == NULL)
418 				err(1, "strdup listen address");
419 			if (loghost_parse(p, NULL, &listen_host, &listen_port)
420 			    == -1)
421 				errx(1, "bad listen address: %s", optarg);
422 			break;
423 		case 'U':		/* allow udp only from address */
424 			if ((p = strdup(optarg)) == NULL)
425 				err(1, "strdup bind address");
426 			if (loghost_parse(p, NULL, &bind_host, &bind_port)
427 			    == -1)
428 				errx(1, "bad bind address: %s", optarg);
429 			break;
430 		case 'u':		/* allow udp input port */
431 			SecureMode = 0;
432 			break;
433 		case 'V':		/* do not verify certificates */
434 			NoVerify = 1;
435 			break;
436 		default:
437 			usage();
438 		}
439 	if ((argc -= optind) != 0)
440 		usage();
441 
442 	if (Debug)
443 		setvbuf(stdout, NULL, _IOLBF, 0);
444 
445 	if ((nullfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
446 		logerror("Couldn't open /dev/null");
447 		die(0);
448 	}
449 	for (fd = nullfd + 1; fd <= STDERR_FILENO; fd++) {
450 		if (fcntl(fd, F_GETFL) == -1 && errno == EBADF)
451 			if (dup2(nullfd, fd) == -1) {
452 				logerror("dup2");
453 				die(0);
454 			}
455 	}
456 
457 	consfile.f_type = F_CONSOLE;
458 	(void)strlcpy(consfile.f_un.f_fname, ctty,
459 	    sizeof(consfile.f_un.f_fname));
460 	(void)gethostname(LocalHostName, sizeof(LocalHostName));
461 	if ((p = strchr(LocalHostName, '.')) != NULL) {
462 		*p++ = '\0';
463 		LocalDomain = p;
464 	} else
465 		LocalDomain = "";
466 
467 	linesize = getmsgbufsize();
468 	if (linesize < MAXLINE)
469 		linesize = MAXLINE;
470 	linesize++;
471 	if ((linebuf = malloc(linesize)) == NULL) {
472 		logerror("Couldn't allocate line buffer");
473 		die(0);
474 	}
475 
476 	if (socket_bind("udp", NULL, "syslog", SecureMode,
477 	    &fd_udp, &fd_udp6) == -1) {
478 		logerrorx("socket bind *");
479 		if (!Debug)
480 			die(0);
481 	}
482 	fd_bind = -1;
483 	if (bind_host && socket_bind("udp", bind_host, bind_port, 0,
484 	    &fd_bind, &fd_bind) == -1) {
485 		logerrorx("socket bind udp");
486 		if (!Debug)
487 			die(0);
488 	}
489 	fd_listen = -1;
490 	if (listen_host && socket_bind("tcp", listen_host, listen_port, 0,
491 	    &fd_listen, &fd_listen) == -1) {
492 		logerrorx("socket listen tcp");
493 		if (!Debug)
494 			die(0);
495 	}
496 	fd_tls = -1;
497 	if (tls_host && socket_bind("tls", tls_host, tls_port, 0,
498 	    &fd_tls, &fd_tls) == -1) {
499 		logerrorx("socket listen tls");
500 		if (!Debug)
501 			die(0);
502 	}
503 
504 	for (i = 0; i < nunix; i++) {
505 		fd_unix[i] = unix_socket(path_unix[i], SOCK_DGRAM, 0666);
506 		if (fd_unix[i] == -1) {
507 			if (i == 0 && !Debug)
508 				die(0);
509 			continue;
510 		}
511 		double_sockbuf(fd_unix[i], SO_RCVBUF);
512 	}
513 
514 	if (socketpair(AF_UNIX, SOCK_DGRAM, PF_UNSPEC, pair) == -1) {
515 		logerror("socketpair");
516 		die(0);
517 	}
518 	double_sockbuf(pair[0], SO_RCVBUF);
519 	double_sockbuf(pair[1], SO_SNDBUF);
520 	fd_sendsys = pair[0];
521 
522 	fd_ctlsock = fd_ctlconn = -1;
523 	if (path_ctlsock != NULL) {
524 		fd_ctlsock = unix_socket(path_ctlsock, SOCK_STREAM, 0600);
525 		if (fd_ctlsock == -1) {
526 			logdebug("can't open %s (%d)\n", path_ctlsock, errno);
527 			if (!Debug)
528 				die(0);
529 		} else {
530 			if (listen(fd_ctlsock, 5) == -1) {
531 				logerror("ctlsock listen");
532 				die(0);
533 			}
534 		}
535 	}
536 
537 	fd_klog = open(_PATH_KLOG, O_RDONLY, 0);
538 	if (fd_klog == -1) {
539 		logdebug("can't open %s (%d)\n", _PATH_KLOG, errno);
540 	} else {
541 		if (ioctl(fd_klog, LIOCSFD, &pair[1]) == -1)
542 			logdebug("LIOCSFD errno %d\n", errno);
543 	}
544 	close(pair[1]);
545 
546 	if (tls_init() == -1) {
547 		logerrorx("tls_init");
548 	} else {
549 		if ((client_config = tls_config_new()) == NULL)
550 			logerror("tls_config_new client");
551 		if (tls_hostport) {
552 			if ((server_config = tls_config_new()) == NULL)
553 				logerror("tls_config_new server");
554 			if ((server_ctx = tls_server()) == NULL) {
555 				logerror("tls_server");
556 				close(fd_tls);
557 				fd_tls = -1;
558 			}
559 		}
560 	}
561 	if (client_config) {
562 		if (NoVerify) {
563 			tls_config_insecure_noverifycert(client_config);
564 			tls_config_insecure_noverifyname(client_config);
565 		} else {
566 			if (tls_config_set_ca_file(client_config,
567 			    CAfile) == -1) {
568 				logerrortlsconf("Load client TLS CA failed",
569 				    client_config);
570 				/* avoid reading default certs in chroot */
571 				tls_config_set_ca_mem(client_config, "", 0);
572 			} else
573 				logdebug("CAfile %s\n", CAfile);
574 		}
575 		if (ClientCertfile && ClientKeyfile) {
576 			if (tls_config_set_cert_file(client_config,
577 			    ClientCertfile) == -1)
578 				logerrortlsconf("Load client TLS cert failed",
579 				    client_config);
580 			else
581 				logdebug("ClientCertfile %s\n", ClientCertfile);
582 
583 			if (tls_config_set_key_file(client_config,
584 			    ClientKeyfile) == -1)
585 				logerrortlsconf("Load client TLS key failed",
586 				    client_config);
587 			else
588 				logdebug("ClientKeyfile %s\n", ClientKeyfile);
589 		} else if (ClientCertfile || ClientKeyfile) {
590 			logerrorx("options -c and -k must be used together");
591 		}
592 		tls_config_set_protocols(client_config, TLS_PROTOCOLS_ALL);
593 		if (tls_config_set_ciphers(client_config, "all") != 0)
594 			logerrortlsconf("Set client TLS ciphers failed",
595 			    client_config);
596 	}
597 	if (server_config && server_ctx) {
598 		const char *names[2];
599 
600 		names[0] = tls_hostport;
601 		names[1] = tls_host;
602 
603 		for (i = 0; i < 2; i++) {
604 			if (asprintf(&p, "/etc/ssl/private/%s.key", names[i])
605 			    == -1)
606 				continue;
607 			if (tls_config_set_key_file(server_config, p) == -1) {
608 				logerrortlsconf("Load server TLS key failed",
609 				    server_config);
610 				free(p);
611 				continue;
612 			}
613 			logdebug("Keyfile %s\n", p);
614 			free(p);
615 			if (asprintf(&p, "/etc/ssl/%s.crt", names[i]) == -1)
616 				continue;
617 			if (tls_config_set_cert_file(server_config, p) == -1) {
618 				logerrortlsconf("Load server TLS cert failed",
619 				    server_config);
620 				free(p);
621 				continue;
622 			}
623 			logdebug("Certfile %s\n", p);
624 			free(p);
625 			break;
626 		}
627 
628 		tls_config_set_protocols(server_config, TLS_PROTOCOLS_ALL);
629 		if (tls_config_set_ciphers(server_config, "compat") != 0)
630 			logerrortlsconf("Set server TLS ciphers failed",
631 			    server_config);
632 		if (tls_configure(server_ctx, server_config) != 0) {
633 			logerrorctx("tls_configure server", server_ctx);
634 			tls_free(server_ctx);
635 			server_ctx = NULL;
636 			close(fd_tls);
637 			fd_tls = -1;
638 		}
639 	}
640 
641 	logdebug("off & running....\n");
642 
643 	chdir("/");
644 
645 	tzset();
646 
647 	if (!Debug && !Foreground) {
648 		char c;
649 
650 		pipe(lockpipe);
651 
652 		switch(fork()) {
653 		case -1:
654 			err(1, "fork");
655 		case 0:
656 			setsid();
657 			close(lockpipe[0]);
658 			break;
659 		default:
660 			close(lockpipe[1]);
661 			read(lockpipe[0], &c, 1);
662 			_exit(0);
663 		}
664 	}
665 
666 	/* tuck my process id away */
667 	if (!Debug) {
668 		FILE *fp;
669 
670 		fp = fopen(_PATH_LOGPID, "w");
671 		if (fp != NULL) {
672 			fprintf(fp, "%ld\n", (long)getpid());
673 			(void) fclose(fp);
674 		}
675 	}
676 
677 	/* Privilege separation begins here */
678 	if (priv_init(ConfFile, NoDNS, lockpipe[1], nullfd, argv) < 0)
679 		errx(1, "unable to privsep");
680 
681 	if (pledge("stdio unix inet recvfd", NULL) == -1)
682 		err(1, "pledge");
683 
684 	/* Process is now unprivileged and inside a chroot */
685 	if (Debug)
686 		event_set_log_callback(logevent);
687 	event_init();
688 
689 	if ((ev_ctlaccept = malloc(sizeof(struct event))) == NULL ||
690 	    (ev_ctlread = malloc(sizeof(struct event))) == NULL ||
691 	    (ev_ctlwrite = malloc(sizeof(struct event))) == NULL ||
692 	    (ev_klog = malloc(sizeof(struct event))) == NULL ||
693 	    (ev_sendsys = malloc(sizeof(struct event))) == NULL ||
694 	    (ev_udp = malloc(sizeof(struct event))) == NULL ||
695 	    (ev_udp6 = malloc(sizeof(struct event))) == NULL ||
696 	    (ev_bind = malloc(sizeof(struct event))) == NULL ||
697 	    (ev_listen = malloc(sizeof(struct event))) == NULL ||
698 	    (ev_tls = malloc(sizeof(struct event))) == NULL ||
699 	    (ev_unix = reallocarray(NULL,nunix,sizeof(struct event))) == NULL ||
700 	    (ev_hup = malloc(sizeof(struct event))) == NULL ||
701 	    (ev_int = malloc(sizeof(struct event))) == NULL ||
702 	    (ev_quit = malloc(sizeof(struct event))) == NULL ||
703 	    (ev_term = malloc(sizeof(struct event))) == NULL ||
704 	    (ev_mark = malloc(sizeof(struct event))) == NULL)
705 		err(1, "malloc");
706 
707 	event_set(ev_ctlaccept, fd_ctlsock, EV_READ|EV_PERSIST,
708 	    ctlsock_acceptcb, ev_ctlaccept);
709 	event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST,
710 	    ctlconn_readcb, ev_ctlread);
711 	event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST,
712 	    ctlconn_writecb, ev_ctlwrite);
713 	event_set(ev_klog, fd_klog, EV_READ|EV_PERSIST, klog_readcb, ev_klog);
714 	event_set(ev_sendsys, fd_sendsys, EV_READ|EV_PERSIST, unix_readcb,
715 	    ev_sendsys);
716 	event_set(ev_udp, fd_udp, EV_READ|EV_PERSIST, udp_readcb, ev_udp);
717 	event_set(ev_udp6, fd_udp6, EV_READ|EV_PERSIST, udp_readcb, ev_udp6);
718 	event_set(ev_bind, fd_bind, EV_READ|EV_PERSIST, udp_readcb, ev_bind);
719 	event_set(ev_listen, fd_listen, EV_READ|EV_PERSIST, tcp_acceptcb,
720 	    ev_listen);
721 	event_set(ev_tls, fd_tls, EV_READ|EV_PERSIST, tcp_acceptcb, ev_tls);
722 	for (i = 0; i < nunix; i++)
723 		event_set(&ev_unix[i], fd_unix[i], EV_READ|EV_PERSIST,
724 		    unix_readcb, &ev_unix[i]);
725 
726 	signal_set(ev_hup, SIGHUP, init_signalcb, ev_hup);
727 	signal_set(ev_int, SIGINT, die_signalcb, ev_int);
728 	signal_set(ev_quit, SIGQUIT, die_signalcb, ev_quit);
729 	signal_set(ev_term, SIGTERM, die_signalcb, ev_term);
730 
731 	evtimer_set(ev_mark, mark_timercb, ev_mark);
732 
733 	init();
734 
735 	Startup = 0;
736 
737 	/* Allocate ctl socket reply buffer if we have a ctl socket */
738 	if (fd_ctlsock != -1 &&
739 	    (ctl_reply = malloc(CTL_REPLY_MAXSIZE)) == NULL) {
740 		logerror("Couldn't allocate ctlsock reply buffer");
741 		die(0);
742 	}
743 	reply_text = ctl_reply + CTL_HDR_LEN;
744 
745 	if (!Debug) {
746 		close(lockpipe[1]);
747 		dup2(nullfd, STDIN_FILENO);
748 		dup2(nullfd, STDOUT_FILENO);
749 		dup2(nullfd, STDERR_FILENO);
750 	}
751 	if (nullfd > 2)
752 		close(nullfd);
753 
754 	/*
755 	 * Signal to the priv process that the initial config parsing is done
756 	 * so that it will reject any future attempts to open more files
757 	 */
758 	priv_config_parse_done();
759 
760 	if (fd_ctlsock != -1)
761 		event_add(ev_ctlaccept, NULL);
762 	if (fd_klog != -1)
763 		event_add(ev_klog, NULL);
764 	if (fd_sendsys != -1)
765 		event_add(ev_sendsys, NULL);
766 	if (!SecureMode) {
767 		if (fd_udp != -1)
768 			event_add(ev_udp, NULL);
769 		if (fd_udp6 != -1)
770 			event_add(ev_udp6, NULL);
771 	}
772 	if (fd_bind != -1)
773 		event_add(ev_bind, NULL);
774 	if (fd_listen != -1)
775 		event_add(ev_listen, NULL);
776 	if (fd_tls != -1)
777 		event_add(ev_tls, NULL);
778 	for (i = 0; i < nunix; i++)
779 		if (fd_unix[i] != -1)
780 			event_add(&ev_unix[i], NULL);
781 
782 	signal_add(ev_hup, NULL);
783 	signal_add(ev_term, NULL);
784 	if (Debug) {
785 		signal_add(ev_int, NULL);
786 		signal_add(ev_quit, NULL);
787 	} else {
788 		(void)signal(SIGINT, SIG_IGN);
789 		(void)signal(SIGQUIT, SIG_IGN);
790 	}
791 	(void)signal(SIGCHLD, SIG_IGN);
792 	(void)signal(SIGPIPE, SIG_IGN);
793 
794 	to.tv_sec = TIMERINTVL;
795 	to.tv_usec = 0;
796 	evtimer_add(ev_mark, &to);
797 
798 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: start", LocalHostName, ADDDATE);
799 	logdebug("syslogd: started\n");
800 
801 	event_dispatch();
802 	/* NOTREACHED */
803 	return (0);
804 }
805 
806 int
807 socket_bind(const char *proto, const char *host, const char *port,
808     int shutread, int *fd, int *fd6)
809 {
810 	struct addrinfo	 hints, *res, *res0;
811 	char		 hostname[NI_MAXHOST], servname[NI_MAXSERV];
812 	char		 ebuf[ERRBUFSIZE];
813 	int		*fdp, error, reuseaddr;
814 
815 	*fd = *fd6 = -1;
816 	if (proto == NULL)
817 		proto = "udp";
818 	if (port == NULL)
819 		port = strcmp(proto, "tls") == 0 ? "syslog-tls" : "syslog";
820 
821 	memset(&hints, 0, sizeof(hints));
822 	hints.ai_family = Family;
823 	if (strcmp(proto, "udp") == 0) {
824 		hints.ai_socktype = SOCK_DGRAM;
825 		hints.ai_protocol = IPPROTO_UDP;
826 	} else {
827 		hints.ai_socktype = SOCK_STREAM;
828 		hints.ai_protocol = IPPROTO_TCP;
829 	}
830 	hints.ai_flags = AI_PASSIVE;
831 
832 	if ((error = getaddrinfo(host, port, &hints, &res0))) {
833 		snprintf(ebuf, sizeof(ebuf), "getaddrinfo "
834 		    "proto %s, host %s, port %s: %s",
835 		    proto, host ? host : "*", port, gai_strerror(error));
836 		logerrorx(ebuf);
837 		die(0);
838 	}
839 
840 	for (res = res0; res; res = res->ai_next) {
841 		switch (res->ai_family) {
842 		case AF_INET:
843 			fdp = fd;
844 			break;
845 		case AF_INET6:
846 			fdp = fd6;
847 			break;
848 		default:
849 			continue;
850 		}
851 		if (*fdp >= 0)
852 			continue;
853 
854 		if ((*fdp = socket(res->ai_family,
855 		    res->ai_socktype | SOCK_NONBLOCK, res->ai_protocol)) == -1)
856 			continue;
857 
858 		if (getnameinfo(res->ai_addr, res->ai_addrlen, hostname,
859 		    sizeof(hostname), servname, sizeof(servname),
860 		    NI_NUMERICHOST | NI_NUMERICSERV |
861 		    (res->ai_socktype == SOCK_DGRAM ? NI_DGRAM : 0)) != 0) {
862 			logdebug("Malformed bind address\n");
863 			hostname[0] = servname[0] = '\0';
864 		}
865 		if (shutread && shutdown(*fdp, SHUT_RD) == -1) {
866 			snprintf(ebuf, sizeof(ebuf), "shutdown SHUT_RD "
867 			    "protocol %d, address %s, portnum %s",
868 			    res->ai_protocol, hostname, servname);
869 			logerror(ebuf);
870 			close(*fdp);
871 			*fdp = -1;
872 			continue;
873 		}
874 		reuseaddr = 1;
875 		if (setsockopt(*fdp, SOL_SOCKET, SO_REUSEADDR, &reuseaddr,
876 		    sizeof(reuseaddr)) == -1) {
877 			snprintf(ebuf, sizeof(ebuf), "setsockopt SO_REUSEADDR "
878 			    "protocol %d, address %s, portnum %s",
879 			    res->ai_protocol, hostname, servname);
880 			logerror(ebuf);
881 			close(*fdp);
882 			*fdp = -1;
883 			continue;
884 		}
885 		if (bind(*fdp, res->ai_addr, res->ai_addrlen) == -1) {
886 			snprintf(ebuf, sizeof(ebuf), "bind "
887 			    "protocol %d, address %s, portnum %s",
888 			    res->ai_protocol, hostname, servname);
889 			logerror(ebuf);
890 			close(*fdp);
891 			*fdp = -1;
892 			continue;
893 		}
894 		if (!shutread && res->ai_protocol == IPPROTO_TCP &&
895 		    listen(*fdp, 10) == -1) {
896 			snprintf(ebuf, sizeof(ebuf), "listen "
897 			    "protocol %d, address %s, portnum %s",
898 			    res->ai_protocol, hostname, servname);
899 			logerror(ebuf);
900 			close(*fdp);
901 			*fdp = -1;
902 			continue;
903 		}
904 		if (!shutread && res->ai_protocol == IPPROTO_UDP)
905 			double_sockbuf(*fdp, SO_RCVBUF);
906 	}
907 
908 	freeaddrinfo(res0);
909 
910 	if (*fd == -1 && *fd6 == -1)
911 		return (-1);
912 	return (0);
913 }
914 
915 void
916 klog_readcb(int fd, short event, void *arg)
917 {
918 	struct event		*ev = arg;
919 	ssize_t			 n;
920 
921 	n = read(fd, linebuf, linesize - 1);
922 	if (n > 0) {
923 		linebuf[n] = '\0';
924 		printsys(linebuf);
925 	} else if (n < 0 && errno != EINTR) {
926 		logerror("klog");
927 		event_del(ev);
928 	}
929 }
930 
931 void
932 udp_readcb(int fd, short event, void *arg)
933 {
934 	struct sockaddr_storage	 sa;
935 	socklen_t		 salen;
936 	ssize_t			 n;
937 
938 	salen = sizeof(sa);
939 	n = recvfrom(fd, linebuf, MAXLINE, 0, (struct sockaddr *)&sa, &salen);
940 	if (n > 0) {
941 		char	 resolve[NI_MAXHOST];
942 
943 		linebuf[n] = '\0';
944 		cvthname((struct sockaddr *)&sa, resolve, sizeof(resolve));
945 		logdebug("cvthname res: %s\n", resolve);
946 		printline(resolve, linebuf);
947 	} else if (n < 0 && errno != EINTR && errno != EWOULDBLOCK)
948 		logerror("recvfrom udp");
949 }
950 
951 void
952 unix_readcb(int fd, short event, void *arg)
953 {
954 	struct sockaddr_un	 sa;
955 	socklen_t		 salen;
956 	ssize_t			 n;
957 
958 	salen = sizeof(sa);
959 	n = recvfrom(fd, linebuf, MAXLINE, 0, (struct sockaddr *)&sa, &salen);
960 	if (n > 0) {
961 		linebuf[n] = '\0';
962 		printline(LocalHostName, linebuf);
963 	} else if (n < 0 && errno != EINTR && errno != EWOULDBLOCK)
964 		logerror("recvfrom unix");
965 }
966 
967 int
968 reserve_accept4(int lfd, int event, struct event *ev,
969     void (*cb)(int, short, void *),
970     struct sockaddr *sa, socklen_t *salen, int flags)
971 {
972 	struct timeval	 to = { 1, 0 };
973 	char		 ebuf[ERRBUFSIZE];
974 	int		 afd;
975 
976 	if (event & EV_TIMEOUT) {
977 		logdebug("Listen again\n");
978 		/* Enable the listen event, there is no timeout anymore. */
979 		event_set(ev, lfd, EV_READ|EV_PERSIST, cb, ev);
980 		event_add(ev, NULL);
981 		errno = EWOULDBLOCK;
982 		return (-1);
983 	}
984 
985 	if (getdtablecount() + FD_RESERVE >= getdtablesize()) {
986 		afd = -1;
987 		errno = EMFILE;
988 	} else
989 		afd = accept4(lfd, sa, salen, flags);
990 
991 	if (afd == -1 && (errno == ENFILE || errno == EMFILE)) {
992 		snprintf(ebuf, sizeof(ebuf), "syslogd: accept deferred: %s",
993 		    strerror(errno));
994 		logmsg(LOG_SYSLOG|LOG_WARNING, ebuf, LocalHostName, ADDDATE);
995 		/*
996 		 * Disable the listen event and convert it to a timeout.
997 		 * Pass the listen file descriptor to the callback.
998 		 */
999 		event_del(ev);
1000 		event_set(ev, lfd, 0, cb, ev);
1001 		event_add(ev, &to);
1002 		return (-1);
1003 	}
1004 
1005 	return (afd);
1006 }
1007 
1008 void
1009 tcp_acceptcb(int lfd, short event, void *arg)
1010 {
1011 	struct event		*ev = arg;
1012 	struct peer		*p;
1013 	struct sockaddr_storage	 ss;
1014 	socklen_t		 sslen;
1015 	char			 hostname[NI_MAXHOST], servname[NI_MAXSERV];
1016 	char			*peername, ebuf[ERRBUFSIZE];
1017 	int			 fd;
1018 
1019 	sslen = sizeof(ss);
1020 	if ((fd = reserve_accept4(lfd, event, ev, tcp_acceptcb,
1021 	    (struct sockaddr *)&ss, &sslen, SOCK_NONBLOCK)) == -1) {
1022 		if (errno != ENFILE && errno != EMFILE &&
1023 		    errno != EINTR && errno != EWOULDBLOCK &&
1024 		    errno != ECONNABORTED)
1025 			logerror("accept tcp socket");
1026 		return;
1027 	}
1028 	logdebug("Accepting tcp connection\n");
1029 
1030 	if (getnameinfo((struct sockaddr *)&ss, sslen, hostname,
1031 	    sizeof(hostname), servname, sizeof(servname),
1032 	    NI_NUMERICHOST | NI_NUMERICSERV) != 0 ||
1033 	    asprintf(&peername, ss.ss_family == AF_INET6 ?
1034 	    "[%s]:%s" : "%s:%s", hostname, servname) == -1) {
1035 		logdebug("Malformed accept address\n");
1036 		peername = hostname_unknown;
1037 	}
1038 	logdebug("Peer addresss and port %s\n", peername);
1039 	if ((p = malloc(sizeof(*p))) == NULL) {
1040 		snprintf(ebuf, sizeof(ebuf), "malloc \"%s\"", peername);
1041 		logerror(ebuf);
1042 		close(fd);
1043 		return;
1044 	}
1045 	p->p_fd = fd;
1046 	if ((p->p_bufev = bufferevent_new(fd, tcp_readcb, NULL, tcp_closecb,
1047 	    p)) == NULL) {
1048 		snprintf(ebuf, sizeof(ebuf), "bufferevent \"%s\"", peername);
1049 		logerror(ebuf);
1050 		free(p);
1051 		close(fd);
1052 		return;
1053 	}
1054 	p->p_ctx = NULL;
1055 	if (lfd == fd_tls) {
1056 		if (tls_accept_socket(server_ctx, &p->p_ctx, fd) < 0) {
1057 			snprintf(ebuf, sizeof(ebuf), "tls_accept_socket \"%s\"",
1058 			    peername);
1059 			logerrorctx(ebuf, server_ctx);
1060 			bufferevent_free(p->p_bufev);
1061 			free(p);
1062 			close(fd);
1063 			return;
1064 		}
1065 		buffertls_set(&p->p_buftls, p->p_bufev, p->p_ctx, fd);
1066 		buffertls_accept(&p->p_buftls, fd);
1067 		logdebug("tcp accept callback: tls context success\n");
1068 	}
1069 	if (!NoDNS && peername != hostname_unknown &&
1070 	    priv_getnameinfo((struct sockaddr *)&ss, ss.ss_len, hostname,
1071 	    sizeof(hostname)) != 0) {
1072 		logdebug("Host name for accept address (%s) unknown\n",
1073 		    hostname);
1074 	}
1075 	if (peername == hostname_unknown ||
1076 	    (p->p_hostname = strdup(hostname)) == NULL)
1077 		p->p_hostname = hostname_unknown;
1078 	logdebug("Peer hostname %s\n", hostname);
1079 	p->p_peername = peername;
1080 	bufferevent_enable(p->p_bufev, EV_READ);
1081 
1082 	snprintf(ebuf, sizeof(ebuf), "syslogd: %s logger \"%s\" accepted",
1083 	    p->p_ctx ? "tls" : "tcp", peername);
1084 	logmsg(LOG_SYSLOG|LOG_INFO, ebuf, LocalHostName, ADDDATE);
1085 }
1086 
1087 /*
1088  * Syslog over TCP  RFC 6587  3.4.1. Octet Counting
1089  */
1090 int
1091 octet_counting(struct evbuffer *evbuf, char **msg, int drain)
1092 {
1093 	char	*p, *buf, *end;
1094 	int	 len;
1095 
1096 	buf = EVBUFFER_DATA(evbuf);
1097 	end = buf + EVBUFFER_LENGTH(evbuf);
1098 	/*
1099 	 * It can be assumed that octet-counting framing is used if a syslog
1100 	 * frame starts with a digit.
1101 	 */
1102 	if (buf >= end || !isdigit((unsigned char)*buf))
1103 		return (-1);
1104 	/*
1105 	 * SYSLOG-FRAME = MSG-LEN SP SYSLOG-MSG
1106 	 * MSG-LEN is the octet count of the SYSLOG-MSG in the SYSLOG-FRAME.
1107 	 * We support up to 5 digits in MSG-LEN, so the maximum is 99999.
1108 	 */
1109 	for (p = buf; p < end && p < buf + 5; p++) {
1110 		if (!isdigit((unsigned char)*p))
1111 			break;
1112 	}
1113 	if (buf >= p || p >= end || *p != ' ')
1114 		return (-1);
1115 	p++;
1116 	/* Using atoi() is safe as buf starts with 1 to 5 digits and a space. */
1117 	len = atoi(buf);
1118 	if (drain)
1119 		logdebug(" octet counting %d", len);
1120 	if (p + len > end)
1121 		return (0);
1122 	if (drain)
1123 		evbuffer_drain(evbuf, p - buf);
1124 	if (msg)
1125 		*msg = p;
1126 	return (len);
1127 }
1128 
1129 /*
1130  * Syslog over TCP  RFC 6587  3.4.2. Non-Transparent-Framing
1131  */
1132 int
1133 non_transparent_framing(struct evbuffer *evbuf, char **msg)
1134 {
1135 	char	*p, *buf, *end;
1136 
1137 	buf = EVBUFFER_DATA(evbuf);
1138 	end = buf + EVBUFFER_LENGTH(evbuf);
1139 	/*
1140 	 * The TRAILER has usually been a single character and most often
1141 	 * is ASCII LF (%d10).  However, other characters have also been
1142 	 * seen, with ASCII NUL (%d00) being a prominent example.
1143 	 */
1144 	for (p = buf; p < end; p++) {
1145 		if (*p == '\0' || *p == '\n')
1146 			break;
1147 	}
1148 	if (p + 1 - buf >= INT_MAX)
1149 		return (-1);
1150 	logdebug(" non transparent framing");
1151 	if (p >= end)
1152 		return (0);
1153 	/*
1154 	 * Some devices have also been seen to emit a two-character
1155 	 * TRAILER, which is usually CR and LF.
1156 	 */
1157 	if (buf < p && p[0] == '\n' && p[-1] == '\r')
1158 		p[-1] = '\0';
1159 	if (msg)
1160 		*msg = buf;
1161 	return (p + 1 - buf);
1162 }
1163 
1164 void
1165 tcp_readcb(struct bufferevent *bufev, void *arg)
1166 {
1167 	struct peer		*p = arg;
1168 	char			*msg;
1169 	int			 len;
1170 
1171 	while (EVBUFFER_LENGTH(bufev->input) > 0) {
1172 		logdebug("%s logger \"%s\"", p->p_ctx ? "tls" : "tcp",
1173 		    p->p_peername);
1174 		msg = NULL;
1175 		len = octet_counting(bufev->input, &msg, 1);
1176 		if (len < 0)
1177 			len = non_transparent_framing(bufev->input, &msg);
1178 		if (len < 0)
1179 			logdebug("unknown method");
1180 		if (msg == NULL) {
1181 			logdebug(", incomplete frame");
1182 			break;
1183 		}
1184 		logdebug(", use %d bytes\n", len);
1185 		if (len > 0 && msg[len-1] == '\n')
1186 			msg[len-1] = '\0';
1187 		if (len == 0 || msg[len-1] != '\0') {
1188 			memcpy(linebuf, msg, MINIMUM(len, MAXLINE));
1189 			linebuf[MINIMUM(len, MAXLINE)] = '\0';
1190 			msg = linebuf;
1191 		}
1192 		printline(p->p_hostname, msg);
1193 		evbuffer_drain(bufev->input, len);
1194 	}
1195 	/* Maximum frame has 5 digits, 1 space, MAXLINE chars, 1 new line. */
1196 	if (EVBUFFER_LENGTH(bufev->input) >= 5 + 1 + MAXLINE + 1) {
1197 		logdebug(", use %zu bytes\n", EVBUFFER_LENGTH(bufev->input));
1198 		printline(p->p_hostname, EVBUFFER_DATA(bufev->input));
1199 		evbuffer_drain(bufev->input, -1);
1200 	} else if (EVBUFFER_LENGTH(bufev->input) > 0)
1201 		logdebug(", buffer %zu bytes\n", EVBUFFER_LENGTH(bufev->input));
1202 }
1203 
1204 void
1205 tcp_closecb(struct bufferevent *bufev, short event, void *arg)
1206 {
1207 	struct peer		*p = arg;
1208 	char			 ebuf[ERRBUFSIZE];
1209 
1210 	if (event & EVBUFFER_EOF) {
1211 		snprintf(ebuf, sizeof(ebuf), "syslogd: %s logger \"%s\" "
1212 		    "connection close", p->p_ctx ? "tls" : "tcp",
1213 		    p->p_peername);
1214 		logmsg(LOG_SYSLOG|LOG_INFO, ebuf, LocalHostName, ADDDATE);
1215 	} else {
1216 		snprintf(ebuf, sizeof(ebuf), "syslogd: %s logger \"%s\" "
1217 		    "connection error: %s", p->p_ctx ? "tls" : "tcp",
1218 		    p->p_peername,
1219 		    p->p_ctx ? tls_error(p->p_ctx) : strerror(errno));
1220 		logmsg(LOG_SYSLOG|LOG_NOTICE, ebuf, LocalHostName, ADDDATE);
1221 	}
1222 
1223 	if (p->p_peername != hostname_unknown)
1224 		free(p->p_peername);
1225 	if (p->p_hostname != hostname_unknown)
1226 		free(p->p_hostname);
1227 	bufferevent_free(p->p_bufev);
1228 	close(p->p_fd);
1229 	free(p);
1230 }
1231 
1232 int
1233 tcp_socket(struct filed *f)
1234 {
1235 	int	 s;
1236 	char	 ebuf[ERRBUFSIZE];
1237 
1238 	if ((s = socket(f->f_un.f_forw.f_addr.ss_family,
1239 	    SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) {
1240 		snprintf(ebuf, sizeof(ebuf), "socket \"%s\"",
1241 		    f->f_un.f_forw.f_loghost);
1242 		logerror(ebuf);
1243 		return (-1);
1244 	}
1245 	if (connect(s, (struct sockaddr *)&f->f_un.f_forw.f_addr,
1246 	    f->f_un.f_forw.f_addr.ss_len) == -1 && errno != EINPROGRESS) {
1247 		snprintf(ebuf, sizeof(ebuf), "connect \"%s\"",
1248 		    f->f_un.f_forw.f_loghost);
1249 		logerror(ebuf);
1250 		close(s);
1251 		return (-1);
1252 	}
1253 	return (s);
1254 }
1255 
1256 void
1257 tcp_dropcb(struct bufferevent *bufev, void *arg)
1258 {
1259 	struct filed	*f = arg;
1260 
1261 	/*
1262 	 * Drop data received from the forward log server.
1263 	 */
1264 	logdebug("loghost \"%s\" did send %zu bytes back\n",
1265 	    f->f_un.f_forw.f_loghost, EVBUFFER_LENGTH(bufev->input));
1266 	evbuffer_drain(bufev->input, -1);
1267 }
1268 
1269 void
1270 tcp_writecb(struct bufferevent *bufev, void *arg)
1271 {
1272 	struct filed	*f = arg;
1273 	char		 ebuf[ERRBUFSIZE];
1274 
1275 	/*
1276 	 * Successful write, connection to server is good, reset wait time.
1277 	 */
1278 	logdebug("loghost \"%s\" successful write\n", f->f_un.f_forw.f_loghost);
1279 	f->f_un.f_forw.f_reconnectwait = 0;
1280 
1281 	if (f->f_un.f_forw.f_dropped > 0 &&
1282 	    EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) < MAX_TCPBUF) {
1283 		snprintf(ebuf, sizeof(ebuf),
1284 		    "syslogd: dropped %d message%s to loghost \"%s\"",
1285 		    f->f_un.f_forw.f_dropped,
1286 		    f->f_un.f_forw.f_dropped == 1 ? "" : "s",
1287 		    f->f_un.f_forw.f_loghost);
1288 		f->f_un.f_forw.f_dropped = 0;
1289 		logmsg(LOG_SYSLOG|LOG_WARNING, ebuf, LocalHostName, ADDDATE);
1290 	}
1291 }
1292 
1293 void
1294 tcp_errorcb(struct bufferevent *bufev, short event, void *arg)
1295 {
1296 	struct filed	*f = arg;
1297 	char		*p, *buf, *end;
1298 	int		 l;
1299 	char		 ebuf[ERRBUFSIZE];
1300 
1301 	if (event & EVBUFFER_EOF)
1302 		snprintf(ebuf, sizeof(ebuf),
1303 		    "syslogd: loghost \"%s\" connection close",
1304 		    f->f_un.f_forw.f_loghost);
1305 	else
1306 		snprintf(ebuf, sizeof(ebuf),
1307 		    "syslogd: loghost \"%s\" connection error: %s",
1308 		    f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_ctx ?
1309 		    tls_error(f->f_un.f_forw.f_ctx) : strerror(errno));
1310 	logdebug("%s\n", ebuf);
1311 
1312 	/* The SIGHUP handler may also close the socket, so invalidate it. */
1313 	if (f->f_un.f_forw.f_ctx) {
1314 		tls_close(f->f_un.f_forw.f_ctx);
1315 		tls_free(f->f_un.f_forw.f_ctx);
1316 		f->f_un.f_forw.f_ctx = NULL;
1317 	}
1318 	close(f->f_file);
1319 	f->f_file = -1;
1320 
1321 	/*
1322 	 * The messages in the output buffer may be out of sync.
1323 	 * Check that the buffer starts with "1234 <1234 octets>\n".
1324 	 * Otherwise remove the partial message from the beginning.
1325 	 */
1326 	buf = EVBUFFER_DATA(bufev->output);
1327 	end = buf + EVBUFFER_LENGTH(bufev->output);
1328 	if (buf < end && !((l = octet_counting(bufev->output, &p, 0)) > 0 &&
1329 	    p[l-1] == '\n')) {
1330 		for (p = buf; p < end; p++) {
1331 			if (*p == '\n') {
1332 				evbuffer_drain(bufev->output, p - buf + 1);
1333 				break;
1334 			}
1335 		}
1336 		/* Without '\n' discard everything. */
1337 		if (p == end)
1338 			evbuffer_drain(bufev->output, -1);
1339 		logdebug("loghost \"%s\" dropped partial message\n",
1340 		    f->f_un.f_forw.f_loghost);
1341 		f->f_un.f_forw.f_dropped++;
1342 	}
1343 
1344 	tcp_connect_retry(bufev, f);
1345 
1346 	/* Log the connection error to the fresh buffer after reconnecting. */
1347 	logmsg(LOG_SYSLOG|LOG_WARNING, ebuf, LocalHostName, ADDDATE);
1348 }
1349 
1350 void
1351 tcp_connectcb(int fd, short event, void *arg)
1352 {
1353 	struct filed		*f = arg;
1354 	struct bufferevent	*bufev = f->f_un.f_forw.f_bufev;
1355 	char			 ebuf[ERRBUFSIZE];
1356 	int			 s;
1357 
1358 	if ((s = tcp_socket(f)) == -1) {
1359 		tcp_connect_retry(bufev, f);
1360 		return;
1361 	}
1362 	logdebug("tcp connect callback: socket success, event %#x\n", event);
1363 	f->f_file = s;
1364 
1365 	bufferevent_setfd(bufev, s);
1366 	bufferevent_setcb(bufev, tcp_dropcb, tcp_writecb, tcp_errorcb, f);
1367 	/*
1368 	 * Although syslog is a write only protocol, enable reading from
1369 	 * the socket to detect connection close and errors.
1370 	 */
1371 	bufferevent_enable(bufev, EV_READ|EV_WRITE);
1372 
1373 	if (f->f_type == F_FORWTLS) {
1374 		if ((f->f_un.f_forw.f_ctx = tls_client()) == NULL) {
1375 			snprintf(ebuf, sizeof(ebuf), "tls_client \"%s\"",
1376 			    f->f_un.f_forw.f_loghost);
1377 			logerror(ebuf);
1378 			goto error;
1379 		}
1380 		if (client_config &&
1381 		    tls_configure(f->f_un.f_forw.f_ctx, client_config) == -1) {
1382 			snprintf(ebuf, sizeof(ebuf), "tls_configure \"%s\"",
1383 			    f->f_un.f_forw.f_loghost);
1384 			logerrorctx(ebuf, f->f_un.f_forw.f_ctx);
1385 			goto error;
1386 		}
1387 		if (tls_connect_socket(f->f_un.f_forw.f_ctx, s,
1388 		    f->f_un.f_forw.f_host) == -1) {
1389 			snprintf(ebuf, sizeof(ebuf), "tls_connect_socket "
1390 			    "\"%s\"", f->f_un.f_forw.f_loghost);
1391 			logerrorctx(ebuf, f->f_un.f_forw.f_ctx);
1392 			goto error;
1393 		}
1394 		logdebug("tcp connect callback: tls context success\n");
1395 
1396 		buffertls_set(&f->f_un.f_forw.f_buftls, bufev,
1397 		    f->f_un.f_forw.f_ctx, s);
1398 		buffertls_connect(&f->f_un.f_forw.f_buftls, s);
1399 	}
1400 
1401 	return;
1402 
1403  error:
1404 	if (f->f_un.f_forw.f_ctx) {
1405 		tls_free(f->f_un.f_forw.f_ctx);
1406 		f->f_un.f_forw.f_ctx = NULL;
1407 	}
1408 	close(f->f_file);
1409 	f->f_file = -1;
1410 	tcp_connect_retry(bufev, f);
1411 }
1412 
1413 void
1414 tcp_connect_retry(struct bufferevent *bufev, struct filed *f)
1415 {
1416 	struct timeval		 to;
1417 
1418 	if (f->f_un.f_forw.f_reconnectwait == 0)
1419 		f->f_un.f_forw.f_reconnectwait = 1;
1420 	else
1421 		f->f_un.f_forw.f_reconnectwait <<= 1;
1422 	if (f->f_un.f_forw.f_reconnectwait > 600)
1423 		f->f_un.f_forw.f_reconnectwait = 600;
1424 	to.tv_sec = f->f_un.f_forw.f_reconnectwait;
1425 	to.tv_usec = 0;
1426 
1427 	logdebug("tcp connect retry: wait %d\n",
1428 	    f->f_un.f_forw.f_reconnectwait);
1429 	bufferevent_setfd(bufev, -1);
1430 	/* We can reuse the write event as bufferevent is disabled. */
1431 	evtimer_set(&bufev->ev_write, tcp_connectcb, f);
1432 	evtimer_add(&bufev->ev_write, &to);
1433 }
1434 
1435 int
1436 tcpbuf_countmsg(struct bufferevent *bufev)
1437 {
1438 	char	*p, *buf, *end;
1439 	int	 i = 0;
1440 
1441 	buf = EVBUFFER_DATA(bufev->output);
1442 	end = buf + EVBUFFER_LENGTH(bufev->output);
1443 	for (p = buf; p < end; p++) {
1444 		if (*p == '\n')
1445 			i++;
1446 	}
1447 	return (i);
1448 }
1449 
1450 void
1451 usage(void)
1452 {
1453 
1454 	(void)fprintf(stderr,
1455 	    "usage: syslogd [-46dFhnuV] [-a path] [-C CAfile] [-c cert_file]\n"
1456 	    "\t[-f config_file] [-k key_file] [-m mark_interval]\n"
1457 	    "\t[-p log_socket] [-S listen_address] [-s reporting_socket]\n"
1458 	    "\t[-T listen_address] [-U bind_address]\n");
1459 	exit(1);
1460 }
1461 
1462 /*
1463  * Parse a priority code of the form "<123>" into pri, and return the
1464  * length of the priority code including the surrounding angle brackets.
1465  */
1466 size_t
1467 parsepriority(const char *msg, int *pri)
1468 {
1469 	size_t nlen;
1470 	char buf[11];
1471 	const char *errstr;
1472 	int maybepri;
1473 
1474 	if (*msg++ == '<') {
1475 		nlen = strspn(msg, "1234567890");
1476 		if (nlen > 0 && nlen < sizeof(buf) && msg[nlen] == '>') {
1477 			strlcpy(buf, msg, nlen + 1);
1478 			maybepri = strtonum(buf, 0, INT_MAX, &errstr);
1479 			if (errstr == NULL) {
1480 				*pri = maybepri;
1481 				return nlen + 2;
1482 			}
1483 		}
1484 	}
1485 
1486 	return 0;
1487 }
1488 
1489 /*
1490  * Take a raw input line, decode the message, and print the message
1491  * on the appropriate log files.
1492  */
1493 void
1494 printline(char *hname, char *msg)
1495 {
1496 	int pri;
1497 	char *p, *q, line[MAXLINE + 4 + 1];  /* message, encoding, NUL */
1498 
1499 	/* test for special codes */
1500 	pri = DEFUPRI;
1501 	p = msg;
1502 	p += parsepriority(p, &pri);
1503 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1504 		pri = DEFUPRI;
1505 
1506 	/*
1507 	 * Don't allow users to log kernel messages.
1508 	 * NOTE: since LOG_KERN == 0 this will also match
1509 	 * messages with no facility specified.
1510 	 */
1511 	if (LOG_FAC(pri) == LOG_KERN)
1512 		pri = LOG_USER | LOG_PRI(pri);
1513 
1514 	for (q = line; *p && q < &line[MAXLINE]; p++) {
1515 		if (*p == '\n')
1516 			*q++ = ' ';
1517 		else
1518 			q = vis(q, *p, 0, 0);
1519 	}
1520 	line[MAXLINE] = *q = '\0';
1521 
1522 	logmsg(pri, line, hname, 0);
1523 }
1524 
1525 /*
1526  * Take a raw input line from /dev/klog, split and format similar to syslog().
1527  */
1528 void
1529 printsys(char *msg)
1530 {
1531 	int c, pri, flags;
1532 	char *lp, *p, *q, line[MAXLINE + 1];
1533 	size_t prilen;
1534 
1535 	(void)snprintf(line, sizeof line, "%s: ", _PATH_UNIX);
1536 	lp = line + strlen(line);
1537 	for (p = msg; *p != '\0'; ) {
1538 		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
1539 		pri = DEFSPRI;
1540 		prilen = parsepriority(p, &pri);
1541 		p += prilen;
1542 		if (prilen == 0) {
1543 			/* kernel printf's come out on console */
1544 			flags |= IGN_CONS;
1545 		}
1546 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1547 			pri = DEFSPRI;
1548 
1549 		q = lp;
1550 		while (*p && (c = *p++) != '\n' && q < &line[sizeof(line) - 4])
1551 			q = vis(q, c, 0, 0);
1552 
1553 		logmsg(pri, line, LocalHostName, flags);
1554 	}
1555 }
1556 
1557 time_t	now;
1558 
1559 /*
1560  * Log a message to the appropriate log files, users, etc. based on
1561  * the priority.
1562  */
1563 void
1564 logmsg(int pri, char *msg, char *from, int flags)
1565 {
1566 	struct filed *f;
1567 	int fac, msglen, prilev, i;
1568 	char *timestamp;
1569 	char prog[NAME_MAX+1];
1570 
1571 	logdebug("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
1572 	    pri, flags, from, msg);
1573 
1574 	/*
1575 	 * Check to see if msg looks non-standard.
1576 	 */
1577 	msglen = strlen(msg);
1578 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
1579 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
1580 		flags |= ADDDATE;
1581 
1582 	(void)time(&now);
1583 	if (flags & ADDDATE)
1584 		timestamp = ctime(&now) + 4;
1585 	else {
1586 		timestamp = msg;
1587 		msg += 16;
1588 		msglen -= 16;
1589 	}
1590 
1591 	/* extract facility and priority level */
1592 	if (flags & MARK)
1593 		fac = LOG_NFACILITIES;
1594 	else {
1595 		fac = LOG_FAC(pri);
1596 		if (fac >= LOG_NFACILITIES || fac < 0)
1597 			fac = LOG_USER;
1598 	}
1599 	prilev = LOG_PRI(pri);
1600 
1601 	/* extract program name */
1602 	while (isspace((unsigned char)*msg)) {
1603 		msg++;
1604 		msglen--;
1605 	}
1606 	for (i = 0; i < NAME_MAX; i++) {
1607 		if (!isalnum((unsigned char)msg[i]) && msg[i] != '-')
1608 			break;
1609 		prog[i] = msg[i];
1610 	}
1611 	prog[i] = 0;
1612 
1613 	/* log the message to the particular outputs */
1614 	if (!Initialized) {
1615 		f = &consfile;
1616 		f->f_file = priv_open_tty(ctty);
1617 
1618 		if (f->f_file >= 0) {
1619 			fprintlog(f, flags, msg);
1620 			(void)close(f->f_file);
1621 			f->f_file = -1;
1622 		}
1623 		return;
1624 	}
1625 	SIMPLEQ_FOREACH(f, &Files, f_next) {
1626 		/* skip messages that are incorrect priority */
1627 		if (f->f_pmask[fac] < prilev ||
1628 		    f->f_pmask[fac] == INTERNAL_NOPRI)
1629 			continue;
1630 
1631 		/* skip messages with the incorrect program or hostname */
1632 		if (f->f_program && strcmp(prog, f->f_program) != 0)
1633 			continue;
1634 		if (f->f_hostname && strcmp(from, f->f_hostname) != 0)
1635 			continue;
1636 
1637 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1638 			continue;
1639 
1640 		/* don't output marks to recently written files */
1641 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1642 			continue;
1643 
1644 		/*
1645 		 * suppress duplicate lines to this file
1646 		 */
1647 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
1648 		    !strcmp(msg, f->f_prevline) &&
1649 		    !strcmp(from, f->f_prevhost)) {
1650 			strlcpy(f->f_lasttime, timestamp, 16);
1651 			f->f_prevcount++;
1652 			logdebug("msg repeated %d times, %ld sec of %d\n",
1653 			    f->f_prevcount, (long)(now - f->f_time),
1654 			    repeatinterval[f->f_repeatcount]);
1655 			/*
1656 			 * If domark would have logged this by now,
1657 			 * flush it now (so we don't hold isolated messages),
1658 			 * but back off so we'll flush less often
1659 			 * in the future.
1660 			 */
1661 			if (now > REPEATTIME(f)) {
1662 				fprintlog(f, flags, (char *)NULL);
1663 				BACKOFF(f);
1664 			}
1665 		} else {
1666 			/* new line, save it */
1667 			if (f->f_prevcount)
1668 				fprintlog(f, 0, (char *)NULL);
1669 			f->f_repeatcount = 0;
1670 			f->f_prevpri = pri;
1671 			strlcpy(f->f_lasttime, timestamp, 16);
1672 			strlcpy(f->f_prevhost, from,
1673 			    sizeof(f->f_prevhost));
1674 			if (msglen < MAXSVLINE) {
1675 				f->f_prevlen = msglen;
1676 				strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1677 				fprintlog(f, flags, (char *)NULL);
1678 			} else {
1679 				f->f_prevline[0] = 0;
1680 				f->f_prevlen = 0;
1681 				fprintlog(f, flags, msg);
1682 			}
1683 		}
1684 
1685 		if (f->f_quick)
1686 			break;
1687 	}
1688 }
1689 
1690 void
1691 fprintlog(struct filed *f, int flags, char *msg)
1692 {
1693 	struct iovec iov[6];
1694 	struct iovec *v;
1695 	int l, retryonce;
1696 	char line[MAXLINE + 1], repbuf[80], greetings[500];
1697 
1698 	v = iov;
1699 	if (f->f_type == F_WALL) {
1700 		l = snprintf(greetings, sizeof(greetings),
1701 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1702 		    f->f_prevhost, ctime(&now));
1703 		if (l < 0 || (size_t)l >= sizeof(greetings))
1704 			l = strlen(greetings);
1705 		v->iov_base = greetings;
1706 		v->iov_len = l;
1707 		v++;
1708 		v->iov_base = "";
1709 		v->iov_len = 0;
1710 		v++;
1711 	} else if (f->f_lasttime[0] != '\0') {
1712 		v->iov_base = f->f_lasttime;
1713 		v->iov_len = 15;
1714 		v++;
1715 		v->iov_base = " ";
1716 		v->iov_len = 1;
1717 		v++;
1718 	} else {
1719 		v->iov_base = "";
1720 		v->iov_len = 0;
1721 		v++;
1722 		v->iov_base = "";
1723 		v->iov_len = 0;
1724 		v++;
1725 	}
1726 	if (f->f_prevhost[0] != '\0') {
1727 		v->iov_base = f->f_prevhost;
1728 		v->iov_len = strlen(v->iov_base);
1729 		v++;
1730 		v->iov_base = " ";
1731 		v->iov_len = 1;
1732 		v++;
1733 	} else {
1734 		v->iov_base = "";
1735 		v->iov_len = 0;
1736 		v++;
1737 		v->iov_base = "";
1738 		v->iov_len = 0;
1739 		v++;
1740 	}
1741 
1742 	if (msg) {
1743 		v->iov_base = msg;
1744 		v->iov_len = strlen(msg);
1745 	} else if (f->f_prevcount > 1) {
1746 		l = snprintf(repbuf, sizeof(repbuf),
1747 		    "last message repeated %d times", f->f_prevcount);
1748 		if (l < 0 || (size_t)l >= sizeof(repbuf))
1749 			l = strlen(repbuf);
1750 		v->iov_base = repbuf;
1751 		v->iov_len = l;
1752 	} else {
1753 		v->iov_base = f->f_prevline;
1754 		v->iov_len = f->f_prevlen;
1755 	}
1756 	v++;
1757 
1758 	logdebug("Logging to %s", TypeNames[f->f_type]);
1759 	f->f_time = now;
1760 
1761 	switch (f->f_type) {
1762 	case F_UNUSED:
1763 		logdebug("\n");
1764 		break;
1765 
1766 	case F_FORWUDP:
1767 		logdebug(" %s\n", f->f_un.f_forw.f_loghost);
1768 		l = snprintf(line, MINIMUM(MAX_UDPMSG + 1, sizeof(line)),
1769 		    "<%d>%.15s %s%s%s", f->f_prevpri, (char *)iov[0].iov_base,
1770 		    IncludeHostname ? LocalHostName : "",
1771 		    IncludeHostname ? " " : "",
1772 		    (char *)iov[4].iov_base);
1773 		if (l < 0 || (size_t)l > MINIMUM(MAX_UDPMSG, sizeof(line)))
1774 			l = MINIMUM(MAX_UDPMSG, sizeof(line));
1775 		if (sendto(f->f_file, line, l, 0,
1776 		    (struct sockaddr *)&f->f_un.f_forw.f_addr,
1777 		    f->f_un.f_forw.f_addr.ss_len) != l) {
1778 			switch (errno) {
1779 			case EHOSTDOWN:
1780 			case EHOSTUNREACH:
1781 			case ENETDOWN:
1782 			case ENETUNREACH:
1783 			case ENOBUFS:
1784 			case EWOULDBLOCK:
1785 				/* silently dropped */
1786 				break;
1787 			default:
1788 				f->f_type = F_UNUSED;
1789 				logerror("sendto");
1790 				break;
1791 			}
1792 		}
1793 		break;
1794 
1795 	case F_FORWTCP:
1796 	case F_FORWTLS:
1797 		logdebug(" %s", f->f_un.f_forw.f_loghost);
1798 		if (EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) >=
1799 		    MAX_TCPBUF) {
1800 			logdebug(" (dropped)\n");
1801 			f->f_un.f_forw.f_dropped++;
1802 			break;
1803 		}
1804 		/*
1805 		 * Syslog over TLS  RFC 5425  4.3.  Sending Data
1806 		 * Syslog over TCP  RFC 6587  3.4.1.  Octet Counting
1807 		 * Use an additional '\n' to split messages.  This allows
1808 		 * buffer synchronisation, helps legacy implementations,
1809 		 * and makes line based testing easier.
1810 		 */
1811 		l = snprintf(line, sizeof(line), "<%d>%.15s %s%s\n",
1812 		    f->f_prevpri, (char *)iov[0].iov_base,
1813 		    IncludeHostname ? LocalHostName : "",
1814 		    IncludeHostname ? " " : "");
1815 		if (l < 0) {
1816 			logdebug(" (dropped snprintf)\n");
1817 			f->f_un.f_forw.f_dropped++;
1818 			break;
1819 		}
1820 		l = evbuffer_add_printf(f->f_un.f_forw.f_bufev->output,
1821 		    "%zu <%d>%.15s %s%s%s\n",
1822 		    (size_t)l + strlen(iov[4].iov_base),
1823 		    f->f_prevpri, (char *)iov[0].iov_base,
1824 		    IncludeHostname ? LocalHostName : "",
1825 		    IncludeHostname ? " " : "",
1826 		    (char *)iov[4].iov_base);
1827 		if (l < 0) {
1828 			logdebug(" (dropped evbuffer_add_printf)\n");
1829 			f->f_un.f_forw.f_dropped++;
1830 			break;
1831 		}
1832 		bufferevent_enable(f->f_un.f_forw.f_bufev, EV_WRITE);
1833 		logdebug("\n");
1834 		break;
1835 
1836 	case F_CONSOLE:
1837 		if (flags & IGN_CONS) {
1838 			logdebug(" (ignored)\n");
1839 			break;
1840 		}
1841 		/* FALLTHROUGH */
1842 
1843 	case F_TTY:
1844 	case F_FILE:
1845 	case F_PIPE:
1846 		logdebug(" %s\n", f->f_un.f_fname);
1847 		if (f->f_type != F_FILE && f->f_type != F_PIPE) {
1848 			v->iov_base = "\r\n";
1849 			v->iov_len = 2;
1850 		} else {
1851 			v->iov_base = "\n";
1852 			v->iov_len = 1;
1853 		}
1854 		retryonce = 0;
1855 	again:
1856 		if (writev(f->f_file, iov, 6) < 0) {
1857 			int e = errno;
1858 
1859 			/* pipe is non-blocking. log and drop message if full */
1860 			if (e == EAGAIN && f->f_type == F_PIPE) {
1861 				if (now - f->f_lasterrtime > 120) {
1862 					f->f_lasterrtime = now;
1863 					logerror(f->f_un.f_fname);
1864 				}
1865 				break;
1866 			}
1867 
1868 			(void)close(f->f_file);
1869 			/*
1870 			 * Check for errors on TTY's or program pipes.
1871 			 * Errors happen due to loss of tty or died programs.
1872 			 */
1873 			if (e == EAGAIN) {
1874 				/*
1875 				 * Silently drop messages on blocked write.
1876 				 * This can happen when logging to a locked tty.
1877 				 */
1878 				break;
1879 			} else if ((e == EIO || e == EBADF) &&
1880 			    f->f_type != F_FILE && f->f_type != F_PIPE &&
1881 			    !retryonce) {
1882 				f->f_file = priv_open_tty(f->f_un.f_fname);
1883 				retryonce = 1;
1884 				if (f->f_file < 0) {
1885 					f->f_type = F_UNUSED;
1886 					logerror(f->f_un.f_fname);
1887 				} else
1888 					goto again;
1889 			} else if ((e == EPIPE || e == EBADF) &&
1890 			    f->f_type == F_PIPE && !retryonce) {
1891 				f->f_file = priv_open_log(f->f_un.f_fname);
1892 				retryonce = 1;
1893 				if (f->f_file < 0) {
1894 					f->f_type = F_UNUSED;
1895 					logerror(f->f_un.f_fname);
1896 				} else
1897 					goto again;
1898 			} else {
1899 				f->f_type = F_UNUSED;
1900 				f->f_file = -1;
1901 				errno = e;
1902 				logerror(f->f_un.f_fname);
1903 			}
1904 		} else if (flags & SYNC_FILE)
1905 			(void)fsync(f->f_file);
1906 		break;
1907 
1908 	case F_USERS:
1909 	case F_WALL:
1910 		logdebug("\n");
1911 		v->iov_base = "\r\n";
1912 		v->iov_len = 2;
1913 		wallmsg(f, iov);
1914 		break;
1915 
1916 	case F_MEMBUF:
1917 		logdebug("\n");
1918 		snprintf(line, sizeof(line), "%.15s %s %s",
1919 		    (char *)iov[0].iov_base, (char *)iov[2].iov_base,
1920 		    (char *)iov[4].iov_base);
1921 		if (ringbuf_append_line(f->f_un.f_mb.f_rb, line) == 1)
1922 			f->f_un.f_mb.f_overflow = 1;
1923 		if (f->f_un.f_mb.f_attached)
1924 			ctlconn_logto(line);
1925 		break;
1926 	}
1927 	f->f_prevcount = 0;
1928 }
1929 
1930 /*
1931  *  WALLMSG -- Write a message to the world at large
1932  *
1933  *	Write the specified message to either the entire
1934  *	world, or a list of approved users.
1935  */
1936 void
1937 wallmsg(struct filed *f, struct iovec *iov)
1938 {
1939 	struct utmp ut;
1940 	char utline[sizeof(ut.ut_line) + 1], *p;
1941 	static int reenter;			/* avoid calling ourselves */
1942 	FILE *uf;
1943 	int i;
1944 
1945 	if (reenter++)
1946 		return;
1947 	if ((uf = priv_open_utmp()) == NULL) {
1948 		logerror(_PATH_UTMP);
1949 		reenter = 0;
1950 		return;
1951 	}
1952 	while (fread(&ut, sizeof(ut), 1, uf) == 1) {
1953 		if (ut.ut_name[0] == '\0')
1954 			continue;
1955 		/* must use strncpy since ut_* may not be NUL terminated */
1956 		strncpy(utline, ut.ut_line, sizeof(utline) - 1);
1957 		utline[sizeof(utline) - 1] = '\0';
1958 		if (f->f_type == F_WALL) {
1959 			if ((p = ttymsg(iov, 6, utline)) != NULL)
1960 				logerrorx(p);
1961 			continue;
1962 		}
1963 		/* should we send the message to this user? */
1964 		for (i = 0; i < MAXUNAMES; i++) {
1965 			if (!f->f_un.f_uname[i][0])
1966 				break;
1967 			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1968 			    UT_NAMESIZE)) {
1969 				if ((p = ttymsg(iov, 6, utline)) != NULL)
1970 					logerrorx(p);
1971 				break;
1972 			}
1973 		}
1974 	}
1975 	(void)fclose(uf);
1976 	reenter = 0;
1977 }
1978 
1979 /*
1980  * Return a printable representation of a host address.
1981  */
1982 void
1983 cvthname(struct sockaddr *f, char *result, size_t res_len)
1984 {
1985 	if (getnameinfo(f, f->sa_len, result, res_len, NULL, 0,
1986 	    NI_NUMERICHOST|NI_NUMERICSERV|NI_DGRAM) != 0) {
1987 		logdebug("Malformed from address\n");
1988 		strlcpy(result, hostname_unknown, res_len);
1989 		return;
1990 	}
1991 	logdebug("cvthname(%s)\n", result);
1992 	if (NoDNS)
1993 		return;
1994 
1995 	if (priv_getnameinfo(f, f->sa_len, result, res_len) != 0)
1996 		logdebug("Host name for from address (%s) unknown\n", result);
1997 }
1998 
1999 void
2000 die_signalcb(int signum, short event, void *arg)
2001 {
2002 	die(signum);
2003 }
2004 
2005 void
2006 mark_timercb(int unused, short event, void *arg)
2007 {
2008 	struct event		*ev = arg;
2009 	struct timeval		 to;
2010 
2011 	markit();
2012 
2013 	to.tv_sec = TIMERINTVL;
2014 	to.tv_usec = 0;
2015 	evtimer_add(ev, &to);
2016 }
2017 
2018 void
2019 init_signalcb(int signum, short event, void *arg)
2020 {
2021 	char	 ebuf[ERRBUFSIZE];
2022 
2023 	init();
2024 
2025 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart",
2026 	    LocalHostName, ADDDATE);
2027 	logdebug("syslogd: restarted\n");
2028 
2029 	if (tcpbuf_dropped > 0) {
2030 		snprintf(ebuf, sizeof(ebuf),
2031 		    "syslogd: dropped %d message%s to remote loghost",
2032 		    tcpbuf_dropped, tcpbuf_dropped == 1 ? "" : "s");
2033 		tcpbuf_dropped = 0;
2034 		logmsg(LOG_SYSLOG|LOG_WARNING, ebuf, LocalHostName, ADDDATE);
2035 	}
2036 }
2037 
2038 void
2039 logevent(int severity, const char *msg)
2040 {
2041 	logdebug("libevent: [%d] %s\n", severity, msg);
2042 }
2043 
2044 void
2045 logdebug(const char *fmt, ...)
2046 {
2047 	va_list ap;
2048 
2049 	if (Debug) {
2050 		va_start(ap, fmt);
2051 		vprintf(fmt, ap);
2052 		va_end(ap);
2053 	}
2054 }
2055 
2056 void
2057 logerror(const char *message)
2058 {
2059 	logerror_reason(message, errno ? strerror(errno) : NULL);
2060 }
2061 
2062 void
2063 logerrorx(const char *message)
2064 {
2065 	logerror_reason(message, NULL);
2066 }
2067 
2068 void
2069 logerrorctx(const char *message, struct tls *ctx)
2070 {
2071 	logerror_reason(message, ctx ? tls_error(ctx) : NULL);
2072 }
2073 
2074 void
2075 logerrortlsconf(const char *message, struct tls_config *config)
2076 {
2077 	logerror_reason(message, config ? tls_config_error(config) : NULL);
2078 }
2079 
2080 void
2081 logerror_reason(const char *message, const char *reason)
2082 {
2083 	char ebuf[ERRBUFSIZE];
2084 
2085 	if (reason)
2086 		(void)snprintf(ebuf, sizeof(ebuf), "syslogd: %s: %s",
2087 		    message, reason);
2088 	else
2089 		(void)snprintf(ebuf, sizeof(ebuf), "syslogd: %s", message);
2090 	errno = 0;
2091 	logdebug("%s\n", ebuf);
2092 	if (Startup)
2093 		fprintf(stderr, "%s\n", ebuf);
2094 	else
2095 		logmsg(LOG_SYSLOG|LOG_ERR, ebuf, LocalHostName, ADDDATE);
2096 }
2097 
2098 void
2099 die(int signo)
2100 {
2101 	struct filed *f;
2102 	int was_initialized = Initialized;
2103 	char ebuf[ERRBUFSIZE];
2104 
2105 	Initialized = 0;		/* Don't log SIGCHLDs */
2106 	SIMPLEQ_FOREACH(f, &Files, f_next) {
2107 		/* flush any pending output */
2108 		if (f->f_prevcount)
2109 			fprintlog(f, 0, (char *)NULL);
2110 		if (f->f_type == F_FORWTLS || f->f_type == F_FORWTCP) {
2111 			tcpbuf_dropped += f->f_un.f_forw.f_dropped +
2112 			    tcpbuf_countmsg(f->f_un.f_forw.f_bufev);
2113 			f->f_un.f_forw.f_dropped = 0;
2114 		}
2115 	}
2116 	Initialized = was_initialized;
2117 
2118 	if (tcpbuf_dropped > 0) {
2119 		snprintf(ebuf, sizeof(ebuf),
2120 		    "syslogd: dropped %d message%s to remote loghost",
2121 		    tcpbuf_dropped, tcpbuf_dropped == 1 ? "" : "s");
2122 		tcpbuf_dropped = 0;
2123 		logmsg(LOG_SYSLOG|LOG_WARNING, ebuf, LocalHostName, ADDDATE);
2124 	}
2125 
2126 	if (signo) {
2127 		logdebug("syslogd: exiting on signal %d\n", signo);
2128 		(void)snprintf(ebuf, sizeof(ebuf), "exiting on signal %d",
2129 		    signo);
2130 		logerrorx(ebuf);
2131 	}
2132 	logdebug("[unpriv] syslogd child about to exit\n");
2133 	exit(0);
2134 }
2135 
2136 /*
2137  *  INIT -- Initialize syslogd from configuration table
2138  */
2139 void
2140 init(void)
2141 {
2142 	char progblock[NAME_MAX+1], hostblock[NAME_MAX+1], *cline, *p, *q;
2143 	struct filed_list mb;
2144 	struct filed *f, *m;
2145 	FILE *cf;
2146 	int i;
2147 	size_t s;
2148 
2149 	logdebug("init\n");
2150 
2151 	/* If config file has been modified, then just die to restart */
2152 	if (priv_config_modified()) {
2153 		logdebug("config file changed: dying\n");
2154 		die(0);
2155 	}
2156 
2157 	/*
2158 	 *  Close all open log files.
2159 	 */
2160 	Initialized = 0;
2161 	SIMPLEQ_INIT(&mb);
2162 	while (!SIMPLEQ_EMPTY(&Files)) {
2163 		f = SIMPLEQ_FIRST(&Files);
2164 		SIMPLEQ_REMOVE_HEAD(&Files, f_next);
2165 		/* flush any pending output */
2166 		if (f->f_prevcount)
2167 			fprintlog(f, 0, (char *)NULL);
2168 
2169 		switch (f->f_type) {
2170 		case F_FORWTLS:
2171 			if (f->f_un.f_forw.f_ctx) {
2172 				tls_close(f->f_un.f_forw.f_ctx);
2173 				tls_free(f->f_un.f_forw.f_ctx);
2174 			}
2175 			free(f->f_un.f_forw.f_host);
2176 			/* FALLTHROUGH */
2177 		case F_FORWTCP:
2178 			tcpbuf_dropped += f->f_un.f_forw.f_dropped +
2179 			     tcpbuf_countmsg(f->f_un.f_forw.f_bufev);
2180 			bufferevent_free(f->f_un.f_forw.f_bufev);
2181 			/* FALLTHROUGH */
2182 		case F_FILE:
2183 		case F_TTY:
2184 		case F_CONSOLE:
2185 		case F_PIPE:
2186 			(void)close(f->f_file);
2187 			break;
2188 		}
2189 		free(f->f_program);
2190 		free(f->f_hostname);
2191 		if (f->f_type == F_MEMBUF) {
2192 			f->f_program = NULL;
2193 			f->f_hostname = NULL;
2194 			logdebug("add %p to mb\n", f);
2195 			SIMPLEQ_INSERT_HEAD(&mb, f, f_next);
2196 		} else
2197 			free(f);
2198 	}
2199 	SIMPLEQ_INIT(&Files);
2200 
2201 	/* open the configuration file */
2202 	if ((cf = priv_open_config()) == NULL) {
2203 		logdebug("cannot open %s\n", ConfFile);
2204 		SIMPLEQ_INSERT_TAIL(&Files,
2205 		    cfline("*.ERR\t/dev/console", "*", "*"), f_next);
2206 		SIMPLEQ_INSERT_TAIL(&Files,
2207 		    cfline("*.PANIC\t*", "*", "*"), f_next);
2208 		Initialized = 1;
2209 		return;
2210 	}
2211 
2212 	/*
2213 	 *  Foreach line in the conf table, open that file.
2214 	 */
2215 	cline = NULL;
2216 	s = 0;
2217 	strlcpy(progblock, "*", sizeof(progblock));
2218 	strlcpy(hostblock, "*", sizeof(hostblock));
2219 	while (getline(&cline, &s, cf) != -1) {
2220 		/*
2221 		 * check for end-of-section, comments, strip off trailing
2222 		 * spaces and newline character. !progblock and +hostblock
2223 		 * are treated specially: the following lines apply only to
2224 		 * that program.
2225 		 */
2226 		for (p = cline; isspace((unsigned char)*p); ++p)
2227 			continue;
2228 		if (*p == '\0' || *p == '#')
2229 			continue;
2230 		if (*p == '!' || *p == '+') {
2231 			q = (*p == '!') ? progblock : hostblock;
2232 			p++;
2233 			while (isspace((unsigned char)*p))
2234 				p++;
2235 			if (*p == '\0' || (*p == '*' && (p[1] == '\0' ||
2236 			    isspace((unsigned char)p[1])))) {
2237 				strlcpy(q, "*", NAME_MAX+1);
2238 				continue;
2239 			}
2240 			for (i = 0; i < NAME_MAX; i++) {
2241 				if (*p == '\0' || isspace((unsigned char)*p))
2242 					break;
2243 				*q++ = *p++;
2244 			}
2245 			*q = '\0';
2246 			continue;
2247 		}
2248 
2249 		p = cline + strlen(cline);
2250 		while (p > cline)
2251 			if (!isspace((unsigned char)*--p)) {
2252 				p++;
2253 				break;
2254 			}
2255 		*p = '\0';
2256 		f = cfline(cline, progblock, hostblock);
2257 		if (f != NULL)
2258 			SIMPLEQ_INSERT_TAIL(&Files, f, f_next);
2259 	}
2260 	free(cline);
2261 	if (!feof(cf)) {
2262 		logerror("Unable to read config file");
2263 		die(0);
2264 	}
2265 
2266 	/* Match and initialize the memory buffers */
2267 	SIMPLEQ_FOREACH(f, &Files, f_next) {
2268 		if (f->f_type != F_MEMBUF)
2269 			continue;
2270 		logdebug("Initialize membuf %s at %p\n",
2271 		    f->f_un.f_mb.f_mname, f);
2272 
2273 		SIMPLEQ_FOREACH(m, &mb, f_next) {
2274 			if (m->f_un.f_mb.f_rb == NULL)
2275 				continue;
2276 			if (strcmp(m->f_un.f_mb.f_mname,
2277 			    f->f_un.f_mb.f_mname) == 0)
2278 				break;
2279 		}
2280 		if (m == NULL) {
2281 			logdebug("Membuf no match\n");
2282 			f->f_un.f_mb.f_rb = ringbuf_init(f->f_un.f_mb.f_len);
2283 			if (f->f_un.f_mb.f_rb == NULL) {
2284 				f->f_type = F_UNUSED;
2285 				logerror("Failed to allocate membuf");
2286 			}
2287 		} else {
2288 			logdebug("Membuf match f:%p, m:%p\n", f, m);
2289 			f->f_un = m->f_un;
2290 			m->f_un.f_mb.f_rb = NULL;
2291 		}
2292 	}
2293 
2294 	/* make sure remaining buffers are freed */
2295 	while (!SIMPLEQ_EMPTY(&mb)) {
2296 		m = SIMPLEQ_FIRST(&mb);
2297 		SIMPLEQ_REMOVE_HEAD(&mb, f_next);
2298 		if (m->f_un.f_mb.f_rb != NULL) {
2299 			logerrorx("Mismatched membuf");
2300 			ringbuf_free(m->f_un.f_mb.f_rb);
2301 		}
2302 		logdebug("Freeing membuf %p\n", m);
2303 
2304 		free(m);
2305 	}
2306 
2307 	/* close the configuration file */
2308 	(void)fclose(cf);
2309 
2310 	Initialized = 1;
2311 
2312 	if (Debug) {
2313 		SIMPLEQ_FOREACH(f, &Files, f_next) {
2314 			for (i = 0; i <= LOG_NFACILITIES; i++)
2315 				if (f->f_pmask[i] == INTERNAL_NOPRI)
2316 					printf("X ");
2317 				else
2318 					printf("%d ", f->f_pmask[i]);
2319 			printf("%s: ", TypeNames[f->f_type]);
2320 			switch (f->f_type) {
2321 			case F_FILE:
2322 			case F_TTY:
2323 			case F_CONSOLE:
2324 			case F_PIPE:
2325 				printf("%s", f->f_un.f_fname);
2326 				break;
2327 
2328 			case F_FORWUDP:
2329 			case F_FORWTCP:
2330 			case F_FORWTLS:
2331 				printf("%s", f->f_un.f_forw.f_loghost);
2332 				break;
2333 
2334 			case F_USERS:
2335 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
2336 					printf("%s, ", f->f_un.f_uname[i]);
2337 				break;
2338 
2339 			case F_MEMBUF:
2340 				printf("%s", f->f_un.f_mb.f_mname);
2341 				break;
2342 
2343 			}
2344 			if (f->f_program || f->f_hostname)
2345 				printf(" (%s, %s)",
2346 				    f->f_program ? f->f_program : "*",
2347 				    f->f_hostname ? f->f_hostname : "*");
2348 			printf("\n");
2349 		}
2350 	}
2351 }
2352 
2353 #define progmatches(p1, p2) \
2354 	(p1 == p2 || (p1 != NULL && p2 != NULL && strcmp(p1, p2) == 0))
2355 
2356 /*
2357  * Spot a line with a duplicate file, pipe, console, tty, or membuf target.
2358  */
2359 struct filed *
2360 find_dup(struct filed *f)
2361 {
2362 	struct filed *list;
2363 
2364 	SIMPLEQ_FOREACH(list, &Files, f_next) {
2365 		if (list->f_quick || f->f_quick)
2366 			continue;
2367 		switch (list->f_type) {
2368 		case F_FILE:
2369 		case F_TTY:
2370 		case F_CONSOLE:
2371 		case F_PIPE:
2372 			if (strcmp(list->f_un.f_fname, f->f_un.f_fname) == 0 &&
2373 			    progmatches(list->f_program, f->f_program) &&
2374 			    progmatches(list->f_hostname, f->f_hostname)) {
2375 				logdebug("duplicate %s\n", f->f_un.f_fname);
2376 				return (list);
2377 			}
2378 			break;
2379 		case F_MEMBUF:
2380 			if (strcmp(list->f_un.f_mb.f_mname,
2381 			    f->f_un.f_mb.f_mname) == 0 &&
2382 			    progmatches(list->f_program, f->f_program) &&
2383 			    progmatches(list->f_hostname, f->f_hostname)) {
2384 				logdebug("duplicate membuf %s\n",
2385 				    f->f_un.f_mb.f_mname);
2386 				return (list);
2387 			}
2388 			break;
2389 		}
2390 	}
2391 	return (NULL);
2392 }
2393 
2394 /*
2395  * Crack a configuration file line
2396  */
2397 struct filed *
2398 cfline(char *line, char *progblock, char *hostblock)
2399 {
2400 	int i, pri;
2401 	size_t rb_len;
2402 	char *bp, *p, *q, *proto, *host, *port, *ipproto;
2403 	char buf[MAXLINE], ebuf[ERRBUFSIZE];
2404 	struct filed *xf, *f, *d;
2405 	struct timeval to;
2406 
2407 	logdebug("cfline(\"%s\", f, \"%s\", \"%s\")\n",
2408 	    line, progblock, hostblock);
2409 
2410 	if ((f = calloc(1, sizeof(*f))) == NULL) {
2411 		logerror("Couldn't allocate struct filed");
2412 		die(0);
2413 	}
2414 	for (i = 0; i <= LOG_NFACILITIES; i++)
2415 		f->f_pmask[i] = INTERNAL_NOPRI;
2416 
2417 	/* save program name if any */
2418 	f->f_quick = 0;
2419 	if (*progblock == '!') {
2420 		progblock++;
2421 		f->f_quick = 1;
2422 	}
2423 	if (*hostblock == '+') {
2424 		hostblock++;
2425 		f->f_quick = 1;
2426 	}
2427 	if (strcmp(progblock, "*") != 0)
2428 		f->f_program = strdup(progblock);
2429 	if (strcmp(hostblock, "*") != 0)
2430 		f->f_hostname = strdup(hostblock);
2431 
2432 	/* scan through the list of selectors */
2433 	for (p = line; *p && *p != '\t' && *p != ' ';) {
2434 
2435 		/* find the end of this facility name list */
2436 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2437 			continue;
2438 
2439 		/* collect priority name */
2440 		for (bp = buf; *q && !strchr("\t,; ", *q); )
2441 			*bp++ = *q++;
2442 		*bp = '\0';
2443 
2444 		/* skip cruft */
2445 		while (*q && strchr(",;", *q))
2446 			q++;
2447 
2448 		/* decode priority name */
2449 		if (*buf == '*')
2450 			pri = LOG_PRIMASK + 1;
2451 		else {
2452 			/* ignore trailing spaces */
2453 			for (i=strlen(buf)-1; i >= 0 && buf[i] == ' '; i--) {
2454 				buf[i]='\0';
2455 			}
2456 
2457 			pri = decode(buf, prioritynames);
2458 			if (pri < 0) {
2459 				(void)snprintf(ebuf, sizeof ebuf,
2460 				    "unknown priority name \"%s\"", buf);
2461 				logerrorx(ebuf);
2462 				free(f);
2463 				return (NULL);
2464 			}
2465 		}
2466 
2467 		/* scan facilities */
2468 		while (*p && !strchr("\t.; ", *p)) {
2469 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
2470 				*bp++ = *p++;
2471 			*bp = '\0';
2472 			if (*buf == '*')
2473 				for (i = 0; i < LOG_NFACILITIES; i++)
2474 					f->f_pmask[i] = pri;
2475 			else {
2476 				i = decode(buf, facilitynames);
2477 				if (i < 0) {
2478 					(void)snprintf(ebuf, sizeof(ebuf),
2479 					    "unknown facility name \"%s\"",
2480 					    buf);
2481 					logerrorx(ebuf);
2482 					free(f);
2483 					return (NULL);
2484 				}
2485 				f->f_pmask[i >> 3] = pri;
2486 			}
2487 			while (*p == ',' || *p == ' ')
2488 				p++;
2489 		}
2490 
2491 		p = q;
2492 	}
2493 
2494 	/* skip to action part */
2495 	while (*p == '\t' || *p == ' ')
2496 		p++;
2497 
2498 	switch (*p) {
2499 	case '@':
2500 		if ((strlcpy(f->f_un.f_forw.f_loghost, p,
2501 		    sizeof(f->f_un.f_forw.f_loghost)) >=
2502 		    sizeof(f->f_un.f_forw.f_loghost))) {
2503 			snprintf(ebuf, sizeof(ebuf), "loghost too long \"%s\"",
2504 			    p);
2505 			logerrorx(ebuf);
2506 			break;
2507 		}
2508 		if (loghost_parse(++p, &proto, &host, &port) == -1) {
2509 			snprintf(ebuf, sizeof(ebuf), "bad loghost \"%s\"",
2510 			    f->f_un.f_forw.f_loghost);
2511 			logerrorx(ebuf);
2512 			break;
2513 		}
2514 		if (proto == NULL)
2515 			proto = "udp";
2516 		ipproto = proto;
2517 		if (strcmp(proto, "udp") == 0) {
2518 			if (fd_udp == -1)
2519 				proto = "udp6";
2520 			if (fd_udp6 == -1)
2521 				proto = "udp4";
2522 			ipproto = proto;
2523 		} else if (strcmp(proto, "udp4") == 0) {
2524 			if (fd_udp == -1) {
2525 				snprintf(ebuf, sizeof(ebuf), "no udp4 \"%s\"",
2526 				    f->f_un.f_forw.f_loghost);
2527 				logerrorx(ebuf);
2528 				break;
2529 			}
2530 		} else if (strcmp(proto, "udp6") == 0) {
2531 			if (fd_udp6 == -1) {
2532 				snprintf(ebuf, sizeof(ebuf), "no udp6 \"%s\"",
2533 				    f->f_un.f_forw.f_loghost);
2534 				logerrorx(ebuf);
2535 				break;
2536 			}
2537 		} else if (strcmp(proto, "tcp") == 0 ||
2538 		    strcmp(proto, "tcp4") == 0 || strcmp(proto, "tcp6") == 0) {
2539 			;
2540 		} else if (strcmp(proto, "tls") == 0) {
2541 			ipproto = "tcp";
2542 		} else if (strcmp(proto, "tls4") == 0) {
2543 			ipproto = "tcp4";
2544 		} else if (strcmp(proto, "tls6") == 0) {
2545 			ipproto = "tcp6";
2546 		} else {
2547 			snprintf(ebuf, sizeof(ebuf), "bad protocol \"%s\"",
2548 			    f->f_un.f_forw.f_loghost);
2549 			logerrorx(ebuf);
2550 			break;
2551 		}
2552 		if (strlen(host) >= NI_MAXHOST) {
2553 			snprintf(ebuf, sizeof(ebuf), "host too long \"%s\"",
2554 			    f->f_un.f_forw.f_loghost);
2555 			logerrorx(ebuf);
2556 			break;
2557 		}
2558 		if (port == NULL)
2559 			port = strncmp(proto, "tls", 3) == 0 ?
2560 			    "syslog-tls" : "syslog";
2561 		if (strlen(port) >= NI_MAXSERV) {
2562 			snprintf(ebuf, sizeof(ebuf), "port too long \"%s\"",
2563 			    f->f_un.f_forw.f_loghost);
2564 			logerrorx(ebuf);
2565 			break;
2566 		}
2567 		if (priv_getaddrinfo(ipproto, host, port,
2568 		    (struct sockaddr*)&f->f_un.f_forw.f_addr,
2569 		    sizeof(f->f_un.f_forw.f_addr)) != 0) {
2570 			snprintf(ebuf, sizeof(ebuf), "bad hostname \"%s\"",
2571 			    f->f_un.f_forw.f_loghost);
2572 			logerrorx(ebuf);
2573 			break;
2574 		}
2575 		f->f_file = -1;
2576 		if (strncmp(proto, "udp", 3) == 0) {
2577 			switch (f->f_un.f_forw.f_addr.ss_family) {
2578 			case AF_INET:
2579 				f->f_file = fd_udp;
2580 				break;
2581 			case AF_INET6:
2582 				f->f_file = fd_udp6;
2583 				break;
2584 			}
2585 			f->f_type = F_FORWUDP;
2586 		} else if (strncmp(ipproto, "tcp", 3) == 0) {
2587 			if ((f->f_un.f_forw.f_bufev = bufferevent_new(-1,
2588 			    tcp_dropcb, tcp_writecb, tcp_errorcb, f)) == NULL) {
2589 				snprintf(ebuf, sizeof(ebuf),
2590 				    "bufferevent \"%s\"",
2591 				    f->f_un.f_forw.f_loghost);
2592 				logerror(ebuf);
2593 				break;
2594 			}
2595 			if (strncmp(proto, "tls", 3) == 0) {
2596 				f->f_un.f_forw.f_host = strdup(host);
2597 				f->f_type = F_FORWTLS;
2598 			} else {
2599 				f->f_type = F_FORWTCP;
2600 			}
2601 			/*
2602 			 * If we try to connect to a TLS server immediately
2603 			 * syslogd gets an SIGPIPE as the signal handlers have
2604 			 * not been set up.  Delay the connection until the
2605 			 * event loop is started.  We can reuse the write event
2606 			 * for that as bufferevent is still disabled.
2607 			 */
2608 			to.tv_sec = 0;
2609 			to.tv_usec = 1;
2610 			evtimer_set(&f->f_un.f_forw.f_bufev->ev_write,
2611 			    tcp_connectcb, f);
2612 			evtimer_add(&f->f_un.f_forw.f_bufev->ev_write, &to);
2613 		}
2614 		break;
2615 
2616 	case '/':
2617 	case '|':
2618 		(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2619 		d = find_dup(f);
2620 		if (d != NULL) {
2621 			for (i = 0; i <= LOG_NFACILITIES; i++)
2622 				if (f->f_pmask[i] != INTERNAL_NOPRI)
2623 					d->f_pmask[i] = f->f_pmask[i];
2624 			free(f);
2625 			return (NULL);
2626 		}
2627 		if (strcmp(p, ctty) == 0)
2628 			f->f_file = priv_open_tty(p);
2629 		else
2630 			f->f_file = priv_open_log(p);
2631 		if (f->f_file < 0) {
2632 			f->f_type = F_UNUSED;
2633 			logerror(p);
2634 			break;
2635 		}
2636 		if (isatty(f->f_file)) {
2637 			if (strcmp(p, ctty) == 0)
2638 				f->f_type = F_CONSOLE;
2639 			else
2640 				f->f_type = F_TTY;
2641 		} else {
2642 			if (*p == '|')
2643 				f->f_type = F_PIPE;
2644 			else {
2645 				f->f_type = F_FILE;
2646 
2647 				/* Clear O_NONBLOCK flag on f->f_file */
2648 				if ((i = fcntl(f->f_file, F_GETFL)) != -1) {
2649 					i &= ~O_NONBLOCK;
2650 					fcntl(f->f_file, F_SETFL, i);
2651 				}
2652 			}
2653 		}
2654 		break;
2655 
2656 	case '*':
2657 		f->f_type = F_WALL;
2658 		break;
2659 
2660 	case ':':
2661 		f->f_type = F_MEMBUF;
2662 
2663 		/* Parse buffer size (in kb) */
2664 		errno = 0;
2665 		rb_len = strtoul(++p, &q, 0);
2666 		if (*p == '\0' || (errno == ERANGE && rb_len == ULONG_MAX) ||
2667 		    *q != ':' || rb_len == 0) {
2668 			f->f_type = F_UNUSED;
2669 			logerror(p);
2670 			break;
2671 		}
2672 		q++;
2673 		rb_len *= 1024;
2674 
2675 		/* Copy buffer name */
2676 		for(i = 0; (size_t)i < sizeof(f->f_un.f_mb.f_mname) - 1; i++) {
2677 			if (!isalnum((unsigned char)q[i]))
2678 				break;
2679 			f->f_un.f_mb.f_mname[i] = q[i];
2680 		}
2681 
2682 		/* Make sure buffer name is unique */
2683 		xf = find_dup(f);
2684 
2685 		/* Error on missing or non-unique name, or bad buffer length */
2686 		if (i == 0 || rb_len > MAX_MEMBUF || xf != NULL) {
2687 			f->f_type = F_UNUSED;
2688 			logerrorx(p);
2689 			break;
2690 		}
2691 
2692 		/* Set buffer length */
2693 		rb_len = MAXIMUM(rb_len, MIN_MEMBUF);
2694 		f->f_un.f_mb.f_len = rb_len;
2695 		f->f_un.f_mb.f_overflow = 0;
2696 		f->f_un.f_mb.f_attached = 0;
2697 		break;
2698 
2699 	default:
2700 		for (i = 0; i < MAXUNAMES && *p; i++) {
2701 			for (q = p; *q && *q != ','; )
2702 				q++;
2703 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
2704 			if ((q - p) > UT_NAMESIZE)
2705 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2706 			else
2707 				f->f_un.f_uname[i][q - p] = '\0';
2708 			while (*q == ',' || *q == ' ')
2709 				q++;
2710 			p = q;
2711 		}
2712 		f->f_type = F_USERS;
2713 		break;
2714 	}
2715 	return (f);
2716 }
2717 
2718 /*
2719  * Parse the host and port parts from a loghost string.
2720  */
2721 int
2722 loghost_parse(char *str, char **proto, char **host, char **port)
2723 {
2724 	char *prefix = NULL;
2725 
2726 	if ((*host = strchr(str, ':')) &&
2727 	    (*host)[1] == '/' && (*host)[2] == '/') {
2728 		prefix = str;
2729 		**host = '\0';
2730 		str = *host + 3;
2731 	}
2732 	if (proto)
2733 		*proto = prefix;
2734 	else if (prefix)
2735 		return (-1);
2736 
2737 	*host = str;
2738 	if (**host == '[') {
2739 		(*host)++;
2740 		str = strchr(*host, ']');
2741 		if (str == NULL)
2742 			return (-1);
2743 		*str++ = '\0';
2744 	}
2745 	*port = strrchr(str, ':');
2746 	if (*port != NULL)
2747 		*(*port)++ = '\0';
2748 
2749 	return (0);
2750 }
2751 
2752 /*
2753  * Retrieve the size of the kernel message buffer, via sysctl.
2754  */
2755 int
2756 getmsgbufsize(void)
2757 {
2758 	int msgbufsize, mib[2];
2759 	size_t size;
2760 
2761 	mib[0] = CTL_KERN;
2762 	mib[1] = KERN_MSGBUFSIZE;
2763 	size = sizeof msgbufsize;
2764 	if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
2765 		logdebug("couldn't get kern.msgbufsize\n");
2766 		return (0);
2767 	}
2768 	return (msgbufsize);
2769 }
2770 
2771 /*
2772  *  Decode a symbolic name to a numeric value
2773  */
2774 int
2775 decode(const char *name, const CODE *codetab)
2776 {
2777 	const CODE *c;
2778 	char *p, buf[40];
2779 
2780 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2781 		if (isupper((unsigned char)*name))
2782 			*p = tolower((unsigned char)*name);
2783 		else
2784 			*p = *name;
2785 	}
2786 	*p = '\0';
2787 	for (c = codetab; c->c_name; c++)
2788 		if (!strcmp(buf, c->c_name))
2789 			return (c->c_val);
2790 
2791 	return (-1);
2792 }
2793 
2794 void
2795 markit(void)
2796 {
2797 	struct filed *f;
2798 
2799 	now = time(NULL);
2800 	MarkSeq += TIMERINTVL;
2801 	if (MarkSeq >= MarkInterval) {
2802 		logmsg(LOG_INFO, "-- MARK --",
2803 		    LocalHostName, ADDDATE|MARK);
2804 		MarkSeq = 0;
2805 	}
2806 
2807 	SIMPLEQ_FOREACH(f, &Files, f_next) {
2808 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2809 			logdebug("flush %s: repeated %d times, %d sec.\n",
2810 			    TypeNames[f->f_type], f->f_prevcount,
2811 			    repeatinterval[f->f_repeatcount]);
2812 			fprintlog(f, 0, (char *)NULL);
2813 			BACKOFF(f);
2814 		}
2815 	}
2816 }
2817 
2818 int
2819 unix_socket(char *path, int type, mode_t mode)
2820 {
2821 	struct sockaddr_un s_un;
2822 	char ebuf[512];
2823 	int fd, optval;
2824 	mode_t old_umask;
2825 
2826 	memset(&s_un, 0, sizeof(s_un));
2827 	s_un.sun_family = AF_UNIX;
2828 	if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
2829 	    sizeof(s_un.sun_path)) {
2830 		snprintf(ebuf, sizeof(ebuf), "socket path too long: %s", path);
2831 		logerrorx(ebuf);
2832 		die(0);
2833 	}
2834 
2835 	if ((fd = socket(AF_UNIX, type, 0)) == -1) {
2836 		logerror("socket");
2837 		return (-1);
2838 	}
2839 
2840 	if (Debug) {
2841 		if (connect(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == 0 ||
2842 		    errno == EPROTOTYPE) {
2843 			close(fd);
2844 			errno = EISCONN;
2845 			logerror("connect");
2846 			return (-1);
2847 		}
2848 	}
2849 
2850 	old_umask = umask(0177);
2851 
2852 	unlink(path);
2853 	if (bind(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) {
2854 		snprintf(ebuf, sizeof(ebuf), "cannot bind %s", path);
2855 		logerror(ebuf);
2856 		umask(old_umask);
2857 		close(fd);
2858 		return (-1);
2859 	}
2860 
2861 	umask(old_umask);
2862 
2863 	if (chmod(path, mode) == -1) {
2864 		snprintf(ebuf, sizeof(ebuf), "cannot chmod %s", path);
2865 		logerror(ebuf);
2866 		close(fd);
2867 		unlink(path);
2868 		return (-1);
2869 	}
2870 
2871 	optval = MAXLINE + PATH_MAX;
2872 	if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval))
2873 	    == -1)
2874 		logerror("setsockopt unix");
2875 
2876 	return (fd);
2877 }
2878 
2879 void
2880 double_sockbuf(int fd, int optname)
2881 {
2882 	socklen_t len;
2883 	int i, newsize, oldsize = 0;
2884 
2885 	len = sizeof(oldsize);
2886 	if (getsockopt(fd, SOL_SOCKET, optname, &oldsize, &len) == -1)
2887 		logerror("getsockopt bufsize");
2888 	len = sizeof(newsize);
2889 	newsize =  MAXLINE + 128;  /* data + control */
2890 	/* allow 8 full length messages */
2891 	for (i = 0; i < 4; i++, newsize *= 2) {
2892 		if (newsize <= oldsize)
2893 			continue;
2894 		if (setsockopt(fd, SOL_SOCKET, optname, &newsize, len) == -1)
2895 			logerror("setsockopt bufsize");
2896 	}
2897 }
2898 
2899 void
2900 ctlconn_cleanup(void)
2901 {
2902 	struct filed *f;
2903 
2904 	if (close(fd_ctlconn) == -1)
2905 		logerror("close ctlconn");
2906 	fd_ctlconn = -1;
2907 	event_del(ev_ctlread);
2908 	event_del(ev_ctlwrite);
2909 	event_add(ev_ctlaccept, NULL);
2910 
2911 	if (ctl_state == CTL_WRITING_CONT_REPLY)
2912 		SIMPLEQ_FOREACH(f, &Files, f_next)
2913 			if (f->f_type == F_MEMBUF)
2914 				f->f_un.f_mb.f_attached = 0;
2915 
2916 	ctl_state = ctl_cmd_bytes = ctl_reply_offset = ctl_reply_size = 0;
2917 }
2918 
2919 void
2920 ctlsock_acceptcb(int fd, short event, void *arg)
2921 {
2922 	struct event		*ev = arg;
2923 
2924 	if ((fd = reserve_accept4(fd, event, ev, ctlsock_acceptcb,
2925 	    NULL, NULL, SOCK_NONBLOCK)) == -1) {
2926 		if (errno != ENFILE && errno != EMFILE &&
2927 		    errno != EINTR && errno != EWOULDBLOCK &&
2928 		    errno != ECONNABORTED)
2929 			logerror("accept ctlsock");
2930 		return;
2931 	}
2932 	logdebug("Accepting control connection\n");
2933 
2934 	if (fd_ctlconn != -1)
2935 		ctlconn_cleanup();
2936 
2937 	/* Only one connection at a time */
2938 	event_del(ev);
2939 
2940 	fd_ctlconn = fd;
2941 	/* file descriptor has changed, reset event */
2942 	event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST,
2943 	    ctlconn_readcb, ev_ctlread);
2944 	event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST,
2945 	    ctlconn_writecb, ev_ctlwrite);
2946 	event_add(ev_ctlread, NULL);
2947 	ctl_state = CTL_READING_CMD;
2948 	ctl_cmd_bytes = 0;
2949 }
2950 
2951 static struct filed
2952 *find_membuf_log(const char *name)
2953 {
2954 	struct filed *f;
2955 
2956 	SIMPLEQ_FOREACH(f, &Files, f_next) {
2957 		if (f->f_type == F_MEMBUF &&
2958 		    strcmp(f->f_un.f_mb.f_mname, name) == 0)
2959 			break;
2960 	}
2961 	return (f);
2962 }
2963 
2964 void
2965 ctlconn_readcb(int fd, short event, void *arg)
2966 {
2967 	struct filed		*f;
2968 	struct ctl_reply_hdr	*reply_hdr = (struct ctl_reply_hdr *)ctl_reply;
2969 	ssize_t			 n;
2970 	u_int32_t		 flags = 0;
2971 
2972 	if (ctl_state == CTL_WRITING_REPLY ||
2973 	    ctl_state == CTL_WRITING_CONT_REPLY) {
2974 		/* client has closed the connection */
2975 		ctlconn_cleanup();
2976 		return;
2977 	}
2978 
2979  retry:
2980 	n = read(fd, (char*)&ctl_cmd + ctl_cmd_bytes,
2981 	    sizeof(ctl_cmd) - ctl_cmd_bytes);
2982 	switch (n) {
2983 	case -1:
2984 		if (errno == EINTR)
2985 			goto retry;
2986 		if (errno == EWOULDBLOCK)
2987 			return;
2988 		logerror("ctlconn read");
2989 		/* FALLTHROUGH */
2990 	case 0:
2991 		ctlconn_cleanup();
2992 		return;
2993 	default:
2994 		ctl_cmd_bytes += n;
2995 	}
2996 	if (ctl_cmd_bytes < sizeof(ctl_cmd))
2997 		return;
2998 
2999 	if (ntohl(ctl_cmd.version) != CTL_VERSION) {
3000 		logerrorx("Unknown client protocol version");
3001 		ctlconn_cleanup();
3002 		return;
3003 	}
3004 
3005 	/* Ensure that logname is \0 terminated */
3006 	if (memchr(ctl_cmd.logname, '\0', sizeof(ctl_cmd.logname)) == NULL) {
3007 		logerrorx("Corrupt ctlsock command");
3008 		ctlconn_cleanup();
3009 		return;
3010 	}
3011 
3012 	*reply_text = '\0';
3013 
3014 	ctl_reply_size = ctl_reply_offset = 0;
3015 	memset(reply_hdr, '\0', sizeof(*reply_hdr));
3016 
3017 	ctl_cmd.cmd = ntohl(ctl_cmd.cmd);
3018 	logdebug("ctlcmd %x logname \"%s\"\n", ctl_cmd.cmd, ctl_cmd.logname);
3019 
3020 	switch (ctl_cmd.cmd) {
3021 	case CMD_READ:
3022 	case CMD_READ_CLEAR:
3023 	case CMD_READ_CONT:
3024 	case CMD_FLAGS:
3025 		f = find_membuf_log(ctl_cmd.logname);
3026 		if (f == NULL) {
3027 			strlcpy(reply_text, "No such log\n", MAX_MEMBUF);
3028 		} else {
3029 			if (ctl_cmd.cmd != CMD_FLAGS) {
3030 				ringbuf_to_string(reply_text, MAX_MEMBUF,
3031 				    f->f_un.f_mb.f_rb);
3032 			}
3033 			if (f->f_un.f_mb.f_overflow)
3034 				flags |= CTL_HDR_FLAG_OVERFLOW;
3035 			if (ctl_cmd.cmd == CMD_READ_CLEAR) {
3036 				ringbuf_clear(f->f_un.f_mb.f_rb);
3037 				f->f_un.f_mb.f_overflow = 0;
3038 			}
3039 			if (ctl_cmd.cmd == CMD_READ_CONT) {
3040 				f->f_un.f_mb.f_attached = 1;
3041 				tailify_replytext(reply_text,
3042 				    ctl_cmd.lines > 0 ? ctl_cmd.lines : 10);
3043 			} else if (ctl_cmd.lines > 0) {
3044 				tailify_replytext(reply_text, ctl_cmd.lines);
3045 			}
3046 		}
3047 		break;
3048 	case CMD_CLEAR:
3049 		f = find_membuf_log(ctl_cmd.logname);
3050 		if (f == NULL) {
3051 			strlcpy(reply_text, "No such log\n", MAX_MEMBUF);
3052 		} else {
3053 			ringbuf_clear(f->f_un.f_mb.f_rb);
3054 			if (f->f_un.f_mb.f_overflow)
3055 				flags |= CTL_HDR_FLAG_OVERFLOW;
3056 			f->f_un.f_mb.f_overflow = 0;
3057 			strlcpy(reply_text, "Log cleared\n", MAX_MEMBUF);
3058 		}
3059 		break;
3060 	case CMD_LIST:
3061 		SIMPLEQ_FOREACH(f, &Files, f_next) {
3062 			if (f->f_type == F_MEMBUF) {
3063 				strlcat(reply_text, f->f_un.f_mb.f_mname,
3064 				    MAX_MEMBUF);
3065 				if (f->f_un.f_mb.f_overflow) {
3066 					strlcat(reply_text, "*", MAX_MEMBUF);
3067 					flags |= CTL_HDR_FLAG_OVERFLOW;
3068 				}
3069 				strlcat(reply_text, " ", MAX_MEMBUF);
3070 			}
3071 		}
3072 		strlcat(reply_text, "\n", MAX_MEMBUF);
3073 		break;
3074 	default:
3075 		logerrorx("Unsupported ctlsock command");
3076 		ctlconn_cleanup();
3077 		return;
3078 	}
3079 	reply_hdr->version = htonl(CTL_VERSION);
3080 	reply_hdr->flags = htonl(flags);
3081 
3082 	ctl_reply_size = CTL_REPLY_SIZE;
3083 	logdebug("ctlcmd reply length %lu\n", (u_long)ctl_reply_size);
3084 
3085 	/* Otherwise, set up to write out reply */
3086 	ctl_state = (ctl_cmd.cmd == CMD_READ_CONT) ?
3087 	    CTL_WRITING_CONT_REPLY : CTL_WRITING_REPLY;
3088 
3089 	event_add(ev_ctlwrite, NULL);
3090 
3091 	/* another syslogc can kick us out */
3092 	if (ctl_state == CTL_WRITING_CONT_REPLY)
3093 		event_add(ev_ctlaccept, NULL);
3094 }
3095 
3096 void
3097 ctlconn_writecb(int fd, short event, void *arg)
3098 {
3099 	struct event		*ev = arg;
3100 	ssize_t			 n;
3101 
3102 	if (!(ctl_state == CTL_WRITING_REPLY ||
3103 	    ctl_state == CTL_WRITING_CONT_REPLY)) {
3104 		/* Shouldn't be here! */
3105 		logerrorx("ctlconn_write with bad ctl_state");
3106 		ctlconn_cleanup();
3107 		return;
3108 	}
3109 
3110  retry:
3111 	n = write(fd, ctl_reply + ctl_reply_offset,
3112 	    ctl_reply_size - ctl_reply_offset);
3113 	switch (n) {
3114 	case -1:
3115 		if (errno == EINTR)
3116 			goto retry;
3117 		if (errno == EWOULDBLOCK)
3118 			return;
3119 		if (errno != EPIPE)
3120 			logerror("ctlconn write");
3121 		/* FALLTHROUGH */
3122 	case 0:
3123 		ctlconn_cleanup();
3124 		return;
3125 	default:
3126 		ctl_reply_offset += n;
3127 	}
3128 	if (ctl_reply_offset < ctl_reply_size)
3129 		return;
3130 
3131 	if (ctl_state != CTL_WRITING_CONT_REPLY) {
3132 		ctlconn_cleanup();
3133 		return;
3134 	}
3135 
3136 	/*
3137 	 * Make space in the buffer for continous writes.
3138 	 * Set offset behind reply header to skip it
3139 	 */
3140 	*reply_text = '\0';
3141 	ctl_reply_offset = ctl_reply_size = CTL_REPLY_SIZE;
3142 
3143 	/* Now is a good time to report dropped lines */
3144 	if (membuf_drop) {
3145 		strlcat(reply_text, "<ENOBUFS>\n", MAX_MEMBUF);
3146 		ctl_reply_size = CTL_REPLY_SIZE;
3147 		membuf_drop = 0;
3148 	} else {
3149 		/* Nothing left to write */
3150 		event_del(ev);
3151 	}
3152 }
3153 
3154 /* Shorten replytext to number of lines */
3155 void
3156 tailify_replytext(char *replytext, int lines)
3157 {
3158 	char *start, *nl;
3159 	int count = 0;
3160 	start = nl = replytext;
3161 
3162 	while ((nl = strchr(nl, '\n')) != NULL) {
3163 		nl++;
3164 		if (++count > lines) {
3165 			start = strchr(start, '\n');
3166 			start++;
3167 		}
3168 	}
3169 	if (start != replytext) {
3170 		int len = strlen(start);
3171 		memmove(replytext, start, len);
3172 		*(replytext + len) = '\0';
3173 	}
3174 }
3175 
3176 void
3177 ctlconn_logto(char *line)
3178 {
3179 	size_t l;
3180 
3181 	if (membuf_drop)
3182 		return;
3183 
3184 	l = strlen(line);
3185 	if (l + 2 > (CTL_REPLY_MAXSIZE - ctl_reply_size)) {
3186 		/* remember line drops for later report */
3187 		membuf_drop = 1;
3188 		return;
3189 	}
3190 	memcpy(ctl_reply + ctl_reply_size, line, l);
3191 	memcpy(ctl_reply + ctl_reply_size + l, "\n", 2);
3192 	ctl_reply_size += l + 1;
3193 	event_add(ev_ctlwrite, NULL);
3194 }
3195