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