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