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