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