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