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