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