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