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