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