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