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