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