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