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