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