syslogd.c revision 1553
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 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
41static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
42#endif /* not lint */
43
44/*
45 *  syslogd -- log system messages
46 *
47 * This program implements a system log. It takes a series of lines.
48 * Each line may have a priority, signified as "<n>" as
49 * the first characters of the line.  If this is
50 * not present, a default priority is used.
51 *
52 * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
53 * cause it to reread its configuration file.
54 *
55 * Defined Constants:
56 *
57 * MAXLINE -- the maximimum line length that can be handled.
58 * DEFUPRI -- the default priority for user messages
59 * DEFSPRI -- the default priority for kernel messages
60 *
61 * Author: Eric Allman
62 * extensive changes by Ralph Campbell
63 * more extensive changes by Eric Allman (again)
64 */
65
66#define	MAXLINE		1024		/* maximum line length */
67#define	MAXSVLINE	120		/* maximum saved line length */
68#define DEFUPRI		(LOG_USER|LOG_NOTICE)
69#define DEFSPRI		(LOG_KERN|LOG_CRIT)
70#define TIMERINTVL	30		/* interval for checking flush, mark */
71
72#include <sys/param.h>
73#include <sys/ioctl.h>
74#include <sys/stat.h>
75#include <sys/wait.h>
76#include <sys/socket.h>
77#include <sys/msgbuf.h>
78#include <sys/uio.h>
79#include <sys/un.h>
80#include <sys/time.h>
81#include <sys/resource.h>
82
83#include <netinet/in.h>
84#include <netdb.h>
85#include <arpa/inet.h>
86
87#include <ctype.h>
88#include <errno.h>
89#include <fcntl.h>
90#include <setjmp.h>
91#include <signal.h>
92#include <stdio.h>
93#include <stdlib.h>
94#include <string.h>
95#include <unistd.h>
96#include <utmp.h>
97#include "pathnames.h"
98
99#define SYSLOG_NAMES
100#include <sys/syslog.h>
101
102char	*LogName = _PATH_LOG;
103char	*ConfFile = _PATH_LOGCONF;
104char	*PidFile = _PATH_LOGPID;
105char	ctty[] = _PATH_CONSOLE;
106
107#define FDMASK(fd)	(1 << (fd))
108
109#define	dprintf		if (Debug) printf
110
111#define MAXUNAMES	20	/* maximum number of user names */
112
113/*
114 * Flags to logmsg().
115 */
116
117#define IGN_CONS	0x001	/* don't print on console */
118#define SYNC_FILE	0x002	/* do fsync on file after printing */
119#define ADDDATE		0x004	/* add a date to the message */
120#define MARK		0x008	/* this message is a mark */
121
122/*
123 * This structure represents the files that will have log
124 * copies printed.
125 */
126
127struct filed {
128	struct	filed *f_next;		/* next in linked list */
129	short	f_type;			/* entry type, see below */
130	short	f_file;			/* file descriptor */
131	time_t	f_time;			/* time this was last written */
132	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
133	union {
134		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
135		struct {
136			char	f_hname[MAXHOSTNAMELEN+1];
137			struct sockaddr_in	f_addr;
138		} f_forw;		/* forwarding address */
139		char	f_fname[MAXPATHLEN];
140	} f_un;
141	char	f_prevline[MAXSVLINE];		/* last message logged */
142	char	f_lasttime[16];			/* time of last occurrence */
143	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
144	int	f_prevpri;			/* pri of f_prevline */
145	int	f_prevlen;			/* length of f_prevline */
146	int	f_prevcount;			/* repetition cnt of prevline */
147	int	f_repeatcount;			/* number of "repeated" msgs */
148};
149
150/*
151 * Intervals at which we flush out "message repeated" messages,
152 * in seconds after previous message is logged.  After each flush,
153 * we move to the next interval until we reach the largest.
154 */
155int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
156#define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
157#define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
158#define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
159				 (f)->f_repeatcount = MAXREPEAT; \
160			}
161
162/* values for f_type */
163#define F_UNUSED	0		/* unused entry */
164#define F_FILE		1		/* regular file */
165#define F_TTY		2		/* terminal */
166#define F_CONSOLE	3		/* console terminal */
167#define F_FORW		4		/* remote machine */
168#define F_USERS		5		/* list of users */
169#define F_WALL		6		/* everyone logged on */
170
171char	*TypeNames[7] = {
172	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
173	"FORW",		"USERS",	"WALL"
174};
175
176struct	filed *Files;
177struct	filed consfile;
178
179int	Debug;			/* debug flag */
180char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
181char	*LocalDomain;		/* our local domain name */
182int	InetInuse = 0;		/* non-zero if INET sockets are being used */
183int	finet;			/* Internet datagram socket */
184int	LogPort;		/* port number for INET connections */
185int	Initialized = 0;	/* set when we have initialized ourselves */
186int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
187int	MarkSeq = 0;		/* mark sequence number */
188
189void	cfline __P((char *, struct filed *));
190char   *cvthname __P((struct sockaddr_in *));
191int	decode __P((const char *, CODE *));
192void	die __P((int));
193void	domark __P((int));
194void	fprintlog __P((struct filed *, int, char *));
195void	init __P((int));
196void	logerror __P((char *));
197void	logmsg __P((int, char *, char *, int));
198void	printline __P((char *, char *));
199void	printsys __P((char *));
200void	reapchild __P((int));
201char   *ttymsg __P((struct iovec *, int, char *, int));
202void	usage __P((void));
203void	wallmsg __P((struct filed *, struct iovec *));
204
205int
206main(argc, argv)
207	int argc;
208	char *argv[];
209{
210	int ch, funix, i, inetm, fklog, klogm, len;
211	struct sockaddr_un sunx, fromunix;
212	struct sockaddr_in sin, frominet;
213	FILE *fp;
214	char *p, line[MSG_BSIZE + 1];
215
216	while ((ch = getopt(argc, argv, "df:m:p:")) != EOF)
217		switch(ch) {
218		case 'd':		/* debug */
219			Debug++;
220			break;
221		case 'f':		/* configuration file */
222			ConfFile = optarg;
223			break;
224		case 'm':		/* mark interval */
225			MarkInterval = atoi(optarg) * 60;
226			break;
227		case 'p':		/* path */
228			LogName = optarg;
229			break;
230		case '?':
231		default:
232			usage();
233		}
234	if ((argc -= optind) != 0)
235		usage();
236
237	if (!Debug)
238		(void)daemon(0, 0);
239	else
240		setlinebuf(stdout);
241
242	consfile.f_type = F_CONSOLE;
243	(void)strcpy(consfile.f_un.f_fname, ctty);
244	(void)gethostname(LocalHostName, sizeof(LocalHostName));
245	if ((p = strchr(LocalHostName, '.')) != NULL) {
246		*p++ = '\0';
247		LocalDomain = p;
248	} else
249		LocalDomain = "";
250	(void)signal(SIGTERM, die);
251	(void)signal(SIGINT, Debug ? die : SIG_IGN);
252	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
253	(void)signal(SIGCHLD, reapchild);
254	(void)signal(SIGALRM, domark);
255	(void)alarm(TIMERINTVL);
256	(void)unlink(LogName);
257
258#ifndef SUN_LEN
259#define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
260#endif
261	memset(&sunx, 0, sizeof(sunx));
262	sunx.sun_family = AF_UNIX;
263	(void)strncpy(sunx.sun_path, LogName, sizeof(sunx.sun_path));
264	funix = socket(AF_UNIX, SOCK_DGRAM, 0);
265	if (funix < 0 ||
266	    bind(funix, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
267	    chmod(LogName, 0666) < 0) {
268		(void) sprintf(line, "cannot create %s", LogName);
269		logerror(line);
270		dprintf("cannot create %s (%d)\n", LogName, errno);
271		die(0);
272	}
273	finet = socket(AF_INET, SOCK_DGRAM, 0);
274	inetm = 0;
275	if (finet >= 0) {
276		struct servent *sp;
277
278		sp = getservbyname("syslog", "udp");
279		if (sp == NULL) {
280			errno = 0;
281			logerror("syslog/udp: unknown service");
282			die(0);
283		}
284		memset(&sin, 0, sizeof(sin));
285		sin.sin_family = AF_INET;
286		sin.sin_port = LogPort = sp->s_port;
287		if (bind(finet, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
288			logerror("bind");
289			if (!Debug)
290				die(0);
291		} else {
292			inetm = FDMASK(finet);
293			InetInuse = 1;
294		}
295	}
296	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
297		klogm = FDMASK(fklog);
298	else {
299		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
300		klogm = 0;
301	}
302
303	/* tuck my process id away */
304	fp = fopen(PidFile, "w");
305	if (fp != NULL) {
306		fprintf(fp, "%d\n", getpid());
307		(void) fclose(fp);
308	}
309
310	dprintf("off & running....\n");
311
312	init(0);
313	(void)signal(SIGHUP, init);
314
315	for (;;) {
316		int nfds, readfds = FDMASK(funix) | inetm | klogm;
317
318		dprintf("readfds = %#x\n", readfds);
319		nfds = select(20, (fd_set *)&readfds, (fd_set *)NULL,
320		    (fd_set *)NULL, (struct timeval *)NULL);
321		if (nfds == 0)
322			continue;
323		if (nfds < 0) {
324			if (errno != EINTR)
325				logerror("select");
326			continue;
327		}
328		dprintf("got a message (%d, %#x)\n", nfds, readfds);
329		if (readfds & klogm) {
330			i = read(fklog, line, sizeof(line) - 1);
331			if (i > 0) {
332				line[i] = '\0';
333				printsys(line);
334			} else if (i < 0 && errno != EINTR) {
335				logerror("klog");
336				fklog = -1;
337				klogm = 0;
338			}
339		}
340		if (readfds & FDMASK(funix)) {
341			len = sizeof(fromunix);
342			i = recvfrom(funix, line, MAXLINE, 0,
343			    (struct sockaddr *)&fromunix, &len);
344			if (i > 0) {
345				line[i] = '\0';
346				printline(LocalHostName, line);
347			} else if (i < 0 && errno != EINTR)
348				logerror("recvfrom unix");
349		}
350		if (readfds & inetm) {
351			len = sizeof(frominet);
352			i = recvfrom(finet, line, MAXLINE, 0,
353			    (struct sockaddr *)&frominet, &len);
354			if (i > 0) {
355				line[i] = '\0';
356				printline(cvthname(&frominet), line);
357			} else if (i < 0 && errno != EINTR)
358				logerror("recvfrom inet");
359		}
360	}
361}
362
363void
364usage()
365{
366
367	(void)fprintf(stderr,
368	    "usage: syslogd [-f conffile] [-m markinterval] [-p logpath]\n");
369	exit(1);
370}
371
372/*
373 * Take a raw input line, decode the message, and print the message
374 * on the appropriate log files.
375 */
376void
377printline(hname, msg)
378	char *hname;
379	char *msg;
380{
381	int c, pri;
382	char *p, *q, line[MAXLINE + 1];
383
384	/* test for special codes */
385	pri = DEFUPRI;
386	p = msg;
387	if (*p == '<') {
388		pri = 0;
389		while (isdigit(*++p))
390			pri = 10 * pri + (*p - '0');
391		if (*p == '>')
392			++p;
393	}
394	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
395		pri = DEFUPRI;
396
397	/* don't allow users to log kernel messages */
398	if (LOG_FAC(pri) == LOG_KERN)
399		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
400
401	q = line;
402
403	while ((c = *p++ & 0177) != '\0' &&
404	    q < &line[sizeof(line) - 1])
405		if (iscntrl(c))
406			if (c == '\n')
407				*q++ = ' ';
408			else if (c == '\t')
409				*q++ = '\t';
410			else {
411				*q++ = '^';
412				*q++ = c ^ 0100;
413			}
414		else
415			*q++ = c;
416	*q = '\0';
417
418	logmsg(pri, line, hname, 0);
419}
420
421/*
422 * Take a raw input line from /dev/klog, split and format similar to syslog().
423 */
424void
425printsys(msg)
426	char *msg;
427{
428	int c, pri, flags;
429	char *lp, *p, *q, line[MAXLINE + 1];
430
431	(void)strcpy(line, "vmunix: ");
432	lp = line + strlen(line);
433	for (p = msg; *p != '\0'; ) {
434		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
435		pri = DEFSPRI;
436		if (*p == '<') {
437			pri = 0;
438			while (isdigit(*++p))
439				pri = 10 * pri + (*p - '0');
440			if (*p == '>')
441				++p;
442		} else {
443			/* kernel printf's come out on console */
444			flags |= IGN_CONS;
445		}
446		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
447			pri = DEFSPRI;
448		q = lp;
449		while (*p != '\0' && (c = *p++) != '\n' &&
450		    q < &line[MAXLINE])
451			*q++ = c;
452		*q = '\0';
453		logmsg(pri, line, LocalHostName, flags);
454	}
455}
456
457time_t	now;
458
459/*
460 * Log a message to the appropriate log files, users, etc. based on
461 * the priority.
462 */
463void
464logmsg(pri, msg, from, flags)
465	int pri;
466	char *msg, *from;
467	int flags;
468{
469	struct filed *f;
470	int fac, msglen, omask, prilev;
471	char *timestamp;
472
473	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
474	    pri, flags, from, msg);
475
476	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
477
478	/*
479	 * Check to see if msg looks non-standard.
480	 */
481	msglen = strlen(msg);
482	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
483	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
484		flags |= ADDDATE;
485
486	(void)time(&now);
487	if (flags & ADDDATE)
488		timestamp = ctime(&now) + 4;
489	else {
490		timestamp = msg;
491		msg += 16;
492		msglen -= 16;
493	}
494
495	/* extract facility and priority level */
496	if (flags & MARK)
497		fac = LOG_NFACILITIES;
498	else
499		fac = LOG_FAC(pri);
500	prilev = LOG_PRI(pri);
501
502	/* log the message to the particular outputs */
503	if (!Initialized) {
504		f = &consfile;
505		f->f_file = open(ctty, O_WRONLY, 0);
506
507		if (f->f_file >= 0) {
508			fprintlog(f, flags, msg);
509			(void)close(f->f_file);
510		}
511		(void)sigsetmask(omask);
512		return;
513	}
514	for (f = Files; f; f = f->f_next) {
515		/* skip messages that are incorrect priority */
516		if (f->f_pmask[fac] < prilev ||
517		    f->f_pmask[fac] == INTERNAL_NOPRI)
518			continue;
519
520		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
521			continue;
522
523		/* don't output marks to recently written files */
524		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
525			continue;
526
527		/*
528		 * suppress duplicate lines to this file
529		 */
530		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
531		    !strcmp(msg, f->f_prevline) &&
532		    !strcmp(from, f->f_prevhost)) {
533			(void)strncpy(f->f_lasttime, timestamp, 15);
534			f->f_prevcount++;
535			dprintf("msg repeated %d times, %ld sec of %d\n",
536			    f->f_prevcount, now - f->f_time,
537			    repeatinterval[f->f_repeatcount]);
538			/*
539			 * If domark would have logged this by now,
540			 * flush it now (so we don't hold isolated messages),
541			 * but back off so we'll flush less often
542			 * in the future.
543			 */
544			if (now > REPEATTIME(f)) {
545				fprintlog(f, flags, (char *)NULL);
546				BACKOFF(f);
547			}
548		} else {
549			/* new line, save it */
550			if (f->f_prevcount)
551				fprintlog(f, 0, (char *)NULL);
552			f->f_repeatcount = 0;
553			(void)strncpy(f->f_lasttime, timestamp, 15);
554			(void)strncpy(f->f_prevhost, from,
555					sizeof(f->f_prevhost));
556			if (msglen < MAXSVLINE) {
557				f->f_prevlen = msglen;
558				f->f_prevpri = pri;
559				(void)strcpy(f->f_prevline, msg);
560				fprintlog(f, flags, (char *)NULL);
561			} else {
562				f->f_prevline[0] = 0;
563				f->f_prevlen = 0;
564				fprintlog(f, flags, msg);
565			}
566		}
567	}
568	(void)sigsetmask(omask);
569}
570
571void
572fprintlog(f, flags, msg)
573	struct filed *f;
574	int flags;
575	char *msg;
576{
577	struct iovec iov[6];
578	struct iovec *v;
579	int l;
580	char line[MAXLINE + 1], repbuf[80], greetings[200];
581
582	v = iov;
583	if (f->f_type == F_WALL) {
584		v->iov_base = greetings;
585		v->iov_len = sprintf(greetings,
586		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
587		    f->f_prevhost, ctime(&now));
588		v++;
589		v->iov_base = "";
590		v->iov_len = 0;
591		v++;
592	} else {
593		v->iov_base = f->f_lasttime;
594		v->iov_len = 15;
595		v++;
596		v->iov_base = " ";
597		v->iov_len = 1;
598		v++;
599	}
600	v->iov_base = f->f_prevhost;
601	v->iov_len = strlen(v->iov_base);
602	v++;
603	v->iov_base = " ";
604	v->iov_len = 1;
605	v++;
606
607	if (msg) {
608		v->iov_base = msg;
609		v->iov_len = strlen(msg);
610	} else if (f->f_prevcount > 1) {
611		v->iov_base = repbuf;
612		v->iov_len = sprintf(repbuf, "last message repeated %d times",
613		    f->f_prevcount);
614	} else {
615		v->iov_base = f->f_prevline;
616		v->iov_len = f->f_prevlen;
617	}
618	v++;
619
620	dprintf("Logging to %s", TypeNames[f->f_type]);
621	f->f_time = now;
622
623	switch (f->f_type) {
624	case F_UNUSED:
625		dprintf("\n");
626		break;
627
628	case F_FORW:
629		dprintf(" %s\n", f->f_un.f_forw.f_hname);
630		l = sprintf(line, "<%d>%.15s %s", f->f_prevpri,
631		    iov[0].iov_base, iov[4].iov_base);
632		if (l > MAXLINE)
633			l = MAXLINE;
634		if (sendto(finet, line, l, 0,
635		    (struct sockaddr *)&f->f_un.f_forw.f_addr,
636		    sizeof(f->f_un.f_forw.f_addr)) != l) {
637			int e = errno;
638			(void)close(f->f_file);
639			f->f_type = F_UNUSED;
640			errno = e;
641			logerror("sendto");
642		}
643		break;
644
645	case F_CONSOLE:
646		if (flags & IGN_CONS) {
647			dprintf(" (ignored)\n");
648			break;
649		}
650		/* FALLTHROUGH */
651
652	case F_TTY:
653	case F_FILE:
654		dprintf(" %s\n", f->f_un.f_fname);
655		if (f->f_type != F_FILE) {
656			v->iov_base = "\r\n";
657			v->iov_len = 2;
658		} else {
659			v->iov_base = "\n";
660			v->iov_len = 1;
661		}
662	again:
663		if (writev(f->f_file, iov, 6) < 0) {
664			int e = errno;
665			(void)close(f->f_file);
666			/*
667			 * Check for errors on TTY's due to loss of tty
668			 */
669			if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
670				f->f_file = open(f->f_un.f_fname,
671				    O_WRONLY|O_APPEND, 0);
672				if (f->f_file < 0) {
673					f->f_type = F_UNUSED;
674					logerror(f->f_un.f_fname);
675				} else
676					goto again;
677			} else {
678				f->f_type = F_UNUSED;
679				errno = e;
680				logerror(f->f_un.f_fname);
681			}
682		} else if (flags & SYNC_FILE)
683			(void)fsync(f->f_file);
684		break;
685
686	case F_USERS:
687	case F_WALL:
688		dprintf("\n");
689		v->iov_base = "\r\n";
690		v->iov_len = 2;
691		wallmsg(f, iov);
692		break;
693	}
694	f->f_prevcount = 0;
695}
696
697/*
698 *  WALLMSG -- Write a message to the world at large
699 *
700 *	Write the specified message to either the entire
701 *	world, or a list of approved users.
702 */
703void
704wallmsg(f, iov)
705	struct filed *f;
706	struct iovec *iov;
707{
708	static int reenter;			/* avoid calling ourselves */
709	FILE *uf;
710	struct utmp ut;
711	int i;
712	char *p;
713	char line[sizeof(ut.ut_line) + 1];
714
715	if (reenter++)
716		return;
717	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
718		logerror(_PATH_UTMP);
719		reenter = 0;
720		return;
721	}
722	/* NOSTRICT */
723	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
724		if (ut.ut_name[0] == '\0')
725			continue;
726		strncpy(line, ut.ut_line, sizeof(ut.ut_line));
727		line[sizeof(ut.ut_line)] = '\0';
728		if (f->f_type == F_WALL) {
729			if ((p = ttymsg(iov, 6, line, 60*5)) != NULL) {
730				errno = 0;	/* already in msg */
731				logerror(p);
732			}
733			continue;
734		}
735		/* should we send the message to this user? */
736		for (i = 0; i < MAXUNAMES; i++) {
737			if (!f->f_un.f_uname[i][0])
738				break;
739			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
740			    UT_NAMESIZE)) {
741				if ((p = ttymsg(iov, 6, line, 60*5)) != NULL) {
742					errno = 0;	/* already in msg */
743					logerror(p);
744				}
745				break;
746			}
747		}
748	}
749	(void)fclose(uf);
750	reenter = 0;
751}
752
753void
754reapchild(signo)
755	int signo;
756{
757	union wait status;
758
759	while (wait3((int *)&status, WNOHANG, (struct rusage *)NULL) > 0)
760		;
761}
762
763/*
764 * Return a printable representation of a host address.
765 */
766char *
767cvthname(f)
768	struct sockaddr_in *f;
769{
770	struct hostent *hp;
771	char *p;
772
773	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
774
775	if (f->sin_family != AF_INET) {
776		dprintf("Malformed from address\n");
777		return ("???");
778	}
779	hp = gethostbyaddr((char *)&f->sin_addr,
780	    sizeof(struct in_addr), f->sin_family);
781	if (hp == 0) {
782		dprintf("Host name for your address (%s) unknown\n",
783			inet_ntoa(f->sin_addr));
784		return (inet_ntoa(f->sin_addr));
785	}
786	if ((p = strchr(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
787		*p = '\0';
788	return (hp->h_name);
789}
790
791void
792domark(signo)
793	int signo;
794{
795	struct filed *f;
796
797	now = time((time_t *)NULL);
798	MarkSeq += TIMERINTVL;
799	if (MarkSeq >= MarkInterval) {
800		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
801		MarkSeq = 0;
802	}
803
804	for (f = Files; f; f = f->f_next) {
805		if (f->f_prevcount && now >= REPEATTIME(f)) {
806			dprintf("flush %s: repeated %d times, %d sec.\n",
807			    TypeNames[f->f_type], f->f_prevcount,
808			    repeatinterval[f->f_repeatcount]);
809			fprintlog(f, 0, (char *)NULL);
810			BACKOFF(f);
811		}
812	}
813	(void)alarm(TIMERINTVL);
814}
815
816/*
817 * Print syslogd errors some place.
818 */
819void
820logerror(type)
821	char *type;
822{
823	char buf[100];
824
825	if (errno)
826		(void)snprintf(buf,
827		    sizeof(buf), "syslogd: %s: %s", type, strerror(errno));
828	else
829		(void)snprintf(buf, sizeof(buf), "syslogd: %s", type);
830	errno = 0;
831	dprintf("%s\n", buf);
832	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
833}
834
835void
836die(signo)
837	int signo;
838{
839	struct filed *f;
840	char buf[100];
841
842	for (f = Files; f != NULL; f = f->f_next) {
843		/* flush any pending output */
844		if (f->f_prevcount)
845			fprintlog(f, 0, (char *)NULL);
846	}
847	if (signo) {
848		dprintf("syslogd: exiting on signal %d\n", signo);
849		(void)sprintf(buf, "exiting on signal %d", signo);
850		errno = 0;
851		logerror(buf);
852	}
853	(void)unlink(LogName);
854	exit(0);
855}
856
857/*
858 *  INIT -- Initialize syslogd from configuration table
859 */
860void
861init(signo)
862	int signo;
863{
864	int i;
865	FILE *cf;
866	struct filed *f, *next, **nextp;
867	char *p;
868	char cline[LINE_MAX];
869
870	dprintf("init\n");
871
872	/*
873	 *  Close all open log files.
874	 */
875	Initialized = 0;
876	for (f = Files; f != NULL; f = next) {
877		/* flush any pending output */
878		if (f->f_prevcount)
879			fprintlog(f, 0, (char *)NULL);
880
881		switch (f->f_type) {
882		case F_FILE:
883		case F_TTY:
884		case F_CONSOLE:
885		case F_FORW:
886			(void)close(f->f_file);
887			break;
888		}
889		next = f->f_next;
890		free((char *)f);
891	}
892	Files = NULL;
893	nextp = &Files;
894
895	/* open the configuration file */
896	if ((cf = fopen(ConfFile, "r")) == NULL) {
897		dprintf("cannot open %s\n", ConfFile);
898		*nextp = (struct filed *)calloc(1, sizeof(*f));
899		cfline("*.ERR\t/dev/console", *nextp);
900		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
901		cfline("*.PANIC\t*", (*nextp)->f_next);
902		Initialized = 1;
903		return;
904	}
905
906	/*
907	 *  Foreach line in the conf table, open that file.
908	 */
909	f = NULL;
910	while (fgets(cline, sizeof(cline), cf) != NULL) {
911		/*
912		 * check for end-of-section, comments, strip off trailing
913		 * spaces and newline character.
914		 */
915		for (p = cline; isspace(*p); ++p)
916			continue;
917		if (*p == NULL || *p == '#')
918			continue;
919		for (p = strchr(cline, '\0'); isspace(*--p);)
920			continue;
921		*++p = '\0';
922		f = (struct filed *)calloc(1, sizeof(*f));
923		*nextp = f;
924		nextp = &f->f_next;
925		cfline(cline, f);
926	}
927
928	/* close the configuration file */
929	(void)fclose(cf);
930
931	Initialized = 1;
932
933	if (Debug) {
934		for (f = Files; f; f = f->f_next) {
935			for (i = 0; i <= LOG_NFACILITIES; i++)
936				if (f->f_pmask[i] == INTERNAL_NOPRI)
937					printf("X ");
938				else
939					printf("%d ", f->f_pmask[i]);
940			printf("%s: ", TypeNames[f->f_type]);
941			switch (f->f_type) {
942			case F_FILE:
943			case F_TTY:
944			case F_CONSOLE:
945				printf("%s", f->f_un.f_fname);
946				break;
947
948			case F_FORW:
949				printf("%s", f->f_un.f_forw.f_hname);
950				break;
951
952			case F_USERS:
953				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
954					printf("%s, ", f->f_un.f_uname[i]);
955				break;
956			}
957			printf("\n");
958		}
959	}
960
961	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
962	dprintf("syslogd: restarted\n");
963}
964
965/*
966 * Crack a configuration file line
967 */
968void
969cfline(line, f)
970	char *line;
971	struct filed *f;
972{
973	struct hostent *hp;
974	int i, pri;
975	char *bp, *p, *q;
976	char buf[MAXLINE], ebuf[100];
977
978	dprintf("cfline(%s)\n", line);
979
980	errno = 0;	/* keep strerror() stuff out of logerror messages */
981
982	/* clear out file entry */
983	memset(f, 0, sizeof(*f));
984	for (i = 0; i <= LOG_NFACILITIES; i++)
985		f->f_pmask[i] = INTERNAL_NOPRI;
986
987	/* scan through the list of selectors */
988	for (p = line; *p && *p != '\t';) {
989
990		/* find the end of this facility name list */
991		for (q = p; *q && *q != '\t' && *q++ != '.'; )
992			continue;
993
994		/* collect priority name */
995		for (bp = buf; *q && !strchr("\t,;", *q); )
996			*bp++ = *q++;
997		*bp = '\0';
998
999		/* skip cruft */
1000		while (strchr(", ;", *q))
1001			q++;
1002
1003		/* decode priority name */
1004		if (*buf == '*')
1005			pri = LOG_PRIMASK + 1;
1006		else {
1007			pri = decode(buf, prioritynames);
1008			if (pri < 0) {
1009				(void)sprintf(ebuf,
1010				    "unknown priority name \"%s\"", buf);
1011				logerror(ebuf);
1012				return;
1013			}
1014		}
1015
1016		/* scan facilities */
1017		while (*p && !strchr("\t.;", *p)) {
1018			for (bp = buf; *p && !strchr("\t,;.", *p); )
1019				*bp++ = *p++;
1020			*bp = '\0';
1021			if (*buf == '*')
1022				for (i = 0; i < LOG_NFACILITIES; i++)
1023					f->f_pmask[i] = pri;
1024			else {
1025				i = decode(buf, facilitynames);
1026				if (i < 0) {
1027					(void)sprintf(ebuf,
1028					    "unknown facility name \"%s\"",
1029					    buf);
1030					logerror(ebuf);
1031					return;
1032				}
1033				f->f_pmask[i >> 3] = pri;
1034			}
1035			while (*p == ',' || *p == ' ')
1036				p++;
1037		}
1038
1039		p = q;
1040	}
1041
1042	/* skip to action part */
1043	while (*p == '\t')
1044		p++;
1045
1046	switch (*p)
1047	{
1048	case '@':
1049		if (!InetInuse)
1050			break;
1051		(void)strcpy(f->f_un.f_forw.f_hname, ++p);
1052		hp = gethostbyname(p);
1053		if (hp == NULL) {
1054			extern int h_errno;
1055
1056			logerror(hstrerror(h_errno));
1057			break;
1058		}
1059		memset(&f->f_un.f_forw.f_addr, 0,
1060			 sizeof(f->f_un.f_forw.f_addr));
1061		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1062		f->f_un.f_forw.f_addr.sin_port = LogPort;
1063		memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1064		f->f_type = F_FORW;
1065		break;
1066
1067	case '/':
1068		(void)strcpy(f->f_un.f_fname, p);
1069		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1070			f->f_file = F_UNUSED;
1071			logerror(p);
1072			break;
1073		}
1074		if (isatty(f->f_file))
1075			f->f_type = F_TTY;
1076		else
1077			f->f_type = F_FILE;
1078		if (strcmp(p, ctty) == 0)
1079			f->f_type = F_CONSOLE;
1080		break;
1081
1082	case '*':
1083		f->f_type = F_WALL;
1084		break;
1085
1086	default:
1087		for (i = 0; i < MAXUNAMES && *p; i++) {
1088			for (q = p; *q && *q != ','; )
1089				q++;
1090			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1091			if ((q - p) > UT_NAMESIZE)
1092				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1093			else
1094				f->f_un.f_uname[i][q - p] = '\0';
1095			while (*q == ',' || *q == ' ')
1096				q++;
1097			p = q;
1098		}
1099		f->f_type = F_USERS;
1100		break;
1101	}
1102}
1103
1104
1105/*
1106 *  Decode a symbolic name to a numeric value
1107 */
1108int
1109decode(name, codetab)
1110	const char *name;
1111	CODE *codetab;
1112{
1113	CODE *c;
1114	char *p, buf[40];
1115
1116	if (isdigit(*name))
1117		return (atoi(name));
1118
1119	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1120		if (isupper(*name))
1121			*p = tolower(*name);
1122		else
1123			*p = *name;
1124	}
1125	*p = '\0';
1126	for (c = codetab; c->c_name; c++)
1127		if (!strcmp(buf, c->c_name))
1128			return (c->c_val);
1129
1130	return (-1);
1131}
1132