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