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