syslogd.c revision 35382
10Sstevel@tonic-gate/*
20Sstevel@tonic-gate * Copyright (c) 1983, 1988, 1993, 1994
30Sstevel@tonic-gate *	The Regents of the University of California.  All rights reserved.
40Sstevel@tonic-gate *
50Sstevel@tonic-gate * Redistribution and use in source and binary forms, with or without
60Sstevel@tonic-gate * modification, are permitted provided that the following conditions
70Sstevel@tonic-gate * are met:
80Sstevel@tonic-gate * 1. Redistributions of source code must retain the above copyright
90Sstevel@tonic-gate *    notice, this list of conditions and the following disclaimer.
100Sstevel@tonic-gate * 2. Redistributions in binary form must reproduce the above copyright
110Sstevel@tonic-gate *    notice, this list of conditions and the following disclaimer in the
120Sstevel@tonic-gate *    documentation and/or other materials provided with the distribution.
130Sstevel@tonic-gate * 3. All advertising materials mentioning features or use of this software
140Sstevel@tonic-gate *    must display the following acknowledgement:
150Sstevel@tonic-gate *	This product includes software developed by the University of
160Sstevel@tonic-gate *	California, Berkeley and its contributors.
170Sstevel@tonic-gate * 4. Neither the name of the University nor the names of its contributors
180Sstevel@tonic-gate *    may be used to endorse or promote products derived from this software
190Sstevel@tonic-gate *    without specific prior written permission.
200Sstevel@tonic-gate *
210Sstevel@tonic-gate * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
220Sstevel@tonic-gate * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
230Sstevel@tonic-gate * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
240Sstevel@tonic-gate * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
250Sstevel@tonic-gate * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
260Sstevel@tonic-gate * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
270Sstevel@tonic-gate * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
280Sstevel@tonic-gate * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
290Sstevel@tonic-gate * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
300Sstevel@tonic-gate * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
310Sstevel@tonic-gate * SUCH DAMAGE.
320Sstevel@tonic-gate */
330Sstevel@tonic-gate
340Sstevel@tonic-gate#ifndef lint
350Sstevel@tonic-gatestatic const char copyright[] =
360Sstevel@tonic-gate"@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
370Sstevel@tonic-gate	The Regents of the University of California.  All rights reserved.\n";
380Sstevel@tonic-gate#endif /* not lint */
390Sstevel@tonic-gate
400Sstevel@tonic-gate#ifndef lint
410Sstevel@tonic-gate#if 0
420Sstevel@tonic-gatestatic char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
430Sstevel@tonic-gate#endif
440Sstevel@tonic-gatestatic const char rcsid[] =
45	"$Id: syslogd.c,v 1.28 1998/02/28 15:14:00 jraynard Exp $";
46#endif /* not lint */
47
48/*
49 *  syslogd -- log system messages
50 *
51 * This program implements a system log. It takes a series of lines.
52 * Each line may have a priority, signified as "<n>" as
53 * the first characters of the line.  If this is
54 * not present, a default priority is used.
55 *
56 * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
57 * cause it to reread its configuration file.
58 *
59 * Defined Constants:
60 *
61 * MAXLINE -- the maximimum line length that can be handled.
62 * DEFUPRI -- the default priority for user messages
63 * DEFSPRI -- the default priority for kernel messages
64 *
65 * Author: Eric Allman
66 * extensive changes by Ralph Campbell
67 * more extensive changes by Eric Allman (again)
68 * Extension to log by program name as well as facility and priority
69 *   by Peter da Silva.
70 */
71
72#define	MAXLINE		1024		/* maximum line length */
73#define	MAXSVLINE	120		/* maximum saved line length */
74#define DEFUPRI		(LOG_USER|LOG_NOTICE)
75#define DEFSPRI		(LOG_KERN|LOG_CRIT)
76#define TIMERINTVL	30		/* interval for checking flush, mark */
77#define TTYMSGTIME	1		/* timed out passed to ttymsg */
78
79#include <sys/param.h>
80#include <sys/ioctl.h>
81#include <sys/stat.h>
82#include <sys/wait.h>
83#include <sys/socket.h>
84#include <sys/msgbuf.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 <paths.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 <regex.h>
102#include <setjmp.h>
103#include <signal.h>
104#include <stdio.h>
105#include <stdlib.h>
106#include <string.h>
107#include <sysexits.h>
108#include <unistd.h>
109#include <utmp.h>
110#include "pathnames.h"
111
112#define SYSLOG_NAMES
113#include <sys/syslog.h>
114
115const char	*LogName = _PATH_LOG;
116const char	*ConfFile = _PATH_LOGCONF;
117const char	*PidFile = _PATH_LOGPID;
118const char	ctty[] = _PATH_CONSOLE;
119
120#define FDMASK(fd)	(1 << (fd))
121
122#define	dprintf		if (Debug) printf
123
124#define MAXUNAMES	20	/* maximum number of user names */
125
126/*
127 * Flags to logmsg().
128 */
129
130#define IGN_CONS	0x001	/* don't print on console */
131#define SYNC_FILE	0x002	/* do fsync on file after printing */
132#define ADDDATE		0x004	/* add a date to the message */
133#define MARK		0x008	/* this message is a mark */
134
135/*
136 * This structure represents the files that will have log
137 * copies printed.
138 */
139
140struct filed {
141	struct	filed *f_next;		/* next in linked list */
142	short	f_type;			/* entry type, see below */
143	short	f_file;			/* file descriptor */
144	time_t	f_time;			/* time this was last written */
145	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
146	char	*f_program;		/* program this applies to */
147	union {
148		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
149		struct {
150			char	f_hname[MAXHOSTNAMELEN+1];
151			struct sockaddr_in	f_addr;
152		} f_forw;		/* forwarding address */
153		char	f_fname[MAXPATHLEN];
154		struct {
155			char	f_pname[MAXPATHLEN];
156			pid_t	f_pid;
157		} f_pipe;
158	} f_un;
159	char	f_prevline[MAXSVLINE];		/* last message logged */
160	char	f_lasttime[16];			/* time of last occurrence */
161	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
162	int	f_prevpri;			/* pri of f_prevline */
163	int	f_prevlen;			/* length of f_prevline */
164	int	f_prevcount;			/* repetition cnt of prevline */
165	int	f_repeatcount;			/* number of "repeated" msgs */
166};
167
168/*
169 * Queue of about-to-be dead processes we should watch out for.
170 */
171
172TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
173struct stailhead *deadq_headp;
174
175struct deadq_entry {
176	pid_t				dq_pid;
177	int				dq_timeout;
178	TAILQ_ENTRY(deadq_entry)	dq_entries;
179};
180
181/*
182 * The timeout to apply to processes waiting on the dead queue.  Unit
183 * of measure is `mark intervals', i.e. 20 minutes by default.
184 * Processes on the dead queue will be terminated after that time.
185 */
186
187#define DQ_TIMO_INIT	2
188
189typedef struct deadq_entry *dq_t;
190
191
192/*
193 * Struct to hold records of network addresses that are allowed to log
194 * to us.
195 */
196struct allowedpeer {
197	int isnumeric;
198	u_short port;
199	union {
200		struct {
201			struct in_addr addr;
202			struct in_addr mask;
203		} numeric;
204		char *name;
205	} u;
206#define a_addr u.numeric.addr
207#define a_mask u.numeric.mask
208#define a_name u.name
209};
210
211
212/*
213 * Intervals at which we flush out "message repeated" messages,
214 * in seconds after previous message is logged.  After each flush,
215 * we move to the next interval until we reach the largest.
216 */
217int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
218#define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
219#define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
220#define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
221				 (f)->f_repeatcount = MAXREPEAT; \
222			}
223
224/* values for f_type */
225#define F_UNUSED	0		/* unused entry */
226#define F_FILE		1		/* regular file */
227#define F_TTY		2		/* terminal */
228#define F_CONSOLE	3		/* console terminal */
229#define F_FORW		4		/* remote machine */
230#define F_USERS		5		/* list of users */
231#define F_WALL		6		/* everyone logged on */
232#define F_PIPE		7		/* pipe to program */
233
234char	*TypeNames[8] = {
235	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
236	"FORW",		"USERS",	"WALL",		"PIPE"
237};
238
239struct	filed *Files;
240struct	filed consfile;
241
242int	Debug;			/* debug flag */
243char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
244char	*LocalDomain;		/* our local domain name */
245int	finet;			/* Internet datagram socket */
246int	LogPort;		/* port number for INET connections */
247int	Initialized = 0;	/* set when we have initialized ourselves */
248int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
249int	MarkSeq = 0;		/* mark sequence number */
250int	SecureMode = 0;		/* when true, speak only unix domain socks */
251
252int     created_lsock = 0;      /* Flag if local socket created */
253char	bootfile[MAXLINE+1];	/* booted kernel file */
254
255struct allowedpeer *AllowedPeers;
256int	NumAllowed = 0;		/* # of AllowedPeer entries */
257
258int	allowaddr __P((char *));
259void	cfline __P((char *, struct filed *, char *));
260char   *cvthname __P((struct sockaddr_in *));
261void	deadq_enter __P((pid_t));
262int	decode __P((const char *, CODE *));
263void	die __P((int));
264void	domark __P((int));
265void	fprintlog __P((struct filed *, int, char *));
266void	init __P((int));
267void	logerror __P((const char *));
268void	logmsg __P((int, char *, char *, int));
269void	printline __P((char *, char *));
270void	printsys __P((char *));
271int	p_open __P((char *, pid_t *));
272void	reapchild __P((int));
273char   *ttymsg __P((struct iovec *, int, char *, int));
274static void	usage __P((void));
275int	validate __P((struct sockaddr_in *, const char *));
276void	wallmsg __P((struct filed *, struct iovec *));
277int	waitdaemon __P((int, int, int));
278void	timedout __P((int));
279
280int
281main(argc, argv)
282	int argc;
283	char *argv[];
284{
285	int ch, funix, i, inetm, fklog, klogm, len;
286	struct sockaddr_un sunx, fromunix;
287	struct sockaddr_in sin, frominet;
288	FILE *fp;
289	char *p, *hname, line[MSG_BSIZE + 1];
290	struct timeval tv, *tvp;
291	pid_t ppid;
292
293	while ((ch = getopt(argc, argv, "a:dsf:m:p:")) != -1)
294		switch(ch) {
295		case 'd':		/* debug */
296			Debug++;
297			break;
298		case 'a':		/* allow specific network addresses only */
299			if (allowaddr(optarg) == -1)
300				usage();
301			break;
302		case 'f':		/* configuration file */
303			ConfFile = optarg;
304			break;
305		case 'm':		/* mark interval */
306			MarkInterval = atoi(optarg) * 60;
307			break;
308		case 'p':		/* path */
309			LogName = optarg;
310			break;
311		case 's':		/* no network mode */
312			SecureMode++;
313			break;
314		case '?':
315		default:
316			usage();
317		}
318	if ((argc -= optind) != 0)
319		usage();
320
321	if (!Debug) {
322		ppid = waitdaemon(0, 0, 30);
323		if (ppid < 0)
324			err(1, "could not become daemon");
325	} else
326		setlinebuf(stdout);
327
328	if (NumAllowed)
329		endservent();
330
331	consfile.f_type = F_CONSOLE;
332	(void)strcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1);
333	(void)gethostname(LocalHostName, sizeof(LocalHostName));
334	if ((p = strchr(LocalHostName, '.')) != NULL) {
335		*p++ = '\0';
336		LocalDomain = p;
337	} else
338		LocalDomain = "";
339	(void)strcpy(bootfile, getbootfile());
340	(void)signal(SIGTERM, die);
341	(void)signal(SIGINT, Debug ? die : SIG_IGN);
342	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
343	(void)signal(SIGCHLD, reapchild);
344	(void)signal(SIGALRM, domark);
345	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
346	(void)alarm(TIMERINTVL);
347
348	TAILQ_INIT(&deadq_head);
349
350#ifndef SUN_LEN
351#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
352#endif
353	memset(&sunx, 0, sizeof(sunx));
354	sunx.sun_family = AF_UNIX;
355	(void)strncpy(sunx.sun_path, LogName, sizeof(sunx.sun_path));
356	(void)unlink(LogName);
357	funix = socket(AF_UNIX, SOCK_DGRAM, 0);
358	if (funix < 0 ||
359	    bind(funix, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
360	    chmod(LogName, 0666) < 0) {
361		(void) snprintf(line, sizeof line, "cannot create %s", LogName);
362		logerror(line);
363		dprintf("cannot create %s (%d)\n", LogName, errno);
364		die(0);
365	} else
366		created_lsock = 1;
367
368	inetm = 0;
369	if (!SecureMode) {
370		finet = socket(AF_INET, SOCK_DGRAM, 0);
371		if (finet >= 0) {
372			struct servent *sp;
373
374			sp = getservbyname("syslog", "udp");
375			if (sp == NULL) {
376				errno = 0;
377				logerror("syslog/udp: unknown service");
378				die(0);
379			}
380			memset(&sin, 0, sizeof(sin));
381			sin.sin_family = AF_INET;
382			sin.sin_port = LogPort = sp->s_port;
383
384			if (bind(finet, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
385				logerror("bind");
386				if (!Debug)
387					die(0);
388				inetm = FDMASK(finet);
389			}
390		}
391	}
392	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
393		klogm = FDMASK(fklog);
394	else {
395		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
396		klogm = 0;
397	}
398
399	/* tuck my process id away */
400	fp = fopen(PidFile, "w");
401	if (fp != NULL) {
402		fprintf(fp, "%d\n", getpid());
403		(void) fclose(fp);
404	}
405
406	dprintf("off & running....\n");
407
408	init(0);
409	(void)signal(SIGHUP, init);
410
411	tvp = &tv;
412	tv.tv_sec = tv.tv_usec = 0;
413
414	for (;;) {
415		int nfds, readfds = FDMASK(funix) | inetm | klogm;
416
417		dprintf("readfds = %#x\n", readfds);
418		nfds = select(20, (fd_set *)&readfds, (fd_set *)NULL,
419		    (fd_set *)NULL, tvp);
420		if (nfds == 0) {
421			if (tvp) {
422				tvp = NULL;
423				if (ppid != 1)
424					kill(ppid, SIGALRM);
425			}
426			continue;
427		}
428		if (nfds < 0) {
429			if (errno != EINTR)
430				logerror("select");
431			continue;
432		}
433		dprintf("got a message (%d, %#x)\n", nfds, readfds);
434		if (readfds & klogm) {
435			i = read(fklog, line, sizeof(line) - 1);
436			if (i > 0) {
437				line[i] = '\0';
438				printsys(line);
439			} else if (i < 0 && errno != EINTR) {
440				logerror("klog");
441				fklog = -1;
442				klogm = 0;
443			}
444		}
445		if (readfds & FDMASK(funix)) {
446			len = sizeof(fromunix);
447			i = recvfrom(funix, line, MAXLINE, 0,
448			    (struct sockaddr *)&fromunix, &len);
449			if (i > 0) {
450				line[i] = '\0';
451				printline(LocalHostName, line);
452			} else if (i < 0 && errno != EINTR)
453				logerror("recvfrom unix");
454		}
455		if (readfds & inetm) {
456			len = sizeof(frominet);
457			i = recvfrom(finet, line, MAXLINE, 0,
458			    (struct sockaddr *)&frominet, &len);
459			if (i > 0) {
460				line[i] = '\0';
461				hname = cvthname(&frominet);
462				if (validate(&frominet, hname))
463					printline(hname, line);
464			} else if (i < 0 && errno != EINTR)
465				logerror("recvfrom inet");
466		}
467	}
468}
469
470static void
471usage()
472{
473
474	fprintf(stderr, "%s\n%s\n",
475		"usage: syslogd [-ds] [-a allowed_peer] [-f config_file]",
476		"               [-m mark_interval] [-p log_socket]");
477	exit(1);
478}
479
480/*
481 * Take a raw input line, decode the message, and print the message
482 * on the appropriate log files.
483 */
484void
485printline(hname, msg)
486	char *hname;
487	char *msg;
488{
489	int c, pri;
490	char *p, *q, line[MAXLINE + 1];
491
492	/* test for special codes */
493	pri = DEFUPRI;
494	p = msg;
495	if (*p == '<') {
496		pri = 0;
497		while (isdigit(*++p))
498			pri = 10 * pri + (*p - '0');
499		if (*p == '>')
500			++p;
501	}
502	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
503		pri = DEFUPRI;
504
505	/* don't allow users to log kernel messages */
506	if (LOG_FAC(pri) == LOG_KERN)
507		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
508
509	q = line;
510
511	while ((c = *p++ & 0177) != '\0' &&
512	    q < &line[sizeof(line) - 1])
513		if (iscntrl(c))
514			if (c == '\n')
515				*q++ = ' ';
516			else if (c == '\t')
517				*q++ = '\t';
518			else {
519				*q++ = '^';
520				*q++ = c ^ 0100;
521			}
522		else
523			*q++ = c;
524	*q = '\0';
525
526	logmsg(pri, line, hname, 0);
527}
528
529/*
530 * Take a raw input line from /dev/klog, split and format similar to syslog().
531 */
532void
533printsys(msg)
534	char *msg;
535{
536	int c, pri, flags;
537	char *lp, *p, *q, line[MAXLINE + 1];
538
539	(void)strcpy(line, bootfile);
540	(void)strcat(line, ": ");
541	lp = line + strlen(line);
542	for (p = msg; *p != '\0'; ) {
543		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
544		pri = DEFSPRI;
545		if (*p == '<') {
546			pri = 0;
547			while (isdigit(*++p))
548				pri = 10 * pri + (*p - '0');
549			if (*p == '>')
550				++p;
551		} else {
552			/* kernel printf's come out on console */
553			flags |= IGN_CONS;
554		}
555		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
556			pri = DEFSPRI;
557		q = lp;
558		while (*p != '\0' && (c = *p++) != '\n' &&
559		    q < &line[MAXLINE])
560			*q++ = c;
561		*q = '\0';
562		logmsg(pri, line, LocalHostName, flags);
563	}
564}
565
566time_t	now;
567
568/*
569 * Log a message to the appropriate log files, users, etc. based on
570 * the priority.
571 */
572void
573logmsg(pri, msg, from, flags)
574	int pri;
575	char *msg, *from;
576	int flags;
577{
578	struct filed *f;
579	int fac, msglen, omask, prilev;
580	char *timestamp;
581 	char prog[NAME_MAX+1];
582 	int i;
583
584	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
585	    pri, flags, from, msg);
586
587	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
588
589	/*
590	 * Check to see if msg looks non-standard.
591	 */
592	msglen = strlen(msg);
593	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
594	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
595		flags |= ADDDATE;
596
597	(void)time(&now);
598	if (flags & ADDDATE)
599		timestamp = ctime(&now) + 4;
600	else {
601		timestamp = msg;
602		msg += 16;
603		msglen -= 16;
604	}
605
606	/* skip leading blanks */
607	while(isspace(*msg)) {
608		msg++;
609		msglen--;
610	}
611
612	/* extract facility and priority level */
613	if (flags & MARK)
614		fac = LOG_NFACILITIES;
615	else
616		fac = LOG_FAC(pri);
617	prilev = LOG_PRI(pri);
618
619	/* extract program name */
620	for(i = 0; i < NAME_MAX; i++) {
621		if(!isalnum(msg[i]))
622			break;
623		prog[i] = msg[i];
624	}
625	prog[i] = 0;
626
627	/* log the message to the particular outputs */
628	if (!Initialized) {
629		f = &consfile;
630		f->f_file = open(ctty, O_WRONLY, 0);
631
632		if (f->f_file >= 0) {
633			fprintlog(f, flags, msg);
634			(void)close(f->f_file);
635		}
636		(void)sigsetmask(omask);
637		return;
638	}
639	for (f = Files; f; f = f->f_next) {
640		/* skip messages that are incorrect priority */
641		if (f->f_pmask[fac] < prilev ||
642		    f->f_pmask[fac] == INTERNAL_NOPRI)
643			continue;
644		/* skip messages with the incorrect program name */
645		if(f->f_program)
646			if(strcmp(prog, f->f_program) != 0)
647				continue;
648
649		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
650			continue;
651
652		/* don't output marks to recently written files */
653		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
654			continue;
655
656		/*
657		 * suppress duplicate lines to this file
658		 */
659		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
660		    !strcmp(msg, f->f_prevline) &&
661		    !strcmp(from, f->f_prevhost)) {
662			(void)strncpy(f->f_lasttime, timestamp, 15);
663			f->f_prevcount++;
664			dprintf("msg repeated %d times, %ld sec of %d\n",
665			    f->f_prevcount, now - f->f_time,
666			    repeatinterval[f->f_repeatcount]);
667			/*
668			 * If domark would have logged this by now,
669			 * flush it now (so we don't hold isolated messages),
670			 * but back off so we'll flush less often
671			 * in the future.
672			 */
673			if (now > REPEATTIME(f)) {
674				fprintlog(f, flags, (char *)NULL);
675				BACKOFF(f);
676			}
677		} else {
678			/* new line, save it */
679			if (f->f_prevcount)
680				fprintlog(f, 0, (char *)NULL);
681			f->f_repeatcount = 0;
682			f->f_prevpri = pri;
683			(void)strncpy(f->f_lasttime, timestamp, 15);
684			(void)strncpy(f->f_prevhost, from,
685					sizeof(f->f_prevhost));
686			if (msglen < MAXSVLINE) {
687				f->f_prevlen = msglen;
688				(void)strcpy(f->f_prevline, msg);
689				fprintlog(f, flags, (char *)NULL);
690			} else {
691				f->f_prevline[0] = 0;
692				f->f_prevlen = 0;
693				fprintlog(f, flags, msg);
694			}
695		}
696	}
697	(void)sigsetmask(omask);
698}
699
700void
701fprintlog(f, flags, msg)
702	struct filed *f;
703	int flags;
704	char *msg;
705{
706	struct iovec iov[6];
707	struct iovec *v;
708	int l;
709	char line[MAXLINE + 1], repbuf[80], greetings[200];
710	char *msgret;
711
712	v = iov;
713	if (f->f_type == F_WALL) {
714		v->iov_base = greetings;
715		v->iov_len = snprintf(greetings, sizeof greetings,
716		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
717		    f->f_prevhost, ctime(&now));
718		v++;
719		v->iov_base = "";
720		v->iov_len = 0;
721		v++;
722	} else {
723		v->iov_base = f->f_lasttime;
724		v->iov_len = 15;
725		v++;
726		v->iov_base = " ";
727		v->iov_len = 1;
728		v++;
729	}
730	v->iov_base = f->f_prevhost;
731	v->iov_len = strlen(v->iov_base);
732	v++;
733	v->iov_base = " ";
734	v->iov_len = 1;
735	v++;
736
737	if (msg) {
738		v->iov_base = msg;
739		v->iov_len = strlen(msg);
740	} else if (f->f_prevcount > 1) {
741		v->iov_base = repbuf;
742		v->iov_len = sprintf(repbuf, "last message repeated %d times",
743		    f->f_prevcount);
744	} else {
745		v->iov_base = f->f_prevline;
746		v->iov_len = f->f_prevlen;
747	}
748	v++;
749
750	dprintf("Logging to %s", TypeNames[f->f_type]);
751	f->f_time = now;
752
753	switch (f->f_type) {
754	case F_UNUSED:
755		dprintf("\n");
756		break;
757
758	case F_FORW:
759		dprintf(" %s\n", f->f_un.f_forw.f_hname);
760		l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
761			     f->f_prevpri, iov[0].iov_base, iov[4].iov_base);
762		if (l > MAXLINE)
763			l = MAXLINE;
764		if ((finet >= 0) &&
765		     (sendto(finet, line, l, 0,
766			     (struct sockaddr *)&f->f_un.f_forw.f_addr,
767			     sizeof(f->f_un.f_forw.f_addr)) != l)) {
768			int e = errno;
769			(void)close(f->f_file);
770			f->f_type = F_UNUSED;
771			errno = e;
772			logerror("sendto");
773		}
774		break;
775
776	case F_FILE:
777		dprintf(" %s\n", f->f_un.f_fname);
778		v->iov_base = "\n";
779		v->iov_len = 1;
780		if (writev(f->f_file, iov, 6) < 0) {
781			int e = errno;
782			(void)close(f->f_file);
783			f->f_type = F_UNUSED;
784			errno = e;
785			logerror(f->f_un.f_fname);
786		} else if (flags & SYNC_FILE)
787			(void)fsync(f->f_file);
788		break;
789
790	case F_PIPE:
791		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
792		v->iov_base = "\n";
793		v->iov_len = 1;
794		if (f->f_un.f_pipe.f_pid == 0) {
795			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
796						&f->f_un.f_pipe.f_pid)) < 0) {
797				f->f_type = F_UNUSED;
798				logerror(f->f_un.f_pipe.f_pname);
799				break;
800			}
801		}
802		if (writev(f->f_file, iov, 6) < 0) {
803			int e = errno;
804			(void)close(f->f_file);
805			if (f->f_un.f_pipe.f_pid > 0)
806				deadq_enter(f->f_un.f_pipe.f_pid);
807			f->f_un.f_pipe.f_pid = 0;
808			errno = e;
809			logerror(f->f_un.f_pipe.f_pname);
810		}
811		break;
812
813	case F_CONSOLE:
814		if (flags & IGN_CONS) {
815			dprintf(" (ignored)\n");
816			break;
817		}
818		/* FALLTHROUGH */
819
820	case F_TTY:
821		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
822		v->iov_base = "\r\n";
823		v->iov_len = 2;
824
825		errno = 0;	/* ttymsg() only sometimes returns an errno */
826		if ((msgret = ttymsg(iov, 6, f->f_un.f_fname, 10))) {
827			f->f_type = F_UNUSED;
828			logerror(msgret);
829		}
830		break;
831
832	case F_USERS:
833	case F_WALL:
834		dprintf("\n");
835		v->iov_base = "\r\n";
836		v->iov_len = 2;
837		wallmsg(f, iov);
838		break;
839	}
840	f->f_prevcount = 0;
841}
842
843/*
844 *  WALLMSG -- Write a message to the world at large
845 *
846 *	Write the specified message to either the entire
847 *	world, or a list of approved users.
848 */
849void
850wallmsg(f, iov)
851	struct filed *f;
852	struct iovec *iov;
853{
854	static int reenter;			/* avoid calling ourselves */
855	FILE *uf;
856	struct utmp ut;
857	int i;
858	char *p;
859	char line[sizeof(ut.ut_line) + 1];
860
861	if (reenter++)
862		return;
863	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
864		logerror(_PATH_UTMP);
865		reenter = 0;
866		return;
867	}
868	/* NOSTRICT */
869	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
870		if (ut.ut_name[0] == '\0')
871			continue;
872		strncpy(line, ut.ut_line, sizeof(ut.ut_line));
873		line[sizeof(ut.ut_line)] = '\0';
874		if (f->f_type == F_WALL) {
875			if ((p = ttymsg(iov, 6, line, TTYMSGTIME)) != NULL) {
876				errno = 0;	/* already in msg */
877				logerror(p);
878			}
879			continue;
880		}
881		/* should we send the message to this user? */
882		for (i = 0; i < MAXUNAMES; i++) {
883			if (!f->f_un.f_uname[i][0])
884				break;
885			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
886			    UT_NAMESIZE)) {
887				if ((p = ttymsg(iov, 6, line, TTYMSGTIME))
888								!= NULL) {
889					errno = 0;	/* already in msg */
890					logerror(p);
891				}
892				break;
893			}
894		}
895	}
896	(void)fclose(uf);
897	reenter = 0;
898}
899
900void
901reapchild(signo)
902	int signo;
903{
904	int status, code;
905	pid_t pid;
906	struct filed *f;
907	char buf[256];
908	const char *reason;
909	dq_t q;
910
911	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
912		if (!Initialized)
913			/* Don't tell while we are initting. */
914			continue;
915
916		/* First, look if it's a process from the dead queue. */
917		for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
918			if (q->dq_pid == pid) {
919				TAILQ_REMOVE(&deadq_head, q, dq_entries);
920				free(q);
921				goto oncemore;
922			}
923
924		/* Now, look in list of active processes. */
925		for (f = Files; f; f = f->f_next)
926			if (f->f_type == F_PIPE &&
927			    f->f_un.f_pipe.f_pid == pid) {
928				(void)close(f->f_file);
929
930				errno = 0; /* Keep strerror() stuff out of logerror messages. */
931				f->f_un.f_pipe.f_pid = 0;
932				if (WIFSIGNALED(status)) {
933					reason = "due to signal";
934					code = WTERMSIG(status);
935				} else {
936					reason = "with status";
937					code = WEXITSTATUS(status);
938					if (code == 0)
939						goto oncemore; /* Exited OK. */
940				}
941				(void)snprintf(buf, sizeof buf,
942				"Logging subprocess %d (%s) exited %s %d.",
943					       pid, f->f_un.f_pipe.f_pname,
944					       reason, code);
945				logerror(buf);
946				break;
947			}
948	  oncemore:
949	}
950}
951
952/*
953 * Return a printable representation of a host address.
954 */
955char *
956cvthname(f)
957	struct sockaddr_in *f;
958{
959	struct hostent *hp;
960	char *p;
961
962	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
963
964	if (f->sin_family != AF_INET) {
965		dprintf("Malformed from address\n");
966		return ("???");
967	}
968	hp = gethostbyaddr((char *)&f->sin_addr,
969	    sizeof(struct in_addr), f->sin_family);
970	if (hp == 0) {
971		dprintf("Host name for your address (%s) unknown\n",
972			inet_ntoa(f->sin_addr));
973		return (inet_ntoa(f->sin_addr));
974	}
975	if ((p = strchr(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
976		*p = '\0';
977	return (hp->h_name);
978}
979
980void
981domark(signo)
982	int signo;
983{
984	struct filed *f;
985	dq_t q;
986
987	now = time((time_t *)NULL);
988	MarkSeq += TIMERINTVL;
989	if (MarkSeq >= MarkInterval) {
990		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
991		MarkSeq = 0;
992	}
993
994	for (f = Files; f; f = f->f_next) {
995		if (f->f_prevcount && now >= REPEATTIME(f)) {
996			dprintf("flush %s: repeated %d times, %d sec.\n",
997			    TypeNames[f->f_type], f->f_prevcount,
998			    repeatinterval[f->f_repeatcount]);
999			fprintlog(f, 0, (char *)NULL);
1000			BACKOFF(f);
1001		}
1002	}
1003
1004	/* Walk the dead queue, and see if we should signal somebody. */
1005	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1006		switch (q->dq_timeout) {
1007		case 0:
1008			/* Already signalled once, try harder now. */
1009			kill(q->dq_pid, SIGKILL);
1010			break;
1011
1012		case 1:
1013			/*
1014			 * Timed out on dead queue, send terminate
1015			 * signal.  Note that we leave the removal
1016			 * from the dead queue to reapchild(), which
1017			 * will also log the event.
1018			 */
1019			kill(q->dq_pid, SIGTERM);
1020			/* FALLTROUGH */
1021
1022		default:
1023			q->dq_timeout--;
1024		}
1025
1026	(void)alarm(TIMERINTVL);
1027}
1028
1029/*
1030 * Print syslogd errors some place.
1031 */
1032void
1033logerror(type)
1034	const char *type;
1035{
1036	char buf[512];
1037
1038	if (errno)
1039		(void)snprintf(buf,
1040		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1041	else
1042		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1043	errno = 0;
1044	dprintf("%s\n", buf);
1045	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1046}
1047
1048void
1049die(signo)
1050	int signo;
1051{
1052	struct filed *f;
1053	int was_initialized;
1054	char buf[100];
1055
1056	was_initialized = Initialized;
1057	Initialized = 0;	/* Don't log SIGCHLDs. */
1058	for (f = Files; f != NULL; f = f->f_next) {
1059		/* flush any pending output */
1060		if (f->f_prevcount)
1061			fprintlog(f, 0, (char *)NULL);
1062		if (f->f_type == F_PIPE)
1063			(void)close(f->f_file);
1064	}
1065	Initialized = was_initialized;
1066	if (signo) {
1067		dprintf("syslogd: exiting on signal %d\n", signo);
1068		(void)sprintf(buf, "exiting on signal %d", signo);
1069		errno = 0;
1070		logerror(buf);
1071	}
1072	if (created_lsock)
1073		(void)unlink(LogName);
1074	exit(1);
1075}
1076
1077/*
1078 *  INIT -- Initialize syslogd from configuration table
1079 */
1080void
1081init(signo)
1082	int signo;
1083{
1084	int i;
1085	FILE *cf;
1086	struct filed *f, *next, **nextp;
1087	char *p;
1088	char cline[LINE_MAX];
1089 	char prog[NAME_MAX+1];
1090
1091	dprintf("init\n");
1092
1093	/*
1094	 *  Close all open log files.
1095	 */
1096	Initialized = 0;
1097	for (f = Files; f != NULL; f = next) {
1098		/* flush any pending output */
1099		if (f->f_prevcount)
1100			fprintlog(f, 0, (char *)NULL);
1101
1102		switch (f->f_type) {
1103		case F_FILE:
1104		case F_FORW:
1105		case F_CONSOLE:
1106		case F_TTY:
1107			(void)close(f->f_file);
1108			break;
1109		case F_PIPE:
1110			(void)close(f->f_file);
1111			if (f->f_un.f_pipe.f_pid > 0)
1112				deadq_enter(f->f_un.f_pipe.f_pid);
1113			f->f_un.f_pipe.f_pid = 0;
1114			break;
1115		}
1116		next = f->f_next;
1117		if(f->f_program) free(f->f_program);
1118		free((char *)f);
1119	}
1120	Files = NULL;
1121	nextp = &Files;
1122
1123	/* open the configuration file */
1124	if ((cf = fopen(ConfFile, "r")) == NULL) {
1125		dprintf("cannot open %s\n", ConfFile);
1126		*nextp = (struct filed *)calloc(1, sizeof(*f));
1127		cfline("*.ERR\t/dev/console", *nextp, "*");
1128		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1129		cfline("*.PANIC\t*", (*nextp)->f_next, "*");
1130		Initialized = 1;
1131		return;
1132	}
1133
1134	/*
1135	 *  Foreach line in the conf table, open that file.
1136	 */
1137	f = NULL;
1138	strcpy(prog, "*");
1139	while (fgets(cline, sizeof(cline), cf) != NULL) {
1140		/*
1141		 * check for end-of-section, comments, strip off trailing
1142		 * spaces and newline character. #!prog is treated specially:
1143		 * following lines apply only to that program.
1144		 */
1145		for (p = cline; isspace(*p); ++p)
1146			continue;
1147		if (*p == 0)
1148			continue;
1149		if(*p == '#') {
1150			p++;
1151			if(*p!='!')
1152				continue;
1153		}
1154		if(*p=='!') {
1155			p++;
1156			while(isspace(*p)) p++;
1157			if(!*p) {
1158				strcpy(prog, "*");
1159				continue;
1160			}
1161			for(i = 0; i < NAME_MAX; i++) {
1162				if(!isalnum(p[i]))
1163					break;
1164				prog[i] = p[i];
1165			}
1166			prog[i] = 0;
1167			continue;
1168		}
1169		for (p = strchr(cline, '\0'); isspace(*--p);)
1170			continue;
1171		*++p = '\0';
1172		f = (struct filed *)calloc(1, sizeof(*f));
1173		*nextp = f;
1174		nextp = &f->f_next;
1175		cfline(cline, f, prog);
1176	}
1177
1178	/* close the configuration file */
1179	(void)fclose(cf);
1180
1181	Initialized = 1;
1182
1183	if (Debug) {
1184		for (f = Files; f; f = f->f_next) {
1185			for (i = 0; i <= LOG_NFACILITIES; i++)
1186				if (f->f_pmask[i] == INTERNAL_NOPRI)
1187					printf("X ");
1188				else
1189					printf("%d ", f->f_pmask[i]);
1190			printf("%s: ", TypeNames[f->f_type]);
1191			switch (f->f_type) {
1192			case F_FILE:
1193				printf("%s", f->f_un.f_fname);
1194				break;
1195
1196			case F_CONSOLE:
1197			case F_TTY:
1198				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1199				break;
1200
1201			case F_FORW:
1202				printf("%s", f->f_un.f_forw.f_hname);
1203				break;
1204
1205			case F_PIPE:
1206				printf("%s", f->f_un.f_pipe.f_pname);
1207				break;
1208
1209			case F_USERS:
1210				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1211					printf("%s, ", f->f_un.f_uname[i]);
1212				break;
1213			}
1214			if(f->f_program) {
1215				printf(" (%s)", f->f_program);
1216			}
1217			printf("\n");
1218		}
1219	}
1220
1221	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1222	dprintf("syslogd: restarted\n");
1223}
1224
1225/*
1226 * Crack a configuration file line
1227 */
1228void
1229cfline(line, f, prog)
1230	char *line;
1231	struct filed *f;
1232	char *prog;
1233{
1234	struct hostent *hp;
1235	int i, pri;
1236	char *bp, *p, *q;
1237	char buf[MAXLINE], ebuf[100];
1238
1239	dprintf("cfline(\"%s\", f, \"%s\")\n", line, prog);
1240
1241	errno = 0;	/* keep strerror() stuff out of logerror messages */
1242
1243	/* clear out file entry */
1244	memset(f, 0, sizeof(*f));
1245	for (i = 0; i <= LOG_NFACILITIES; i++)
1246		f->f_pmask[i] = INTERNAL_NOPRI;
1247
1248	/* save program name if any */
1249	if(prog && *prog=='*') prog = NULL;
1250	if(prog) {
1251		f->f_program = calloc(1, strlen(prog)+1);
1252		if(f->f_program) {
1253			strcpy(f->f_program, prog);
1254		}
1255	}
1256
1257	/* scan through the list of selectors */
1258	for (p = line; *p && *p != '\t';) {
1259
1260		/* find the end of this facility name list */
1261		for (q = p; *q && *q != '\t' && *q++ != '.'; )
1262			continue;
1263
1264		/* collect priority name */
1265		for (bp = buf; *q && !strchr("\t,;", *q); )
1266			*bp++ = *q++;
1267		*bp = '\0';
1268
1269		/* skip cruft */
1270		while (strchr(", ;", *q))
1271			q++;
1272
1273		/* decode priority name */
1274		if (*buf == '*')
1275			pri = LOG_PRIMASK + 1;
1276		else {
1277			pri = decode(buf, prioritynames);
1278			if (pri < 0) {
1279				(void)snprintf(ebuf, sizeof ebuf,
1280				    "unknown priority name \"%s\"", buf);
1281				logerror(ebuf);
1282				return;
1283			}
1284		}
1285
1286		/* scan facilities */
1287		while (*p && !strchr("\t.;", *p)) {
1288			for (bp = buf; *p && !strchr("\t,;.", *p); )
1289				*bp++ = *p++;
1290			*bp = '\0';
1291			if (*buf == '*')
1292				for (i = 0; i < LOG_NFACILITIES; i++)
1293					f->f_pmask[i] = pri;
1294			else {
1295				i = decode(buf, facilitynames);
1296				if (i < 0) {
1297					(void)snprintf(ebuf, sizeof ebuf,
1298					    "unknown facility name \"%s\"",
1299					    buf);
1300					logerror(ebuf);
1301					return;
1302				}
1303				f->f_pmask[i >> 3] = pri;
1304			}
1305			while (*p == ',' || *p == ' ')
1306				p++;
1307		}
1308
1309		p = q;
1310	}
1311
1312	/* skip to action part */
1313	while (*p == '\t')
1314		p++;
1315
1316	switch (*p)
1317	{
1318	case '@':
1319		(void)strcpy(f->f_un.f_forw.f_hname, ++p);
1320		hp = gethostbyname(p);
1321		if (hp == NULL) {
1322			extern int h_errno;
1323
1324			logerror(hstrerror(h_errno));
1325			break;
1326		}
1327		memset(&f->f_un.f_forw.f_addr, 0,
1328			 sizeof(f->f_un.f_forw.f_addr));
1329		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1330		f->f_un.f_forw.f_addr.sin_port = LogPort;
1331		memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1332		f->f_type = F_FORW;
1333		break;
1334
1335	case '/':
1336		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1337			f->f_type = F_UNUSED;
1338			logerror(p);
1339			break;
1340		}
1341		if (isatty(f->f_file)) {
1342			if (strcmp(p, ctty) == 0)
1343				f->f_type = F_CONSOLE;
1344			else
1345				f->f_type = F_TTY;
1346			(void)strcpy(f->f_un.f_fname, p + sizeof _PATH_DEV - 1);
1347		} else {
1348			(void)strcpy(f->f_un.f_fname, p);
1349			f->f_type = F_FILE;
1350		}
1351		break;
1352
1353	case '|':
1354		f->f_un.f_pipe.f_pid = 0;
1355		(void)strcpy(f->f_un.f_pipe.f_pname, p + 1);
1356		f->f_type = F_PIPE;
1357		break;
1358
1359	case '*':
1360		f->f_type = F_WALL;
1361		break;
1362
1363	default:
1364		for (i = 0; i < MAXUNAMES && *p; i++) {
1365			for (q = p; *q && *q != ','; )
1366				q++;
1367			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1368			if ((q - p) > UT_NAMESIZE)
1369				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1370			else
1371				f->f_un.f_uname[i][q - p] = '\0';
1372			while (*q == ',' || *q == ' ')
1373				q++;
1374			p = q;
1375		}
1376		f->f_type = F_USERS;
1377		break;
1378	}
1379}
1380
1381
1382/*
1383 *  Decode a symbolic name to a numeric value
1384 */
1385int
1386decode(name, codetab)
1387	const char *name;
1388	CODE *codetab;
1389{
1390	CODE *c;
1391	char *p, buf[40];
1392
1393	if (isdigit(*name))
1394		return (atoi(name));
1395
1396	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1397		if (isupper(*name))
1398			*p = tolower(*name);
1399		else
1400			*p = *name;
1401	}
1402	*p = '\0';
1403	for (c = codetab; c->c_name; c++)
1404		if (!strcmp(buf, c->c_name))
1405			return (c->c_val);
1406
1407	return (-1);
1408}
1409
1410/*
1411 * fork off and become a daemon, but wait for the child to come online
1412 * before returing to the parent, or we get disk thrashing at boot etc.
1413 * Set a timer so we don't hang forever if it wedges.
1414 */
1415int
1416waitdaemon(nochdir, noclose, maxwait)
1417	int nochdir, noclose, maxwait;
1418{
1419	int fd;
1420	int status;
1421	pid_t pid, childpid;
1422
1423	switch (childpid = fork()) {
1424	case -1:
1425		return (-1);
1426	case 0:
1427		break;
1428	default:
1429		signal(SIGALRM, timedout);
1430		alarm(maxwait);
1431		while ((pid = wait3(&status, 0, NULL)) != -1) {
1432			if (WIFEXITED(status))
1433				errx(1, "child pid %d exited with return code %d",
1434					pid, WEXITSTATUS(status));
1435			if (WIFSIGNALED(status))
1436				errx(1, "child pid %d exited on signal %d%s",
1437					pid, WTERMSIG(status),
1438					WCOREDUMP(status) ? " (core dumped)" :
1439					"");
1440			if (pid == childpid)	/* it's gone... */
1441				break;
1442		}
1443		exit(0);
1444	}
1445
1446	if (setsid() == -1)
1447		return (-1);
1448
1449	if (!nochdir)
1450		(void)chdir("/");
1451
1452	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1453		(void)dup2(fd, STDIN_FILENO);
1454		(void)dup2(fd, STDOUT_FILENO);
1455		(void)dup2(fd, STDERR_FILENO);
1456		if (fd > 2)
1457			(void)close (fd);
1458	}
1459	return (getppid());
1460}
1461
1462/*
1463 * We get a SIGALRM from the child when it's running and finished doing it's
1464 * fsync()'s or O_SYNC writes for all the boot messages.
1465 *
1466 * We also get a signal from the kernel if the timer expires, so check to
1467 * see what happened.
1468 */
1469void
1470timedout(sig)
1471	int sig __unused;
1472{
1473	int left;
1474	left = alarm(0);
1475	signal(SIGALRM, SIG_DFL);
1476	if (left == 0)
1477		errx(1, "timed out waiting for child");
1478	else
1479		exit(0);
1480}
1481
1482/*
1483 * Add `s' to the list of allowable peer addresses to accept messages
1484 * from.
1485 *
1486 * `s' is a string in the form:
1487 *
1488 *    [*]domainname[:{servicename|portnumber|*}]
1489 *
1490 * or
1491 *
1492 *    netaddr/maskbits[:{servicename|portnumber|*}]
1493 *
1494 * Returns -1 on error, 0 if the argument was valid.
1495 */
1496int
1497allowaddr(s)
1498	char *s;
1499{
1500	char *cp1, *cp2;
1501	struct allowedpeer ap;
1502	struct servent *se;
1503	regex_t re;
1504	int i;
1505
1506	if ((cp1 = strrchr(s, ':'))) {
1507		/* service/port provided */
1508		*cp1++ = '\0';
1509		if (strlen(cp1) == 1 && *cp1 == '*')
1510			/* any port allowed */
1511			ap.port = htons(0);
1512		else if ((se = getservbyname(cp1, "udp")))
1513			ap.port = se->s_port;
1514		else {
1515			ap.port = htons((int)strtol(cp1, &cp2, 0));
1516			if (*cp2 != '\0')
1517				return -1; /* port not numeric */
1518		}
1519	} else {
1520		if ((se = getservbyname("syslog", "udp")))
1521			ap.port = se->s_port;
1522		else
1523			/* sanity, should not happen */
1524			ap.port = htons(514);
1525	}
1526
1527	/* the regexp's are ugly, but the cleanest way */
1528
1529	if (regcomp(&re, "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+(/[0-9]+)?$",
1530		    REG_EXTENDED))
1531		/* if RE compilation fails, that's an internal error */
1532		abort();
1533	if (regexec(&re, s, 0, 0, 0) == 0) {
1534		/* arg `s' is numeric */
1535		ap.isnumeric = 1;
1536		if ((cp1 = strchr(s, '/')) != NULL) {
1537			*cp1++ = '\0';
1538			i = atoi(cp1);
1539			if (i < 0 || i > 32)
1540				return -1;
1541			/* convert masklen to netmask */
1542			ap.a_mask.s_addr = htonl(~((1 << (32 - i)) - 1));
1543		}
1544		if (ascii2addr(AF_INET, s, &ap.a_addr) == -1)
1545			return -1;
1546		if (cp1 == NULL) {
1547			/* use default netmask */
1548			if (IN_CLASSA(ntohl(ap.a_addr.s_addr)))
1549				ap.a_mask.s_addr = htonl(IN_CLASSA_NET);
1550			else if (IN_CLASSB(ntohl(ap.a_addr.s_addr)))
1551				ap.a_mask.s_addr = htonl(IN_CLASSB_NET);
1552			else
1553				ap.a_mask.s_addr = htonl(IN_CLASSC_NET);
1554		}
1555	} else {
1556		/* arg `s' is domain name */
1557		ap.isnumeric = 0;
1558		ap.a_name = s;
1559	}
1560	regfree(&re);
1561
1562	if (Debug) {
1563		printf("allowaddr: rule %d: ", NumAllowed);
1564		if (ap.isnumeric) {
1565			printf("numeric, ");
1566			printf("addr = %s, ",
1567			       addr2ascii(AF_INET, &ap.a_addr, sizeof(struct in_addr), 0));
1568			printf("mask = %s; ",
1569			       addr2ascii(AF_INET, &ap.a_mask, sizeof(struct in_addr), 0));
1570		} else
1571			printf("domainname = %s; ", ap.a_name);
1572		printf("port = %d\n", ntohs(ap.port));
1573	}
1574
1575	if ((AllowedPeers = realloc(AllowedPeers,
1576				    ++NumAllowed * sizeof(struct allowedpeer)))
1577	    == NULL) {
1578		fprintf(stderr, "Out of memory!\n");
1579		exit(EX_OSERR);
1580	}
1581	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
1582	return 0;
1583}
1584
1585/*
1586 * Validate that the remote peer has permission to log to us.
1587 */
1588int
1589validate(sin, hname)
1590	struct sockaddr_in *sin;
1591	const char *hname;
1592{
1593	int i;
1594	size_t l1, l2;
1595	char *cp, name[MAXHOSTNAMELEN];
1596	struct allowedpeer *ap;
1597
1598	if (NumAllowed == 0)
1599		/* traditional behaviour, allow everything */
1600		return 1;
1601
1602	strncpy(name, hname, sizeof name);
1603	if (strchr(name, '.') == NULL) {
1604		strncat(name, ".", sizeof name - strlen(name) - 1);
1605		strncat(name, LocalDomain, sizeof name - strlen(name) - 1);
1606	}
1607	dprintf("validate: dgram from IP %s, port %d, name %s;\n",
1608		addr2ascii(AF_INET, &sin->sin_addr, sizeof(struct in_addr), 0),
1609		ntohs(sin->sin_port), name);
1610
1611	/* now, walk down the list */
1612	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
1613		if (ntohs(ap->port) != 0 && ap->port != sin->sin_port) {
1614			dprintf("rejected in rule %d due to port mismatch.\n", i);
1615			continue;
1616		}
1617
1618		if (ap->isnumeric) {
1619			if ((sin->sin_addr.s_addr & ap->a_mask.s_addr)
1620			    != ap->a_addr.s_addr) {
1621				dprintf("rejected in rule %d due to IP mismatch.\n", i);
1622				continue;
1623			}
1624		} else {
1625			cp = ap->a_name;
1626			l1 = strlen(name);
1627			if (*cp == '*') {
1628				/* allow wildmatch */
1629				cp++;
1630				l2 = strlen(cp);
1631				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
1632					dprintf("rejected in rule %d due to name mismatch.\n", i);
1633					continue;
1634				}
1635			} else {
1636				/* exact match */
1637				l2 = strlen(cp);
1638				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
1639					dprintf("rejected in rule %d due to name mismatch.\n", i);
1640					continue;
1641				}
1642			}
1643		}
1644		dprintf("accepted in rule %d.\n", i);
1645		return 1;	/* hooray! */
1646	}
1647	return 0;
1648}
1649
1650/*
1651 * Fairly similar to popen(3), but returns an open descriptor, as
1652 * opposed to a FILE *.
1653 */
1654int
1655p_open(prog, pid)
1656	char *prog;
1657	pid_t *pid;
1658{
1659	int pfd[2], nulldesc, i;
1660	sigset_t omask, mask;
1661	char *argv[4]; /* sh -c cmd NULL */
1662	char errmsg[200];
1663
1664	if (pipe(pfd) == -1)
1665		return -1;
1666	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
1667		/* we are royally screwed anyway */
1668		return -1;
1669
1670	sigemptyset(&mask);
1671	sigaddset(&mask, SIGALRM);
1672	sigaddset(&mask, SIGHUP);
1673	sigprocmask(SIG_BLOCK, &mask, &omask);
1674	switch ((*pid = fork())) {
1675	case -1:
1676		sigprocmask(SIG_SETMASK, &omask, 0);
1677		close(nulldesc);
1678		return -1;
1679
1680	case 0:
1681		argv[0] = "sh";
1682		argv[1] = "-c";
1683		argv[2] = prog;
1684		argv[3] = NULL;
1685
1686		alarm(0);
1687		(void)setsid();	/* Avoid catching SIGHUPs. */
1688
1689		/*
1690		 * Throw away pending signals, and reset signal
1691		 * behaviour to standard values.
1692		 */
1693		signal(SIGALRM, SIG_IGN);
1694		signal(SIGHUP, SIG_IGN);
1695		sigprocmask(SIG_SETMASK, &omask, 0);
1696		signal(SIGPIPE, SIG_DFL);
1697		signal(SIGQUIT, SIG_DFL);
1698		signal(SIGALRM, SIG_DFL);
1699		signal(SIGHUP, SIG_DFL);
1700
1701		dup2(pfd[0], STDIN_FILENO);
1702		dup2(nulldesc, STDOUT_FILENO);
1703		dup2(nulldesc, STDERR_FILENO);
1704		for (i = getdtablesize(); i > 2; i--)
1705			(void) close(i);
1706
1707		(void) execvp(_PATH_BSHELL, argv);
1708		_exit(255);
1709	}
1710
1711	sigprocmask(SIG_SETMASK, &omask, 0);
1712	close(nulldesc);
1713	close(pfd[0]);
1714	/*
1715	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
1716	 * supposed to get an EWOULDBLOCK on writev(2), which is
1717	 * caught by the logic above anyway, which will in turn close
1718	 * the pipe, and fork a new logging subprocess if necessary.
1719	 * The stale subprocess will be killed some time later unless
1720	 * it terminated itself due to closing its input pipe (so we
1721	 * get rid of really dead puppies).
1722	 */
1723	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
1724		/* This is bad. */
1725		(void)snprintf(errmsg, sizeof errmsg,
1726			       "Warning: cannot change pipe to PID %d to "
1727			       "non-blocking behaviour.",
1728			       (int)*pid);
1729		logerror(errmsg);
1730	}
1731	return pfd[1];
1732}
1733
1734void
1735deadq_enter(pid)
1736	pid_t pid;
1737{
1738	dq_t p;
1739
1740	p = malloc(sizeof(struct deadq_entry));
1741	if (p == 0) {
1742		errno = 0;
1743		logerror("panic: out of virtual memory!");
1744		exit(1);
1745	}
1746
1747	p->dq_pid = pid;
1748	p->dq_timeout = DQ_TIMO_INIT;
1749	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
1750}
1751