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