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