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