syslogd.c revision 1.26 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.26 1999/02/28 11:46:26 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/poll.h>
85 #include <sys/un.h>
86 #include <sys/time.h>
87 #include <sys/resource.h>
88 #include <sys/sysctl.h>
89
90 #include <netinet/in.h>
91 #include <netdb.h>
92 #include <arpa/inet.h>
93
94 #include <ctype.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <setjmp.h>
98 #include <signal.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <utmp.h>
104 #include <util.h>
105 #include "pathnames.h"
106
107 #define SYSLOG_NAMES
108 #include <sys/syslog.h>
109
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 char **LogPaths; /* array of pathnames to read messages from */
197
198 void cfline __P((char *, struct filed *));
199 char *cvthname __P((struct sockaddr_in *));
200 int decode __P((const char *, CODE *));
201 void die __P((int));
202 void domark __P((int));
203 void fprintlog __P((struct filed *, int, char *));
204 int getmsgbufsize __P((void));
205 void init __P((int));
206 void logerror __P((char *));
207 void logmsg __P((int, char *, char *, int));
208 void printline __P((char *, char *));
209 void printsys __P((char *));
210 void reapchild __P((int));
211 void usage __P((void));
212 void wallmsg __P((struct filed *, struct iovec *));
213 int main __P((int, char *[]));
214 void logpath_add __P((char ***, int *, int *, char *));
215 void logpath_fileadd __P((char ***, int *, int *, char *));
216
217 int
218 main(argc, argv)
219 int argc;
220 char *argv[];
221 {
222 int ch, *funix, i, j, fklog, len, linesize;
223 int nfinetix, nfklogix, nfunixbaseix, nfds;
224 int funixsize = 0, funixmaxsize = 0;
225 struct sockaddr_un sunx, fromunix;
226 struct sockaddr_in sin, frominet;
227 FILE *fp;
228 char *p, *line, **pp;
229 struct pollfd *readfds;
230
231 while ((ch = getopt(argc, argv, "dsf:m:p:P:")) != -1)
232 switch(ch) {
233 case 'd': /* debug */
234 Debug++;
235 break;
236 case 'f': /* configuration file */
237 ConfFile = optarg;
238 break;
239 case 'm': /* mark interval */
240 MarkInterval = atoi(optarg) * 60;
241 break;
242 case 'p': /* path */
243 logpath_add(&LogPaths, &funixsize,
244 &funixmaxsize, optarg);
245 break;
246 case 'P': /* file of paths */
247 logpath_fileadd(&LogPaths, &funixsize,
248 &funixmaxsize, optarg);
249 break;
250 case 's': /* no network mode */
251 SecureMode++;
252 break;
253 case '?':
254 default:
255 usage();
256 }
257 if ((argc -= optind) != 0)
258 usage();
259
260 if (!Debug)
261 (void)daemon(0, 0);
262 else
263 setlinebuf(stdout);
264
265 consfile.f_type = F_CONSOLE;
266 (void)strcpy(consfile.f_un.f_fname, ctty);
267 (void)gethostname(LocalHostName, sizeof(LocalHostName));
268 LocalHostName[sizeof(LocalHostName) - 1] = '\0';
269 if ((p = strchr(LocalHostName, '.')) != NULL) {
270 *p++ = '\0';
271 LocalDomain = p;
272 } else
273 LocalDomain = "";
274 linesize = getmsgbufsize();
275 if (linesize < MAXLINE)
276 linesize = MAXLINE;
277 linesize++;
278 line = malloc(linesize);
279 if (line == NULL) {
280 logerror("couldn't allocate line buffer");
281 die(0);
282 }
283 (void)signal(SIGTERM, die);
284 (void)signal(SIGINT, Debug ? die : SIG_IGN);
285 (void)signal(SIGQUIT, Debug ? die : SIG_IGN);
286 (void)signal(SIGCHLD, reapchild);
287 (void)signal(SIGALRM, domark);
288 (void)alarm(TIMERINTVL);
289
290 #ifndef SUN_LEN
291 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
292 #endif
293 if (funixsize == 0)
294 logpath_add(&LogPaths, &funixsize,
295 &funixmaxsize, _PATH_LOG);
296 funix = (int *)malloc(sizeof(int) * funixsize);
297 if (funix == NULL) {
298 logerror("couldn't allocate funix descriptors");
299 die(0);
300 }
301 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
302 unlink(*pp);
303 memset(&sunx, 0, sizeof(sunx));
304 sunx.sun_family = AF_LOCAL;
305 (void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
306 funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
307 if (funix[j] < 0 || bind(funix[j],
308 (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
309 chmod(*pp, 0666) < 0) {
310 (void)snprintf(line, sizeof line,
311 "cannot create %s", *pp);
312 logerror(line);
313 dprintf("cannot create %s (%d)\n", *pp, errno);
314 die(0);
315 }
316 dprintf("listening on unix dgram socket %s\n", *pp);
317 }
318
319 if (!SecureMode)
320 finet = socket(AF_INET, SOCK_DGRAM, 0);
321 else
322 finet = -1;
323
324 if (finet >= 0) {
325 struct servent *sp;
326
327 sp = getservbyname("syslog", "udp");
328 if (sp == NULL) {
329 errno = 0;
330 logerror("syslog/udp: unknown service");
331 die(0);
332 }
333 memset(&sin, 0, sizeof(sin));
334 sin.sin_family = AF_INET;
335 sin.sin_port = LogPort = sp->s_port;
336 if (bind(finet, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
337 logerror("bind");
338 if (!Debug)
339 die(0);
340 } else {
341 InetInuse = 1;
342 }
343 dprintf("listening on inet socket\n");
344 }
345 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
346 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
347 } else {
348 dprintf("listening on kernel log %s\n", _PATH_KLOG);
349 }
350
351 /* tuck my process id away, if i'm not in debug mode */
352 if (Debug == 0) {
353 fp = fopen(PidFile, "w");
354 if (fp != NULL) {
355 fprintf(fp, "%d\n", getpid());
356 (void) fclose(fp);
357 }
358 }
359
360 dprintf("off & running....\n");
361
362 init(0);
363 (void)signal(SIGHUP, init);
364
365 /* setup pollfd set. */
366 readfds = (struct pollfd *)malloc(sizeof(struct pollfd) *
367 (funixsize + 2));
368 if (readfds == NULL) {
369 logerror("couldn't allocate pollfds");
370 die(0);
371 }
372 nfds = 0;
373 if (fklog >= 0) {
374 nfklogix = nfds++;
375 readfds[nfklogix].fd = fklog;
376 readfds[nfklogix].events = POLLIN | POLLPRI;
377 }
378 if (finet >= 0) {
379 nfinetix = nfds++;
380 readfds[nfinetix].fd = finet;
381 readfds[nfinetix].events = POLLIN | POLLPRI;
382 }
383 nfunixbaseix = nfds;
384 for (j = 0, pp = LogPaths; *pp; pp++) {
385 readfds[nfds].fd = funix[j++];
386 readfds[nfds++].events = POLLIN | POLLPRI;
387 }
388
389 for (;;) {
390 int rv;
391
392 rv = poll(readfds, nfds, INFTIM);
393 if (rv == 0)
394 continue;
395 if (rv < 0) {
396 if (errno != EINTR)
397 logerror("poll");
398 continue;
399 }
400 dprintf("got a message (%d)\n", rv);
401 if (fklog >= 0 &&
402 (readfds[nfklogix].revents & (POLLIN | POLLPRI))) {
403 dprintf("kernel log active\n");
404 i = read(fklog, line, linesize - 1);
405 if (i > 0) {
406 line[i] = '\0';
407 printsys(line);
408 } else if (i < 0 && errno != EINTR) {
409 logerror("klog");
410 fklog = -1;
411 }
412 }
413 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
414 if ((readfds[nfunixbaseix + j].revents &
415 (POLLIN | POLLPRI)) == 0)
416 continue;
417
418 dprintf("unix socket (%s) active\n", *pp);
419 len = sizeof(fromunix);
420 i = recvfrom(funix[j], line, MAXLINE, 0,
421 (struct sockaddr *)&fromunix, &len);
422 if (i > 0) {
423 line[i] = '\0';
424 printline(LocalHostName, line);
425 } else if (i < 0 && errno != EINTR) {
426 char buf[MAXPATHLEN];
427
428 (void)snprintf(buf, sizeof buf,
429 "recvfrom unix %s", *pp);
430 logerror(buf);
431 }
432 }
433 if (finet >= 0 &&
434 (readfds[nfinetix].revents & (POLLIN | POLLPRI))) {
435 dprintf("inet socket active\n");
436 len = sizeof(frominet);
437 i = recvfrom(finet, line, MAXLINE, 0,
438 (struct sockaddr *)&frominet, &len);
439 if (i > 0) {
440 line[i] = '\0';
441 printline(cvthname(&frominet), line);
442 } else if (i < 0 && errno != EINTR)
443 logerror("recvfrom inet");
444 }
445 }
446 }
447
448 void
449 usage()
450 {
451
452 (void)fprintf(stderr,
453 "usage: syslogd [-f conffile] [-m markinterval] [-p logpath1] [-p logpath2 ..]\n");
454 exit(1);
455 }
456
457 /*
458 * given a pointer to an array of char *'s, a pointer to it's current
459 * size and current allocated max size, and a new char * to add, add
460 * it, update everything as necessary, possibly allocating a new array
461 */
462 void
463 logpath_add(lp, szp, maxszp, new)
464 char ***lp;
465 int *szp;
466 int *maxszp;
467 char *new;
468 {
469
470 if (*szp == *maxszp) {
471 if (*maxszp == 0) {
472 *maxszp = 4; /* start of with enough for now */
473 *lp = NULL;
474 }
475 else
476 *maxszp *= 2;
477 *lp = realloc(*lp, sizeof(char *) * (*maxszp + 1));
478 if (*lp == NULL) {
479 logerror("couldn't allocate line buffer");
480 die(0);
481 }
482 }
483 (*lp)[(*szp)++] = new;
484 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
485 }
486
487 /* do a file of log sockets */
488 void
489 logpath_fileadd(lp, szp, maxszp, file)
490 char ***lp;
491 int *szp;
492 int *maxszp;
493 char *file;
494 {
495 FILE *fp;
496 char *line;
497 size_t len;
498
499 fp = fopen(file, "r");
500 if (fp == NULL) {
501 dprintf("can't open %s (%d)\n", file, errno);
502 logerror("could not open socket file list");
503 die(0);
504 }
505
506 while ((line = fgetln(fp, &len))) {
507 line[len - 1] = 0;
508 logpath_add(lp, szp, maxszp, line);
509 }
510 fclose(fp);
511 }
512
513 /*
514 * Take a raw input line, decode the message, and print the message
515 * on the appropriate log files.
516 */
517 void
518 printline(hname, msg)
519 char *hname;
520 char *msg;
521 {
522 int c, pri;
523 char *p, *q, line[MAXLINE + 1];
524
525 /* test for special codes */
526 pri = DEFUPRI;
527 p = msg;
528 if (*p == '<') {
529 pri = 0;
530 while (isdigit(*++p))
531 pri = 10 * pri + (*p - '0');
532 if (*p == '>')
533 ++p;
534 }
535 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
536 pri = DEFUPRI;
537
538 /* don't allow users to log kernel messages */
539 if (LOG_FAC(pri) == LOG_KERN)
540 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
541
542 q = line;
543
544 while ((c = *p++ & 0177) != '\0' &&
545 q < &line[sizeof(line) - 1])
546 if (iscntrl(c))
547 if (c == '\n')
548 *q++ = ' ';
549 else if (c == '\t')
550 *q++ = '\t';
551 else {
552 *q++ = '^';
553 *q++ = c ^ 0100;
554 }
555 else
556 *q++ = c;
557 *q = '\0';
558
559 logmsg(pri, line, hname, 0);
560 }
561
562 /*
563 * Take a raw input line from /dev/klog, split and format similar to syslog().
564 */
565 void
566 printsys(msg)
567 char *msg;
568 {
569 int c, pri, flags;
570 char *lp, *p, *q, line[MAXLINE + 1];
571
572 (void)strcpy(line, _PATH_UNIX);
573 (void)strcat(line, ": ");
574 lp = line + strlen(line);
575 for (p = msg; *p != '\0'; ) {
576 flags = SYNC_FILE | ADDDATE; /* fsync file after write */
577 pri = DEFSPRI;
578 if (*p == '<') {
579 pri = 0;
580 while (isdigit(*++p))
581 pri = 10 * pri + (*p - '0');
582 if (*p == '>')
583 ++p;
584 } else {
585 /* kernel printf's come out on console */
586 flags |= IGN_CONS;
587 }
588 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
589 pri = DEFSPRI;
590 q = lp;
591 while (*p != '\0' && (c = *p++) != '\n' &&
592 q < &line[MAXLINE])
593 *q++ = c;
594 *q = '\0';
595 logmsg(pri, line, LocalHostName, flags);
596 }
597 }
598
599 time_t now;
600
601 /*
602 * Log a message to the appropriate log files, users, etc. based on
603 * the priority.
604 */
605 void
606 logmsg(pri, msg, from, flags)
607 int pri;
608 char *msg, *from;
609 int flags;
610 {
611 struct filed *f;
612 int fac, msglen, omask, prilev;
613 char *timestamp;
614
615 dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
616 pri, flags, from, msg);
617
618 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
619
620 /*
621 * Check to see if msg looks non-standard.
622 */
623 msglen = strlen(msg);
624 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
625 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
626 flags |= ADDDATE;
627
628 (void)time(&now);
629 if (flags & ADDDATE)
630 timestamp = ctime(&now) + 4;
631 else {
632 timestamp = msg;
633 msg += 16;
634 msglen -= 16;
635 }
636
637 /* extract facility and priority level */
638 if (flags & MARK)
639 fac = LOG_NFACILITIES;
640 else
641 fac = LOG_FAC(pri);
642 prilev = LOG_PRI(pri);
643
644 /* log the message to the particular outputs */
645 if (!Initialized) {
646 f = &consfile;
647 f->f_file = open(ctty, O_WRONLY, 0);
648
649 if (f->f_file >= 0) {
650 fprintlog(f, flags, msg);
651 (void)close(f->f_file);
652 }
653 (void)sigsetmask(omask);
654 return;
655 }
656 for (f = Files; f; f = f->f_next) {
657 /* skip messages that are incorrect priority */
658 if (f->f_pmask[fac] < prilev ||
659 f->f_pmask[fac] == INTERNAL_NOPRI)
660 continue;
661
662 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
663 continue;
664
665 /* don't output marks to recently written files */
666 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
667 continue;
668
669 /*
670 * suppress duplicate lines to this file
671 */
672 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
673 !strcmp(msg, f->f_prevline) &&
674 !strcmp(from, f->f_prevhost)) {
675 (void)strncpy(f->f_lasttime, timestamp, 15);
676 f->f_prevcount++;
677 dprintf("msg repeated %d times, %ld sec of %d\n",
678 f->f_prevcount, (long)(now - f->f_time),
679 repeatinterval[f->f_repeatcount]);
680 /*
681 * If domark would have logged this by now,
682 * flush it now (so we don't hold isolated messages),
683 * but back off so we'll flush less often
684 * in the future.
685 */
686 if (now > REPEATTIME(f)) {
687 fprintlog(f, flags, (char *)NULL);
688 BACKOFF(f);
689 }
690 } else {
691 /* new line, save it */
692 if (f->f_prevcount)
693 fprintlog(f, 0, (char *)NULL);
694 f->f_repeatcount = 0;
695 f->f_prevpri = pri;
696 (void)strncpy(f->f_lasttime, timestamp, 15);
697 (void)strncpy(f->f_prevhost, from,
698 sizeof(f->f_prevhost));
699 if (msglen < MAXSVLINE) {
700 f->f_prevlen = msglen;
701 (void)strcpy(f->f_prevline, msg);
702 fprintlog(f, flags, (char *)NULL);
703 } else {
704 f->f_prevline[0] = 0;
705 f->f_prevlen = 0;
706 fprintlog(f, flags, msg);
707 }
708 }
709 }
710 (void)sigsetmask(omask);
711 }
712
713 void
714 fprintlog(f, flags, msg)
715 struct filed *f;
716 int flags;
717 char *msg;
718 {
719 struct iovec iov[6];
720 struct iovec *v;
721 int l;
722 char line[MAXLINE + 1], repbuf[80], greetings[200];
723
724 v = iov;
725 if (f->f_type == F_WALL) {
726 v->iov_base = greetings;
727 v->iov_len = snprintf(greetings, sizeof greetings,
728 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
729 f->f_prevhost, ctime(&now));
730 v++;
731 v->iov_base = "";
732 v->iov_len = 0;
733 v++;
734 } else {
735 v->iov_base = f->f_lasttime;
736 v->iov_len = 15;
737 v++;
738 v->iov_base = " ";
739 v->iov_len = 1;
740 v++;
741 }
742 v->iov_base = f->f_prevhost;
743 v->iov_len = strlen(v->iov_base);
744 v++;
745 v->iov_base = " ";
746 v->iov_len = 1;
747 v++;
748
749 if (msg) {
750 v->iov_base = msg;
751 v->iov_len = strlen(msg);
752 } else if (f->f_prevcount > 1) {
753 v->iov_base = repbuf;
754 v->iov_len = snprintf(repbuf, sizeof repbuf,
755 "last message repeated %d times", f->f_prevcount);
756 } else {
757 v->iov_base = f->f_prevline;
758 v->iov_len = f->f_prevlen;
759 }
760 v++;
761
762 dprintf("Logging to %s", TypeNames[f->f_type]);
763 f->f_time = now;
764
765 switch (f->f_type) {
766 case F_UNUSED:
767 dprintf("\n");
768 break;
769
770 case F_FORW:
771 dprintf(" %s\n", f->f_un.f_forw.f_hname);
772 /* check for local vs remote messages (from FreeBSD PR#bin/7055) */
773 if (strcmp(f->f_prevhost, LocalHostName)) {
774 l = snprintf(line, sizeof(line) - 1,
775 "<%d>%.15s [%s]: %s",
776 f->f_prevpri, (char *) iov[0].iov_base,
777 f->f_prevhost, (char *) iov[4].iov_base);
778 } else {
779 l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
780 f->f_prevpri, (char *) iov[0].iov_base,
781 (char *) iov[4].iov_base);
782 }
783 if (l > MAXLINE)
784 l = MAXLINE;
785 if ((finet >= 0) &&
786 (sendto(finet, line, l, 0,
787 (struct sockaddr *)&f->f_un.f_forw.f_addr,
788 sizeof(f->f_un.f_forw.f_addr)) != l)) {
789 int e = errno;
790 f->f_type = F_UNUSED;
791 errno = e;
792 logerror("sendto");
793 }
794 break;
795
796 case F_CONSOLE:
797 if (flags & IGN_CONS) {
798 dprintf(" (ignored)\n");
799 break;
800 }
801 /* FALLTHROUGH */
802
803 case F_TTY:
804 case F_FILE:
805 dprintf(" %s\n", f->f_un.f_fname);
806 if (f->f_type != F_FILE) {
807 v->iov_base = "\r\n";
808 v->iov_len = 2;
809 } else {
810 v->iov_base = "\n";
811 v->iov_len = 1;
812 }
813 again:
814 if (writev(f->f_file, iov, 6) < 0) {
815 int e = errno;
816 (void)close(f->f_file);
817 /*
818 * Check for errors on TTY's due to loss of tty
819 */
820 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
821 f->f_file = open(f->f_un.f_fname,
822 O_WRONLY|O_APPEND, 0);
823 if (f->f_file < 0) {
824 f->f_type = F_UNUSED;
825 logerror(f->f_un.f_fname);
826 } else
827 goto again;
828 } else {
829 f->f_type = F_UNUSED;
830 errno = e;
831 logerror(f->f_un.f_fname);
832 }
833 } else if (flags & SYNC_FILE)
834 (void)fsync(f->f_file);
835 break;
836
837 case F_USERS:
838 case F_WALL:
839 dprintf("\n");
840 v->iov_base = "\r\n";
841 v->iov_len = 2;
842 wallmsg(f, iov);
843 break;
844 }
845 f->f_prevcount = 0;
846 }
847
848 /*
849 * WALLMSG -- Write a message to the world at large
850 *
851 * Write the specified message to either the entire
852 * world, or a list of approved users.
853 */
854 void
855 wallmsg(f, iov)
856 struct filed *f;
857 struct iovec *iov;
858 {
859 static int reenter; /* avoid calling ourselves */
860 FILE *uf;
861 struct utmp ut;
862 int i;
863 char *p;
864 char line[sizeof(ut.ut_line) + 1];
865
866 if (reenter++)
867 return;
868 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
869 logerror(_PATH_UTMP);
870 reenter = 0;
871 return;
872 }
873 /* NOSTRICT */
874 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
875 if (ut.ut_name[0] == '\0')
876 continue;
877 strncpy(line, ut.ut_line, sizeof(ut.ut_line));
878 line[sizeof(ut.ut_line)] = '\0';
879 if (f->f_type == F_WALL) {
880 if ((p = ttymsg(iov, 6, line, TTYMSGTIME)) != NULL) {
881 errno = 0; /* already in msg */
882 logerror(p);
883 }
884 continue;
885 }
886 /* should we send the message to this user? */
887 for (i = 0; i < MAXUNAMES; i++) {
888 if (!f->f_un.f_uname[i][0])
889 break;
890 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
891 UT_NAMESIZE)) {
892 if ((p = ttymsg(iov, 6, line, TTYMSGTIME))
893 != NULL) {
894 errno = 0; /* already in msg */
895 logerror(p);
896 }
897 break;
898 }
899 }
900 }
901 (void)fclose(uf);
902 reenter = 0;
903 }
904
905 void
906 reapchild(signo)
907 int signo;
908 {
909 union wait status;
910
911 while (wait3((int *)&status, WNOHANG, (struct rusage *)NULL) > 0)
912 ;
913 }
914
915 /*
916 * Return a printable representation of a host address.
917 */
918 char *
919 cvthname(f)
920 struct sockaddr_in *f;
921 {
922 struct hostent *hp;
923 char *p;
924
925 dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
926
927 if (f->sin_family != AF_INET) {
928 dprintf("Malformed from address\n");
929 return ("???");
930 }
931 hp = gethostbyaddr((char *)&f->sin_addr,
932 sizeof(struct in_addr), f->sin_family);
933 if (hp == 0) {
934 dprintf("Host name for your address (%s) unknown\n",
935 inet_ntoa(f->sin_addr));
936 return (inet_ntoa(f->sin_addr));
937 }
938 if ((p = strchr(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
939 *p = '\0';
940 return (hp->h_name);
941 }
942
943 void
944 domark(signo)
945 int signo;
946 {
947 struct filed *f;
948
949 now = time((time_t *)NULL);
950 MarkSeq += TIMERINTVL;
951 if (MarkSeq >= MarkInterval) {
952 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
953 MarkSeq = 0;
954 }
955
956 for (f = Files; f; f = f->f_next) {
957 if (f->f_prevcount && now >= REPEATTIME(f)) {
958 dprintf("flush %s: repeated %d times, %d sec.\n",
959 TypeNames[f->f_type], f->f_prevcount,
960 repeatinterval[f->f_repeatcount]);
961 fprintlog(f, 0, (char *)NULL);
962 BACKOFF(f);
963 }
964 }
965 (void)alarm(TIMERINTVL);
966 }
967
968 /*
969 * Print syslogd errors some place.
970 */
971 void
972 logerror(type)
973 char *type;
974 {
975 char buf[100];
976
977 if (errno)
978 (void)snprintf(buf,
979 sizeof(buf), "syslogd: %s: %s", type, strerror(errno));
980 else
981 (void)snprintf(buf, sizeof(buf), "syslogd: %s", type);
982 errno = 0;
983 dprintf("%s\n", buf);
984 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
985 }
986
987 void
988 die(signo)
989 int signo;
990 {
991 struct filed *f;
992 char buf[100], **p;
993
994 for (f = Files; f != NULL; f = f->f_next) {
995 /* flush any pending output */
996 if (f->f_prevcount)
997 fprintlog(f, 0, (char *)NULL);
998 }
999 if (signo) {
1000 dprintf("syslogd: exiting on signal %d\n", signo);
1001 (void)snprintf(buf, sizeof buf, "exiting on signal %d", signo);
1002 errno = 0;
1003 logerror(buf);
1004 }
1005 for (p = LogPaths; p && *p; p++)
1006 unlink(*p);
1007 exit(0);
1008 }
1009
1010 /*
1011 * INIT -- Initialize syslogd from configuration table
1012 */
1013 void
1014 init(signo)
1015 int signo;
1016 {
1017 int i;
1018 FILE *cf;
1019 struct filed *f, *next, **nextp;
1020 char *p;
1021 char cline[LINE_MAX];
1022
1023 dprintf("init\n");
1024
1025 /*
1026 * Close all open log files.
1027 */
1028 Initialized = 0;
1029 for (f = Files; f != NULL; f = next) {
1030 /* flush any pending output */
1031 if (f->f_prevcount)
1032 fprintlog(f, 0, (char *)NULL);
1033
1034 switch (f->f_type) {
1035 case F_FILE:
1036 case F_TTY:
1037 case F_CONSOLE:
1038 (void)close(f->f_file);
1039 break;
1040 }
1041 next = f->f_next;
1042 free((char *)f);
1043 }
1044 Files = NULL;
1045 nextp = &Files;
1046
1047 /* open the configuration file */
1048 if ((cf = fopen(ConfFile, "r")) == NULL) {
1049 dprintf("cannot open %s\n", ConfFile);
1050 *nextp = (struct filed *)calloc(1, sizeof(*f));
1051 cfline("*.ERR\t/dev/console", *nextp);
1052 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1053 cfline("*.PANIC\t*", (*nextp)->f_next);
1054 Initialized = 1;
1055 return;
1056 }
1057
1058 /*
1059 * Foreach line in the conf table, open that file.
1060 */
1061 f = NULL;
1062 while (fgets(cline, sizeof(cline), cf) != NULL) {
1063 /*
1064 * check for end-of-section, comments, strip off trailing
1065 * spaces and newline character.
1066 */
1067 for (p = cline; isspace(*p); ++p)
1068 continue;
1069 if (*p == '\0' || *p == '#')
1070 continue;
1071 for (p = strchr(cline, '\0'); isspace(*--p);)
1072 continue;
1073 *++p = '\0';
1074 f = (struct filed *)calloc(1, sizeof(*f));
1075 *nextp = f;
1076 nextp = &f->f_next;
1077 cfline(cline, f);
1078 }
1079
1080 /* close the configuration file */
1081 (void)fclose(cf);
1082
1083 Initialized = 1;
1084
1085 if (Debug) {
1086 for (f = Files; f; f = f->f_next) {
1087 for (i = 0; i <= LOG_NFACILITIES; i++)
1088 if (f->f_pmask[i] == INTERNAL_NOPRI)
1089 printf("X ");
1090 else
1091 printf("%d ", f->f_pmask[i]);
1092 printf("%s: ", TypeNames[f->f_type]);
1093 switch (f->f_type) {
1094 case F_FILE:
1095 case F_TTY:
1096 case F_CONSOLE:
1097 printf("%s", f->f_un.f_fname);
1098 break;
1099
1100 case F_FORW:
1101 printf("%s", f->f_un.f_forw.f_hname);
1102 break;
1103
1104 case F_USERS:
1105 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1106 printf("%s, ", f->f_un.f_uname[i]);
1107 break;
1108 }
1109 printf("\n");
1110 }
1111 }
1112
1113 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1114 dprintf("syslogd: restarted\n");
1115 }
1116
1117 /*
1118 * Crack a configuration file line
1119 */
1120 void
1121 cfline(line, f)
1122 char *line;
1123 struct filed *f;
1124 {
1125 struct hostent *hp;
1126 int i, pri;
1127 char *bp, *p, *q;
1128 char buf[MAXLINE], ebuf[100];
1129
1130 dprintf("cfline(%s)\n", line);
1131
1132 errno = 0; /* keep strerror() stuff out of logerror messages */
1133
1134 /* clear out file entry */
1135 memset(f, 0, sizeof(*f));
1136 for (i = 0; i <= LOG_NFACILITIES; i++)
1137 f->f_pmask[i] = INTERNAL_NOPRI;
1138
1139 /* scan through the list of selectors */
1140 for (p = line; *p && *p != '\t';) {
1141
1142 /* find the end of this facility name list */
1143 for (q = p; *q && *q != '\t' && *q++ != '.'; )
1144 continue;
1145
1146 /* collect priority name */
1147 for (bp = buf; *q && !strchr("\t,;", *q); )
1148 *bp++ = *q++;
1149 *bp = '\0';
1150
1151 /* skip cruft */
1152 while (strchr(", ;", *q))
1153 q++;
1154
1155 /* decode priority name */
1156 if (*buf == '*')
1157 pri = LOG_PRIMASK + 1;
1158 else {
1159 pri = decode(buf, prioritynames);
1160 if (pri < 0) {
1161 (void)snprintf(ebuf, sizeof ebuf,
1162 "unknown priority name \"%s\"", buf);
1163 logerror(ebuf);
1164 return;
1165 }
1166 }
1167
1168 /* scan facilities */
1169 while (*p && !strchr("\t.;", *p)) {
1170 for (bp = buf; *p && !strchr("\t,;.", *p); )
1171 *bp++ = *p++;
1172 *bp = '\0';
1173 if (*buf == '*')
1174 for (i = 0; i < LOG_NFACILITIES; i++)
1175 f->f_pmask[i] = pri;
1176 else {
1177 i = decode(buf, facilitynames);
1178 if (i < 0) {
1179 (void)snprintf(ebuf, sizeof ebuf,
1180 "unknown facility name \"%s\"",
1181 buf);
1182 logerror(ebuf);
1183 return;
1184 }
1185 f->f_pmask[i >> 3] = pri;
1186 }
1187 while (*p == ',' || *p == ' ')
1188 p++;
1189 }
1190
1191 p = q;
1192 }
1193
1194 /* skip to action part */
1195 while (*p == '\t')
1196 p++;
1197
1198 switch (*p)
1199 {
1200 case '@':
1201 if (!InetInuse)
1202 break;
1203 (void)strcpy(f->f_un.f_forw.f_hname, ++p);
1204 hp = gethostbyname(p);
1205 if (hp == NULL) {
1206 extern int h_errno;
1207
1208 logerror((char *)hstrerror(h_errno));
1209 break;
1210 }
1211 memset(&f->f_un.f_forw.f_addr, 0,
1212 sizeof(f->f_un.f_forw.f_addr));
1213 f->f_un.f_forw.f_addr.sin_family = AF_INET;
1214 f->f_un.f_forw.f_addr.sin_port = LogPort;
1215 memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1216 f->f_type = F_FORW;
1217 break;
1218
1219 case '/':
1220 (void)strcpy(f->f_un.f_fname, p);
1221 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1222 f->f_type = F_UNUSED;
1223 logerror(p);
1224 break;
1225 }
1226 if (isatty(f->f_file))
1227 f->f_type = F_TTY;
1228 else
1229 f->f_type = F_FILE;
1230 if (strcmp(p, ctty) == 0)
1231 f->f_type = F_CONSOLE;
1232 break;
1233
1234 case '*':
1235 f->f_type = F_WALL;
1236 break;
1237
1238 default:
1239 for (i = 0; i < MAXUNAMES && *p; i++) {
1240 for (q = p; *q && *q != ','; )
1241 q++;
1242 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1243 if ((q - p) > UT_NAMESIZE)
1244 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1245 else
1246 f->f_un.f_uname[i][q - p] = '\0';
1247 while (*q == ',' || *q == ' ')
1248 q++;
1249 p = q;
1250 }
1251 f->f_type = F_USERS;
1252 break;
1253 }
1254 }
1255
1256
1257 /*
1258 * Decode a symbolic name to a numeric value
1259 */
1260 int
1261 decode(name, codetab)
1262 const char *name;
1263 CODE *codetab;
1264 {
1265 CODE *c;
1266 char *p, buf[40];
1267
1268 if (isdigit(*name))
1269 return (atoi(name));
1270
1271 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1272 if (isupper(*name))
1273 *p = tolower(*name);
1274 else
1275 *p = *name;
1276 }
1277 *p = '\0';
1278 for (c = codetab; c->c_name; c++)
1279 if (!strcmp(buf, c->c_name))
1280 return (c->c_val);
1281
1282 return (-1);
1283 }
1284
1285 /*
1286 * Retrieve the size of the kernel message buffer, via sysctl.
1287 */
1288 int
1289 getmsgbufsize()
1290 {
1291 int msgbufsize, mib[2];
1292 size_t size;
1293
1294 mib[0] = CTL_KERN;
1295 mib[1] = KERN_MSGBUFSIZE;
1296 size = sizeof msgbufsize;
1297 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
1298 dprintf("couldn't get kern.msgbufsize\n");
1299 return (0);
1300 }
1301 return (msgbufsize);
1302 }
1303