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