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