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