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