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