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