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