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