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