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