xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision 69718b786d3943ea9a99eeeb5f5f6162f11c78b7)
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 	nextp = &Files;
1839 
1840 	/* open the configuration file */
1841 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1842 		dprintf("cannot open %s\n", ConfFile);
1843 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1844 		if (*nextp == NULL) {
1845 			logerror("calloc");
1846 			exit(1);
1847 		}
1848 		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1849 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1850 		if ((*nextp)->f_next == NULL) {
1851 			logerror("calloc");
1852 			exit(1);
1853 		}
1854 		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1855 		Initialized = 1;
1856 		return;
1857 	}
1858 
1859 	readconfigfile(cf, &Files, 1);
1860 
1861 	/* close the configuration file */
1862 	(void)fclose(cf);
1863 
1864 	Initialized = 1;
1865 
1866 	if (Debug) {
1867 		int port;
1868 		for (f = Files; f; f = f->f_next) {
1869 			for (i = 0; i <= LOG_NFACILITIES; i++)
1870 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1871 					printf("X ");
1872 				else
1873 					printf("%d ", f->f_pmask[i]);
1874 			printf("%s: ", TypeNames[f->f_type]);
1875 			switch (f->f_type) {
1876 			case F_FILE:
1877 				printf("%s", f->f_un.f_fname);
1878 				break;
1879 
1880 			case F_CONSOLE:
1881 			case F_TTY:
1882 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1883 				break;
1884 
1885 			case F_FORW:
1886 				port = (int)ntohs(((struct sockaddr_in *)
1887 				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1888 				if (port != 514) {
1889 					printf("%s:%d",
1890 						f->f_un.f_forw.f_hname, port);
1891 				} else {
1892 					printf("%s", f->f_un.f_forw.f_hname);
1893 				}
1894 				break;
1895 
1896 			case F_PIPE:
1897 				printf("%s", f->f_un.f_pipe.f_pname);
1898 				break;
1899 
1900 			case F_USERS:
1901 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1902 					printf("%s, ", f->f_un.f_uname[i]);
1903 				break;
1904 			}
1905 			if (f->f_program)
1906 				printf(" (%s)", f->f_program);
1907 			printf("\n");
1908 		}
1909 	}
1910 
1911 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1912 	dprintf("syslogd: restarted\n");
1913 	/*
1914 	 * Log a change in hostname, but only on a restart.
1915 	 */
1916 	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1917 		(void)snprintf(hostMsg, sizeof(hostMsg),
1918 		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1919 		    oldLocalHostName, LocalHostName);
1920 		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1921 		dprintf("%s\n", hostMsg);
1922 	}
1923 	/*
1924 	 * Log the kernel boot file if we aren't going to use it as
1925 	 * the prefix, and if this is *not* a restart.
1926 	 */
1927 	if (signo == 0 && !use_bootfile) {
1928 		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1929 		    "syslogd: kernel boot file is %s", bootfile);
1930 		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1931 		dprintf("%s\n", bootfileMsg);
1932 	}
1933 }
1934 
1935 /*
1936  * Crack a configuration file line
1937  */
1938 static void
1939 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1940 {
1941 	struct addrinfo hints, *res;
1942 	int error, i, pri, syncfile;
1943 	const char *p, *q;
1944 	char *bp;
1945 	char buf[MAXLINE], ebuf[100];
1946 
1947 	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1948 
1949 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1950 
1951 	/* clear out file entry */
1952 	memset(f, 0, sizeof(*f));
1953 	for (i = 0; i <= LOG_NFACILITIES; i++)
1954 		f->f_pmask[i] = INTERNAL_NOPRI;
1955 
1956 	/* save hostname if any */
1957 	if (host && *host == '*')
1958 		host = NULL;
1959 	if (host) {
1960 		int hl;
1961 
1962 		f->f_host = strdup(host);
1963 		if (f->f_host == NULL) {
1964 			logerror("strdup");
1965 			exit(1);
1966 		}
1967 		hl = strlen(f->f_host);
1968 		if (hl > 0 && f->f_host[hl-1] == '.')
1969 			f->f_host[--hl] = '\0';
1970 		trimdomain(f->f_host, hl);
1971 	}
1972 
1973 	/* save program name if any */
1974 	if (prog && *prog == '*')
1975 		prog = NULL;
1976 	if (prog) {
1977 		f->f_program = strdup(prog);
1978 		if (f->f_program == NULL) {
1979 			logerror("strdup");
1980 			exit(1);
1981 		}
1982 	}
1983 
1984 	/* scan through the list of selectors */
1985 	for (p = line; *p && *p != '\t' && *p != ' ';) {
1986 		int pri_done;
1987 		int pri_cmp;
1988 		int pri_invert;
1989 
1990 		/* find the end of this facility name list */
1991 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1992 			continue;
1993 
1994 		/* get the priority comparison */
1995 		pri_cmp = 0;
1996 		pri_done = 0;
1997 		pri_invert = 0;
1998 		if (*q == '!') {
1999 			pri_invert = 1;
2000 			q++;
2001 		}
2002 		while (!pri_done) {
2003 			switch (*q) {
2004 			case '<':
2005 				pri_cmp |= PRI_LT;
2006 				q++;
2007 				break;
2008 			case '=':
2009 				pri_cmp |= PRI_EQ;
2010 				q++;
2011 				break;
2012 			case '>':
2013 				pri_cmp |= PRI_GT;
2014 				q++;
2015 				break;
2016 			default:
2017 				pri_done++;
2018 				break;
2019 			}
2020 		}
2021 
2022 		/* collect priority name */
2023 		for (bp = buf; *q && !strchr("\t,; ", *q); )
2024 			*bp++ = *q++;
2025 		*bp = '\0';
2026 
2027 		/* skip cruft */
2028 		while (strchr(",;", *q))
2029 			q++;
2030 
2031 		/* decode priority name */
2032 		if (*buf == '*') {
2033 			pri = LOG_PRIMASK;
2034 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2035 		} else {
2036 			/* Ignore trailing spaces. */
2037 			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2038 				buf[i] = '\0';
2039 
2040 			pri = decode(buf, prioritynames);
2041 			if (pri < 0) {
2042 				errno = 0;
2043 				(void)snprintf(ebuf, sizeof ebuf,
2044 				    "unknown priority name \"%s\"", buf);
2045 				logerror(ebuf);
2046 				return;
2047 			}
2048 		}
2049 		if (!pri_cmp)
2050 			pri_cmp = (UniquePriority)
2051 				  ? (PRI_EQ)
2052 				  : (PRI_EQ | PRI_GT)
2053 				  ;
2054 		if (pri_invert)
2055 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2056 
2057 		/* scan facilities */
2058 		while (*p && !strchr("\t.; ", *p)) {
2059 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
2060 				*bp++ = *p++;
2061 			*bp = '\0';
2062 
2063 			if (*buf == '*') {
2064 				for (i = 0; i < LOG_NFACILITIES; i++) {
2065 					f->f_pmask[i] = pri;
2066 					f->f_pcmp[i] = pri_cmp;
2067 				}
2068 			} else {
2069 				i = decode(buf, facilitynames);
2070 				if (i < 0) {
2071 					errno = 0;
2072 					(void)snprintf(ebuf, sizeof ebuf,
2073 					    "unknown facility name \"%s\"",
2074 					    buf);
2075 					logerror(ebuf);
2076 					return;
2077 				}
2078 				f->f_pmask[i >> 3] = pri;
2079 				f->f_pcmp[i >> 3] = pri_cmp;
2080 			}
2081 			while (*p == ',' || *p == ' ')
2082 				p++;
2083 		}
2084 
2085 		p = q;
2086 	}
2087 
2088 	/* skip to action part */
2089 	while (*p == '\t' || *p == ' ')
2090 		p++;
2091 
2092 	if (*p == '-') {
2093 		syncfile = 0;
2094 		p++;
2095 	} else
2096 		syncfile = 1;
2097 
2098 	switch (*p) {
2099 	case '@':
2100 		{
2101 			char *tp;
2102 			char endkey = ':';
2103 			/*
2104 			 * scan forward to see if there is a port defined.
2105 			 * so we can't use strlcpy..
2106 			 */
2107 			i = sizeof(f->f_un.f_forw.f_hname);
2108 			tp = f->f_un.f_forw.f_hname;
2109 			p++;
2110 
2111 			/*
2112 			 * an ipv6 address should start with a '[' in that case
2113 			 * we should scan for a ']'
2114 			 */
2115 			if (*p == '[') {
2116 				p++;
2117 				endkey = ']';
2118 			}
2119 			while (*p && (*p != endkey) && (i-- > 0)) {
2120 				*tp++ = *p++;
2121 			}
2122 			if (endkey == ']' && *p == endkey)
2123 				p++;
2124 			*tp = '\0';
2125 		}
2126 		/* See if we copied a domain and have a port */
2127 		if (*p == ':')
2128 			p++;
2129 		else
2130 			p = NULL;
2131 
2132 		memset(&hints, 0, sizeof(hints));
2133 		hints.ai_family = family;
2134 		hints.ai_socktype = SOCK_DGRAM;
2135 		error = getaddrinfo(f->f_un.f_forw.f_hname,
2136 				p ? p : "syslog", &hints, &res);
2137 		if (error) {
2138 			logerror(gai_strerror(error));
2139 			break;
2140 		}
2141 		f->f_un.f_forw.f_addr = res;
2142 		f->f_type = F_FORW;
2143 		break;
2144 
2145 	case '/':
2146 		if ((f->f_file = open(p, logflags, 0600)) < 0) {
2147 			f->f_type = F_UNUSED;
2148 			logerror(p);
2149 			break;
2150 		}
2151 		if (syncfile)
2152 			f->f_flags |= FFLAG_SYNC;
2153 		if (isatty(f->f_file)) {
2154 			if (strcmp(p, ctty) == 0)
2155 				f->f_type = F_CONSOLE;
2156 			else
2157 				f->f_type = F_TTY;
2158 			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2159 			    sizeof(f->f_un.f_fname));
2160 		} else {
2161 			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2162 			f->f_type = F_FILE;
2163 		}
2164 		break;
2165 
2166 	case '|':
2167 		f->f_un.f_pipe.f_pid = 0;
2168 		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2169 		    sizeof(f->f_un.f_pipe.f_pname));
2170 		f->f_type = F_PIPE;
2171 		break;
2172 
2173 	case '*':
2174 		f->f_type = F_WALL;
2175 		break;
2176 
2177 	default:
2178 		for (i = 0; i < MAXUNAMES && *p; i++) {
2179 			for (q = p; *q && *q != ','; )
2180 				q++;
2181 			(void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2182 			if ((q - p) >= MAXLOGNAME)
2183 				f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2184 			else
2185 				f->f_un.f_uname[i][q - p] = '\0';
2186 			while (*q == ',' || *q == ' ')
2187 				q++;
2188 			p = q;
2189 		}
2190 		f->f_type = F_USERS;
2191 		break;
2192 	}
2193 }
2194 
2195 
2196 /*
2197  *  Decode a symbolic name to a numeric value
2198  */
2199 static int
2200 decode(const char *name, const CODE *codetab)
2201 {
2202 	const CODE *c;
2203 	char *p, buf[40];
2204 
2205 	if (isdigit(*name))
2206 		return (atoi(name));
2207 
2208 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2209 		if (isupper(*name))
2210 			*p = tolower(*name);
2211 		else
2212 			*p = *name;
2213 	}
2214 	*p = '\0';
2215 	for (c = codetab; c->c_name; c++)
2216 		if (!strcmp(buf, c->c_name))
2217 			return (c->c_val);
2218 
2219 	return (-1);
2220 }
2221 
2222 static void
2223 markit(void)
2224 {
2225 	struct filed *f;
2226 	dq_t q, next;
2227 
2228 	now = time((time_t *)NULL);
2229 	MarkSeq += TIMERINTVL;
2230 	if (MarkSeq >= MarkInterval) {
2231 		logmsg(LOG_INFO, "-- MARK --",
2232 		    LocalHostName, ADDDATE|MARK);
2233 		MarkSeq = 0;
2234 	}
2235 
2236 	for (f = Files; f; f = f->f_next) {
2237 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2238 			dprintf("flush %s: repeated %d times, %d sec.\n",
2239 			    TypeNames[f->f_type], f->f_prevcount,
2240 			    repeatinterval[f->f_repeatcount]);
2241 			fprintlog(f, 0, (char *)NULL);
2242 			BACKOFF(f);
2243 		}
2244 	}
2245 
2246 	/* Walk the dead queue, and see if we should signal somebody. */
2247 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2248 		next = TAILQ_NEXT(q, dq_entries);
2249 
2250 		switch (q->dq_timeout) {
2251 		case 0:
2252 			/* Already signalled once, try harder now. */
2253 			if (kill(q->dq_pid, SIGKILL) != 0)
2254 				(void)deadq_remove(q->dq_pid);
2255 			break;
2256 
2257 		case 1:
2258 			/*
2259 			 * Timed out on dead queue, send terminate
2260 			 * signal.  Note that we leave the removal
2261 			 * from the dead queue to reapchild(), which
2262 			 * will also log the event (unless the process
2263 			 * didn't even really exist, in case we simply
2264 			 * drop it from the dead queue).
2265 			 */
2266 			if (kill(q->dq_pid, SIGTERM) != 0)
2267 				(void)deadq_remove(q->dq_pid);
2268 			/* FALLTHROUGH */
2269 
2270 		default:
2271 			q->dq_timeout--;
2272 		}
2273 	}
2274 	MarkSet = 0;
2275 	(void)alarm(TIMERINTVL);
2276 }
2277 
2278 /*
2279  * fork off and become a daemon, but wait for the child to come online
2280  * before returing to the parent, or we get disk thrashing at boot etc.
2281  * Set a timer so we don't hang forever if it wedges.
2282  */
2283 static int
2284 waitdaemon(int nochdir, int noclose, int maxwait)
2285 {
2286 	int fd;
2287 	int status;
2288 	pid_t pid, childpid;
2289 
2290 	switch (childpid = fork()) {
2291 	case -1:
2292 		return (-1);
2293 	case 0:
2294 		break;
2295 	default:
2296 		signal(SIGALRM, timedout);
2297 		alarm(maxwait);
2298 		while ((pid = wait3(&status, 0, NULL)) != -1) {
2299 			if (WIFEXITED(status))
2300 				errx(1, "child pid %d exited with return code %d",
2301 					pid, WEXITSTATUS(status));
2302 			if (WIFSIGNALED(status))
2303 				errx(1, "child pid %d exited on signal %d%s",
2304 					pid, WTERMSIG(status),
2305 					WCOREDUMP(status) ? " (core dumped)" :
2306 					"");
2307 			if (pid == childpid)	/* it's gone... */
2308 				break;
2309 		}
2310 		exit(0);
2311 	}
2312 
2313 	if (setsid() == -1)
2314 		return (-1);
2315 
2316 	if (!nochdir)
2317 		(void)chdir("/");
2318 
2319 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2320 		(void)dup2(fd, STDIN_FILENO);
2321 		(void)dup2(fd, STDOUT_FILENO);
2322 		(void)dup2(fd, STDERR_FILENO);
2323 		if (fd > 2)
2324 			(void)close (fd);
2325 	}
2326 	return (getppid());
2327 }
2328 
2329 /*
2330  * We get a SIGALRM from the child when it's running and finished doing it's
2331  * fsync()'s or O_SYNC writes for all the boot messages.
2332  *
2333  * We also get a signal from the kernel if the timer expires, so check to
2334  * see what happened.
2335  */
2336 static void
2337 timedout(int sig __unused)
2338 {
2339 	int left;
2340 	left = alarm(0);
2341 	signal(SIGALRM, SIG_DFL);
2342 	if (left == 0)
2343 		errx(1, "timed out waiting for child");
2344 	else
2345 		_exit(0);
2346 }
2347 
2348 /*
2349  * Add `s' to the list of allowable peer addresses to accept messages
2350  * from.
2351  *
2352  * `s' is a string in the form:
2353  *
2354  *    [*]domainname[:{servicename|portnumber|*}]
2355  *
2356  * or
2357  *
2358  *    netaddr/maskbits[:{servicename|portnumber|*}]
2359  *
2360  * Returns -1 on error, 0 if the argument was valid.
2361  */
2362 static int
2363 allowaddr(char *s)
2364 {
2365 	char *cp1, *cp2;
2366 	struct allowedpeer ap;
2367 	struct servent *se;
2368 	int masklen = -1;
2369 	struct addrinfo hints, *res;
2370 	struct in_addr *addrp, *maskp;
2371 #ifdef INET6
2372 	int i;
2373 	u_int32_t *addr6p, *mask6p;
2374 #endif
2375 	char ip[NI_MAXHOST];
2376 
2377 #ifdef INET6
2378 	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2379 #endif
2380 		cp1 = s;
2381 	if ((cp1 = strrchr(cp1, ':'))) {
2382 		/* service/port provided */
2383 		*cp1++ = '\0';
2384 		if (strlen(cp1) == 1 && *cp1 == '*')
2385 			/* any port allowed */
2386 			ap.port = 0;
2387 		else if ((se = getservbyname(cp1, "udp"))) {
2388 			ap.port = ntohs(se->s_port);
2389 		} else {
2390 			ap.port = strtol(cp1, &cp2, 0);
2391 			if (*cp2 != '\0')
2392 				return (-1); /* port not numeric */
2393 		}
2394 	} else {
2395 		if ((se = getservbyname("syslog", "udp")))
2396 			ap.port = ntohs(se->s_port);
2397 		else
2398 			/* sanity, should not happen */
2399 			ap.port = 514;
2400 	}
2401 
2402 	if ((cp1 = strchr(s, '/')) != NULL &&
2403 	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2404 		*cp1 = '\0';
2405 		if ((masklen = atoi(cp1 + 1)) < 0)
2406 			return (-1);
2407 	}
2408 #ifdef INET6
2409 	if (*s == '[') {
2410 		cp2 = s + strlen(s) - 1;
2411 		if (*cp2 == ']') {
2412 			++s;
2413 			*cp2 = '\0';
2414 		} else {
2415 			cp2 = NULL;
2416 		}
2417 	} else {
2418 		cp2 = NULL;
2419 	}
2420 #endif
2421 	memset(&hints, 0, sizeof(hints));
2422 	hints.ai_family = PF_UNSPEC;
2423 	hints.ai_socktype = SOCK_DGRAM;
2424 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2425 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2426 		ap.isnumeric = 1;
2427 		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2428 		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2429 		ap.a_mask.ss_family = res->ai_family;
2430 		if (res->ai_family == AF_INET) {
2431 			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2432 			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2433 			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2434 			if (masklen < 0) {
2435 				/* use default netmask */
2436 				if (IN_CLASSA(ntohl(addrp->s_addr)))
2437 					maskp->s_addr = htonl(IN_CLASSA_NET);
2438 				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2439 					maskp->s_addr = htonl(IN_CLASSB_NET);
2440 				else
2441 					maskp->s_addr = htonl(IN_CLASSC_NET);
2442 			} else if (masklen <= 32) {
2443 				/* convert masklen to netmask */
2444 				if (masklen == 0)
2445 					maskp->s_addr = 0;
2446 				else
2447 					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2448 			} else {
2449 				freeaddrinfo(res);
2450 				return (-1);
2451 			}
2452 			/* Lose any host bits in the network number. */
2453 			addrp->s_addr &= maskp->s_addr;
2454 		}
2455 #ifdef INET6
2456 		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2457 			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2458 			if (masklen < 0)
2459 				masklen = 128;
2460 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2461 			/* convert masklen to netmask */
2462 			while (masklen > 0) {
2463 				if (masklen < 32) {
2464 					*mask6p = htonl(~(0xffffffff >> masklen));
2465 					break;
2466 				}
2467 				*mask6p++ = 0xffffffff;
2468 				masklen -= 32;
2469 			}
2470 			/* Lose any host bits in the network number. */
2471 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2472 			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2473 			for (i = 0; i < 4; i++)
2474 				addr6p[i] &= mask6p[i];
2475 		}
2476 #endif
2477 		else {
2478 			freeaddrinfo(res);
2479 			return (-1);
2480 		}
2481 		freeaddrinfo(res);
2482 	} else {
2483 		/* arg `s' is domain name */
2484 		ap.isnumeric = 0;
2485 		ap.a_name = s;
2486 		if (cp1)
2487 			*cp1 = '/';
2488 #ifdef INET6
2489 		if (cp2) {
2490 			*cp2 = ']';
2491 			--s;
2492 		}
2493 #endif
2494 	}
2495 
2496 	if (Debug) {
2497 		printf("allowaddr: rule %d: ", NumAllowed);
2498 		if (ap.isnumeric) {
2499 			printf("numeric, ");
2500 			getnameinfo((struct sockaddr *)&ap.a_addr,
2501 				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2502 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2503 			printf("addr = %s, ", ip);
2504 			getnameinfo((struct sockaddr *)&ap.a_mask,
2505 				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2506 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2507 			printf("mask = %s; ", ip);
2508 		} else {
2509 			printf("domainname = %s; ", ap.a_name);
2510 		}
2511 		printf("port = %d\n", ap.port);
2512 	}
2513 
2514 	if ((AllowedPeers = realloc(AllowedPeers,
2515 				    ++NumAllowed * sizeof(struct allowedpeer)))
2516 	    == NULL) {
2517 		logerror("realloc");
2518 		exit(1);
2519 	}
2520 	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2521 	return (0);
2522 }
2523 
2524 /*
2525  * Validate that the remote peer has permission to log to us.
2526  */
2527 static int
2528 validate(struct sockaddr *sa, const char *hname)
2529 {
2530 	int i;
2531 	size_t l1, l2;
2532 	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2533 	struct allowedpeer *ap;
2534 	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2535 #ifdef INET6
2536 	int j, reject;
2537 	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2538 #endif
2539 	struct addrinfo hints, *res;
2540 	u_short sport;
2541 
2542 	if (NumAllowed == 0)
2543 		/* traditional behaviour, allow everything */
2544 		return (1);
2545 
2546 	(void)strlcpy(name, hname, sizeof(name));
2547 	memset(&hints, 0, sizeof(hints));
2548 	hints.ai_family = PF_UNSPEC;
2549 	hints.ai_socktype = SOCK_DGRAM;
2550 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2551 	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2552 		freeaddrinfo(res);
2553 	else if (strchr(name, '.') == NULL) {
2554 		strlcat(name, ".", sizeof name);
2555 		strlcat(name, LocalDomain, sizeof name);
2556 	}
2557 	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2558 			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2559 		return (0);	/* for safety, should not occur */
2560 	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2561 		ip, port, name);
2562 	sport = atoi(port);
2563 
2564 	/* now, walk down the list */
2565 	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2566 		if (ap->port != 0 && ap->port != sport) {
2567 			dprintf("rejected in rule %d due to port mismatch.\n", i);
2568 			continue;
2569 		}
2570 
2571 		if (ap->isnumeric) {
2572 			if (ap->a_addr.ss_family != sa->sa_family) {
2573 				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2574 				continue;
2575 			}
2576 			if (ap->a_addr.ss_family == AF_INET) {
2577 				sin4 = (struct sockaddr_in *)sa;
2578 				a4p = (struct sockaddr_in *)&ap->a_addr;
2579 				m4p = (struct sockaddr_in *)&ap->a_mask;
2580 				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2581 				    != a4p->sin_addr.s_addr) {
2582 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2583 					continue;
2584 				}
2585 			}
2586 #ifdef INET6
2587 			else if (ap->a_addr.ss_family == AF_INET6) {
2588 				sin6 = (struct sockaddr_in6 *)sa;
2589 				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2590 				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2591 				if (a6p->sin6_scope_id != 0 &&
2592 				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2593 					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2594 					continue;
2595 				}
2596 				reject = 0;
2597 				for (j = 0; j < 16; j += 4) {
2598 					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2599 					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2600 						++reject;
2601 						break;
2602 					}
2603 				}
2604 				if (reject) {
2605 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2606 					continue;
2607 				}
2608 			}
2609 #endif
2610 			else
2611 				continue;
2612 		} else {
2613 			cp = ap->a_name;
2614 			l1 = strlen(name);
2615 			if (*cp == '*') {
2616 				/* allow wildmatch */
2617 				cp++;
2618 				l2 = strlen(cp);
2619 				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2620 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2621 					continue;
2622 				}
2623 			} else {
2624 				/* exact match */
2625 				l2 = strlen(cp);
2626 				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2627 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2628 					continue;
2629 				}
2630 			}
2631 		}
2632 		dprintf("accepted in rule %d.\n", i);
2633 		return (1);	/* hooray! */
2634 	}
2635 	return (0);
2636 }
2637 
2638 /*
2639  * Fairly similar to popen(3), but returns an open descriptor, as
2640  * opposed to a FILE *.
2641  */
2642 static int
2643 p_open(const char *prog, pid_t *rpid)
2644 {
2645 	int pfd[2], nulldesc;
2646 	pid_t pid;
2647 	sigset_t omask, mask;
2648 	char *argv[4]; /* sh -c cmd NULL */
2649 	char errmsg[200];
2650 
2651 	if (pipe(pfd) == -1)
2652 		return (-1);
2653 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2654 		/* we are royally screwed anyway */
2655 		return (-1);
2656 
2657 	sigemptyset(&mask);
2658 	sigaddset(&mask, SIGALRM);
2659 	sigaddset(&mask, SIGHUP);
2660 	sigprocmask(SIG_BLOCK, &mask, &omask);
2661 	switch ((pid = fork())) {
2662 	case -1:
2663 		sigprocmask(SIG_SETMASK, &omask, 0);
2664 		close(nulldesc);
2665 		return (-1);
2666 
2667 	case 0:
2668 		argv[0] = strdup("sh");
2669 		argv[1] = strdup("-c");
2670 		argv[2] = strdup(prog);
2671 		argv[3] = NULL;
2672 		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2673 			logerror("strdup");
2674 			exit(1);
2675 		}
2676 
2677 		alarm(0);
2678 		(void)setsid();	/* Avoid catching SIGHUPs. */
2679 
2680 		/*
2681 		 * Throw away pending signals, and reset signal
2682 		 * behaviour to standard values.
2683 		 */
2684 		signal(SIGALRM, SIG_IGN);
2685 		signal(SIGHUP, SIG_IGN);
2686 		sigprocmask(SIG_SETMASK, &omask, 0);
2687 		signal(SIGPIPE, SIG_DFL);
2688 		signal(SIGQUIT, SIG_DFL);
2689 		signal(SIGALRM, SIG_DFL);
2690 		signal(SIGHUP, SIG_DFL);
2691 
2692 		dup2(pfd[0], STDIN_FILENO);
2693 		dup2(nulldesc, STDOUT_FILENO);
2694 		dup2(nulldesc, STDERR_FILENO);
2695 		closefrom(3);
2696 
2697 		(void)execvp(_PATH_BSHELL, argv);
2698 		_exit(255);
2699 	}
2700 
2701 	sigprocmask(SIG_SETMASK, &omask, 0);
2702 	close(nulldesc);
2703 	close(pfd[0]);
2704 	/*
2705 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2706 	 * supposed to get an EWOULDBLOCK on writev(2), which is
2707 	 * caught by the logic above anyway, which will in turn close
2708 	 * the pipe, and fork a new logging subprocess if necessary.
2709 	 * The stale subprocess will be killed some time later unless
2710 	 * it terminated itself due to closing its input pipe (so we
2711 	 * get rid of really dead puppies).
2712 	 */
2713 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2714 		/* This is bad. */
2715 		(void)snprintf(errmsg, sizeof errmsg,
2716 			       "Warning: cannot change pipe to PID %d to "
2717 			       "non-blocking behaviour.",
2718 			       (int)pid);
2719 		logerror(errmsg);
2720 	}
2721 	*rpid = pid;
2722 	return (pfd[1]);
2723 }
2724 
2725 static void
2726 deadq_enter(pid_t pid, const char *name)
2727 {
2728 	dq_t p;
2729 	int status;
2730 
2731 	/*
2732 	 * Be paranoid, if we can't signal the process, don't enter it
2733 	 * into the dead queue (perhaps it's already dead).  If possible,
2734 	 * we try to fetch and log the child's status.
2735 	 */
2736 	if (kill(pid, 0) != 0) {
2737 		if (waitpid(pid, &status, WNOHANG) > 0)
2738 			log_deadchild(pid, status, name);
2739 		return;
2740 	}
2741 
2742 	p = malloc(sizeof(struct deadq_entry));
2743 	if (p == NULL) {
2744 		logerror("malloc");
2745 		exit(1);
2746 	}
2747 
2748 	p->dq_pid = pid;
2749 	p->dq_timeout = DQ_TIMO_INIT;
2750 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2751 }
2752 
2753 static int
2754 deadq_remove(pid_t pid)
2755 {
2756 	dq_t q;
2757 
2758 	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2759 		if (q->dq_pid == pid) {
2760 			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2761 				free(q);
2762 				return (1);
2763 		}
2764 	}
2765 
2766 	return (0);
2767 }
2768 
2769 static void
2770 log_deadchild(pid_t pid, int status, const char *name)
2771 {
2772 	int code;
2773 	char buf[256];
2774 	const char *reason;
2775 
2776 	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2777 	if (WIFSIGNALED(status)) {
2778 		reason = "due to signal";
2779 		code = WTERMSIG(status);
2780 	} else {
2781 		reason = "with status";
2782 		code = WEXITSTATUS(status);
2783 		if (code == 0)
2784 			return;
2785 	}
2786 	(void)snprintf(buf, sizeof buf,
2787 		       "Logging subprocess %d (%s) exited %s %d.",
2788 		       pid, name, reason, code);
2789 	logerror(buf);
2790 }
2791 
2792 static int *
2793 socksetup(int af, char *bindhostname)
2794 {
2795 	struct addrinfo hints, *res, *r;
2796 	const char *bindservice;
2797 	char *cp;
2798 	int error, maxs, *s, *socks;
2799 
2800 	/*
2801 	 * We have to handle this case for backwards compatibility:
2802 	 * If there are two (or more) colons but no '[' and ']',
2803 	 * assume this is an inet6 address without a service.
2804 	 */
2805 	bindservice = "syslog";
2806 	if (bindhostname != NULL) {
2807 #ifdef INET6
2808 		if (*bindhostname == '[' &&
2809 		    (cp = strchr(bindhostname + 1, ']')) != NULL) {
2810 			++bindhostname;
2811 			*cp = '\0';
2812 			if (cp[1] == ':' && cp[2] != '\0')
2813 				bindservice = cp + 2;
2814 		} else {
2815 #endif
2816 			cp = strchr(bindhostname, ':');
2817 			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2818 				*cp = '\0';
2819 				if (cp[1] != '\0')
2820 					bindservice = cp + 1;
2821 				if (cp == bindhostname)
2822 					bindhostname = NULL;
2823 			}
2824 #ifdef INET6
2825 		}
2826 #endif
2827 	}
2828 
2829 	memset(&hints, 0, sizeof(hints));
2830 	hints.ai_flags = AI_PASSIVE;
2831 	hints.ai_family = af;
2832 	hints.ai_socktype = SOCK_DGRAM;
2833 	error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2834 	if (error) {
2835 		logerror(gai_strerror(error));
2836 		errno = 0;
2837 		die(0);
2838 	}
2839 
2840 	/* Count max number of sockets we may open */
2841 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2842 	socks = malloc((maxs+1) * sizeof(int));
2843 	if (socks == NULL) {
2844 		logerror("couldn't allocate memory for sockets");
2845 		die(0);
2846 	}
2847 
2848 	*socks = 0;   /* num of sockets counter at start of array */
2849 	s = socks + 1;
2850 	for (r = res; r; r = r->ai_next) {
2851 		int on = 1;
2852 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2853 		if (*s < 0) {
2854 			logerror("socket");
2855 			continue;
2856 		}
2857 #ifdef INET6
2858 		if (r->ai_family == AF_INET6) {
2859 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2860 				       (char *)&on, sizeof (on)) < 0) {
2861 				logerror("setsockopt");
2862 				close(*s);
2863 				continue;
2864 			}
2865 		}
2866 #endif
2867 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2868 			       (char *)&on, sizeof (on)) < 0) {
2869 			logerror("setsockopt");
2870 			close(*s);
2871 			continue;
2872 		}
2873 		/*
2874 		 * RFC 3164 recommends that client side message
2875 		 * should come from the privileged syslogd port.
2876 		 *
2877 		 * If the system administrator choose not to obey
2878 		 * this, we can skip the bind() step so that the
2879 		 * system will choose a port for us.
2880 		 */
2881 		if (!NoBind) {
2882 			if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2883 				logerror("bind");
2884 				close(*s);
2885 				continue;
2886 			}
2887 
2888 			if (!SecureMode)
2889 				increase_rcvbuf(*s);
2890 		}
2891 
2892 		(*socks)++;
2893 		dprintf("socksetup: new socket fd is %d\n", *s);
2894 		s++;
2895 	}
2896 
2897 	if (*socks == 0) {
2898 		free(socks);
2899 		if (Debug)
2900 			return (NULL);
2901 		else
2902 			die(0);
2903 	}
2904 	if (res)
2905 		freeaddrinfo(res);
2906 
2907 	return (socks);
2908 }
2909 
2910 static void
2911 increase_rcvbuf(int fd)
2912 {
2913 	socklen_t len, slen;
2914 
2915 	slen = sizeof(len);
2916 
2917 	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2918 		if (len < RCVBUF_MINSIZE) {
2919 			len = RCVBUF_MINSIZE;
2920 			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
2921 		}
2922 	}
2923 }
2924