xref: /freebsd-12.1/usr.sbin/syslogd/syslogd.c (revision 047a2ef6)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1988, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 /*-
32  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
33  *
34  * Copyright (c) 2018 Prodrive Technologies, https://prodrive-technologies.com/
35  * Author: Ed Schouten <[email protected]>
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  */
58 
59 #ifndef lint
60 static const char copyright[] =
61 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
62 	The Regents of the University of California.  All rights reserved.\n";
63 #endif /* not lint */
64 
65 #ifndef lint
66 #if 0
67 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
68 #endif
69 #endif /* not lint */
70 
71 #include <sys/cdefs.h>
72 __FBSDID("$FreeBSD$");
73 
74 /*
75  *  syslogd -- log system messages
76  *
77  * This program implements a system log. It takes a series of lines.
78  * Each line may have a priority, signified as "<n>" as
79  * the first characters of the line.  If this is
80  * not present, a default priority is used.
81  *
82  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
83  * cause it to reread its configuration file.
84  *
85  * Defined Constants:
86  *
87  * MAXLINE -- the maximum line length that can be handled.
88  * DEFUPRI -- the default priority for user messages
89  * DEFSPRI -- the default priority for kernel messages
90  *
91  * Author: Eric Allman
92  * extensive changes by Ralph Campbell
93  * more extensive changes by Eric Allman (again)
94  * Extension to log by program name as well as facility and priority
95  *   by Peter da Silva.
96  * -u and -v by Harlan Stenn.
97  * Priority comparison code by Harlan Stenn.
98  */
99 
100 /* Maximum number of characters in time of last occurrence */
101 #define	MAXLINE		2048		/* maximum line length */
102 #define	MAXSVLINE	MAXLINE		/* maximum saved line length */
103 #define	DEFUPRI		(LOG_USER|LOG_NOTICE)
104 #define	DEFSPRI		(LOG_KERN|LOG_CRIT)
105 #define	TIMERINTVL	30		/* interval for checking flush, mark */
106 #define	TTYMSGTIME	1		/* timeout passed to ttymsg */
107 #define	RCVBUF_MINSIZE	(80 * 1024)	/* minimum size of dgram rcv buffer */
108 
109 #include <sys/param.h>
110 #include <sys/ioctl.h>
111 #include <sys/mman.h>
112 #include <sys/queue.h>
113 #include <sys/resource.h>
114 #include <sys/socket.h>
115 #include <sys/stat.h>
116 #include <sys/syslimits.h>
117 #include <sys/time.h>
118 #include <sys/uio.h>
119 #include <sys/un.h>
120 #include <sys/wait.h>
121 
122 #if defined(INET) || defined(INET6)
123 #include <netinet/in.h>
124 #include <arpa/inet.h>
125 #endif
126 
127 #include <assert.h>
128 #include <ctype.h>
129 #include <dirent.h>
130 #include <err.h>
131 #include <errno.h>
132 #include <fcntl.h>
133 #include <fnmatch.h>
134 #include <libutil.h>
135 #include <limits.h>
136 #include <netdb.h>
137 #include <paths.h>
138 #include <signal.h>
139 #include <stdio.h>
140 #include <stdlib.h>
141 #include <string.h>
142 #include <sysexits.h>
143 #include <unistd.h>
144 #include <utmpx.h>
145 
146 #include "pathnames.h"
147 #include "ttymsg.h"
148 
149 #define SYSLOG_NAMES
150 #include <sys/syslog.h>
151 
152 static const char *ConfFile = _PATH_LOGCONF;
153 static const char *PidFile = _PATH_LOGPID;
154 static const char ctty[] = _PATH_CONSOLE;
155 static const char include_str[] = "include";
156 static const char include_ext[] = ".conf";
157 
158 #define	dprintf		if (Debug) printf
159 
160 #define	MAXUNAMES	20	/* maximum number of user names */
161 
162 #define	sstosa(ss)	((struct sockaddr *)(ss))
163 #ifdef INET
164 #define	sstosin(ss)	((struct sockaddr_in *)(void *)(ss))
165 #define	satosin(sa)	((struct sockaddr_in *)(void *)(sa))
166 #endif
167 #ifdef INET6
168 #define	sstosin6(ss)	((struct sockaddr_in6 *)(void *)(ss))
169 #define	satosin6(sa)	((struct sockaddr_in6 *)(void *)(sa))
170 #define	s6_addr32	__u6_addr.__u6_addr32
171 #define	IN6_ARE_MASKED_ADDR_EQUAL(d, a, m)	(	\
172 	(((d)->s6_addr32[0] ^ (a)->s6_addr32[0]) & (m)->s6_addr32[0]) == 0 && \
173 	(((d)->s6_addr32[1] ^ (a)->s6_addr32[1]) & (m)->s6_addr32[1]) == 0 && \
174 	(((d)->s6_addr32[2] ^ (a)->s6_addr32[2]) & (m)->s6_addr32[2]) == 0 && \
175 	(((d)->s6_addr32[3] ^ (a)->s6_addr32[3]) & (m)->s6_addr32[3]) == 0 )
176 #endif
177 /*
178  * List of peers and sockets for binding.
179  */
180 struct peer {
181 	const char	*pe_name;
182 	const char	*pe_serv;
183 	mode_t		pe_mode;
184 	STAILQ_ENTRY(peer)	next;
185 };
186 static STAILQ_HEAD(, peer) pqueue = STAILQ_HEAD_INITIALIZER(pqueue);
187 
188 struct socklist {
189 	struct sockaddr_storage	sl_ss;
190 	int			sl_socket;
191 	struct peer		*sl_peer;
192 	int			(*sl_recv)(struct socklist *);
193 	STAILQ_ENTRY(socklist)	next;
194 };
195 static STAILQ_HEAD(, socklist) shead = STAILQ_HEAD_INITIALIZER(shead);
196 
197 /*
198  * Flags to logmsg().
199  */
200 
201 #define	IGN_CONS	0x001	/* don't print on console */
202 #define	SYNC_FILE	0x002	/* do fsync on file after printing */
203 #define	MARK		0x008	/* this message is a mark */
204 
205 /* Timestamps of log entries. */
206 struct logtime {
207 	struct tm	tm;
208 	suseconds_t	usec;
209 };
210 
211 /* Traditional syslog timestamp format. */
212 #define	RFC3164_DATELEN	15
213 #define	RFC3164_DATEFMT	"%b %e %H:%M:%S"
214 
215 /*
216  * This structure represents the files that will have log
217  * copies printed.
218  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
219  * or if f_type is F_PIPE and f_pid > 0.
220  */
221 
222 struct filed {
223 	STAILQ_ENTRY(filed)	next;	/* next in linked list */
224 	short	f_type;			/* entry type, see below */
225 	short	f_file;			/* file descriptor */
226 	time_t	f_time;			/* time this was last written */
227 	char	*f_host;		/* host from which to recd. */
228 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
229 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
230 #define PRI_LT	0x1
231 #define PRI_EQ	0x2
232 #define PRI_GT	0x4
233 	char	*f_program;		/* program this applies to */
234 	union {
235 		char	f_uname[MAXUNAMES][MAXLOGNAME];
236 		struct {
237 			char	f_hname[MAXHOSTNAMELEN];
238 			struct addrinfo *f_addr;
239 
240 		} f_forw;		/* forwarding address */
241 		char	f_fname[MAXPATHLEN];
242 		struct {
243 			char	f_pname[MAXPATHLEN];
244 			pid_t	f_pid;
245 		} f_pipe;
246 	} f_un;
247 #define	fu_uname	f_un.f_uname
248 #define	fu_forw_hname	f_un.f_forw.f_hname
249 #define	fu_forw_addr	f_un.f_forw.f_addr
250 #define	fu_fname	f_un.f_fname
251 #define	fu_pipe_pname	f_un.f_pipe.f_pname
252 #define	fu_pipe_pid	f_un.f_pipe.f_pid
253 	char	f_prevline[MAXSVLINE];		/* last message logged */
254 	struct logtime f_lasttime;		/* time of last occurrence */
255 	int	f_prevpri;			/* pri of f_prevline */
256 	size_t	f_prevlen;			/* length of f_prevline */
257 	int	f_prevcount;			/* repetition cnt of prevline */
258 	u_int	f_repeatcount;			/* number of "repeated" msgs */
259 	int	f_flags;			/* file-specific flags */
260 #define	FFLAG_SYNC 0x01
261 #define	FFLAG_NEEDSYNC	0x02
262 };
263 
264 /*
265  * Queue of about-to-be dead processes we should watch out for.
266  */
267 struct deadq_entry {
268 	pid_t				dq_pid;
269 	int				dq_timeout;
270 	TAILQ_ENTRY(deadq_entry)	dq_entries;
271 };
272 static TAILQ_HEAD(, deadq_entry) deadq_head =
273     TAILQ_HEAD_INITIALIZER(deadq_head);
274 
275 /*
276  * The timeout to apply to processes waiting on the dead queue.  Unit
277  * of measure is `mark intervals', i.e. 20 minutes by default.
278  * Processes on the dead queue will be terminated after that time.
279  */
280 
281 #define	 DQ_TIMO_INIT	2
282 
283 /*
284  * Struct to hold records of network addresses that are allowed to log
285  * to us.
286  */
287 struct allowedpeer {
288 	int isnumeric;
289 	u_short port;
290 	union {
291 		struct {
292 			struct sockaddr_storage addr;
293 			struct sockaddr_storage mask;
294 		} numeric;
295 		char *name;
296 	} u;
297 #define a_addr u.numeric.addr
298 #define a_mask u.numeric.mask
299 #define a_name u.name
300 	STAILQ_ENTRY(allowedpeer)	next;
301 };
302 static STAILQ_HEAD(, allowedpeer) aphead = STAILQ_HEAD_INITIALIZER(aphead);
303 
304 
305 /*
306  * Intervals at which we flush out "message repeated" messages,
307  * in seconds after previous message is logged.  After each flush,
308  * we move to the next interval until we reach the largest.
309  */
310 static int repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
311 #define	MAXREPEAT	(nitems(repeatinterval) - 1)
312 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
313 #define	BACKOFF(f)	do {						\
314 				if (++(f)->f_repeatcount > MAXREPEAT)	\
315 					(f)->f_repeatcount = MAXREPEAT;	\
316 			} while (0)
317 
318 /* values for f_type */
319 #define F_UNUSED	0		/* unused entry */
320 #define F_FILE		1		/* regular file */
321 #define F_TTY		2		/* terminal */
322 #define F_CONSOLE	3		/* console terminal */
323 #define F_FORW		4		/* remote machine */
324 #define F_USERS		5		/* list of users */
325 #define F_WALL		6		/* everyone logged on */
326 #define F_PIPE		7		/* pipe to program */
327 
328 static const char *TypeNames[] = {
329 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
330 	"FORW",		"USERS",	"WALL",		"PIPE"
331 };
332 
333 static STAILQ_HEAD(, filed) fhead =
334     STAILQ_HEAD_INITIALIZER(fhead);	/* Log files that we write to */
335 static struct filed consfile;	/* Console */
336 
337 static int	Debug;		/* debug flag */
338 static int	Foreground = 0;	/* Run in foreground, instead of daemonizing */
339 static int	resolve = 1;	/* resolve hostname */
340 static char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
341 static const char *LocalDomain;	/* our local domain name */
342 static int	Initialized;	/* set when we have initialized ourselves */
343 static int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
344 static int	MarkSeq;	/* mark sequence number */
345 static int	NoBind;		/* don't bind() as suggested by RFC 3164 */
346 static int	SecureMode;	/* when true, receive only unix domain socks */
347 #ifdef INET6
348 static int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
349 #else
350 static int	family = PF_INET; /* protocol family (IPv4 only) */
351 #endif
352 static int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
353 static int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
354 static int	use_bootfile;	/* log entire bootfile for every kern msg */
355 static int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
356 static int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
357 
358 static char	bootfile[MAXLINE+1]; /* booted kernel file */
359 
360 static int	RemoteAddDate;	/* Always set the date on remote messages */
361 static int	RemoteHostname;	/* Log remote hostname from the message */
362 
363 static int	UniquePriority;	/* Only log specified priority? */
364 static int	LogFacPri;	/* Put facility and priority in log message: */
365 				/* 0=no, 1=numeric, 2=names */
366 static int	KeepKernFac;	/* Keep remotely logged kernel facility */
367 static int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
368 static struct pidfh *pfh;
369 static int	sigpipe[2];	/* Pipe to catch a signal during select(). */
370 
371 static volatile sig_atomic_t MarkSet, WantDie, WantInitialize, WantReapchild;
372 
373 static int	allowaddr(char *);
374 static int	addfile(struct filed *);
375 static int	addpeer(struct peer *);
376 static int	addsock(struct sockaddr *, socklen_t, struct socklist *);
377 static struct filed *cfline(const char *, const char *, const char *);
378 static const char *cvthname(struct sockaddr *);
379 static void	deadq_enter(pid_t, const char *);
380 static int	deadq_remove(struct deadq_entry *);
381 static int	deadq_removebypid(pid_t);
382 static int	decode(const char *, const CODE *);
383 static void	die(int) __dead2;
384 static void	dodie(int);
385 static void	dofsync(void);
386 static void	domark(int);
387 static void	fprintlog_first(struct filed *, const char *, const char *,
388     const char *, const char *, const char *, const char *, int);
389 static void	fprintlog_successive(struct filed *, int);
390 static void	init(int);
391 static void	logerror(const char *);
392 static void	logmsg(int, const struct logtime *, const char *, const char *,
393     const char *, const char *, const char *, const char *, int);
394 static void	log_deadchild(pid_t, int, const char *);
395 static void	markit(void);
396 static int	socksetup(struct peer *);
397 static int	socklist_recv_file(struct socklist *);
398 static int	socklist_recv_sock(struct socklist *);
399 static int	socklist_recv_signal(struct socklist *);
400 static void	sighandler(int);
401 static int	skip_message(const char *, const char *, int);
402 static void	parsemsg(const char *, char *);
403 static void	printsys(char *);
404 static int	p_open(const char *, pid_t *);
405 static void	reapchild(int);
406 static const char *ttymsg_check(struct iovec *, int, char *, int);
407 static void	usage(void);
408 static int	validate(struct sockaddr *, const char *);
409 static void	unmapped(struct sockaddr *);
410 static void	wallmsg(struct filed *, struct iovec *, const int iovlen);
411 static int	waitdaemon(int);
412 static void	timedout(int);
413 static void	increase_rcvbuf(int);
414 
415 static void
416 close_filed(struct filed *f)
417 {
418 
419 	if (f == NULL || f->f_file == -1)
420 		return;
421 
422 	switch (f->f_type) {
423 	case F_FORW:
424 		if (f->f_un.f_forw.f_addr) {
425 			freeaddrinfo(f->f_un.f_forw.f_addr);
426 			f->f_un.f_forw.f_addr = NULL;
427 		}
428 		/* FALLTHROUGH */
429 
430 	case F_FILE:
431 	case F_TTY:
432 	case F_CONSOLE:
433 		f->f_type = F_UNUSED;
434 		break;
435 	case F_PIPE:
436 		f->fu_pipe_pid = 0;
437 		break;
438 	}
439 	(void)close(f->f_file);
440 	f->f_file = -1;
441 }
442 
443 static int
444 addfile(struct filed *f0)
445 {
446 	struct filed *f;
447 
448 	f = calloc(1, sizeof(*f));
449 	if (f == NULL)
450 		err(1, "malloc failed");
451 	*f = *f0;
452 	STAILQ_INSERT_TAIL(&fhead, f, next);
453 
454 	return (0);
455 }
456 
457 static int
458 addpeer(struct peer *pe0)
459 {
460 	struct peer *pe;
461 
462 	pe = calloc(1, sizeof(*pe));
463 	if (pe == NULL)
464 		err(1, "malloc failed");
465 	*pe = *pe0;
466 	STAILQ_INSERT_TAIL(&pqueue, pe, next);
467 
468 	return (0);
469 }
470 
471 static int
472 addsock(struct sockaddr *sa, socklen_t sa_len, struct socklist *sl0)
473 {
474 	struct socklist *sl;
475 
476 	sl = calloc(1, sizeof(*sl));
477 	if (sl == NULL)
478 		err(1, "malloc failed");
479 	*sl = *sl0;
480 	if (sa != NULL && sa_len > 0)
481 		memcpy(&sl->sl_ss, sa, sa_len);
482 	STAILQ_INSERT_TAIL(&shead, sl, next);
483 
484 	return (0);
485 }
486 
487 int
488 main(int argc, char *argv[])
489 {
490 	int ch, i, s, fdsrmax = 0, bflag = 0, pflag = 0, Sflag = 0;
491 	fd_set *fdsr = NULL;
492 	struct timeval tv, *tvp;
493 	struct peer *pe;
494 	struct socklist *sl;
495 	pid_t ppid = 1, spid;
496 	char *p;
497 
498 	if (madvise(NULL, 0, MADV_PROTECT) != 0)
499 		dprintf("madvise() failed: %s\n", strerror(errno));
500 
501 	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:FHkl:m:nNop:P:sS:Tuv"))
502 	    != -1)
503 		switch (ch) {
504 #ifdef INET
505 		case '4':
506 			family = PF_INET;
507 			break;
508 #endif
509 #ifdef INET6
510 		case '6':
511 			family = PF_INET6;
512 			break;
513 #endif
514 		case '8':
515 			mask_C1 = 0;
516 			break;
517 		case 'A':
518 			send_to_all++;
519 			break;
520 		case 'a':		/* allow specific network addresses only */
521 			if (allowaddr(optarg) == -1)
522 				usage();
523 			break;
524 		case 'b':
525 			bflag = 1;
526 			p = strchr(optarg, ']');
527 			if (p != NULL)
528 				p = strchr(p + 1, ':');
529 			else {
530 				p = strchr(optarg, ':');
531 				if (p != NULL && strchr(p + 1, ':') != NULL)
532 					p = NULL; /* backward compatibility */
533 			}
534 			if (p == NULL) {
535 				/* A hostname or filename only. */
536 				addpeer(&(struct peer){
537 					.pe_name = optarg,
538 					.pe_serv = "syslog"
539 				});
540 			} else {
541 				/* The case of "name:service". */
542 				*p++ = '\0';
543 				addpeer(&(struct peer){
544 					.pe_serv = p,
545 					.pe_name = (strlen(optarg) == 0) ?
546 					    NULL : optarg,
547 				});
548 			}
549 			break;
550 		case 'c':
551 			no_compress++;
552 			break;
553 		case 'C':
554 			logflags |= O_CREAT;
555 			break;
556 		case 'd':		/* debug */
557 			Debug++;
558 			break;
559 		case 'f':		/* configuration file */
560 			ConfFile = optarg;
561 			break;
562 		case 'F':		/* run in foreground instead of daemon */
563 			Foreground++;
564 			break;
565 		case 'H':
566 			RemoteHostname = 1;
567 			break;
568 		case 'k':		/* keep remote kern fac */
569 			KeepKernFac = 1;
570 			break;
571 		case 'l':
572 		case 'p':
573 		case 'S':
574 		    {
575 			long	perml;
576 			mode_t	mode;
577 			char	*name, *ep;
578 
579 			if (ch == 'l')
580 				mode = DEFFILEMODE;
581 			else if (ch == 'p') {
582 				mode = DEFFILEMODE;
583 				pflag = 1;
584 			} else if (ch == 'S') {
585 				mode = S_IRUSR | S_IWUSR;
586 				Sflag = 1;
587 			}
588 			if (optarg[0] == '/')
589 				name = optarg;
590 			else if ((name = strchr(optarg, ':')) != NULL) {
591 				*name++ = '\0';
592 				if (name[0] != '/')
593 					errx(1, "socket name must be absolute "
594 					    "path");
595 				if (isdigit(*optarg)) {
596 					perml = strtol(optarg, &ep, 8);
597 				    if (*ep || perml < 0 ||
598 					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
599 					    errx(1, "invalid mode %s, exiting",
600 						optarg);
601 				    mode = (mode_t )perml;
602 				} else
603 					errx(1, "invalid mode %s, exiting",
604 					    optarg);
605 			} else
606 				errx(1, "invalid filename %s, exiting",
607 				    optarg);
608 			addpeer(&(struct peer){
609 				.pe_name = name,
610 				.pe_mode = mode
611 			});
612 			break;
613 		   }
614 		case 'm':		/* mark interval */
615 			MarkInterval = atoi(optarg) * 60;
616 			break;
617 		case 'N':
618 			NoBind = 1;
619 			SecureMode = 1;
620 			break;
621 		case 'n':
622 			resolve = 0;
623 			break;
624 		case 'o':
625 			use_bootfile = 1;
626 			break;
627 		case 'P':		/* path for alt. PID */
628 			PidFile = optarg;
629 			break;
630 		case 's':		/* no network mode */
631 			SecureMode++;
632 			break;
633 		case 'T':
634 			RemoteAddDate = 1;
635 			break;
636 		case 'u':		/* only log specified priority */
637 			UniquePriority++;
638 			break;
639 		case 'v':		/* log facility and priority */
640 		  	LogFacPri++;
641 			break;
642 		default:
643 			usage();
644 		}
645 	if ((argc -= optind) != 0)
646 		usage();
647 
648 	/* Pipe to catch a signal during select(). */
649 	s = pipe2(sigpipe, O_CLOEXEC);
650 	if (s < 0) {
651 		err(1, "cannot open a pipe for signals");
652 	} else {
653 		addsock(NULL, 0, &(struct socklist){
654 		    .sl_socket = sigpipe[0],
655 		    .sl_recv = socklist_recv_signal
656 		});
657 	}
658 
659 	/* Listen by default: /dev/klog. */
660 	s = open(_PATH_KLOG, O_RDONLY | O_NONBLOCK | O_CLOEXEC, 0);
661 	if (s < 0) {
662 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
663 	} else {
664 		addsock(NULL, 0, &(struct socklist){
665 			.sl_socket = s,
666 			.sl_recv = socklist_recv_file,
667 		});
668 	}
669 	/* Listen by default: *:514 if no -b flag. */
670 	if (bflag == 0)
671 		addpeer(&(struct peer){
672 			.pe_serv = "syslog"
673 		});
674 	/* Listen by default: /var/run/log if no -p flag. */
675 	if (pflag == 0)
676 		addpeer(&(struct peer){
677 			.pe_name = _PATH_LOG,
678 			.pe_mode = DEFFILEMODE,
679 		});
680 	/* Listen by default: /var/run/logpriv if no -S flag. */
681 	if (Sflag == 0)
682 		addpeer(&(struct peer){
683 			.pe_name = _PATH_LOG_PRIV,
684 			.pe_mode = S_IRUSR | S_IWUSR,
685 		});
686 	STAILQ_FOREACH(pe, &pqueue, next)
687 		socksetup(pe);
688 
689 	pfh = pidfile_open(PidFile, 0600, &spid);
690 	if (pfh == NULL) {
691 		if (errno == EEXIST)
692 			errx(1, "syslogd already running, pid: %d", spid);
693 		warn("cannot open pid file");
694 	}
695 
696 	if ((!Foreground) && (!Debug)) {
697 		ppid = waitdaemon(30);
698 		if (ppid < 0) {
699 			warn("could not become daemon");
700 			pidfile_remove(pfh);
701 			exit(1);
702 		}
703 	} else if (Debug)
704 		setlinebuf(stdout);
705 
706 	consfile.f_type = F_CONSOLE;
707 	(void)strlcpy(consfile.fu_fname, ctty + sizeof _PATH_DEV - 1,
708 	    sizeof(consfile.fu_fname));
709 	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
710 	(void)signal(SIGTERM, dodie);
711 	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
712 	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
713 	(void)signal(SIGHUP, sighandler);
714 	(void)signal(SIGCHLD, sighandler);
715 	(void)signal(SIGALRM, domark);
716 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
717 	(void)alarm(TIMERINTVL);
718 
719 	/* tuck my process id away */
720 	pidfile_write(pfh);
721 
722 	dprintf("off & running....\n");
723 
724 	tvp = &tv;
725 	tv.tv_sec = tv.tv_usec = 0;
726 
727 	STAILQ_FOREACH(sl, &shead, next) {
728 		if (sl->sl_socket > fdsrmax)
729 			fdsrmax = sl->sl_socket;
730 	}
731 	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
732 	    sizeof(fd_mask));
733 	if (fdsr == NULL)
734 		errx(1, "calloc fd_set");
735 
736 	for (;;) {
737 		if (Initialized == 0)
738 			init(0);
739 		else if (WantInitialize)
740 			init(WantInitialize);
741 		if (WantReapchild)
742 			reapchild(WantReapchild);
743 		if (MarkSet)
744 			markit();
745 		if (WantDie) {
746 			free(fdsr);
747 			die(WantDie);
748 		}
749 
750 		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
751 		    sizeof(fd_mask));
752 
753 		STAILQ_FOREACH(sl, &shead, next) {
754 			if (sl->sl_socket != -1 && sl->sl_recv != NULL)
755 				FD_SET(sl->sl_socket, fdsr);
756 		}
757 		i = select(fdsrmax + 1, fdsr, NULL, NULL,
758 		    needdofsync ? &tv : tvp);
759 		switch (i) {
760 		case 0:
761 			dofsync();
762 			needdofsync = 0;
763 			if (tvp) {
764 				tvp = NULL;
765 				if (ppid != 1)
766 					kill(ppid, SIGALRM);
767 			}
768 			continue;
769 		case -1:
770 			if (errno != EINTR)
771 				logerror("select");
772 			continue;
773 		}
774 		STAILQ_FOREACH(sl, &shead, next) {
775 			if (FD_ISSET(sl->sl_socket, fdsr))
776 				(*sl->sl_recv)(sl);
777 		}
778 	}
779 	free(fdsr);
780 }
781 
782 static int
783 socklist_recv_signal(struct socklist *sl __unused)
784 {
785 	ssize_t len;
786 	int i, nsig, signo;
787 
788 	if (ioctl(sigpipe[0], FIONREAD, &i) != 0) {
789 		logerror("ioctl(FIONREAD)");
790 		err(1, "signal pipe read failed");
791 	}
792 	nsig = i / sizeof(signo);
793 	dprintf("# of received signals = %d\n", nsig);
794 	for (i = 0; i < nsig; i++) {
795 		len = read(sigpipe[0], &signo, sizeof(signo));
796 		if (len != sizeof(signo)) {
797 			logerror("signal pipe read failed");
798 			err(1, "signal pipe read failed");
799 		}
800 		dprintf("Received signal: %d from fd=%d\n", signo,
801 		    sigpipe[0]);
802 		switch (signo) {
803 		case SIGHUP:
804 			WantInitialize = 1;
805 			break;
806 		case SIGCHLD:
807 			WantReapchild = 1;
808 			break;
809 		}
810 	}
811 	return (0);
812 }
813 
814 static int
815 socklist_recv_sock(struct socklist *sl)
816 {
817 	struct sockaddr_storage ss;
818 	struct sockaddr *sa = (struct sockaddr *)&ss;
819 	socklen_t sslen;
820 	const char *hname;
821 	char line[MAXLINE + 1];
822 	int len;
823 
824 	sslen = sizeof(ss);
825 	len = recvfrom(sl->sl_socket, line, sizeof(line) - 1, 0, sa, &sslen);
826 	dprintf("received sa_len = %d\n", sslen);
827 	if (len == 0)
828 		return (-1);
829 	if (len < 0) {
830 		if (errno != EINTR)
831 			logerror("recvfrom");
832 		return (-1);
833 	}
834 	/* Received valid data. */
835 	line[len] = '\0';
836 	if (sl->sl_ss.ss_family == AF_LOCAL)
837 		hname = LocalHostName;
838 	else {
839 		hname = cvthname(sa);
840 		unmapped(sa);
841 		if (validate(sa, hname) == 0) {
842 			dprintf("Message from %s was ignored.", hname);
843 			return (-1);
844 		}
845 	}
846 	parsemsg(hname, line);
847 
848 	return (0);
849 }
850 
851 static void
852 unmapped(struct sockaddr *sa)
853 {
854 #if defined(INET) && defined(INET6)
855 	struct sockaddr_in6 *sin6;
856 	struct sockaddr_in sin;
857 
858 	if (sa == NULL ||
859 	    sa->sa_family != AF_INET6 ||
860 	    sa->sa_len != sizeof(*sin6))
861 		return;
862 	sin6 = satosin6(sa);
863 	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
864 		return;
865 	sin = (struct sockaddr_in){
866 		.sin_family = AF_INET,
867 		.sin_len = sizeof(sin),
868 		.sin_port = sin6->sin6_port
869 	};
870 	memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
871 	    sizeof(sin.sin_addr));
872 	memcpy(sa, &sin, sizeof(sin));
873 #else
874 	if (sa == NULL)
875 		return;
876 #endif
877 }
878 
879 static void
880 usage(void)
881 {
882 
883 	fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
884 		"usage: syslogd [-468ACcdFHknosTuv] [-a allowed_peer]",
885 		"               [-b bind_address] [-f config_file]",
886 		"               [-l [mode:]path] [-m mark_interval]",
887 		"               [-P pid_file] [-p log_socket]",
888 		"               [-S logpriv_socket]");
889 	exit(1);
890 }
891 
892 /*
893  * Removes characters from log messages that are unsafe to display.
894  * TODO: Permit UTF-8 strings that include a BOM per RFC 5424?
895  */
896 static void
897 parsemsg_remove_unsafe_characters(const char *in, char *out, size_t outlen)
898 {
899 	char *q;
900 	int c;
901 
902 	q = out;
903 	while ((c = (unsigned char)*in++) != '\0' && q < out + outlen - 4) {
904 		if (mask_C1 && (c & 0x80) && c < 0xA0) {
905 			c &= 0x7F;
906 			*q++ = 'M';
907 			*q++ = '-';
908 		}
909 		if (isascii(c) && iscntrl(c)) {
910 			if (c == '\n') {
911 				*q++ = ' ';
912 			} else if (c == '\t') {
913 				*q++ = '\t';
914 			} else {
915 				*q++ = '^';
916 				*q++ = c ^ 0100;
917 			}
918 		} else {
919 			*q++ = c;
920 		}
921 	}
922 	*q = '\0';
923 }
924 
925 /*
926  * Parses a syslog message according to RFC 5424, assuming that PRI and
927  * VERSION (i.e., "<%d>1 ") have already been parsed by parsemsg(). The
928  * parsed result is passed to logmsg().
929  */
930 static void
931 parsemsg_rfc5424(const char *from, int pri, char *msg)
932 {
933 	const struct logtime *timestamp;
934 	struct logtime timestamp_remote = { 0 };
935 	const char *omsg, *hostname, *app_name, *procid, *msgid,
936 	    *structured_data;
937 	char line[MAXLINE + 1];
938 
939 #define	FAIL_IF(field, expr) do {					\
940 	if (expr) {							\
941 		dprintf("Failed to parse " field " from %s: %s\n",	\
942 		    from, omsg);					\
943 		return;							\
944 	}								\
945 } while (0)
946 #define	PARSE_CHAR(field, sep) do {					\
947 	FAIL_IF(field, *msg != sep);					\
948 	++msg;								\
949 } while (0)
950 #define	IF_NOT_NILVALUE(var)						\
951 	if (msg[0] == '-' && msg[1] == ' ') {				\
952 		msg += 2;						\
953 		var = NULL;						\
954 	} else if (msg[0] == '-' && msg[1] == '\0') {			\
955 		++msg;							\
956 		var = NULL;						\
957 	} else
958 
959 	omsg = msg;
960 	IF_NOT_NILVALUE(timestamp) {
961 		/* Parse RFC 3339-like timestamp. */
962 #define	PARSE_NUMBER(dest, length, min, max) do {			\
963 	int i, v;							\
964 									\
965 	v = 0;								\
966 	for (i = 0; i < length; ++i) {					\
967 		FAIL_IF("TIMESTAMP", *msg < '0' || *msg > '9');		\
968 		v = v * 10 + *msg++ - '0';				\
969 	}								\
970 	FAIL_IF("TIMESTAMP", v < min || v > max);			\
971 	dest = v;							\
972 } while (0)
973 		/* Date and time. */
974 		PARSE_NUMBER(timestamp_remote.tm.tm_year, 4, 0, 9999);
975 		timestamp_remote.tm.tm_year -= 1900;
976 		PARSE_CHAR("TIMESTAMP", '-');
977 		PARSE_NUMBER(timestamp_remote.tm.tm_mon, 2, 1, 12);
978 		--timestamp_remote.tm.tm_mon;
979 		PARSE_CHAR("TIMESTAMP", '-');
980 		PARSE_NUMBER(timestamp_remote.tm.tm_mday, 2, 1, 31);
981 		PARSE_CHAR("TIMESTAMP", 'T');
982 		PARSE_NUMBER(timestamp_remote.tm.tm_hour, 2, 0, 23);
983 		PARSE_CHAR("TIMESTAMP", ':');
984 		PARSE_NUMBER(timestamp_remote.tm.tm_min, 2, 0, 59);
985 		PARSE_CHAR("TIMESTAMP", ':');
986 		PARSE_NUMBER(timestamp_remote.tm.tm_sec, 2, 0, 59);
987 		/* Perform normalization. */
988 		timegm(&timestamp_remote.tm);
989 		/* Optional: fractional seconds. */
990 		if (msg[0] == '.' && msg[1] >= '0' && msg[1] <= '9') {
991 			int i;
992 
993 			++msg;
994 			for (i = 100000; i != 0; i /= 10) {
995 				if (*msg < '0' || *msg > '9')
996 					break;
997 				timestamp_remote.usec += (*msg++ - '0') * i;
998 			}
999 		}
1000 		/* Timezone. */
1001 		if (*msg == 'Z') {
1002 			/* UTC. */
1003 			++msg;
1004 		} else {
1005 			int sign, tz_hour, tz_min;
1006 
1007 			/* Local time zone offset. */
1008 			FAIL_IF("TIMESTAMP", *msg != '-' && *msg != '+');
1009 			sign = *msg++ == '-' ? -1 : 1;
1010 			PARSE_NUMBER(tz_hour, 2, 0, 23);
1011 			PARSE_CHAR("TIMESTAMP", ':');
1012 			PARSE_NUMBER(tz_min, 2, 0, 59);
1013 			timestamp_remote.tm.tm_gmtoff =
1014 			    sign * (tz_hour * 3600 + tz_min * 60);
1015 		}
1016 #undef PARSE_NUMBER
1017 		PARSE_CHAR("TIMESTAMP", ' ');
1018 		timestamp = RemoteAddDate ? NULL : &timestamp_remote;
1019 	}
1020 
1021 	/* String fields part of the HEADER. */
1022 #define	PARSE_STRING(field, var)					\
1023 	IF_NOT_NILVALUE(var) {						\
1024 		var = msg;						\
1025 		while (*msg >= '!' && *msg <= '~')			\
1026 			++msg;						\
1027 		FAIL_IF(field, var == msg);				\
1028 		PARSE_CHAR(field, ' ');					\
1029 		msg[-1] = '\0';						\
1030 	}
1031 	PARSE_STRING("HOSTNAME", hostname);
1032 	if (hostname == NULL || !RemoteHostname)
1033 		hostname = from;
1034 	PARSE_STRING("APP-NAME", app_name);
1035 	PARSE_STRING("PROCID", procid);
1036 	PARSE_STRING("MSGID", msgid);
1037 #undef PARSE_STRING
1038 
1039 	/* Structured data. */
1040 #define	PARSE_SD_NAME() do {						\
1041 	const char *start;						\
1042 									\
1043 	start = msg;							\
1044 	while (*msg >= '!' && *msg <= '~' && *msg != '=' &&		\
1045 	    *msg != ']' && *msg != '"')					\
1046 		++msg;							\
1047 	FAIL_IF("STRUCTURED-NAME", start == msg);			\
1048 } while (0)
1049 	IF_NOT_NILVALUE(structured_data) {
1050 		/* SD-ELEMENT. */
1051 		while (*msg == '[') {
1052 			++msg;
1053 			/* SD-ID. */
1054 			PARSE_SD_NAME();
1055 			/* SD-PARAM. */
1056 			while (*msg == ' ') {
1057 				++msg;
1058 				/* PARAM-NAME. */
1059 				PARSE_SD_NAME();
1060 				PARSE_CHAR("STRUCTURED-NAME", '=');
1061 				PARSE_CHAR("STRUCTURED-NAME", '"');
1062 				while (*msg != '"') {
1063 					FAIL_IF("STRUCTURED-NAME",
1064 					    *msg == '\0');
1065 					if (*msg++ == '\\') {
1066 						FAIL_IF("STRUCTURED-NAME",
1067 						    *msg == '\0');
1068 						++msg;
1069 					}
1070 				}
1071 				++msg;
1072 			}
1073 			PARSE_CHAR("STRUCTURED-NAME", ']');
1074 		}
1075 		PARSE_CHAR("STRUCTURED-NAME", ' ');
1076 		msg[-1] = '\0';
1077 	}
1078 #undef PARSE_SD_NAME
1079 
1080 #undef FAIL_IF
1081 #undef PARSE_CHAR
1082 #undef IF_NOT_NILVALUE
1083 
1084 	parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1085 	logmsg(pri, timestamp, hostname, app_name, procid, msgid,
1086 	    structured_data, line, 0);
1087 }
1088 
1089 /*
1090  * Trims the application name ("TAG" in RFC 3164 terminology) and
1091  * process ID from a message if present.
1092  */
1093 static void
1094 parsemsg_rfc3164_app_name_procid(char **msg, const char **app_name,
1095     const char **procid) {
1096 	char *m, *app_name_begin, *procid_begin;
1097 	size_t app_name_length, procid_length;
1098 
1099 	m = *msg;
1100 
1101 	/* Application name. */
1102 	app_name_begin = m;
1103 	app_name_length = strspn(m,
1104 	    "abcdefghijklmnopqrstuvwxyz"
1105 	    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1106 	    "0123456789"
1107 	    "_-");
1108 	if (app_name_length == 0)
1109 		goto bad;
1110 	m += app_name_length;
1111 
1112 	/* Process identifier (optional). */
1113 	if (*m == '[') {
1114 		procid_begin = ++m;
1115 		procid_length = strspn(m, "0123456789");
1116 		if (procid_length == 0)
1117 			goto bad;
1118 		m += procid_length;
1119 		if (*m++ != ']')
1120 			goto bad;
1121 	} else {
1122 		procid_begin = NULL;
1123 		procid_length = 0;
1124 	}
1125 
1126 	/* Separator. */
1127 	if (m[0] != ':' || m[1] != ' ')
1128 		goto bad;
1129 
1130 	/* Split strings from input. */
1131 	app_name_begin[app_name_length] = '\0';
1132 	if (procid_begin != 0)
1133 		procid_begin[procid_length] = '\0';
1134 
1135 	*msg = m + 2;
1136 	*app_name = app_name_begin;
1137 	*procid = procid_begin;
1138 	return;
1139 bad:
1140 	*app_name = NULL;
1141 	*procid = NULL;
1142 }
1143 
1144 /*
1145  * Parses a syslog message according to RFC 3164, assuming that PRI
1146  * (i.e., "<%d>") has already been parsed by parsemsg(). The parsed
1147  * result is passed to logmsg().
1148  */
1149 static void
1150 parsemsg_rfc3164(const char *from, int pri, char *msg)
1151 {
1152 	struct tm tm_parsed;
1153 	const struct logtime *timestamp;
1154 	struct logtime timestamp_remote = { 0 };
1155 	const char *app_name, *procid;
1156 	size_t i, msglen;
1157 	char line[MAXLINE + 1];
1158 
1159 	/* Parse the timestamp provided by the remote side. */
1160 	if (strptime(msg, RFC3164_DATEFMT, &tm_parsed) !=
1161 	    msg + RFC3164_DATELEN || msg[RFC3164_DATELEN] != ' ') {
1162 		dprintf("Failed to parse TIMESTAMP from %s: %s\n", from, msg);
1163 		return;
1164 	}
1165 	msg += RFC3164_DATELEN + 1;
1166 
1167 	if (!RemoteAddDate) {
1168 		struct tm tm_now;
1169 		time_t t_now;
1170 		int year;
1171 
1172 		/*
1173 		 * As the timestamp does not contain the year number,
1174 		 * daylight saving time information, nor a time zone,
1175 		 * attempt to infer it. Due to clock skews, the
1176 		 * timestamp may even be part of the next year. Use the
1177 		 * last year for which the timestamp is at most one week
1178 		 * in the future.
1179 		 *
1180 		 * This loop can only run for at most three iterations
1181 		 * before terminating.
1182 		 */
1183 		t_now = time(NULL);
1184 		localtime_r(&t_now, &tm_now);
1185 		for (year = tm_now.tm_year + 1;; --year) {
1186 			assert(year >= tm_now.tm_year - 1);
1187 			timestamp_remote.tm = tm_parsed;
1188 			timestamp_remote.tm.tm_year = year;
1189 			timestamp_remote.tm.tm_isdst = -1;
1190 			if (mktime(&timestamp_remote.tm) <
1191 			    t_now + 7 * 24 * 60 * 60)
1192 				break;
1193 		}
1194 		timestamp = &timestamp_remote;
1195 	} else
1196 		timestamp = NULL;
1197 
1198 	/*
1199 	 * A single space character MUST also follow the HOSTNAME field.
1200 	 */
1201 	msglen = strlen(msg);
1202 	for (i = 0; i < MIN(MAXHOSTNAMELEN, msglen); i++) {
1203 		if (msg[i] == ' ') {
1204 			if (RemoteHostname) {
1205 				msg[i] = '\0';
1206 				from = msg;
1207 			}
1208 			msg += i + 1;
1209 			break;
1210 		}
1211 		/*
1212 		 * Support non RFC compliant messages, without hostname.
1213 		 */
1214 		if (msg[i] == ':')
1215 			break;
1216 	}
1217 	if (i == MIN(MAXHOSTNAMELEN, msglen)) {
1218 		dprintf("Invalid HOSTNAME from %s: %s\n", from, msg);
1219 		return;
1220 	}
1221 
1222 	/* Remove the TAG, if present. */
1223 	parsemsg_rfc3164_app_name_procid(&msg, &app_name, &procid);
1224 	parsemsg_remove_unsafe_characters(msg, line, sizeof(line));
1225 	logmsg(pri, timestamp, from, app_name, procid, NULL, NULL, line, 0);
1226 }
1227 
1228 /*
1229  * Takes a raw input line, extracts PRI and determines whether the
1230  * message is formatted according to RFC 3164 or RFC 5424. Continues
1231  * parsing of addition fields in the message according to those
1232  * standards and prints the message on the appropriate log files.
1233  */
1234 static void
1235 parsemsg(const char *from, char *msg)
1236 {
1237 	char *q;
1238 	long n;
1239 	size_t i;
1240 	int pri;
1241 
1242 	/* Parse PRI. */
1243 	if (msg[0] != '<' || !isdigit(msg[1])) {
1244 		dprintf("Invalid PRI from %s\n", from);
1245 		return;
1246 	}
1247 	for (i = 2; i <= 4; i++) {
1248 		if (msg[i] == '>')
1249 			break;
1250 		if (!isdigit(msg[i])) {
1251 			dprintf("Invalid PRI header from %s\n", from);
1252 			return;
1253 		}
1254 	}
1255 	if (msg[i] != '>') {
1256 		dprintf("Invalid PRI header from %s\n", from);
1257 		return;
1258 	}
1259 	errno = 0;
1260 	n = strtol(msg + 1, &q, 10);
1261 	if (errno != 0 || *q != msg[i] || n < 0 || n >= INT_MAX) {
1262 		dprintf("Invalid PRI %ld from %s: %s\n",
1263 		    n, from, strerror(errno));
1264 		return;
1265 	}
1266 	pri = n;
1267 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1268 		pri = DEFUPRI;
1269 
1270 	/*
1271 	 * Don't allow users to log kernel messages.
1272 	 * NOTE: since LOG_KERN == 0 this will also match
1273 	 *       messages with no facility specified.
1274 	 */
1275 	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
1276 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1277 
1278 	/* Parse VERSION. */
1279 	msg += i + 1;
1280 	if (msg[0] == '1' && msg[1] == ' ')
1281 		parsemsg_rfc5424(from, pri, msg + 2);
1282 	else
1283 		parsemsg_rfc3164(from, pri, msg);
1284 }
1285 
1286 /*
1287  * Read /dev/klog while data are available, split into lines.
1288  */
1289 static int
1290 socklist_recv_file(struct socklist *sl)
1291 {
1292 	char *p, *q, line[MAXLINE + 1];
1293 	int len, i;
1294 
1295 	len = 0;
1296 	for (;;) {
1297 		i = read(sl->sl_socket, line + len, MAXLINE - 1 - len);
1298 		if (i > 0) {
1299 			line[i + len] = '\0';
1300 		} else {
1301 			if (i < 0 && errno != EINTR && errno != EAGAIN) {
1302 				logerror("klog");
1303 				close(sl->sl_socket);
1304 				sl->sl_socket = -1;
1305 			}
1306 			break;
1307 		}
1308 
1309 		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
1310 			*q = '\0';
1311 			printsys(p);
1312 		}
1313 		len = strlen(p);
1314 		if (len >= MAXLINE - 1) {
1315 			printsys(p);
1316 			len = 0;
1317 		}
1318 		if (len > 0)
1319 			memmove(line, p, len + 1);
1320 	}
1321 	if (len > 0)
1322 		printsys(line);
1323 
1324 	return (len);
1325 }
1326 
1327 /*
1328  * Take a raw input line from /dev/klog, format similar to syslog().
1329  */
1330 static void
1331 printsys(char *msg)
1332 {
1333 	char *p, *q;
1334 	long n;
1335 	int flags, isprintf, pri;
1336 
1337 	flags = SYNC_FILE;	/* fsync after write */
1338 	p = msg;
1339 	pri = DEFSPRI;
1340 	isprintf = 1;
1341 	if (*p == '<') {
1342 		errno = 0;
1343 		n = strtol(p + 1, &q, 10);
1344 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1345 			p = q + 1;
1346 			pri = n;
1347 			isprintf = 0;
1348 		}
1349 	}
1350 	/*
1351 	 * Kernel printf's and LOG_CONSOLE messages have been displayed
1352 	 * on the console already.
1353 	 */
1354 	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1355 		flags |= IGN_CONS;
1356 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1357 		pri = DEFSPRI;
1358 	logmsg(pri, NULL, LocalHostName, "kernel", NULL, NULL, NULL, p, flags);
1359 }
1360 
1361 static time_t	now;
1362 
1363 /*
1364  * Match a program or host name against a specification.
1365  * Return a non-0 value if the message must be ignored
1366  * based on the specification.
1367  */
1368 static int
1369 skip_message(const char *name, const char *spec, int checkcase)
1370 {
1371 	const char *s;
1372 	char prev, next;
1373 	int exclude = 0;
1374 	/* Behaviour on explicit match */
1375 
1376 	if (spec == NULL)
1377 		return 0;
1378 	switch (*spec) {
1379 	case '-':
1380 		exclude = 1;
1381 		/*FALLTHROUGH*/
1382 	case '+':
1383 		spec++;
1384 		break;
1385 	default:
1386 		break;
1387 	}
1388 	if (checkcase)
1389 		s = strstr (spec, name);
1390 	else
1391 		s = strcasestr (spec, name);
1392 
1393 	if (s != NULL) {
1394 		prev = (s == spec ? ',' : *(s - 1));
1395 		next = *(s + strlen (name));
1396 
1397 		if (prev == ',' && (next == '\0' || next == ','))
1398 			/* Explicit match: skip iff the spec is an
1399 			   exclusive one. */
1400 			return exclude;
1401 	}
1402 
1403 	/* No explicit match for this name: skip the message iff
1404 	   the spec is an inclusive one. */
1405 	return !exclude;
1406 }
1407 
1408 /*
1409  * Logs a message to the appropriate log files, users, etc. based on the
1410  * priority. Log messages are always formatted according to RFC 3164,
1411  * even if they were in RFC 5424 format originally, The MSGID and
1412  * STRUCTURED-DATA fields are thus discarded for the time being.
1413  */
1414 static void
1415 logmsg(int pri, const struct logtime *timestamp, const char *hostname,
1416     const char *app_name, const char *procid, const char *msgid,
1417     const char *structured_data, const char *msg, int flags)
1418 {
1419 	struct timeval tv;
1420 	struct logtime timestamp_now;
1421 	struct filed *f;
1422 	size_t savedlen;
1423 	int fac, prilev;
1424 	char saved[MAXSVLINE];
1425 
1426 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1427 	    pri, flags, hostname, msg);
1428 
1429 	(void)gettimeofday(&tv, NULL);
1430 	now = tv.tv_sec;
1431 	if (timestamp == NULL) {
1432 		localtime_r(&now, &timestamp_now.tm);
1433 		timestamp_now.usec = tv.tv_usec;
1434 		timestamp = &timestamp_now;
1435 	}
1436 
1437 	/* extract facility and priority level */
1438 	if (flags & MARK)
1439 		fac = LOG_NFACILITIES;
1440 	else
1441 		fac = LOG_FAC(pri);
1442 
1443 	/* Check maximum facility number. */
1444 	if (fac > LOG_NFACILITIES)
1445 		return;
1446 
1447 	prilev = LOG_PRI(pri);
1448 
1449 	/* log the message to the particular outputs */
1450 	if (!Initialized) {
1451 		f = &consfile;
1452 		/*
1453 		 * Open in non-blocking mode to avoid hangs during open
1454 		 * and close(waiting for the port to drain).
1455 		 */
1456 		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1457 
1458 		if (f->f_file >= 0) {
1459 			f->f_lasttime = *timestamp;
1460 			fprintlog_first(f, hostname, app_name, procid, msgid,
1461 			    structured_data, msg, flags);
1462 			close(f->f_file);
1463 			f->f_file = -1;
1464 		}
1465 		return;
1466 	}
1467 
1468 	/*
1469 	 * Store all of the fields of the message, except the timestamp,
1470 	 * in a single string. This string is used to detect duplicate
1471 	 * messages.
1472 	 */
1473 	assert(hostname != NULL);
1474 	assert(msg != NULL);
1475 	savedlen = snprintf(saved, sizeof(saved),
1476 	    "%d %s %s %s %s %s %s", pri, hostname,
1477 	    app_name == NULL ? "-" : app_name, procid == NULL ? "-" : procid,
1478 	    msgid == NULL ? "-" : msgid,
1479 	    structured_data == NULL ? "-" : structured_data, msg);
1480 
1481 	STAILQ_FOREACH(f, &fhead, next) {
1482 		/* skip messages that are incorrect priority */
1483 		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1484 		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1485 		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1486 		     )
1487 		    || f->f_pmask[fac] == INTERNAL_NOPRI)
1488 			continue;
1489 
1490 		/* skip messages with the incorrect hostname */
1491 		if (skip_message(hostname, f->f_host, 0))
1492 			continue;
1493 
1494 		/* skip messages with the incorrect program name */
1495 		if (skip_message(app_name == NULL ? "" : app_name,
1496 		    f->f_program, 1))
1497 			continue;
1498 
1499 		/* skip message to console if it has already been printed */
1500 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1501 			continue;
1502 
1503 		/* don't output marks to recently written files */
1504 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1505 			continue;
1506 
1507 		/*
1508 		 * suppress duplicate lines to this file
1509 		 */
1510 		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1511 		    (flags & MARK) == 0 && savedlen == f->f_prevlen &&
1512 		    strcmp(saved, f->f_prevline) == 0) {
1513 			f->f_lasttime = *timestamp;
1514 			f->f_prevcount++;
1515 			dprintf("msg repeated %d times, %ld sec of %d\n",
1516 			    f->f_prevcount, (long)(now - f->f_time),
1517 			    repeatinterval[f->f_repeatcount]);
1518 			/*
1519 			 * If domark would have logged this by now,
1520 			 * flush it now (so we don't hold isolated messages),
1521 			 * but back off so we'll flush less often
1522 			 * in the future.
1523 			 */
1524 			if (now > REPEATTIME(f)) {
1525 				fprintlog_successive(f, flags);
1526 				BACKOFF(f);
1527 			}
1528 		} else {
1529 			/* new line, save it */
1530 			if (f->f_prevcount)
1531 				fprintlog_successive(f, 0);
1532 			f->f_repeatcount = 0;
1533 			f->f_prevpri = pri;
1534 			f->f_lasttime = *timestamp;
1535 			static_assert(sizeof(f->f_prevline) == sizeof(saved),
1536 			    "Space to store saved line incorrect");
1537 			(void)strcpy(f->f_prevline, saved);
1538 			f->f_prevlen = savedlen;
1539 			fprintlog_first(f, hostname, app_name, procid, msgid,
1540 			    structured_data, msg, flags);
1541 		}
1542 	}
1543 }
1544 
1545 static void
1546 dofsync(void)
1547 {
1548 	struct filed *f;
1549 
1550 	STAILQ_FOREACH(f, &fhead, next) {
1551 		if ((f->f_type == F_FILE) &&
1552 		    (f->f_flags & FFLAG_NEEDSYNC)) {
1553 			f->f_flags &= ~FFLAG_NEEDSYNC;
1554 			(void)fsync(f->f_file);
1555 		}
1556 	}
1557 }
1558 
1559 #define IOV_SIZE 7
1560 static void
1561 fprintlog_first(struct filed *f, const char *hostname, const char *app_name,
1562     const char *procid, const char *msgid __unused,
1563     const char *structured_data __unused, const char *msg, int flags)
1564 {
1565 	struct iovec iov[IOV_SIZE];
1566 	struct addrinfo *r;
1567 	int l, lsent = 0;
1568 	char tagged_msg[MAXLINE + 1], line[MAXLINE + 1], greetings[200];
1569 	char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1570 	char timebuf[RFC3164_DATELEN + 1];
1571 	const char *msgret;
1572 
1573 	if (strftime(timebuf, sizeof(timebuf), RFC3164_DATEFMT,
1574 	    &f->f_lasttime.tm) == 0)
1575 		timebuf[0] = '\0';
1576 	if (f->f_type == F_WALL) {
1577 		/* The time displayed is not synchornized with the other log
1578 		 * destinations (like messages).  Following fragment was using
1579 		 * ctime(&now), which was updating the time every 30 sec.
1580 		 * With f_lasttime, time is synchronized correctly.
1581 		 */
1582 		iov[0] = (struct iovec){
1583 			.iov_base = greetings,
1584 			.iov_len = snprintf(greetings, sizeof(greetings),
1585 				    "\r\n\7Message from syslogd@%s "
1586 				    "at %.24s ...\r\n", hostname, timebuf)
1587 		};
1588 		if (iov[0].iov_len >= sizeof(greetings))
1589 			iov[0].iov_len = sizeof(greetings) - 1;
1590 		iov[1] = (struct iovec){
1591 			.iov_base = nul,
1592 			.iov_len = 0
1593 		};
1594 	} else {
1595 		iov[0] = (struct iovec){
1596 			.iov_base = timebuf,
1597 			.iov_len = strlen(timebuf)
1598 		};
1599 		iov[1] = (struct iovec){
1600 			.iov_base = space,
1601 			.iov_len = 1
1602 		};
1603 	}
1604 
1605 	if (LogFacPri) {
1606 	  	static char fp_buf[30];	/* Hollow laugh */
1607 		int fac = f->f_prevpri & LOG_FACMASK;
1608 		int pri = LOG_PRI(f->f_prevpri);
1609 		const char *f_s = NULL;
1610 		char f_n[5];	/* Hollow laugh */
1611 		const char *p_s = NULL;
1612 		char p_n[5];	/* Hollow laugh */
1613 
1614 		if (LogFacPri > 1) {
1615 		  const CODE *c;
1616 
1617 		  for (c = facilitynames; c->c_name; c++) {
1618 		    if (c->c_val == fac) {
1619 		      f_s = c->c_name;
1620 		      break;
1621 		    }
1622 		  }
1623 		  for (c = prioritynames; c->c_name; c++) {
1624 		    if (c->c_val == pri) {
1625 		      p_s = c->c_name;
1626 		      break;
1627 		    }
1628 		  }
1629 		}
1630 		if (!f_s) {
1631 		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1632 		  f_s = f_n;
1633 		}
1634 		if (!p_s) {
1635 		  snprintf(p_n, sizeof p_n, "%d", pri);
1636 		  p_s = p_n;
1637 		}
1638 		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1639 		iov[2] = (struct iovec){
1640 			.iov_base = fp_buf,
1641 			.iov_len = strlen(fp_buf)
1642 		};
1643 	} else {
1644 		iov[2] = (struct iovec){
1645 			.iov_base = nul,
1646 			.iov_len = 0
1647 		};
1648 	}
1649 	/* Prepend the application name to the message if provided. */
1650 	if (app_name != NULL) {
1651 		if (procid != NULL)
1652 			snprintf(tagged_msg, sizeof(tagged_msg),
1653 			    "%s[%s]: %s", app_name, procid, msg);
1654 		else
1655 			snprintf(tagged_msg, sizeof(tagged_msg),
1656 			    "%s: %s", app_name, msg);
1657 		msg = tagged_msg;
1658 	}
1659 	iov[3] = (struct iovec){
1660 		.iov_base = __DECONST(char *, hostname),
1661 		.iov_len = strlen(hostname)
1662 	};
1663 	iov[4] = (struct iovec){
1664 		.iov_base = space,
1665 		.iov_len = 1
1666 	};
1667 	iov[5] = (struct iovec){
1668 		.iov_base = __DECONST(char *, msg),
1669 		.iov_len = strlen(msg)
1670 	};
1671 	dprintf("Logging to %s", TypeNames[f->f_type]);
1672 	f->f_time = now;
1673 
1674 	switch (f->f_type) {
1675 	case F_UNUSED:
1676 		dprintf("\n");
1677 		break;
1678 
1679 	case F_FORW:
1680 		dprintf(" %s", f->fu_forw_hname);
1681 		switch (f->fu_forw_addr->ai_addr->sa_family) {
1682 #ifdef INET
1683 		case AF_INET:
1684 			dprintf(":%d\n",
1685 			    ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port));
1686 			break;
1687 #endif
1688 #ifdef INET6
1689 		case AF_INET6:
1690 			dprintf(":%d\n",
1691 			    ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port));
1692 			break;
1693 #endif
1694 		default:
1695 			dprintf("\n");
1696 		}
1697 		/* check for local vs remote messages */
1698 		if (strcasecmp(hostname, LocalHostName))
1699 			l = snprintf(line, sizeof line - 1,
1700 			    "<%d>%.15s Forwarded from %s: %s",
1701 			    f->f_prevpri, (char *)iov[0].iov_base,
1702 			    hostname, (char *)iov[5].iov_base);
1703 		else
1704 			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1705 			     f->f_prevpri, (char *)iov[0].iov_base,
1706 			    (char *)iov[5].iov_base);
1707 		if (l < 0)
1708 			l = 0;
1709 		else if (l > MAXLINE)
1710 			l = MAXLINE;
1711 
1712 		for (r = f->fu_forw_addr; r; r = r->ai_next) {
1713 			struct socklist *sl;
1714 
1715 			STAILQ_FOREACH(sl, &shead, next) {
1716 				if (sl->sl_ss.ss_family == AF_LOCAL ||
1717 				    sl->sl_ss.ss_family == AF_UNSPEC ||
1718 				    sl->sl_socket < 0)
1719 					continue;
1720 				lsent = sendto(sl->sl_socket, line, l, 0,
1721 				    r->ai_addr, r->ai_addrlen);
1722 				if (lsent == l)
1723 					break;
1724 			}
1725 			if (lsent == l && !send_to_all)
1726 				break;
1727 		}
1728 		dprintf("lsent/l: %d/%d\n", lsent, l);
1729 		if (lsent != l) {
1730 			int e = errno;
1731 			logerror("sendto");
1732 			errno = e;
1733 			switch (errno) {
1734 			case ENOBUFS:
1735 			case ENETDOWN:
1736 			case ENETUNREACH:
1737 			case EHOSTUNREACH:
1738 			case EHOSTDOWN:
1739 			case EADDRNOTAVAIL:
1740 				break;
1741 			/* case EBADF: */
1742 			/* case EACCES: */
1743 			/* case ENOTSOCK: */
1744 			/* case EFAULT: */
1745 			/* case EMSGSIZE: */
1746 			/* case EAGAIN: */
1747 			/* case ENOBUFS: */
1748 			/* case ECONNREFUSED: */
1749 			default:
1750 				dprintf("removing entry: errno=%d\n", e);
1751 				f->f_type = F_UNUSED;
1752 				break;
1753 			}
1754 		}
1755 		break;
1756 
1757 	case F_FILE:
1758 		dprintf(" %s\n", f->fu_fname);
1759 		iov[6] = (struct iovec){
1760 			.iov_base = lf,
1761 			.iov_len = 1
1762 		};
1763 		if (writev(f->f_file, iov, nitems(iov)) < 0) {
1764 			/*
1765 			 * If writev(2) fails for potentially transient errors
1766 			 * like the filesystem being full, ignore it.
1767 			 * Otherwise remove this logfile from the list.
1768 			 */
1769 			if (errno != ENOSPC) {
1770 				int e = errno;
1771 				close_filed(f);
1772 				errno = e;
1773 				logerror(f->fu_fname);
1774 			}
1775 		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1776 			f->f_flags |= FFLAG_NEEDSYNC;
1777 			needdofsync = 1;
1778 		}
1779 		break;
1780 
1781 	case F_PIPE:
1782 		dprintf(" %s\n", f->fu_pipe_pname);
1783 		iov[6] = (struct iovec){
1784 			.iov_base = lf,
1785 			.iov_len = 1
1786 		};
1787 		if (f->fu_pipe_pid == 0) {
1788 			if ((f->f_file = p_open(f->fu_pipe_pname,
1789 						&f->fu_pipe_pid)) < 0) {
1790 				logerror(f->fu_pipe_pname);
1791 				break;
1792 			}
1793 		}
1794 		if (writev(f->f_file, iov, nitems(iov)) < 0) {
1795 			int e = errno;
1796 
1797 			deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
1798 			close_filed(f);
1799 			errno = e;
1800 			logerror(f->fu_pipe_pname);
1801 		}
1802 		break;
1803 
1804 	case F_CONSOLE:
1805 		if (flags & IGN_CONS) {
1806 			dprintf(" (ignored)\n");
1807 			break;
1808 		}
1809 		/* FALLTHROUGH */
1810 
1811 	case F_TTY:
1812 		dprintf(" %s%s\n", _PATH_DEV, f->fu_fname);
1813 		iov[6] = (struct iovec){
1814 			.iov_base = crlf,
1815 			.iov_len = 2
1816 		};
1817 		errno = 0;	/* ttymsg() only sometimes returns an errno */
1818 		if ((msgret = ttymsg(iov, nitems(iov), f->fu_fname, 10))) {
1819 			f->f_type = F_UNUSED;
1820 			logerror(msgret);
1821 		}
1822 		break;
1823 
1824 	case F_USERS:
1825 	case F_WALL:
1826 		dprintf("\n");
1827 		iov[6] = (struct iovec){
1828 			.iov_base = crlf,
1829 			.iov_len = 2
1830 		};
1831 		wallmsg(f, iov, nitems(iov));
1832 		break;
1833 	}
1834 	f->f_prevcount = 0;
1835 }
1836 
1837 /*
1838  * Prints a message to a log file that the previously logged message was
1839  * received multiple times.
1840  */
1841 static void
1842 fprintlog_successive(struct filed *f, int flags)
1843 {
1844 	char msg[100];
1845 
1846 	assert(f->f_prevcount > 0);
1847 	snprintf(msg, sizeof(msg), "last message repeated %d times",
1848 	    f->f_prevcount);
1849 	fprintlog_first(f, LocalHostName, "syslogd", NULL, NULL, NULL, msg,
1850 	    flags);
1851 }
1852 
1853 /*
1854  *  WALLMSG -- Write a message to the world at large
1855  *
1856  *	Write the specified message to either the entire
1857  *	world, or a list of approved users.
1858  */
1859 static void
1860 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1861 {
1862 	static int reenter;			/* avoid calling ourselves */
1863 	struct utmpx *ut;
1864 	int i;
1865 	const char *p;
1866 
1867 	if (reenter++)
1868 		return;
1869 	setutxent();
1870 	/* NOSTRICT */
1871 	while ((ut = getutxent()) != NULL) {
1872 		if (ut->ut_type != USER_PROCESS)
1873 			continue;
1874 		if (f->f_type == F_WALL) {
1875 			if ((p = ttymsg(iov, iovlen, ut->ut_line,
1876 			    TTYMSGTIME)) != NULL) {
1877 				errno = 0;	/* already in msg */
1878 				logerror(p);
1879 			}
1880 			continue;
1881 		}
1882 		/* should we send the message to this user? */
1883 		for (i = 0; i < MAXUNAMES; i++) {
1884 			if (!f->fu_uname[i][0])
1885 				break;
1886 			if (!strcmp(f->fu_uname[i], ut->ut_user)) {
1887 				if ((p = ttymsg_check(iov, iovlen, ut->ut_line,
1888 				    TTYMSGTIME)) != NULL) {
1889 					errno = 0;	/* already in msg */
1890 					logerror(p);
1891 				}
1892 				break;
1893 			}
1894 		}
1895 	}
1896 	endutxent();
1897 	reenter = 0;
1898 }
1899 
1900 /*
1901  * Wrapper routine for ttymsg() that checks the terminal for messages enabled.
1902  */
1903 static const char *
1904 ttymsg_check(struct iovec *iov, int iovcnt, char *line, int tmout)
1905 {
1906 	static char device[1024];
1907 	static char errbuf[1024];
1908 	struct stat sb;
1909 
1910 	(void) snprintf(device, sizeof(device), "%s%s", _PATH_DEV, line);
1911 
1912 	if (stat(device, &sb) < 0) {
1913 		(void) snprintf(errbuf, sizeof(errbuf),
1914 		    "%s: %s", device, strerror(errno));
1915 		return (errbuf);
1916 	}
1917 	if ((sb.st_mode & S_IWGRP) == 0)
1918 		/* Messages disabled. */
1919 		return (NULL);
1920 	return ttymsg(iov, iovcnt, line, tmout);
1921 }
1922 
1923 static void
1924 reapchild(int signo __unused)
1925 {
1926 	int status;
1927 	pid_t pid;
1928 	struct filed *f;
1929 
1930 	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1931 		/* First, look if it's a process from the dead queue. */
1932 		if (deadq_removebypid(pid))
1933 			continue;
1934 
1935 		/* Now, look in list of active processes. */
1936 		STAILQ_FOREACH(f, &fhead, next) {
1937 			if (f->f_type == F_PIPE &&
1938 			    f->fu_pipe_pid == pid) {
1939 				close_filed(f);
1940 				log_deadchild(pid, status, f->fu_pipe_pname);
1941 				break;
1942 			}
1943 		}
1944 	}
1945 	WantReapchild = 0;
1946 }
1947 
1948 /*
1949  * Return a printable representation of a host address.
1950  */
1951 static const char *
1952 cvthname(struct sockaddr *f)
1953 {
1954 	int error, hl;
1955 	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1956 
1957 	dprintf("cvthname(%d) len = %d\n", f->sa_family, f->sa_len);
1958 	error = getnameinfo(f, f->sa_len, ip, sizeof(ip), NULL, 0,
1959 		    NI_NUMERICHOST);
1960 	if (error) {
1961 		dprintf("Malformed from address %s\n", gai_strerror(error));
1962 		return ("???");
1963 	}
1964 	dprintf("cvthname(%s)\n", ip);
1965 
1966 	if (!resolve)
1967 		return (ip);
1968 
1969 	error = getnameinfo(f, f->sa_len, hname, sizeof(hname),
1970 		    NULL, 0, NI_NAMEREQD);
1971 	if (error) {
1972 		dprintf("Host name for your address (%s) unknown\n", ip);
1973 		return (ip);
1974 	}
1975 	hl = strlen(hname);
1976 	if (hl > 0 && hname[hl-1] == '.')
1977 		hname[--hl] = '\0';
1978 	trimdomain(hname, hl);
1979 	return (hname);
1980 }
1981 
1982 static void
1983 dodie(int signo)
1984 {
1985 
1986 	WantDie = signo;
1987 }
1988 
1989 static void
1990 domark(int signo __unused)
1991 {
1992 
1993 	MarkSet = 1;
1994 }
1995 
1996 /*
1997  * Print syslogd errors some place.
1998  */
1999 static void
2000 logerror(const char *msg)
2001 {
2002 	char buf[512];
2003 	static int recursed = 0;
2004 
2005 	/* If there's an error while trying to log an error, give up. */
2006 	if (recursed)
2007 		return;
2008 	recursed++;
2009 	if (errno != 0) {
2010 		(void)snprintf(buf, sizeof(buf), "%s: %s", msg,
2011 		    strerror(errno));
2012 		msg = buf;
2013 	}
2014 	errno = 0;
2015 	dprintf("%s\n", buf);
2016 	logmsg(LOG_SYSLOG|LOG_ERR, NULL, LocalHostName, "syslogd", NULL, NULL,
2017 	    NULL, msg, 0);
2018 	recursed--;
2019 }
2020 
2021 static void
2022 die(int signo)
2023 {
2024 	struct filed *f;
2025 	struct socklist *sl;
2026 	char buf[100];
2027 
2028 	STAILQ_FOREACH(f, &fhead, next) {
2029 		/* flush any pending output */
2030 		if (f->f_prevcount)
2031 			fprintlog_successive(f, 0);
2032 		if (f->f_type == F_PIPE && f->fu_pipe_pid > 0)
2033 			close_filed(f);
2034 	}
2035 	if (signo) {
2036 		dprintf("syslogd: exiting on signal %d\n", signo);
2037 		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
2038 		errno = 0;
2039 		logerror(buf);
2040 	}
2041 	STAILQ_FOREACH(sl, &shead, next) {
2042 		if (sl->sl_ss.ss_family == AF_LOCAL)
2043 			unlink(sl->sl_peer->pe_name);
2044 	}
2045 	pidfile_remove(pfh);
2046 
2047 	exit(1);
2048 }
2049 
2050 static int
2051 configfiles(const struct dirent *dp)
2052 {
2053 	const char *p;
2054 	size_t ext_len;
2055 
2056 	if (dp->d_name[0] == '.')
2057 		return (0);
2058 
2059 	ext_len = sizeof(include_ext) -1;
2060 
2061 	if (dp->d_namlen <= ext_len)
2062 		return (0);
2063 
2064 	p = &dp->d_name[dp->d_namlen - ext_len];
2065 	if (strcmp(p, include_ext) != 0)
2066 		return (0);
2067 
2068 	return (1);
2069 }
2070 
2071 static void
2072 readconfigfile(FILE *cf, int allow_includes)
2073 {
2074 	FILE *cf2;
2075 	struct filed *f;
2076 	struct dirent **ent;
2077 	char cline[LINE_MAX];
2078 	char host[MAXHOSTNAMELEN];
2079 	char prog[LINE_MAX];
2080 	char file[MAXPATHLEN];
2081 	char *p, *tmp;
2082 	int i, nents;
2083 	size_t include_len;
2084 
2085 	/*
2086 	 *  Foreach line in the conf table, open that file.
2087 	 */
2088 	include_len = sizeof(include_str) -1;
2089 	(void)strlcpy(host, "*", sizeof(host));
2090 	(void)strlcpy(prog, "*", sizeof(prog));
2091 	while (fgets(cline, sizeof(cline), cf) != NULL) {
2092 		/*
2093 		 * check for end-of-section, comments, strip off trailing
2094 		 * spaces and newline character. #!prog is treated specially:
2095 		 * following lines apply only to that program.
2096 		 */
2097 		for (p = cline; isspace(*p); ++p)
2098 			continue;
2099 		if (*p == 0)
2100 			continue;
2101 		if (allow_includes &&
2102 		    strncmp(p, include_str, include_len) == 0 &&
2103 		    isspace(p[include_len])) {
2104 			p += include_len;
2105 			while (isspace(*p))
2106 				p++;
2107 			tmp = p;
2108 			while (*tmp != '\0' && !isspace(*tmp))
2109 				tmp++;
2110 			*tmp = '\0';
2111 			dprintf("Trying to include files in '%s'\n", p);
2112 			nents = scandir(p, &ent, configfiles, alphasort);
2113 			if (nents == -1) {
2114 				dprintf("Unable to open '%s': %s\n", p,
2115 				    strerror(errno));
2116 				continue;
2117 			}
2118 			for (i = 0; i < nents; i++) {
2119 				if (snprintf(file, sizeof(file), "%s/%s", p,
2120 				    ent[i]->d_name) >= (int)sizeof(file)) {
2121 					dprintf("ignoring path too long: "
2122 					    "'%s/%s'\n", p, ent[i]->d_name);
2123 					free(ent[i]);
2124 					continue;
2125 				}
2126 				free(ent[i]);
2127 				cf2 = fopen(file, "r");
2128 				if (cf2 == NULL)
2129 					continue;
2130 				dprintf("reading %s\n", file);
2131 				readconfigfile(cf2, 0);
2132 				fclose(cf2);
2133 			}
2134 			free(ent);
2135 			continue;
2136 		}
2137 		if (*p == '#') {
2138 			p++;
2139 			if (*p != '!' && *p != '+' && *p != '-')
2140 				continue;
2141 		}
2142 		if (*p == '+' || *p == '-') {
2143 			host[0] = *p++;
2144 			while (isspace(*p))
2145 				p++;
2146 			if ((!*p) || (*p == '*')) {
2147 				(void)strlcpy(host, "*", sizeof(host));
2148 				continue;
2149 			}
2150 			if (*p == '@')
2151 				p = LocalHostName;
2152 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
2153 				if (!isalnum(*p) && *p != '.' && *p != '-'
2154 				    && *p != ',' && *p != ':' && *p != '%')
2155 					break;
2156 				host[i] = *p++;
2157 			}
2158 			host[i] = '\0';
2159 			continue;
2160 		}
2161 		if (*p == '!') {
2162 			p++;
2163 			while (isspace(*p)) p++;
2164 			if ((!*p) || (*p == '*')) {
2165 				(void)strlcpy(prog, "*", sizeof(prog));
2166 				continue;
2167 			}
2168 			for (i = 0; i < LINE_MAX - 1; i++) {
2169 				if (!isprint(p[i]) || isspace(p[i]))
2170 					break;
2171 				prog[i] = p[i];
2172 			}
2173 			prog[i] = 0;
2174 			continue;
2175 		}
2176 		for (p = cline + 1; *p != '\0'; p++) {
2177 			if (*p != '#')
2178 				continue;
2179 			if (*(p - 1) == '\\') {
2180 				strcpy(p - 1, p);
2181 				p--;
2182 				continue;
2183 			}
2184 			*p = '\0';
2185 			break;
2186 		}
2187 		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
2188 			cline[i] = '\0';
2189 		f = cfline(cline, prog, host);
2190 		if (f != NULL)
2191 			addfile(f);
2192 		free(f);
2193 	}
2194 }
2195 
2196 static void
2197 sighandler(int signo)
2198 {
2199 
2200 	/* Send an wake-up signal to the select() loop. */
2201 	write(sigpipe[1], &signo, sizeof(signo));
2202 }
2203 
2204 /*
2205  *  INIT -- Initialize syslogd from configuration table
2206  */
2207 static void
2208 init(int signo)
2209 {
2210 	int i;
2211 	FILE *cf;
2212 	struct filed *f;
2213 	char *p;
2214 	char oldLocalHostName[MAXHOSTNAMELEN];
2215 	char hostMsg[2*MAXHOSTNAMELEN+40];
2216 	char bootfileMsg[LINE_MAX];
2217 
2218 	dprintf("init\n");
2219 	WantInitialize = 0;
2220 
2221 	/*
2222 	 * Load hostname (may have changed).
2223 	 */
2224 	if (signo != 0)
2225 		(void)strlcpy(oldLocalHostName, LocalHostName,
2226 		    sizeof(oldLocalHostName));
2227 	if (gethostname(LocalHostName, sizeof(LocalHostName)))
2228 		err(EX_OSERR, "gethostname() failed");
2229 	if ((p = strchr(LocalHostName, '.')) != NULL) {
2230 		*p++ = '\0';
2231 		LocalDomain = p;
2232 	} else {
2233 		LocalDomain = "";
2234 	}
2235 
2236 	/*
2237 	 * Load / reload timezone data (in case it changed).
2238 	 *
2239 	 * Just calling tzset() again does not work, the timezone code
2240 	 * caches the result.  However, by setting the TZ variable, one
2241 	 * can defeat the caching and have the timezone code really
2242 	 * reload the timezone data.  Respect any initial setting of
2243 	 * TZ, in case the system is configured specially.
2244 	 */
2245 	dprintf("loading timezone data via tzset()\n");
2246 	if (getenv("TZ")) {
2247 		tzset();
2248 	} else {
2249 		setenv("TZ", ":/etc/localtime", 1);
2250 		tzset();
2251 		unsetenv("TZ");
2252 	}
2253 
2254 	/*
2255 	 *  Close all open log files.
2256 	 */
2257 	Initialized = 0;
2258 	STAILQ_FOREACH(f, &fhead, next) {
2259 		/* flush any pending output */
2260 		if (f->f_prevcount)
2261 			fprintlog_successive(f, 0);
2262 
2263 		switch (f->f_type) {
2264 		case F_FILE:
2265 		case F_FORW:
2266 		case F_CONSOLE:
2267 		case F_TTY:
2268 			close_filed(f);
2269 			break;
2270 		case F_PIPE:
2271 			deadq_enter(f->fu_pipe_pid, f->fu_pipe_pname);
2272 			close_filed(f);
2273 			break;
2274 		}
2275 	}
2276 	while(!STAILQ_EMPTY(&fhead)) {
2277 		f = STAILQ_FIRST(&fhead);
2278 		STAILQ_REMOVE_HEAD(&fhead, next);
2279 		free(f->f_program);
2280 		free(f->f_host);
2281 		free(f);
2282 	}
2283 
2284 	/* open the configuration file */
2285 	if ((cf = fopen(ConfFile, "r")) == NULL) {
2286 		dprintf("cannot open %s\n", ConfFile);
2287 		f = cfline("*.ERR\t/dev/console", "*", "*");
2288 		if (f != NULL)
2289 			addfile(f);
2290 		free(f);
2291 		f = cfline("*.PANIC\t*", "*", "*");
2292 		if (f != NULL)
2293 			addfile(f);
2294 		free(f);
2295 		Initialized = 1;
2296 
2297 		return;
2298 	}
2299 
2300 	readconfigfile(cf, 1);
2301 
2302 	/* close the configuration file */
2303 	(void)fclose(cf);
2304 
2305 	Initialized = 1;
2306 
2307 	if (Debug) {
2308 		int port;
2309 		STAILQ_FOREACH(f, &fhead, next) {
2310 			for (i = 0; i <= LOG_NFACILITIES; i++)
2311 				if (f->f_pmask[i] == INTERNAL_NOPRI)
2312 					printf("X ");
2313 				else
2314 					printf("%d ", f->f_pmask[i]);
2315 			printf("%s: ", TypeNames[f->f_type]);
2316 			switch (f->f_type) {
2317 			case F_FILE:
2318 				printf("%s", f->fu_fname);
2319 				break;
2320 
2321 			case F_CONSOLE:
2322 			case F_TTY:
2323 				printf("%s%s", _PATH_DEV, f->fu_fname);
2324 				break;
2325 
2326 			case F_FORW:
2327 				switch (f->fu_forw_addr->ai_addr->sa_family) {
2328 #ifdef INET
2329 				case AF_INET:
2330 					port = ntohs(satosin(f->fu_forw_addr->ai_addr)->sin_port);
2331 					break;
2332 #endif
2333 #ifdef INET6
2334 				case AF_INET6:
2335 					port = ntohs(satosin6(f->fu_forw_addr->ai_addr)->sin6_port);
2336 					break;
2337 #endif
2338 				default:
2339 					port = 0;
2340 				}
2341 				if (port != 514) {
2342 					printf("%s:%d",
2343 						f->fu_forw_hname, port);
2344 				} else {
2345 					printf("%s", f->fu_forw_hname);
2346 				}
2347 				break;
2348 
2349 			case F_PIPE:
2350 				printf("%s", f->fu_pipe_pname);
2351 				break;
2352 
2353 			case F_USERS:
2354 				for (i = 0; i < MAXUNAMES && *f->fu_uname[i]; i++)
2355 					printf("%s, ", f->fu_uname[i]);
2356 				break;
2357 			}
2358 			if (f->f_program)
2359 				printf(" (%s)", f->f_program);
2360 			printf("\n");
2361 		}
2362 	}
2363 
2364 	logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd", NULL,
2365 	    NULL, NULL, "restart", 0);
2366 	dprintf("syslogd: restarted\n");
2367 	/*
2368 	 * Log a change in hostname, but only on a restart.
2369 	 */
2370 	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
2371 		(void)snprintf(hostMsg, sizeof(hostMsg),
2372 		    "hostname changed, \"%s\" to \"%s\"",
2373 		    oldLocalHostName, LocalHostName);
2374 		logmsg(LOG_SYSLOG | LOG_INFO, NULL, LocalHostName, "syslogd",
2375 		    NULL, NULL, NULL, hostMsg, 0);
2376 		dprintf("%s\n", hostMsg);
2377 	}
2378 	/*
2379 	 * Log the kernel boot file if we aren't going to use it as
2380 	 * the prefix, and if this is *not* a restart.
2381 	 */
2382 	if (signo == 0 && !use_bootfile) {
2383 		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
2384 		    "kernel boot file is %s", bootfile);
2385 		logmsg(LOG_KERN | LOG_INFO, NULL, LocalHostName, "syslogd",
2386 		    NULL, NULL, NULL, bootfileMsg, 0);
2387 		dprintf("%s\n", bootfileMsg);
2388 	}
2389 }
2390 
2391 /*
2392  * Crack a configuration file line
2393  */
2394 static struct filed *
2395 cfline(const char *line, const char *prog, const char *host)
2396 {
2397 	struct filed *f;
2398 	struct addrinfo hints, *res;
2399 	int error, i, pri, syncfile;
2400 	const char *p, *q;
2401 	char *bp;
2402 	char buf[MAXLINE], ebuf[100];
2403 
2404 	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
2405 
2406 	f = calloc(1, sizeof(*f));
2407 	if (f == NULL) {
2408 		logerror("malloc");
2409 		exit(1);
2410 	}
2411 	errno = 0;	/* keep strerror() stuff out of logerror messages */
2412 
2413 	for (i = 0; i <= LOG_NFACILITIES; i++)
2414 		f->f_pmask[i] = INTERNAL_NOPRI;
2415 
2416 	/* save hostname if any */
2417 	if (host && *host == '*')
2418 		host = NULL;
2419 	if (host) {
2420 		int hl;
2421 
2422 		f->f_host = strdup(host);
2423 		if (f->f_host == NULL) {
2424 			logerror("strdup");
2425 			exit(1);
2426 		}
2427 		hl = strlen(f->f_host);
2428 		if (hl > 0 && f->f_host[hl-1] == '.')
2429 			f->f_host[--hl] = '\0';
2430 		trimdomain(f->f_host, hl);
2431 	}
2432 
2433 	/* save program name if any */
2434 	if (prog && *prog == '*')
2435 		prog = NULL;
2436 	if (prog) {
2437 		f->f_program = strdup(prog);
2438 		if (f->f_program == NULL) {
2439 			logerror("strdup");
2440 			exit(1);
2441 		}
2442 	}
2443 
2444 	/* scan through the list of selectors */
2445 	for (p = line; *p && *p != '\t' && *p != ' ';) {
2446 		int pri_done;
2447 		int pri_cmp;
2448 		int pri_invert;
2449 
2450 		/* find the end of this facility name list */
2451 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2452 			continue;
2453 
2454 		/* get the priority comparison */
2455 		pri_cmp = 0;
2456 		pri_done = 0;
2457 		pri_invert = 0;
2458 		if (*q == '!') {
2459 			pri_invert = 1;
2460 			q++;
2461 		}
2462 		while (!pri_done) {
2463 			switch (*q) {
2464 			case '<':
2465 				pri_cmp |= PRI_LT;
2466 				q++;
2467 				break;
2468 			case '=':
2469 				pri_cmp |= PRI_EQ;
2470 				q++;
2471 				break;
2472 			case '>':
2473 				pri_cmp |= PRI_GT;
2474 				q++;
2475 				break;
2476 			default:
2477 				pri_done++;
2478 				break;
2479 			}
2480 		}
2481 
2482 		/* collect priority name */
2483 		for (bp = buf; *q && !strchr("\t,; ", *q); )
2484 			*bp++ = *q++;
2485 		*bp = '\0';
2486 
2487 		/* skip cruft */
2488 		while (strchr(",;", *q))
2489 			q++;
2490 
2491 		/* decode priority name */
2492 		if (*buf == '*') {
2493 			pri = LOG_PRIMASK;
2494 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2495 		} else {
2496 			/* Ignore trailing spaces. */
2497 			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2498 				buf[i] = '\0';
2499 
2500 			pri = decode(buf, prioritynames);
2501 			if (pri < 0) {
2502 				errno = 0;
2503 				(void)snprintf(ebuf, sizeof ebuf,
2504 				    "unknown priority name \"%s\"", buf);
2505 				logerror(ebuf);
2506 				free(f);
2507 				return (NULL);
2508 			}
2509 		}
2510 		if (!pri_cmp)
2511 			pri_cmp = (UniquePriority)
2512 				  ? (PRI_EQ)
2513 				  : (PRI_EQ | PRI_GT)
2514 				  ;
2515 		if (pri_invert)
2516 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2517 
2518 		/* scan facilities */
2519 		while (*p && !strchr("\t.; ", *p)) {
2520 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
2521 				*bp++ = *p++;
2522 			*bp = '\0';
2523 
2524 			if (*buf == '*') {
2525 				for (i = 0; i < LOG_NFACILITIES; i++) {
2526 					f->f_pmask[i] = pri;
2527 					f->f_pcmp[i] = pri_cmp;
2528 				}
2529 			} else {
2530 				i = decode(buf, facilitynames);
2531 				if (i < 0) {
2532 					errno = 0;
2533 					(void)snprintf(ebuf, sizeof ebuf,
2534 					    "unknown facility name \"%s\"",
2535 					    buf);
2536 					logerror(ebuf);
2537 					free(f);
2538 					return (NULL);
2539 				}
2540 				f->f_pmask[i >> 3] = pri;
2541 				f->f_pcmp[i >> 3] = pri_cmp;
2542 			}
2543 			while (*p == ',' || *p == ' ')
2544 				p++;
2545 		}
2546 
2547 		p = q;
2548 	}
2549 
2550 	/* skip to action part */
2551 	while (*p == '\t' || *p == ' ')
2552 		p++;
2553 
2554 	if (*p == '-') {
2555 		syncfile = 0;
2556 		p++;
2557 	} else
2558 		syncfile = 1;
2559 
2560 	switch (*p) {
2561 	case '@':
2562 		{
2563 			char *tp;
2564 			char endkey = ':';
2565 			/*
2566 			 * scan forward to see if there is a port defined.
2567 			 * so we can't use strlcpy..
2568 			 */
2569 			i = sizeof(f->fu_forw_hname);
2570 			tp = f->fu_forw_hname;
2571 			p++;
2572 
2573 			/*
2574 			 * an ipv6 address should start with a '[' in that case
2575 			 * we should scan for a ']'
2576 			 */
2577 			if (*p == '[') {
2578 				p++;
2579 				endkey = ']';
2580 			}
2581 			while (*p && (*p != endkey) && (i-- > 0)) {
2582 				*tp++ = *p++;
2583 			}
2584 			if (endkey == ']' && *p == endkey)
2585 				p++;
2586 			*tp = '\0';
2587 		}
2588 		/* See if we copied a domain and have a port */
2589 		if (*p == ':')
2590 			p++;
2591 		else
2592 			p = NULL;
2593 
2594 		hints = (struct addrinfo){
2595 			.ai_family = family,
2596 			.ai_socktype = SOCK_DGRAM
2597 		};
2598 		error = getaddrinfo(f->fu_forw_hname,
2599 				p ? p : "syslog", &hints, &res);
2600 		if (error) {
2601 			logerror(gai_strerror(error));
2602 			break;
2603 		}
2604 		f->fu_forw_addr = res;
2605 		f->f_type = F_FORW;
2606 		break;
2607 
2608 	case '/':
2609 		if ((f->f_file = open(p, logflags, 0600)) < 0) {
2610 			f->f_type = F_UNUSED;
2611 			logerror(p);
2612 			break;
2613 		}
2614 		if (syncfile)
2615 			f->f_flags |= FFLAG_SYNC;
2616 		if (isatty(f->f_file)) {
2617 			if (strcmp(p, ctty) == 0)
2618 				f->f_type = F_CONSOLE;
2619 			else
2620 				f->f_type = F_TTY;
2621 			(void)strlcpy(f->fu_fname, p + sizeof(_PATH_DEV) - 1,
2622 			    sizeof(f->fu_fname));
2623 		} else {
2624 			(void)strlcpy(f->fu_fname, p, sizeof(f->fu_fname));
2625 			f->f_type = F_FILE;
2626 		}
2627 		break;
2628 
2629 	case '|':
2630 		f->fu_pipe_pid = 0;
2631 		(void)strlcpy(f->fu_pipe_pname, p + 1,
2632 		    sizeof(f->fu_pipe_pname));
2633 		f->f_type = F_PIPE;
2634 		break;
2635 
2636 	case '*':
2637 		f->f_type = F_WALL;
2638 		break;
2639 
2640 	default:
2641 		for (i = 0; i < MAXUNAMES && *p; i++) {
2642 			for (q = p; *q && *q != ','; )
2643 				q++;
2644 			(void)strncpy(f->fu_uname[i], p, MAXLOGNAME - 1);
2645 			if ((q - p) >= MAXLOGNAME)
2646 				f->fu_uname[i][MAXLOGNAME - 1] = '\0';
2647 			else
2648 				f->fu_uname[i][q - p] = '\0';
2649 			while (*q == ',' || *q == ' ')
2650 				q++;
2651 			p = q;
2652 		}
2653 		f->f_type = F_USERS;
2654 		break;
2655 	}
2656 	return (f);
2657 }
2658 
2659 
2660 /*
2661  *  Decode a symbolic name to a numeric value
2662  */
2663 static int
2664 decode(const char *name, const CODE *codetab)
2665 {
2666 	const CODE *c;
2667 	char *p, buf[40];
2668 
2669 	if (isdigit(*name))
2670 		return (atoi(name));
2671 
2672 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2673 		if (isupper(*name))
2674 			*p = tolower(*name);
2675 		else
2676 			*p = *name;
2677 	}
2678 	*p = '\0';
2679 	for (c = codetab; c->c_name; c++)
2680 		if (!strcmp(buf, c->c_name))
2681 			return (c->c_val);
2682 
2683 	return (-1);
2684 }
2685 
2686 static void
2687 markit(void)
2688 {
2689 	struct filed *f;
2690 	struct deadq_entry *dq, *dq0;
2691 
2692 	now = time((time_t *)NULL);
2693 	MarkSeq += TIMERINTVL;
2694 	if (MarkSeq >= MarkInterval) {
2695 		logmsg(LOG_INFO, NULL, LocalHostName, NULL, NULL, NULL, NULL,
2696 		    "-- MARK --", MARK);
2697 		MarkSeq = 0;
2698 	}
2699 
2700 	STAILQ_FOREACH(f, &fhead, next) {
2701 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2702 			dprintf("flush %s: repeated %d times, %d sec.\n",
2703 			    TypeNames[f->f_type], f->f_prevcount,
2704 			    repeatinterval[f->f_repeatcount]);
2705 			fprintlog_successive(f, 0);
2706 			BACKOFF(f);
2707 		}
2708 	}
2709 
2710 	/* Walk the dead queue, and see if we should signal somebody. */
2711 	TAILQ_FOREACH_SAFE(dq, &deadq_head, dq_entries, dq0) {
2712 		switch (dq->dq_timeout) {
2713 		case 0:
2714 			/* Already signalled once, try harder now. */
2715 			if (kill(dq->dq_pid, SIGKILL) != 0)
2716 				(void)deadq_remove(dq);
2717 			break;
2718 
2719 		case 1:
2720 			/*
2721 			 * Timed out on dead queue, send terminate
2722 			 * signal.  Note that we leave the removal
2723 			 * from the dead queue to reapchild(), which
2724 			 * will also log the event (unless the process
2725 			 * didn't even really exist, in case we simply
2726 			 * drop it from the dead queue).
2727 			 */
2728 			if (kill(dq->dq_pid, SIGTERM) != 0)
2729 				(void)deadq_remove(dq);
2730 			else
2731 				dq->dq_timeout--;
2732 			break;
2733 		default:
2734 			dq->dq_timeout--;
2735 		}
2736 	}
2737 	MarkSet = 0;
2738 	(void)alarm(TIMERINTVL);
2739 }
2740 
2741 /*
2742  * fork off and become a daemon, but wait for the child to come online
2743  * before returning to the parent, or we get disk thrashing at boot etc.
2744  * Set a timer so we don't hang forever if it wedges.
2745  */
2746 static int
2747 waitdaemon(int maxwait)
2748 {
2749 	int fd;
2750 	int status;
2751 	pid_t pid, childpid;
2752 
2753 	switch (childpid = fork()) {
2754 	case -1:
2755 		return (-1);
2756 	case 0:
2757 		break;
2758 	default:
2759 		signal(SIGALRM, timedout);
2760 		alarm(maxwait);
2761 		while ((pid = wait3(&status, 0, NULL)) != -1) {
2762 			if (WIFEXITED(status))
2763 				errx(1, "child pid %d exited with return code %d",
2764 					pid, WEXITSTATUS(status));
2765 			if (WIFSIGNALED(status))
2766 				errx(1, "child pid %d exited on signal %d%s",
2767 					pid, WTERMSIG(status),
2768 					WCOREDUMP(status) ? " (core dumped)" :
2769 					"");
2770 			if (pid == childpid)	/* it's gone... */
2771 				break;
2772 		}
2773 		exit(0);
2774 	}
2775 
2776 	if (setsid() == -1)
2777 		return (-1);
2778 
2779 	(void)chdir("/");
2780 	if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2781 		(void)dup2(fd, STDIN_FILENO);
2782 		(void)dup2(fd, STDOUT_FILENO);
2783 		(void)dup2(fd, STDERR_FILENO);
2784 		if (fd > STDERR_FILENO)
2785 			(void)close(fd);
2786 	}
2787 	return (getppid());
2788 }
2789 
2790 /*
2791  * We get a SIGALRM from the child when it's running and finished doing it's
2792  * fsync()'s or O_SYNC writes for all the boot messages.
2793  *
2794  * We also get a signal from the kernel if the timer expires, so check to
2795  * see what happened.
2796  */
2797 static void
2798 timedout(int sig __unused)
2799 {
2800 	int left;
2801 	left = alarm(0);
2802 	signal(SIGALRM, SIG_DFL);
2803 	if (left == 0)
2804 		errx(1, "timed out waiting for child");
2805 	else
2806 		_exit(0);
2807 }
2808 
2809 /*
2810  * Add `s' to the list of allowable peer addresses to accept messages
2811  * from.
2812  *
2813  * `s' is a string in the form:
2814  *
2815  *    [*]domainname[:{servicename|portnumber|*}]
2816  *
2817  * or
2818  *
2819  *    netaddr/maskbits[:{servicename|portnumber|*}]
2820  *
2821  * Returns -1 on error, 0 if the argument was valid.
2822  */
2823 static int
2824 allowaddr(char *s)
2825 {
2826 #if defined(INET) || defined(INET6)
2827 	char *cp1, *cp2;
2828 	struct allowedpeer *ap;
2829 	struct servent *se;
2830 	int masklen = -1;
2831 	struct addrinfo hints, *res = NULL;
2832 #ifdef INET
2833 	in_addr_t *addrp, *maskp;
2834 #endif
2835 #ifdef INET6
2836 	uint32_t *addr6p, *mask6p;
2837 #endif
2838 	char ip[NI_MAXHOST];
2839 
2840 	ap = calloc(1, sizeof(*ap));
2841 	if (ap == NULL)
2842 		err(1, "malloc failed");
2843 
2844 #ifdef INET6
2845 	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2846 #endif
2847 		cp1 = s;
2848 	if ((cp1 = strrchr(cp1, ':'))) {
2849 		/* service/port provided */
2850 		*cp1++ = '\0';
2851 		if (strlen(cp1) == 1 && *cp1 == '*')
2852 			/* any port allowed */
2853 			ap->port = 0;
2854 		else if ((se = getservbyname(cp1, "udp"))) {
2855 			ap->port = ntohs(se->s_port);
2856 		} else {
2857 			ap->port = strtol(cp1, &cp2, 0);
2858 			/* port not numeric */
2859 			if (*cp2 != '\0')
2860 				goto err;
2861 		}
2862 	} else {
2863 		if ((se = getservbyname("syslog", "udp")))
2864 			ap->port = ntohs(se->s_port);
2865 		else
2866 			/* sanity, should not happen */
2867 			ap->port = 514;
2868 	}
2869 
2870 	if ((cp1 = strchr(s, '/')) != NULL &&
2871 	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2872 		*cp1 = '\0';
2873 		if ((masklen = atoi(cp1 + 1)) < 0)
2874 			goto err;
2875 	}
2876 #ifdef INET6
2877 	if (*s == '[') {
2878 		cp2 = s + strlen(s) - 1;
2879 		if (*cp2 == ']') {
2880 			++s;
2881 			*cp2 = '\0';
2882 		} else {
2883 			cp2 = NULL;
2884 		}
2885 	} else {
2886 		cp2 = NULL;
2887 	}
2888 #endif
2889 	hints = (struct addrinfo){
2890 		.ai_family = PF_UNSPEC,
2891 		.ai_socktype = SOCK_DGRAM,
2892 		.ai_flags = AI_PASSIVE | AI_NUMERICHOST
2893 	};
2894 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2895 		ap->isnumeric = 1;
2896 		memcpy(&ap->a_addr, res->ai_addr, res->ai_addrlen);
2897 		ap->a_mask = (struct sockaddr_storage){
2898 			.ss_family = res->ai_family,
2899 			.ss_len = res->ai_addrlen
2900 		};
2901 		switch (res->ai_family) {
2902 #ifdef INET
2903 		case AF_INET:
2904 			maskp = &sstosin(&ap->a_mask)->sin_addr.s_addr;
2905 			addrp = &sstosin(&ap->a_addr)->sin_addr.s_addr;
2906 			if (masklen < 0) {
2907 				/* use default netmask */
2908 				if (IN_CLASSA(ntohl(*addrp)))
2909 					*maskp = htonl(IN_CLASSA_NET);
2910 				else if (IN_CLASSB(ntohl(*addrp)))
2911 					*maskp = htonl(IN_CLASSB_NET);
2912 				else
2913 					*maskp = htonl(IN_CLASSC_NET);
2914 			} else if (masklen == 0) {
2915 				*maskp = 0;
2916 			} else if (masklen <= 32) {
2917 				/* convert masklen to netmask */
2918 				*maskp = htonl(~((1 << (32 - masklen)) - 1));
2919 			} else {
2920 				goto err;
2921 			}
2922 			/* Lose any host bits in the network number. */
2923 			*addrp &= *maskp;
2924 			break;
2925 #endif
2926 #ifdef INET6
2927 		case AF_INET6:
2928 			if (masklen > 128)
2929 				goto err;
2930 
2931 			if (masklen < 0)
2932 				masklen = 128;
2933 			mask6p = (uint32_t *)&sstosin6(&ap->a_mask)->sin6_addr.s6_addr32[0];
2934 			addr6p = (uint32_t *)&sstosin6(&ap->a_addr)->sin6_addr.s6_addr32[0];
2935 			/* convert masklen to netmask */
2936 			while (masklen > 0) {
2937 				if (masklen < 32) {
2938 					*mask6p =
2939 					    htonl(~(0xffffffff >> masklen));
2940 					*addr6p &= *mask6p;
2941 					break;
2942 				} else {
2943 					*mask6p++ = 0xffffffff;
2944 					addr6p++;
2945 					masklen -= 32;
2946 				}
2947 			}
2948 			break;
2949 #endif
2950 		default:
2951 			goto err;
2952 		}
2953 		freeaddrinfo(res);
2954 	} else {
2955 		/* arg `s' is domain name */
2956 		ap->isnumeric = 0;
2957 		ap->a_name = s;
2958 		if (cp1)
2959 			*cp1 = '/';
2960 #ifdef INET6
2961 		if (cp2) {
2962 			*cp2 = ']';
2963 			--s;
2964 		}
2965 #endif
2966 	}
2967 	STAILQ_INSERT_TAIL(&aphead, ap, next);
2968 
2969 	if (Debug) {
2970 		printf("allowaddr: rule ");
2971 		if (ap->isnumeric) {
2972 			printf("numeric, ");
2973 			getnameinfo(sstosa(&ap->a_addr),
2974 				    (sstosa(&ap->a_addr))->sa_len,
2975 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2976 			printf("addr = %s, ", ip);
2977 			getnameinfo(sstosa(&ap->a_mask),
2978 				    (sstosa(&ap->a_mask))->sa_len,
2979 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2980 			printf("mask = %s; ", ip);
2981 		} else {
2982 			printf("domainname = %s; ", ap->a_name);
2983 		}
2984 		printf("port = %d\n", ap->port);
2985 	}
2986 #endif
2987 
2988 	return (0);
2989 err:
2990 	if (res != NULL)
2991 		freeaddrinfo(res);
2992 	free(ap);
2993 	return (-1);
2994 }
2995 
2996 /*
2997  * Validate that the remote peer has permission to log to us.
2998  */
2999 static int
3000 validate(struct sockaddr *sa, const char *hname)
3001 {
3002 	int i;
3003 	char name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
3004 	struct allowedpeer *ap;
3005 #ifdef INET
3006 	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
3007 #endif
3008 #ifdef INET6
3009 	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
3010 #endif
3011 	struct addrinfo hints, *res;
3012 	u_short sport;
3013 	int num = 0;
3014 
3015 	STAILQ_FOREACH(ap, &aphead, next) {
3016 		num++;
3017 	}
3018 	dprintf("# of validation rule: %d\n", num);
3019 	if (num == 0)
3020 		/* traditional behaviour, allow everything */
3021 		return (1);
3022 
3023 	(void)strlcpy(name, hname, sizeof(name));
3024 	hints = (struct addrinfo){
3025 		.ai_family = PF_UNSPEC,
3026 		.ai_socktype = SOCK_DGRAM,
3027 		.ai_flags = AI_PASSIVE | AI_NUMERICHOST
3028 	};
3029 	if (getaddrinfo(name, NULL, &hints, &res) == 0)
3030 		freeaddrinfo(res);
3031 	else if (strchr(name, '.') == NULL) {
3032 		strlcat(name, ".", sizeof name);
3033 		strlcat(name, LocalDomain, sizeof name);
3034 	}
3035 	if (getnameinfo(sa, sa->sa_len, ip, sizeof(ip), port, sizeof(port),
3036 			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
3037 		return (0);	/* for safety, should not occur */
3038 	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
3039 		ip, port, name);
3040 	sport = atoi(port);
3041 
3042 	/* now, walk down the list */
3043 	i = 0;
3044 	STAILQ_FOREACH(ap, &aphead, next) {
3045 		i++;
3046 		if (ap->port != 0 && ap->port != sport) {
3047 			dprintf("rejected in rule %d due to port mismatch.\n",
3048 			    i);
3049 			continue;
3050 		}
3051 
3052 		if (ap->isnumeric) {
3053 			if (ap->a_addr.ss_family != sa->sa_family) {
3054 				dprintf("rejected in rule %d due to address family mismatch.\n", i);
3055 				continue;
3056 			}
3057 #ifdef INET
3058 			else if (ap->a_addr.ss_family == AF_INET) {
3059 				sin4 = satosin(sa);
3060 				a4p = satosin(&ap->a_addr);
3061 				m4p = satosin(&ap->a_mask);
3062 				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
3063 				    != a4p->sin_addr.s_addr) {
3064 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
3065 					continue;
3066 				}
3067 			}
3068 #endif
3069 #ifdef INET6
3070 			else if (ap->a_addr.ss_family == AF_INET6) {
3071 				sin6 = satosin6(sa);
3072 				a6p = satosin6(&ap->a_addr);
3073 				m6p = satosin6(&ap->a_mask);
3074 				if (a6p->sin6_scope_id != 0 &&
3075 				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
3076 					dprintf("rejected in rule %d due to scope mismatch.\n", i);
3077 					continue;
3078 				}
3079 				if (IN6_ARE_MASKED_ADDR_EQUAL(&sin6->sin6_addr,
3080 				    &a6p->sin6_addr, &m6p->sin6_addr) != 0) {
3081 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
3082 					continue;
3083 				}
3084 			}
3085 #endif
3086 			else
3087 				continue;
3088 		} else {
3089 			if (fnmatch(ap->a_name, name, FNM_NOESCAPE) ==
3090 			    FNM_NOMATCH) {
3091 				dprintf("rejected in rule %d due to name "
3092 				    "mismatch.\n", i);
3093 				continue;
3094 			}
3095 		}
3096 		dprintf("accepted in rule %d.\n", i);
3097 		return (1);	/* hooray! */
3098 	}
3099 	return (0);
3100 }
3101 
3102 /*
3103  * Fairly similar to popen(3), but returns an open descriptor, as
3104  * opposed to a FILE *.
3105  */
3106 static int
3107 p_open(const char *prog, pid_t *rpid)
3108 {
3109 	int pfd[2], nulldesc;
3110 	pid_t pid;
3111 	char *argv[4]; /* sh -c cmd NULL */
3112 	char errmsg[200];
3113 
3114 	if (pipe(pfd) == -1)
3115 		return (-1);
3116 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
3117 		/* we are royally screwed anyway */
3118 		return (-1);
3119 
3120 	switch ((pid = fork())) {
3121 	case -1:
3122 		close(nulldesc);
3123 		return (-1);
3124 
3125 	case 0:
3126 		(void)setsid();	/* Avoid catching SIGHUPs. */
3127 		argv[0] = strdup("sh");
3128 		argv[1] = strdup("-c");
3129 		argv[2] = strdup(prog);
3130 		argv[3] = NULL;
3131 		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
3132 			logerror("strdup");
3133 			exit(1);
3134 		}
3135 
3136 		alarm(0);
3137 
3138 		/* Restore signals marked as SIG_IGN. */
3139 		(void)signal(SIGINT, SIG_DFL);
3140 		(void)signal(SIGQUIT, SIG_DFL);
3141 		(void)signal(SIGPIPE, SIG_DFL);
3142 
3143 		dup2(pfd[0], STDIN_FILENO);
3144 		dup2(nulldesc, STDOUT_FILENO);
3145 		dup2(nulldesc, STDERR_FILENO);
3146 		closefrom(STDERR_FILENO + 1);
3147 
3148 		(void)execvp(_PATH_BSHELL, argv);
3149 		_exit(255);
3150 	}
3151 	close(nulldesc);
3152 	close(pfd[0]);
3153 	/*
3154 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
3155 	 * supposed to get an EWOULDBLOCK on writev(2), which is
3156 	 * caught by the logic above anyway, which will in turn close
3157 	 * the pipe, and fork a new logging subprocess if necessary.
3158 	 * The stale subprocess will be killed some time later unless
3159 	 * it terminated itself due to closing its input pipe (so we
3160 	 * get rid of really dead puppies).
3161 	 */
3162 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
3163 		/* This is bad. */
3164 		(void)snprintf(errmsg, sizeof errmsg,
3165 			       "Warning: cannot change pipe to PID %d to "
3166 			       "non-blocking behaviour.",
3167 			       (int)pid);
3168 		logerror(errmsg);
3169 	}
3170 	*rpid = pid;
3171 	return (pfd[1]);
3172 }
3173 
3174 static void
3175 deadq_enter(pid_t pid, const char *name)
3176 {
3177 	struct deadq_entry *dq;
3178 	int status;
3179 
3180 	if (pid == 0)
3181 		return;
3182 	/*
3183 	 * Be paranoid, if we can't signal the process, don't enter it
3184 	 * into the dead queue (perhaps it's already dead).  If possible,
3185 	 * we try to fetch and log the child's status.
3186 	 */
3187 	if (kill(pid, 0) != 0) {
3188 		if (waitpid(pid, &status, WNOHANG) > 0)
3189 			log_deadchild(pid, status, name);
3190 		return;
3191 	}
3192 
3193 	dq = malloc(sizeof(*dq));
3194 	if (dq == NULL) {
3195 		logerror("malloc");
3196 		exit(1);
3197 	}
3198 	*dq = (struct deadq_entry){
3199 		.dq_pid = pid,
3200 		.dq_timeout = DQ_TIMO_INIT
3201 	};
3202 	TAILQ_INSERT_TAIL(&deadq_head, dq, dq_entries);
3203 }
3204 
3205 static int
3206 deadq_remove(struct deadq_entry *dq)
3207 {
3208 	if (dq != NULL) {
3209 		TAILQ_REMOVE(&deadq_head, dq, dq_entries);
3210 		free(dq);
3211 		return (1);
3212 	}
3213 
3214 	return (0);
3215 }
3216 
3217 static int
3218 deadq_removebypid(pid_t pid)
3219 {
3220 	struct deadq_entry *dq;
3221 
3222 	TAILQ_FOREACH(dq, &deadq_head, dq_entries) {
3223 		if (dq->dq_pid == pid)
3224 			break;
3225 	}
3226 	return (deadq_remove(dq));
3227 }
3228 
3229 static void
3230 log_deadchild(pid_t pid, int status, const char *name)
3231 {
3232 	int code;
3233 	char buf[256];
3234 	const char *reason;
3235 
3236 	errno = 0; /* Keep strerror() stuff out of logerror messages. */
3237 	if (WIFSIGNALED(status)) {
3238 		reason = "due to signal";
3239 		code = WTERMSIG(status);
3240 	} else {
3241 		reason = "with status";
3242 		code = WEXITSTATUS(status);
3243 		if (code == 0)
3244 			return;
3245 	}
3246 	(void)snprintf(buf, sizeof buf,
3247 		       "Logging subprocess %d (%s) exited %s %d.",
3248 		       pid, name, reason, code);
3249 	logerror(buf);
3250 }
3251 
3252 static int
3253 socksetup(struct peer *pe)
3254 {
3255 	struct addrinfo hints, *res, *res0;
3256 	int error;
3257 	char *cp;
3258 	int (*sl_recv)(struct socklist *);
3259 	/*
3260 	 * We have to handle this case for backwards compatibility:
3261 	 * If there are two (or more) colons but no '[' and ']',
3262 	 * assume this is an inet6 address without a service.
3263 	 */
3264 	if (pe->pe_name != NULL) {
3265 #ifdef INET6
3266 		if (pe->pe_name[0] == '[' &&
3267 		    (cp = strchr(pe->pe_name + 1, ']')) != NULL) {
3268 			pe->pe_name = &pe->pe_name[1];
3269 			*cp = '\0';
3270 			if (cp[1] == ':' && cp[2] != '\0')
3271 				pe->pe_serv = cp + 2;
3272 		} else {
3273 #endif
3274 			cp = strchr(pe->pe_name, ':');
3275 			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
3276 				*cp = '\0';
3277 				if (cp[1] != '\0')
3278 					pe->pe_serv = cp + 1;
3279 				if (cp == pe->pe_name)
3280 					pe->pe_name = NULL;
3281 			}
3282 #ifdef INET6
3283 		}
3284 #endif
3285 	}
3286 	hints = (struct addrinfo){
3287 		.ai_family = AF_UNSPEC,
3288 		.ai_socktype = SOCK_DGRAM,
3289 		.ai_flags = AI_PASSIVE
3290 	};
3291 	if (pe->pe_name != NULL)
3292 		dprintf("Trying peer: %s\n", pe->pe_name);
3293 	if (pe->pe_serv == NULL)
3294 		pe->pe_serv = "syslog";
3295 	error = getaddrinfo(pe->pe_name, pe->pe_serv, &hints, &res0);
3296 	if (error) {
3297 		char *msgbuf;
3298 
3299 		asprintf(&msgbuf, "getaddrinfo failed for %s%s: %s",
3300 		    pe->pe_name == NULL ? "" : pe->pe_name, pe->pe_serv,
3301 		    gai_strerror(error));
3302 		errno = 0;
3303 		if (msgbuf == NULL)
3304 			logerror(gai_strerror(error));
3305 		else
3306 			logerror(msgbuf);
3307 		free(msgbuf);
3308 		die(0);
3309 	}
3310 	for (res = res0; res != NULL; res = res->ai_next) {
3311 		int s;
3312 
3313 		if (res->ai_family != AF_LOCAL &&
3314 		    SecureMode > 1) {
3315 			/* Only AF_LOCAL in secure mode. */
3316 			continue;
3317 		}
3318 		if (family != AF_UNSPEC &&
3319 		    res->ai_family != AF_LOCAL && res->ai_family != family)
3320 			continue;
3321 
3322 		s = socket(res->ai_family, res->ai_socktype,
3323 		    res->ai_protocol);
3324 		if (s < 0) {
3325 			logerror("socket");
3326 			error++;
3327 			continue;
3328 		}
3329 #ifdef INET6
3330 		if (res->ai_family == AF_INET6) {
3331 			if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
3332 			       &(int){1}, sizeof(int)) < 0) {
3333 				logerror("setsockopt(IPV6_V6ONLY)");
3334 				close(s);
3335 				error++;
3336 				continue;
3337 			}
3338 		}
3339 #endif
3340 		if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
3341 		    &(int){1}, sizeof(int)) < 0) {
3342 			logerror("setsockopt(SO_REUSEADDR)");
3343 			close(s);
3344 			error++;
3345 			continue;
3346 		}
3347 
3348 		/*
3349 		 * Bind INET and UNIX-domain sockets.
3350 		 *
3351 		 * A UNIX-domain socket is always bound to a pathname
3352 		 * regardless of -N flag.
3353 		 *
3354 		 * For INET sockets, RFC 3164 recommends that client
3355 		 * side message should come from the privileged syslogd port.
3356 		 *
3357 		 * If the system administrator chooses not to obey
3358 		 * this, we can skip the bind() step so that the
3359 		 * system will choose a port for us.
3360 		 */
3361 		if (res->ai_family == AF_LOCAL)
3362 			unlink(pe->pe_name);
3363 		if (res->ai_family == AF_LOCAL ||
3364 		    NoBind == 0 || pe->pe_name != NULL) {
3365 			if (bind(s, res->ai_addr, res->ai_addrlen) < 0) {
3366 				logerror("bind");
3367 				close(s);
3368 				error++;
3369 				continue;
3370 			}
3371 			if (res->ai_family == AF_LOCAL ||
3372 			    SecureMode == 0)
3373 				increase_rcvbuf(s);
3374 		}
3375 		if (res->ai_family == AF_LOCAL &&
3376 		    chmod(pe->pe_name, pe->pe_mode) < 0) {
3377 			dprintf("chmod %s: %s\n", pe->pe_name,
3378 			    strerror(errno));
3379 			close(s);
3380 			error++;
3381 			continue;
3382 		}
3383 		dprintf("new socket fd is %d\n", s);
3384 		if (res->ai_socktype != SOCK_DGRAM) {
3385 			listen(s, 5);
3386 		}
3387 		sl_recv = socklist_recv_sock;
3388 #if defined(INET) || defined(INET6)
3389 		if (SecureMode && (res->ai_family == AF_INET ||
3390 		    res->ai_family == AF_INET6)) {
3391 			dprintf("shutdown\n");
3392 			/* Forbid communication in secure mode. */
3393 			if (shutdown(s, SHUT_RD) < 0 &&
3394 			    errno != ENOTCONN) {
3395 				logerror("shutdown");
3396 				if (!Debug)
3397 					die(0);
3398 			}
3399 			sl_recv = NULL;
3400 		} else
3401 #endif
3402 			dprintf("listening on socket\n");
3403 		dprintf("sending on socket\n");
3404 		addsock(res->ai_addr, res->ai_addrlen,
3405 		    &(struct socklist){
3406 			.sl_socket = s,
3407 			.sl_peer = pe,
3408 			.sl_recv = sl_recv
3409 		});
3410 	}
3411 	freeaddrinfo(res0);
3412 
3413 	return(error);
3414 }
3415 
3416 static void
3417 increase_rcvbuf(int fd)
3418 {
3419 	socklen_t len;
3420 
3421 	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len,
3422 	    &(socklen_t){sizeof(len)}) == 0) {
3423 		if (len < RCVBUF_MINSIZE) {
3424 			len = RCVBUF_MINSIZE;
3425 			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
3426 		}
3427 	}
3428 }
3429