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