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