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