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