xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision 168fce73b59d6023cab45d063a452551a1f2103e)
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 <dirent.h>
99 #include <err.h>
100 #include <errno.h>
101 #include <fcntl.h>
102 #include <libutil.h>
103 #include <limits.h>
104 #include <paths.h>
105 #include <signal.h>
106 #include <stdio.h>
107 #include <stdlib.h>
108 #include <string.h>
109 #include <sysexits.h>
110 #include <unistd.h>
111 #include <utmpx.h>
112 
113 #include "pathnames.h"
114 #include "ttymsg.h"
115 
116 #define SYSLOG_NAMES
117 #include <sys/syslog.h>
118 
119 const char	*ConfFile = _PATH_LOGCONF;
120 const char	*PidFile = _PATH_LOGPID;
121 const char	ctty[] = _PATH_CONSOLE;
122 static const char	include_str[] = "include";
123 static const char	include_ext[] = ".conf";
124 
125 #define	dprintf		if (Debug) printf
126 
127 #define	MAXUNAMES	20	/* maximum number of user names */
128 
129 /*
130  * List of hosts for binding.
131  */
132 static STAILQ_HEAD(, host) hqueue;
133 struct host {
134 	char			*name;
135 	STAILQ_ENTRY(host)	next;
136 };
137 
138 /*
139  * Unix sockets.
140  * We have two default sockets, one with 666 permissions,
141  * and one for privileged programs.
142  */
143 struct funix {
144 	int			s;
145 	const char		*name;
146 	mode_t			mode;
147 	STAILQ_ENTRY(funix)	next;
148 };
149 struct funix funix_secure =	{ -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
150 				{ NULL } };
151 struct funix funix_default =	{ -1, _PATH_LOG, DEFFILEMODE,
152 				{ &funix_secure } };
153 
154 STAILQ_HEAD(, funix) funixes =	{ &funix_default,
155 				&(funix_secure.next.stqe_next) };
156 
157 /*
158  * Flags to logmsg().
159  */
160 
161 #define	IGN_CONS	0x001	/* don't print on console */
162 #define	SYNC_FILE	0x002	/* do fsync on file after printing */
163 #define	ADDDATE		0x004	/* add a date to the message */
164 #define	MARK		0x008	/* this message is a mark */
165 #define	ISKERNEL	0x010	/* kernel generated message */
166 
167 /*
168  * This structure represents the files that will have log
169  * copies printed.
170  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
171  * or if f_type if F_PIPE and f_pid > 0.
172  */
173 
174 struct filed {
175 	struct	filed *f_next;		/* next in linked list */
176 	short	f_type;			/* entry type, see below */
177 	short	f_file;			/* file descriptor */
178 	time_t	f_time;			/* time this was last written */
179 	char	*f_host;		/* host from which to recd. */
180 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
181 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
182 #define PRI_LT	0x1
183 #define PRI_EQ	0x2
184 #define PRI_GT	0x4
185 	char	*f_program;		/* program this applies to */
186 	union {
187 		char	f_uname[MAXUNAMES][MAXLOGNAME];
188 		struct {
189 			char	f_hname[MAXHOSTNAMELEN];
190 			struct addrinfo *f_addr;
191 
192 		} f_forw;		/* forwarding address */
193 		char	f_fname[MAXPATHLEN];
194 		struct {
195 			char	f_pname[MAXPATHLEN];
196 			pid_t	f_pid;
197 		} f_pipe;
198 	} f_un;
199 	char	f_prevline[MAXSVLINE];		/* last message logged */
200 	char	f_lasttime[16];			/* time of last occurrence */
201 	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
202 	int	f_prevpri;			/* pri of f_prevline */
203 	int	f_prevlen;			/* length of f_prevline */
204 	int	f_prevcount;			/* repetition cnt of prevline */
205 	u_int	f_repeatcount;			/* number of "repeated" msgs */
206 	int	f_flags;			/* file-specific flags */
207 #define	FFLAG_SYNC 0x01
208 #define	FFLAG_NEEDSYNC	0x02
209 };
210 
211 /*
212  * Queue of about-to-be dead processes we should watch out for.
213  */
214 
215 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
216 struct stailhead *deadq_headp;
217 
218 struct deadq_entry {
219 	pid_t				dq_pid;
220 	int				dq_timeout;
221 	TAILQ_ENTRY(deadq_entry)	dq_entries;
222 };
223 
224 /*
225  * The timeout to apply to processes waiting on the dead queue.  Unit
226  * of measure is `mark intervals', i.e. 20 minutes by default.
227  * Processes on the dead queue will be terminated after that time.
228  */
229 
230 #define	 DQ_TIMO_INIT	2
231 
232 typedef struct deadq_entry *dq_t;
233 
234 
235 /*
236  * Struct to hold records of network addresses that are allowed to log
237  * to us.
238  */
239 struct allowedpeer {
240 	int isnumeric;
241 	u_short port;
242 	union {
243 		struct {
244 			struct sockaddr_storage addr;
245 			struct sockaddr_storage mask;
246 		} numeric;
247 		char *name;
248 	} u;
249 #define a_addr u.numeric.addr
250 #define a_mask u.numeric.mask
251 #define a_name u.name
252 };
253 
254 
255 /*
256  * Intervals at which we flush out "message repeated" messages,
257  * in seconds after previous message is logged.  After each flush,
258  * we move to the next interval until we reach the largest.
259  */
260 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
261 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
262 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
263 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
264 				 (f)->f_repeatcount = MAXREPEAT; \
265 			}
266 
267 /* values for f_type */
268 #define F_UNUSED	0		/* unused entry */
269 #define F_FILE		1		/* regular file */
270 #define F_TTY		2		/* terminal */
271 #define F_CONSOLE	3		/* console terminal */
272 #define F_FORW		4		/* remote machine */
273 #define F_USERS		5		/* list of users */
274 #define F_WALL		6		/* everyone logged on */
275 #define F_PIPE		7		/* pipe to program */
276 
277 const char *TypeNames[8] = {
278 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
279 	"FORW",		"USERS",	"WALL",		"PIPE"
280 };
281 
282 static struct filed *Files;	/* Log files that we write to */
283 static struct filed consfile;	/* Console */
284 
285 static int	Debug;		/* debug flag */
286 static int	Foreground = 0;	/* Run in foreground, instead of daemonizing */
287 static int	resolve = 1;	/* resolve hostname */
288 static char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
289 static const char *LocalDomain;	/* our local domain name */
290 static int	*finet;		/* Internet datagram sockets */
291 static int	fklog = -1;	/* /dev/klog */
292 static int	Initialized;	/* set when we have initialized ourselves */
293 static int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
294 static int	MarkSeq;	/* mark sequence number */
295 static int	NoBind;		/* don't bind() as suggested by RFC 3164 */
296 static int	SecureMode;	/* when true, receive only unix domain socks */
297 #ifdef INET6
298 static int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
299 #else
300 static int	family = PF_INET; /* protocol family (IPv4 only) */
301 #endif
302 static int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
303 static int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
304 static int	use_bootfile;	/* log entire bootfile for every kern msg */
305 static int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
306 static int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
307 
308 static char	bootfile[MAXLINE+1]; /* booted kernel file */
309 
310 struct allowedpeer *AllowedPeers; /* List of allowed peers */
311 static int	NumAllowed;	/* Number of entries in AllowedPeers */
312 static int	RemoteAddDate;	/* Always set the date on remote messages */
313 
314 static int	UniquePriority;	/* Only log specified priority? */
315 static int	LogFacPri;	/* Put facility and priority in log message: */
316 				/* 0=no, 1=numeric, 2=names */
317 static int	KeepKernFac;	/* Keep remotely logged kernel facility */
318 static int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
319 static struct pidfh *pfh;
320 
321 volatile sig_atomic_t MarkSet, WantDie;
322 
323 static int	allowaddr(char *);
324 static void	cfline(const char *, struct filed *,
325 		    const char *, const char *);
326 static const char *cvthname(struct sockaddr *);
327 static void	deadq_enter(pid_t, const char *);
328 static int	deadq_remove(pid_t);
329 static int	decode(const char *, const CODE *);
330 static void	die(int) __dead2;
331 static void	dodie(int);
332 static void	dofsync(void);
333 static void	domark(int);
334 static void	fprintlog(struct filed *, int, const char *);
335 static int	*socksetup(int, char *);
336 static void	init(int);
337 static void	logerror(const char *);
338 static void	logmsg(int, const char *, const char *, int);
339 static void	log_deadchild(pid_t, int, const char *);
340 static void	markit(void);
341 static int	skip_message(const char *, const char *, int);
342 static void	printline(const char *, char *, int);
343 static void	printsys(char *);
344 static int	p_open(const char *, pid_t *);
345 static void	readklog(void);
346 static void	reapchild(int);
347 static const char *ttymsg_check(struct iovec *, int, char *, int);
348 static void	usage(void);
349 static int	validate(struct sockaddr *, const char *);
350 static void	unmapped(struct sockaddr *);
351 static void	wallmsg(struct filed *, struct iovec *, const int iovlen);
352 static int	waitdaemon(int, int, int);
353 static void	timedout(int);
354 static void	increase_rcvbuf(int);
355 
356 static void
357 close_filed(struct filed *f)
358 {
359 
360 	if (f == NULL || f->f_file == -1)
361 		return;
362 
363 	(void)close(f->f_file);
364 	f->f_file = -1;
365 	f->f_type = F_UNUSED;
366 }
367 
368 int
369 main(int argc, char *argv[])
370 {
371 	int ch, i, fdsrmax = 0, l;
372 	struct sockaddr_un sunx, fromunix;
373 	struct sockaddr_storage frominet;
374 	fd_set *fdsr = NULL;
375 	char line[MAXLINE + 1];
376 	const char *hname;
377 	struct timeval tv, *tvp;
378 	struct sigaction sact;
379 	struct host *host;
380 	struct funix *fx, *fx1;
381 	sigset_t mask;
382 	pid_t ppid = 1, spid;
383 	socklen_t len;
384 
385 	if (madvise(NULL, 0, MADV_PROTECT) != 0)
386 		dprintf("madvise() failed: %s\n", strerror(errno));
387 
388 	STAILQ_INIT(&hqueue);
389 
390 	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:Fkl:m:nNop:P:sS:Tuv"))
391 	    != -1)
392 		switch (ch) {
393 		case '4':
394 			family = PF_INET;
395 			break;
396 #ifdef INET6
397 		case '6':
398 			family = PF_INET6;
399 			break;
400 #endif
401 		case '8':
402 			mask_C1 = 0;
403 			break;
404 		case 'A':
405 			send_to_all++;
406 			break;
407 		case 'a':		/* allow specific network addresses only */
408 			if (allowaddr(optarg) == -1)
409 				usage();
410 			break;
411 		case 'b':
412 		   {
413 			if ((host = malloc(sizeof(struct host))) == NULL)
414 				err(1, "malloc failed");
415 			host->name = optarg;
416 			STAILQ_INSERT_TAIL(&hqueue, host, next);
417 			break;
418 		   }
419 		case 'c':
420 			no_compress++;
421 			break;
422 		case 'C':
423 			logflags |= O_CREAT;
424 			break;
425 		case 'd':		/* debug */
426 			Debug++;
427 			break;
428 		case 'f':		/* configuration file */
429 			ConfFile = optarg;
430 			break;
431 		case 'F':		/* run in foreground instead of daemon */
432 			Foreground++;
433 			break;
434 		case 'k':		/* keep remote kern fac */
435 			KeepKernFac = 1;
436 			break;
437 		case 'l':
438 		    {
439 			long	perml;
440 			mode_t	mode;
441 			char	*name, *ep;
442 
443 			if (optarg[0] == '/') {
444 				mode = DEFFILEMODE;
445 				name = optarg;
446 			} else if ((name = strchr(optarg, ':')) != NULL) {
447 				*name++ = '\0';
448 				if (name[0] != '/')
449 					errx(1, "socket name must be absolute "
450 					    "path");
451 				if (isdigit(*optarg)) {
452 					perml = strtol(optarg, &ep, 8);
453 				    if (*ep || perml < 0 ||
454 					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
455 					    errx(1, "invalid mode %s, exiting",
456 						optarg);
457 				    mode = (mode_t )perml;
458 				} else
459 					errx(1, "invalid mode %s, exiting",
460 					    optarg);
461 			} else	/* doesn't begin with '/', and no ':' */
462 				errx(1, "can't parse path %s", optarg);
463 
464 			if (strlen(name) >= sizeof(sunx.sun_path))
465 				errx(1, "%s path too long, exiting", name);
466 			if ((fx = malloc(sizeof(struct funix))) == NULL)
467 				err(1, "malloc failed");
468 			fx->s = -1;
469 			fx->name = name;
470 			fx->mode = mode;
471 			STAILQ_INSERT_TAIL(&funixes, fx, next);
472 			break;
473 		   }
474 		case 'm':		/* mark interval */
475 			MarkInterval = atoi(optarg) * 60;
476 			break;
477 		case 'N':
478 			NoBind = 1;
479 			SecureMode = 1;
480 			break;
481 		case 'n':
482 			resolve = 0;
483 			break;
484 		case 'o':
485 			use_bootfile = 1;
486 			break;
487 		case 'p':		/* path */
488 			if (strlen(optarg) >= sizeof(sunx.sun_path))
489 				errx(1, "%s path too long, exiting", optarg);
490 			funix_default.name = optarg;
491 			break;
492 		case 'P':		/* path for alt. PID */
493 			PidFile = optarg;
494 			break;
495 		case 's':		/* no network mode */
496 			SecureMode++;
497 			break;
498 		case 'S':		/* path for privileged originator */
499 			if (strlen(optarg) >= sizeof(sunx.sun_path))
500 				errx(1, "%s path too long, exiting", optarg);
501 			funix_secure.name = optarg;
502 			break;
503 		case 'T':
504 			RemoteAddDate = 1;
505 			break;
506 		case 'u':		/* only log specified priority */
507 			UniquePriority++;
508 			break;
509 		case 'v':		/* log facility and priority */
510 		  	LogFacPri++;
511 			break;
512 		default:
513 			usage();
514 		}
515 	if ((argc -= optind) != 0)
516 		usage();
517 
518 	pfh = pidfile_open(PidFile, 0600, &spid);
519 	if (pfh == NULL) {
520 		if (errno == EEXIST)
521 			errx(1, "syslogd already running, pid: %d", spid);
522 		warn("cannot open pid file");
523 	}
524 
525 	if ((!Foreground) && (!Debug)) {
526 		ppid = waitdaemon(0, 0, 30);
527 		if (ppid < 0) {
528 			warn("could not become daemon");
529 			pidfile_remove(pfh);
530 			exit(1);
531 		}
532 	} else if (Debug) {
533 		setlinebuf(stdout);
534 	}
535 
536 	if (NumAllowed)
537 		endservent();
538 
539 	consfile.f_type = F_CONSOLE;
540 	(void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
541 	    sizeof(consfile.f_un.f_fname));
542 	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
543 	(void)signal(SIGTERM, dodie);
544 	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
545 	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
546 	/*
547 	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
548 	 * with each other; they are likely candidates for being called
549 	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
550 	 * SIGCHLD happens).
551 	 */
552 	sigemptyset(&mask);
553 	sigaddset(&mask, SIGHUP);
554 	sact.sa_handler = reapchild;
555 	sact.sa_mask = mask;
556 	sact.sa_flags = SA_RESTART;
557 	(void)sigaction(SIGCHLD, &sact, NULL);
558 	(void)signal(SIGALRM, domark);
559 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
560 	(void)alarm(TIMERINTVL);
561 
562 	TAILQ_INIT(&deadq_head);
563 
564 #ifndef SUN_LEN
565 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
566 #endif
567 	STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
568 		(void)unlink(fx->name);
569 		memset(&sunx, 0, sizeof(sunx));
570 		sunx.sun_family = AF_LOCAL;
571 		(void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
572 		fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
573 		if (fx->s < 0 ||
574 		    bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
575 		    chmod(fx->name, fx->mode) < 0) {
576 			(void)snprintf(line, sizeof line,
577 					"cannot create %s", fx->name);
578 			logerror(line);
579 			dprintf("cannot create %s (%d)\n", fx->name, errno);
580 			if (fx == &funix_default || fx == &funix_secure)
581 				die(0);
582 			else {
583 				STAILQ_REMOVE(&funixes, fx, funix, next);
584 				continue;
585 			}
586 		}
587 		increase_rcvbuf(fx->s);
588 	}
589 	if (SecureMode <= 1) {
590 		if (STAILQ_EMPTY(&hqueue))
591 			finet = socksetup(family, NULL);
592 		STAILQ_FOREACH(host, &hqueue, next) {
593 			int *finet0, total;
594 			finet0 = socksetup(family, host->name);
595 			if (finet0 && !finet) {
596 				finet = finet0;
597 			} else if (finet0 && finet) {
598 				total = *finet0 + *finet + 1;
599 				finet = realloc(finet, total * sizeof(int));
600 				if (finet == NULL)
601 					err(1, "realloc failed");
602 				for (i = 1; i <= *finet0; i++) {
603 					finet[(*finet)+i] = finet0[i];
604 				}
605 				*finet = total - 1;
606 				free(finet0);
607 			}
608 		}
609 	}
610 
611 	if (finet) {
612 		if (SecureMode) {
613 			for (i = 0; i < *finet; i++) {
614 				if (shutdown(finet[i+1], SHUT_RD) < 0 &&
615 				    errno != ENOTCONN) {
616 					logerror("shutdown");
617 					if (!Debug)
618 						die(0);
619 				}
620 			}
621 		} else {
622 			dprintf("listening on inet and/or inet6 socket\n");
623 		}
624 		dprintf("sending on inet and/or inet6 socket\n");
625 	}
626 
627 	if ((fklog = open(_PATH_KLOG, O_RDONLY|O_NONBLOCK, 0)) < 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 static int
1608 configfiles(const struct dirent *dp)
1609 {
1610 	const char *p;
1611 	size_t ext_len;
1612 
1613 	if (dp->d_name[0] == '.')
1614 		return (0);
1615 
1616 	ext_len = sizeof(include_ext) -1;
1617 
1618 	if (dp->d_namlen <= ext_len)
1619 		return (0);
1620 
1621 	p = &dp->d_name[dp->d_namlen - ext_len];
1622 	if (strcmp(p, include_ext) != 0)
1623 		return (0);
1624 
1625 	return (1);
1626 }
1627 
1628 static void
1629 readconfigfile(FILE *cf, struct filed **nextp, int allow_includes)
1630 {
1631 	FILE *cf2;
1632 	struct filed *f;
1633 	struct dirent **ent;
1634 	char cline[LINE_MAX];
1635 	char host[MAXHOSTNAMELEN];
1636 	char prog[LINE_MAX];
1637 	char file[MAXPATHLEN];
1638 	char *p, *tmp;
1639 	int i, nents;
1640 	size_t include_len;
1641 
1642 	/*
1643 	 *  Foreach line in the conf table, open that file.
1644 	 */
1645 	f = NULL;
1646 	include_len = sizeof(include_str) -1;
1647 	(void)strlcpy(host, "*", sizeof(host));
1648 	(void)strlcpy(prog, "*", sizeof(prog));
1649 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1650 		/*
1651 		 * check for end-of-section, comments, strip off trailing
1652 		 * spaces and newline character. #!prog is treated specially:
1653 		 * following lines apply only to that program.
1654 		 */
1655 		for (p = cline; isspace(*p); ++p)
1656 			continue;
1657 		if (*p == 0)
1658 			continue;
1659 		if (allow_includes &&
1660 		    strncmp(p, include_str, include_len) == 0 &&
1661 		    isspace(p[include_len])) {
1662 			p += include_len;
1663 			while (isspace(*p))
1664 				p++;
1665 			tmp = p;
1666 			while (*tmp != '\0' && !isspace(*tmp))
1667 				tmp++;
1668 			*tmp = '\0';
1669 			dprintf("Trying to include files in '%s'\n", p);
1670 			nents = scandir(p, &ent, configfiles, alphasort);
1671 			if (nents == -1) {
1672 				dprintf("Unable to open '%s': %s\n", p,
1673 				    strerror(errno));
1674 				continue;
1675 			}
1676 			for (i = 0; i < nents; i++) {
1677 				if (snprintf(file, sizeof(file), "%s/%s", p,
1678 				    ent[i]->d_name) >= (int)sizeof(file)) {
1679 					dprintf("ignoring path too long: "
1680 					    "'%s/%s'\n", p, ent[i]->d_name);
1681 					free(ent[i]);
1682 					continue;
1683 				}
1684 				free(ent[i]);
1685 				cf2 = fopen(file, "r");
1686 				if (cf2 == NULL)
1687 					continue;
1688 				dprintf("reading %s\n", file);
1689 				readconfigfile(cf2, nextp, 0);
1690 				fclose(cf2);
1691 			}
1692 			free(ent);
1693 			continue;
1694 		}
1695 		if (*p == '#') {
1696 			p++;
1697 			if (*p != '!' && *p != '+' && *p != '-')
1698 				continue;
1699 		}
1700 		if (*p == '+' || *p == '-') {
1701 			host[0] = *p++;
1702 			while (isspace(*p))
1703 				p++;
1704 			if ((!*p) || (*p == '*')) {
1705 				(void)strlcpy(host, "*", sizeof(host));
1706 				continue;
1707 			}
1708 			if (*p == '@')
1709 				p = LocalHostName;
1710 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1711 				if (!isalnum(*p) && *p != '.' && *p != '-'
1712 				    && *p != ',' && *p != ':' && *p != '%')
1713 					break;
1714 				host[i] = *p++;
1715 			}
1716 			host[i] = '\0';
1717 			continue;
1718 		}
1719 		if (*p == '!') {
1720 			p++;
1721 			while (isspace(*p)) p++;
1722 			if ((!*p) || (*p == '*')) {
1723 				(void)strlcpy(prog, "*", sizeof(prog));
1724 				continue;
1725 			}
1726 			for (i = 0; i < LINE_MAX - 1; i++) {
1727 				if (!isprint(p[i]) || isspace(p[i]))
1728 					break;
1729 				prog[i] = p[i];
1730 			}
1731 			prog[i] = 0;
1732 			continue;
1733 		}
1734 		for (p = cline + 1; *p != '\0'; p++) {
1735 			if (*p != '#')
1736 				continue;
1737 			if (*(p - 1) == '\\') {
1738 				strcpy(p - 1, p);
1739 				p--;
1740 				continue;
1741 			}
1742 			*p = '\0';
1743 			break;
1744 		}
1745 		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1746 			cline[i] = '\0';
1747 		f = (struct filed *)calloc(1, sizeof(*f));
1748 		if (f == NULL) {
1749 			logerror("calloc");
1750 			exit(1);
1751 		}
1752 		*nextp = f;
1753 		nextp = &f->f_next;
1754 		cfline(cline, f, prog, host);
1755 	}
1756 }
1757 
1758 /*
1759  *  INIT -- Initialize syslogd from configuration table
1760  */
1761 static void
1762 init(int signo)
1763 {
1764 	int i;
1765 	FILE *cf;
1766 	struct filed *f, *next, **nextp;
1767 	char *p;
1768 	char oldLocalHostName[MAXHOSTNAMELEN];
1769 	char hostMsg[2*MAXHOSTNAMELEN+40];
1770 	char bootfileMsg[LINE_MAX];
1771 
1772 	dprintf("init\n");
1773 
1774 	/*
1775 	 * Load hostname (may have changed).
1776 	 */
1777 	if (signo != 0)
1778 		(void)strlcpy(oldLocalHostName, LocalHostName,
1779 		    sizeof(oldLocalHostName));
1780 	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1781 		err(EX_OSERR, "gethostname() failed");
1782 	if ((p = strchr(LocalHostName, '.')) != NULL) {
1783 		*p++ = '\0';
1784 		LocalDomain = p;
1785 	} else {
1786 		LocalDomain = "";
1787 	}
1788 
1789 	/*
1790 	 * Load / reload timezone data (in case it changed).
1791 	 *
1792 	 * Just calling tzset() again does not work, the timezone code
1793 	 * caches the result.  However, by setting the TZ variable, one
1794 	 * can defeat the caching and have the timezone code really
1795 	 * reload the timezone data.  Respect any initial setting of
1796 	 * TZ, in case the system is configured specially.
1797 	 */
1798 	dprintf("loading timezone data via tzset()\n");
1799 	if (getenv("TZ")) {
1800 		tzset();
1801 	} else {
1802 		setenv("TZ", ":/etc/localtime", 1);
1803 		tzset();
1804 		unsetenv("TZ");
1805 	}
1806 
1807 	/*
1808 	 *  Close all open log files.
1809 	 */
1810 	Initialized = 0;
1811 	for (f = Files; f != NULL; f = next) {
1812 		/* flush any pending output */
1813 		if (f->f_prevcount)
1814 			fprintlog(f, 0, (char *)NULL);
1815 
1816 		switch (f->f_type) {
1817 		case F_FILE:
1818 		case F_FORW:
1819 		case F_CONSOLE:
1820 		case F_TTY:
1821 			close_filed(f);
1822 			break;
1823 		case F_PIPE:
1824 			if (f->f_un.f_pipe.f_pid > 0) {
1825 				close_filed(f);
1826 				deadq_enter(f->f_un.f_pipe.f_pid,
1827 					    f->f_un.f_pipe.f_pname);
1828 			}
1829 			f->f_un.f_pipe.f_pid = 0;
1830 			break;
1831 		}
1832 		next = f->f_next;
1833 		if (f->f_program) free(f->f_program);
1834 		if (f->f_host) free(f->f_host);
1835 		free((char *)f);
1836 	}
1837 	Files = NULL;
1838 
1839 	/* open the configuration file */
1840 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1841 		dprintf("cannot open %s\n", ConfFile);
1842 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1843 		if (*nextp == NULL) {
1844 			logerror("calloc");
1845 			exit(1);
1846 		}
1847 		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1848 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1849 		if ((*nextp)->f_next == NULL) {
1850 			logerror("calloc");
1851 			exit(1);
1852 		}
1853 		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1854 		Initialized = 1;
1855 		return;
1856 	}
1857 
1858 	readconfigfile(cf, &Files, 1);
1859 
1860 	/* close the configuration file */
1861 	(void)fclose(cf);
1862 
1863 	Initialized = 1;
1864 
1865 	if (Debug) {
1866 		int port;
1867 		for (f = Files; f; f = f->f_next) {
1868 			for (i = 0; i <= LOG_NFACILITIES; i++)
1869 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1870 					printf("X ");
1871 				else
1872 					printf("%d ", f->f_pmask[i]);
1873 			printf("%s: ", TypeNames[f->f_type]);
1874 			switch (f->f_type) {
1875 			case F_FILE:
1876 				printf("%s", f->f_un.f_fname);
1877 				break;
1878 
1879 			case F_CONSOLE:
1880 			case F_TTY:
1881 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1882 				break;
1883 
1884 			case F_FORW:
1885 				port = (int)ntohs(((struct sockaddr_in *)
1886 				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1887 				if (port != 514) {
1888 					printf("%s:%d",
1889 						f->f_un.f_forw.f_hname, port);
1890 				} else {
1891 					printf("%s", f->f_un.f_forw.f_hname);
1892 				}
1893 				break;
1894 
1895 			case F_PIPE:
1896 				printf("%s", f->f_un.f_pipe.f_pname);
1897 				break;
1898 
1899 			case F_USERS:
1900 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1901 					printf("%s, ", f->f_un.f_uname[i]);
1902 				break;
1903 			}
1904 			if (f->f_program)
1905 				printf(" (%s)", f->f_program);
1906 			printf("\n");
1907 		}
1908 	}
1909 
1910 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1911 	dprintf("syslogd: restarted\n");
1912 	/*
1913 	 * Log a change in hostname, but only on a restart.
1914 	 */
1915 	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1916 		(void)snprintf(hostMsg, sizeof(hostMsg),
1917 		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1918 		    oldLocalHostName, LocalHostName);
1919 		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1920 		dprintf("%s\n", hostMsg);
1921 	}
1922 	/*
1923 	 * Log the kernel boot file if we aren't going to use it as
1924 	 * the prefix, and if this is *not* a restart.
1925 	 */
1926 	if (signo == 0 && !use_bootfile) {
1927 		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1928 		    "syslogd: kernel boot file is %s", bootfile);
1929 		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1930 		dprintf("%s\n", bootfileMsg);
1931 	}
1932 }
1933 
1934 /*
1935  * Crack a configuration file line
1936  */
1937 static void
1938 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1939 {
1940 	struct addrinfo hints, *res;
1941 	int error, i, pri, syncfile;
1942 	const char *p, *q;
1943 	char *bp;
1944 	char buf[MAXLINE], ebuf[100];
1945 
1946 	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1947 
1948 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1949 
1950 	/* clear out file entry */
1951 	memset(f, 0, sizeof(*f));
1952 	for (i = 0; i <= LOG_NFACILITIES; i++)
1953 		f->f_pmask[i] = INTERNAL_NOPRI;
1954 
1955 	/* save hostname if any */
1956 	if (host && *host == '*')
1957 		host = NULL;
1958 	if (host) {
1959 		int hl;
1960 
1961 		f->f_host = strdup(host);
1962 		if (f->f_host == NULL) {
1963 			logerror("strdup");
1964 			exit(1);
1965 		}
1966 		hl = strlen(f->f_host);
1967 		if (hl > 0 && f->f_host[hl-1] == '.')
1968 			f->f_host[--hl] = '\0';
1969 		trimdomain(f->f_host, hl);
1970 	}
1971 
1972 	/* save program name if any */
1973 	if (prog && *prog == '*')
1974 		prog = NULL;
1975 	if (prog) {
1976 		f->f_program = strdup(prog);
1977 		if (f->f_program == NULL) {
1978 			logerror("strdup");
1979 			exit(1);
1980 		}
1981 	}
1982 
1983 	/* scan through the list of selectors */
1984 	for (p = line; *p && *p != '\t' && *p != ' ';) {
1985 		int pri_done;
1986 		int pri_cmp;
1987 		int pri_invert;
1988 
1989 		/* find the end of this facility name list */
1990 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1991 			continue;
1992 
1993 		/* get the priority comparison */
1994 		pri_cmp = 0;
1995 		pri_done = 0;
1996 		pri_invert = 0;
1997 		if (*q == '!') {
1998 			pri_invert = 1;
1999 			q++;
2000 		}
2001 		while (!pri_done) {
2002 			switch (*q) {
2003 			case '<':
2004 				pri_cmp |= PRI_LT;
2005 				q++;
2006 				break;
2007 			case '=':
2008 				pri_cmp |= PRI_EQ;
2009 				q++;
2010 				break;
2011 			case '>':
2012 				pri_cmp |= PRI_GT;
2013 				q++;
2014 				break;
2015 			default:
2016 				pri_done++;
2017 				break;
2018 			}
2019 		}
2020 
2021 		/* collect priority name */
2022 		for (bp = buf; *q && !strchr("\t,; ", *q); )
2023 			*bp++ = *q++;
2024 		*bp = '\0';
2025 
2026 		/* skip cruft */
2027 		while (strchr(",;", *q))
2028 			q++;
2029 
2030 		/* decode priority name */
2031 		if (*buf == '*') {
2032 			pri = LOG_PRIMASK;
2033 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2034 		} else {
2035 			/* Ignore trailing spaces. */
2036 			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2037 				buf[i] = '\0';
2038 
2039 			pri = decode(buf, prioritynames);
2040 			if (pri < 0) {
2041 				errno = 0;
2042 				(void)snprintf(ebuf, sizeof ebuf,
2043 				    "unknown priority name \"%s\"", buf);
2044 				logerror(ebuf);
2045 				return;
2046 			}
2047 		}
2048 		if (!pri_cmp)
2049 			pri_cmp = (UniquePriority)
2050 				  ? (PRI_EQ)
2051 				  : (PRI_EQ | PRI_GT)
2052 				  ;
2053 		if (pri_invert)
2054 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2055 
2056 		/* scan facilities */
2057 		while (*p && !strchr("\t.; ", *p)) {
2058 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
2059 				*bp++ = *p++;
2060 			*bp = '\0';
2061 
2062 			if (*buf == '*') {
2063 				for (i = 0; i < LOG_NFACILITIES; i++) {
2064 					f->f_pmask[i] = pri;
2065 					f->f_pcmp[i] = pri_cmp;
2066 				}
2067 			} else {
2068 				i = decode(buf, facilitynames);
2069 				if (i < 0) {
2070 					errno = 0;
2071 					(void)snprintf(ebuf, sizeof ebuf,
2072 					    "unknown facility name \"%s\"",
2073 					    buf);
2074 					logerror(ebuf);
2075 					return;
2076 				}
2077 				f->f_pmask[i >> 3] = pri;
2078 				f->f_pcmp[i >> 3] = pri_cmp;
2079 			}
2080 			while (*p == ',' || *p == ' ')
2081 				p++;
2082 		}
2083 
2084 		p = q;
2085 	}
2086 
2087 	/* skip to action part */
2088 	while (*p == '\t' || *p == ' ')
2089 		p++;
2090 
2091 	if (*p == '-') {
2092 		syncfile = 0;
2093 		p++;
2094 	} else
2095 		syncfile = 1;
2096 
2097 	switch (*p) {
2098 	case '@':
2099 		{
2100 			char *tp;
2101 			char endkey = ':';
2102 			/*
2103 			 * scan forward to see if there is a port defined.
2104 			 * so we can't use strlcpy..
2105 			 */
2106 			i = sizeof(f->f_un.f_forw.f_hname);
2107 			tp = f->f_un.f_forw.f_hname;
2108 			p++;
2109 
2110 			/*
2111 			 * an ipv6 address should start with a '[' in that case
2112 			 * we should scan for a ']'
2113 			 */
2114 			if (*p == '[') {
2115 				p++;
2116 				endkey = ']';
2117 			}
2118 			while (*p && (*p != endkey) && (i-- > 0)) {
2119 				*tp++ = *p++;
2120 			}
2121 			if (endkey == ']' && *p == endkey)
2122 				p++;
2123 			*tp = '\0';
2124 		}
2125 		/* See if we copied a domain and have a port */
2126 		if (*p == ':')
2127 			p++;
2128 		else
2129 			p = NULL;
2130 
2131 		memset(&hints, 0, sizeof(hints));
2132 		hints.ai_family = family;
2133 		hints.ai_socktype = SOCK_DGRAM;
2134 		error = getaddrinfo(f->f_un.f_forw.f_hname,
2135 				p ? p : "syslog", &hints, &res);
2136 		if (error) {
2137 			logerror(gai_strerror(error));
2138 			break;
2139 		}
2140 		f->f_un.f_forw.f_addr = res;
2141 		f->f_type = F_FORW;
2142 		break;
2143 
2144 	case '/':
2145 		if ((f->f_file = open(p, logflags, 0600)) < 0) {
2146 			f->f_type = F_UNUSED;
2147 			logerror(p);
2148 			break;
2149 		}
2150 		if (syncfile)
2151 			f->f_flags |= FFLAG_SYNC;
2152 		if (isatty(f->f_file)) {
2153 			if (strcmp(p, ctty) == 0)
2154 				f->f_type = F_CONSOLE;
2155 			else
2156 				f->f_type = F_TTY;
2157 			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2158 			    sizeof(f->f_un.f_fname));
2159 		} else {
2160 			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2161 			f->f_type = F_FILE;
2162 		}
2163 		break;
2164 
2165 	case '|':
2166 		f->f_un.f_pipe.f_pid = 0;
2167 		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2168 		    sizeof(f->f_un.f_pipe.f_pname));
2169 		f->f_type = F_PIPE;
2170 		break;
2171 
2172 	case '*':
2173 		f->f_type = F_WALL;
2174 		break;
2175 
2176 	default:
2177 		for (i = 0; i < MAXUNAMES && *p; i++) {
2178 			for (q = p; *q && *q != ','; )
2179 				q++;
2180 			(void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2181 			if ((q - p) >= MAXLOGNAME)
2182 				f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2183 			else
2184 				f->f_un.f_uname[i][q - p] = '\0';
2185 			while (*q == ',' || *q == ' ')
2186 				q++;
2187 			p = q;
2188 		}
2189 		f->f_type = F_USERS;
2190 		break;
2191 	}
2192 }
2193 
2194 
2195 /*
2196  *  Decode a symbolic name to a numeric value
2197  */
2198 static int
2199 decode(const char *name, const CODE *codetab)
2200 {
2201 	const CODE *c;
2202 	char *p, buf[40];
2203 
2204 	if (isdigit(*name))
2205 		return (atoi(name));
2206 
2207 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2208 		if (isupper(*name))
2209 			*p = tolower(*name);
2210 		else
2211 			*p = *name;
2212 	}
2213 	*p = '\0';
2214 	for (c = codetab; c->c_name; c++)
2215 		if (!strcmp(buf, c->c_name))
2216 			return (c->c_val);
2217 
2218 	return (-1);
2219 }
2220 
2221 static void
2222 markit(void)
2223 {
2224 	struct filed *f;
2225 	dq_t q, next;
2226 
2227 	now = time((time_t *)NULL);
2228 	MarkSeq += TIMERINTVL;
2229 	if (MarkSeq >= MarkInterval) {
2230 		logmsg(LOG_INFO, "-- MARK --",
2231 		    LocalHostName, ADDDATE|MARK);
2232 		MarkSeq = 0;
2233 	}
2234 
2235 	for (f = Files; f; f = f->f_next) {
2236 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2237 			dprintf("flush %s: repeated %d times, %d sec.\n",
2238 			    TypeNames[f->f_type], f->f_prevcount,
2239 			    repeatinterval[f->f_repeatcount]);
2240 			fprintlog(f, 0, (char *)NULL);
2241 			BACKOFF(f);
2242 		}
2243 	}
2244 
2245 	/* Walk the dead queue, and see if we should signal somebody. */
2246 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2247 		next = TAILQ_NEXT(q, dq_entries);
2248 
2249 		switch (q->dq_timeout) {
2250 		case 0:
2251 			/* Already signalled once, try harder now. */
2252 			if (kill(q->dq_pid, SIGKILL) != 0)
2253 				(void)deadq_remove(q->dq_pid);
2254 			break;
2255 
2256 		case 1:
2257 			/*
2258 			 * Timed out on dead queue, send terminate
2259 			 * signal.  Note that we leave the removal
2260 			 * from the dead queue to reapchild(), which
2261 			 * will also log the event (unless the process
2262 			 * didn't even really exist, in case we simply
2263 			 * drop it from the dead queue).
2264 			 */
2265 			if (kill(q->dq_pid, SIGTERM) != 0)
2266 				(void)deadq_remove(q->dq_pid);
2267 			/* FALLTHROUGH */
2268 
2269 		default:
2270 			q->dq_timeout--;
2271 		}
2272 	}
2273 	MarkSet = 0;
2274 	(void)alarm(TIMERINTVL);
2275 }
2276 
2277 /*
2278  * fork off and become a daemon, but wait for the child to come online
2279  * before returing to the parent, or we get disk thrashing at boot etc.
2280  * Set a timer so we don't hang forever if it wedges.
2281  */
2282 static int
2283 waitdaemon(int nochdir, int noclose, int maxwait)
2284 {
2285 	int fd;
2286 	int status;
2287 	pid_t pid, childpid;
2288 
2289 	switch (childpid = fork()) {
2290 	case -1:
2291 		return (-1);
2292 	case 0:
2293 		break;
2294 	default:
2295 		signal(SIGALRM, timedout);
2296 		alarm(maxwait);
2297 		while ((pid = wait3(&status, 0, NULL)) != -1) {
2298 			if (WIFEXITED(status))
2299 				errx(1, "child pid %d exited with return code %d",
2300 					pid, WEXITSTATUS(status));
2301 			if (WIFSIGNALED(status))
2302 				errx(1, "child pid %d exited on signal %d%s",
2303 					pid, WTERMSIG(status),
2304 					WCOREDUMP(status) ? " (core dumped)" :
2305 					"");
2306 			if (pid == childpid)	/* it's gone... */
2307 				break;
2308 		}
2309 		exit(0);
2310 	}
2311 
2312 	if (setsid() == -1)
2313 		return (-1);
2314 
2315 	if (!nochdir)
2316 		(void)chdir("/");
2317 
2318 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2319 		(void)dup2(fd, STDIN_FILENO);
2320 		(void)dup2(fd, STDOUT_FILENO);
2321 		(void)dup2(fd, STDERR_FILENO);
2322 		if (fd > 2)
2323 			(void)close (fd);
2324 	}
2325 	return (getppid());
2326 }
2327 
2328 /*
2329  * We get a SIGALRM from the child when it's running and finished doing it's
2330  * fsync()'s or O_SYNC writes for all the boot messages.
2331  *
2332  * We also get a signal from the kernel if the timer expires, so check to
2333  * see what happened.
2334  */
2335 static void
2336 timedout(int sig __unused)
2337 {
2338 	int left;
2339 	left = alarm(0);
2340 	signal(SIGALRM, SIG_DFL);
2341 	if (left == 0)
2342 		errx(1, "timed out waiting for child");
2343 	else
2344 		_exit(0);
2345 }
2346 
2347 /*
2348  * Add `s' to the list of allowable peer addresses to accept messages
2349  * from.
2350  *
2351  * `s' is a string in the form:
2352  *
2353  *    [*]domainname[:{servicename|portnumber|*}]
2354  *
2355  * or
2356  *
2357  *    netaddr/maskbits[:{servicename|portnumber|*}]
2358  *
2359  * Returns -1 on error, 0 if the argument was valid.
2360  */
2361 static int
2362 allowaddr(char *s)
2363 {
2364 	char *cp1, *cp2;
2365 	struct allowedpeer ap;
2366 	struct servent *se;
2367 	int masklen = -1;
2368 	struct addrinfo hints, *res;
2369 	struct in_addr *addrp, *maskp;
2370 #ifdef INET6
2371 	int i;
2372 	u_int32_t *addr6p, *mask6p;
2373 #endif
2374 	char ip[NI_MAXHOST];
2375 
2376 #ifdef INET6
2377 	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2378 #endif
2379 		cp1 = s;
2380 	if ((cp1 = strrchr(cp1, ':'))) {
2381 		/* service/port provided */
2382 		*cp1++ = '\0';
2383 		if (strlen(cp1) == 1 && *cp1 == '*')
2384 			/* any port allowed */
2385 			ap.port = 0;
2386 		else if ((se = getservbyname(cp1, "udp"))) {
2387 			ap.port = ntohs(se->s_port);
2388 		} else {
2389 			ap.port = strtol(cp1, &cp2, 0);
2390 			if (*cp2 != '\0')
2391 				return (-1); /* port not numeric */
2392 		}
2393 	} else {
2394 		if ((se = getservbyname("syslog", "udp")))
2395 			ap.port = ntohs(se->s_port);
2396 		else
2397 			/* sanity, should not happen */
2398 			ap.port = 514;
2399 	}
2400 
2401 	if ((cp1 = strchr(s, '/')) != NULL &&
2402 	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2403 		*cp1 = '\0';
2404 		if ((masklen = atoi(cp1 + 1)) < 0)
2405 			return (-1);
2406 	}
2407 #ifdef INET6
2408 	if (*s == '[') {
2409 		cp2 = s + strlen(s) - 1;
2410 		if (*cp2 == ']') {
2411 			++s;
2412 			*cp2 = '\0';
2413 		} else {
2414 			cp2 = NULL;
2415 		}
2416 	} else {
2417 		cp2 = NULL;
2418 	}
2419 #endif
2420 	memset(&hints, 0, sizeof(hints));
2421 	hints.ai_family = PF_UNSPEC;
2422 	hints.ai_socktype = SOCK_DGRAM;
2423 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2424 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2425 		ap.isnumeric = 1;
2426 		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2427 		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2428 		ap.a_mask.ss_family = res->ai_family;
2429 		if (res->ai_family == AF_INET) {
2430 			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2431 			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2432 			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2433 			if (masklen < 0) {
2434 				/* use default netmask */
2435 				if (IN_CLASSA(ntohl(addrp->s_addr)))
2436 					maskp->s_addr = htonl(IN_CLASSA_NET);
2437 				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2438 					maskp->s_addr = htonl(IN_CLASSB_NET);
2439 				else
2440 					maskp->s_addr = htonl(IN_CLASSC_NET);
2441 			} else if (masklen <= 32) {
2442 				/* convert masklen to netmask */
2443 				if (masklen == 0)
2444 					maskp->s_addr = 0;
2445 				else
2446 					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2447 			} else {
2448 				freeaddrinfo(res);
2449 				return (-1);
2450 			}
2451 			/* Lose any host bits in the network number. */
2452 			addrp->s_addr &= maskp->s_addr;
2453 		}
2454 #ifdef INET6
2455 		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2456 			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2457 			if (masklen < 0)
2458 				masklen = 128;
2459 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2460 			/* convert masklen to netmask */
2461 			while (masklen > 0) {
2462 				if (masklen < 32) {
2463 					*mask6p = htonl(~(0xffffffff >> masklen));
2464 					break;
2465 				}
2466 				*mask6p++ = 0xffffffff;
2467 				masklen -= 32;
2468 			}
2469 			/* Lose any host bits in the network number. */
2470 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2471 			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2472 			for (i = 0; i < 4; i++)
2473 				addr6p[i] &= mask6p[i];
2474 		}
2475 #endif
2476 		else {
2477 			freeaddrinfo(res);
2478 			return (-1);
2479 		}
2480 		freeaddrinfo(res);
2481 	} else {
2482 		/* arg `s' is domain name */
2483 		ap.isnumeric = 0;
2484 		ap.a_name = s;
2485 		if (cp1)
2486 			*cp1 = '/';
2487 #ifdef INET6
2488 		if (cp2) {
2489 			*cp2 = ']';
2490 			--s;
2491 		}
2492 #endif
2493 	}
2494 
2495 	if (Debug) {
2496 		printf("allowaddr: rule %d: ", NumAllowed);
2497 		if (ap.isnumeric) {
2498 			printf("numeric, ");
2499 			getnameinfo((struct sockaddr *)&ap.a_addr,
2500 				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2501 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2502 			printf("addr = %s, ", ip);
2503 			getnameinfo((struct sockaddr *)&ap.a_mask,
2504 				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2505 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2506 			printf("mask = %s; ", ip);
2507 		} else {
2508 			printf("domainname = %s; ", ap.a_name);
2509 		}
2510 		printf("port = %d\n", ap.port);
2511 	}
2512 
2513 	if ((AllowedPeers = realloc(AllowedPeers,
2514 				    ++NumAllowed * sizeof(struct allowedpeer)))
2515 	    == NULL) {
2516 		logerror("realloc");
2517 		exit(1);
2518 	}
2519 	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2520 	return (0);
2521 }
2522 
2523 /*
2524  * Validate that the remote peer has permission to log to us.
2525  */
2526 static int
2527 validate(struct sockaddr *sa, const char *hname)
2528 {
2529 	int i;
2530 	size_t l1, l2;
2531 	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2532 	struct allowedpeer *ap;
2533 	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2534 #ifdef INET6
2535 	int j, reject;
2536 	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2537 #endif
2538 	struct addrinfo hints, *res;
2539 	u_short sport;
2540 
2541 	if (NumAllowed == 0)
2542 		/* traditional behaviour, allow everything */
2543 		return (1);
2544 
2545 	(void)strlcpy(name, hname, sizeof(name));
2546 	memset(&hints, 0, sizeof(hints));
2547 	hints.ai_family = PF_UNSPEC;
2548 	hints.ai_socktype = SOCK_DGRAM;
2549 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2550 	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2551 		freeaddrinfo(res);
2552 	else if (strchr(name, '.') == NULL) {
2553 		strlcat(name, ".", sizeof name);
2554 		strlcat(name, LocalDomain, sizeof name);
2555 	}
2556 	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2557 			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2558 		return (0);	/* for safety, should not occur */
2559 	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2560 		ip, port, name);
2561 	sport = atoi(port);
2562 
2563 	/* now, walk down the list */
2564 	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2565 		if (ap->port != 0 && ap->port != sport) {
2566 			dprintf("rejected in rule %d due to port mismatch.\n", i);
2567 			continue;
2568 		}
2569 
2570 		if (ap->isnumeric) {
2571 			if (ap->a_addr.ss_family != sa->sa_family) {
2572 				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2573 				continue;
2574 			}
2575 			if (ap->a_addr.ss_family == AF_INET) {
2576 				sin4 = (struct sockaddr_in *)sa;
2577 				a4p = (struct sockaddr_in *)&ap->a_addr;
2578 				m4p = (struct sockaddr_in *)&ap->a_mask;
2579 				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2580 				    != a4p->sin_addr.s_addr) {
2581 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2582 					continue;
2583 				}
2584 			}
2585 #ifdef INET6
2586 			else if (ap->a_addr.ss_family == AF_INET6) {
2587 				sin6 = (struct sockaddr_in6 *)sa;
2588 				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2589 				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2590 				if (a6p->sin6_scope_id != 0 &&
2591 				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2592 					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2593 					continue;
2594 				}
2595 				reject = 0;
2596 				for (j = 0; j < 16; j += 4) {
2597 					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2598 					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2599 						++reject;
2600 						break;
2601 					}
2602 				}
2603 				if (reject) {
2604 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2605 					continue;
2606 				}
2607 			}
2608 #endif
2609 			else
2610 				continue;
2611 		} else {
2612 			cp = ap->a_name;
2613 			l1 = strlen(name);
2614 			if (*cp == '*') {
2615 				/* allow wildmatch */
2616 				cp++;
2617 				l2 = strlen(cp);
2618 				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2619 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2620 					continue;
2621 				}
2622 			} else {
2623 				/* exact match */
2624 				l2 = strlen(cp);
2625 				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2626 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2627 					continue;
2628 				}
2629 			}
2630 		}
2631 		dprintf("accepted in rule %d.\n", i);
2632 		return (1);	/* hooray! */
2633 	}
2634 	return (0);
2635 }
2636 
2637 /*
2638  * Fairly similar to popen(3), but returns an open descriptor, as
2639  * opposed to a FILE *.
2640  */
2641 static int
2642 p_open(const char *prog, pid_t *rpid)
2643 {
2644 	int pfd[2], nulldesc;
2645 	pid_t pid;
2646 	sigset_t omask, mask;
2647 	char *argv[4]; /* sh -c cmd NULL */
2648 	char errmsg[200];
2649 
2650 	if (pipe(pfd) == -1)
2651 		return (-1);
2652 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2653 		/* we are royally screwed anyway */
2654 		return (-1);
2655 
2656 	sigemptyset(&mask);
2657 	sigaddset(&mask, SIGALRM);
2658 	sigaddset(&mask, SIGHUP);
2659 	sigprocmask(SIG_BLOCK, &mask, &omask);
2660 	switch ((pid = fork())) {
2661 	case -1:
2662 		sigprocmask(SIG_SETMASK, &omask, 0);
2663 		close(nulldesc);
2664 		return (-1);
2665 
2666 	case 0:
2667 		argv[0] = strdup("sh");
2668 		argv[1] = strdup("-c");
2669 		argv[2] = strdup(prog);
2670 		argv[3] = NULL;
2671 		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2672 			logerror("strdup");
2673 			exit(1);
2674 		}
2675 
2676 		alarm(0);
2677 		(void)setsid();	/* Avoid catching SIGHUPs. */
2678 
2679 		/*
2680 		 * Throw away pending signals, and reset signal
2681 		 * behaviour to standard values.
2682 		 */
2683 		signal(SIGALRM, SIG_IGN);
2684 		signal(SIGHUP, SIG_IGN);
2685 		sigprocmask(SIG_SETMASK, &omask, 0);
2686 		signal(SIGPIPE, SIG_DFL);
2687 		signal(SIGQUIT, SIG_DFL);
2688 		signal(SIGALRM, SIG_DFL);
2689 		signal(SIGHUP, SIG_DFL);
2690 
2691 		dup2(pfd[0], STDIN_FILENO);
2692 		dup2(nulldesc, STDOUT_FILENO);
2693 		dup2(nulldesc, STDERR_FILENO);
2694 		closefrom(3);
2695 
2696 		(void)execvp(_PATH_BSHELL, argv);
2697 		_exit(255);
2698 	}
2699 
2700 	sigprocmask(SIG_SETMASK, &omask, 0);
2701 	close(nulldesc);
2702 	close(pfd[0]);
2703 	/*
2704 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2705 	 * supposed to get an EWOULDBLOCK on writev(2), which is
2706 	 * caught by the logic above anyway, which will in turn close
2707 	 * the pipe, and fork a new logging subprocess if necessary.
2708 	 * The stale subprocess will be killed some time later unless
2709 	 * it terminated itself due to closing its input pipe (so we
2710 	 * get rid of really dead puppies).
2711 	 */
2712 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2713 		/* This is bad. */
2714 		(void)snprintf(errmsg, sizeof errmsg,
2715 			       "Warning: cannot change pipe to PID %d to "
2716 			       "non-blocking behaviour.",
2717 			       (int)pid);
2718 		logerror(errmsg);
2719 	}
2720 	*rpid = pid;
2721 	return (pfd[1]);
2722 }
2723 
2724 static void
2725 deadq_enter(pid_t pid, const char *name)
2726 {
2727 	dq_t p;
2728 	int status;
2729 
2730 	/*
2731 	 * Be paranoid, if we can't signal the process, don't enter it
2732 	 * into the dead queue (perhaps it's already dead).  If possible,
2733 	 * we try to fetch and log the child's status.
2734 	 */
2735 	if (kill(pid, 0) != 0) {
2736 		if (waitpid(pid, &status, WNOHANG) > 0)
2737 			log_deadchild(pid, status, name);
2738 		return;
2739 	}
2740 
2741 	p = malloc(sizeof(struct deadq_entry));
2742 	if (p == NULL) {
2743 		logerror("malloc");
2744 		exit(1);
2745 	}
2746 
2747 	p->dq_pid = pid;
2748 	p->dq_timeout = DQ_TIMO_INIT;
2749 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2750 }
2751 
2752 static int
2753 deadq_remove(pid_t pid)
2754 {
2755 	dq_t q;
2756 
2757 	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2758 		if (q->dq_pid == pid) {
2759 			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2760 				free(q);
2761 				return (1);
2762 		}
2763 	}
2764 
2765 	return (0);
2766 }
2767 
2768 static void
2769 log_deadchild(pid_t pid, int status, const char *name)
2770 {
2771 	int code;
2772 	char buf[256];
2773 	const char *reason;
2774 
2775 	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2776 	if (WIFSIGNALED(status)) {
2777 		reason = "due to signal";
2778 		code = WTERMSIG(status);
2779 	} else {
2780 		reason = "with status";
2781 		code = WEXITSTATUS(status);
2782 		if (code == 0)
2783 			return;
2784 	}
2785 	(void)snprintf(buf, sizeof buf,
2786 		       "Logging subprocess %d (%s) exited %s %d.",
2787 		       pid, name, reason, code);
2788 	logerror(buf);
2789 }
2790 
2791 static int *
2792 socksetup(int af, char *bindhostname)
2793 {
2794 	struct addrinfo hints, *res, *r;
2795 	const char *bindservice;
2796 	char *cp;
2797 	int error, maxs, *s, *socks;
2798 
2799 	/*
2800 	 * We have to handle this case for backwards compatibility:
2801 	 * If there are two (or more) colons but no '[' and ']',
2802 	 * assume this is an inet6 address without a service.
2803 	 */
2804 	bindservice = "syslog";
2805 	if (bindhostname != NULL) {
2806 #ifdef INET6
2807 		if (*bindhostname == '[' &&
2808 		    (cp = strchr(bindhostname + 1, ']')) != NULL) {
2809 			++bindhostname;
2810 			*cp = '\0';
2811 			if (cp[1] == ':' && cp[2] != '\0')
2812 				bindservice = cp + 2;
2813 		} else {
2814 #endif
2815 			cp = strchr(bindhostname, ':');
2816 			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2817 				*cp = '\0';
2818 				if (cp[1] != '\0')
2819 					bindservice = cp + 1;
2820 				if (cp == bindhostname)
2821 					bindhostname = NULL;
2822 			}
2823 #ifdef INET6
2824 		}
2825 #endif
2826 	}
2827 
2828 	memset(&hints, 0, sizeof(hints));
2829 	hints.ai_flags = AI_PASSIVE;
2830 	hints.ai_family = af;
2831 	hints.ai_socktype = SOCK_DGRAM;
2832 	error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2833 	if (error) {
2834 		logerror(gai_strerror(error));
2835 		errno = 0;
2836 		die(0);
2837 	}
2838 
2839 	/* Count max number of sockets we may open */
2840 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2841 	socks = malloc((maxs+1) * sizeof(int));
2842 	if (socks == NULL) {
2843 		logerror("couldn't allocate memory for sockets");
2844 		die(0);
2845 	}
2846 
2847 	*socks = 0;   /* num of sockets counter at start of array */
2848 	s = socks + 1;
2849 	for (r = res; r; r = r->ai_next) {
2850 		int on = 1;
2851 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2852 		if (*s < 0) {
2853 			logerror("socket");
2854 			continue;
2855 		}
2856 #ifdef INET6
2857 		if (r->ai_family == AF_INET6) {
2858 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2859 				       (char *)&on, sizeof (on)) < 0) {
2860 				logerror("setsockopt");
2861 				close(*s);
2862 				continue;
2863 			}
2864 		}
2865 #endif
2866 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2867 			       (char *)&on, sizeof (on)) < 0) {
2868 			logerror("setsockopt");
2869 			close(*s);
2870 			continue;
2871 		}
2872 		/*
2873 		 * RFC 3164 recommends that client side message
2874 		 * should come from the privileged syslogd port.
2875 		 *
2876 		 * If the system administrator choose not to obey
2877 		 * this, we can skip the bind() step so that the
2878 		 * system will choose a port for us.
2879 		 */
2880 		if (!NoBind) {
2881 			if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2882 				logerror("bind");
2883 				close(*s);
2884 				continue;
2885 			}
2886 
2887 			if (!SecureMode)
2888 				increase_rcvbuf(*s);
2889 		}
2890 
2891 		(*socks)++;
2892 		dprintf("socksetup: new socket fd is %d\n", *s);
2893 		s++;
2894 	}
2895 
2896 	if (*socks == 0) {
2897 		free(socks);
2898 		if (Debug)
2899 			return (NULL);
2900 		else
2901 			die(0);
2902 	}
2903 	if (res)
2904 		freeaddrinfo(res);
2905 
2906 	return (socks);
2907 }
2908 
2909 static void
2910 increase_rcvbuf(int fd)
2911 {
2912 	socklen_t len, slen;
2913 
2914 	slen = sizeof(len);
2915 
2916 	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2917 		if (len < RCVBUF_MINSIZE) {
2918 			len = RCVBUF_MINSIZE;
2919 			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
2920 		}
2921 	}
2922 }
2923