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