syslogd.c revision 1.37 1 /* $NetBSD: syslogd.c,v 1.37 2000/06/30 18:22:54 jwise Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
39 The Regents of the University of California. All rights reserved.\n");
40 #endif /* not lint */
41
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
45 #else
46 __RCSID("$NetBSD: syslogd.c,v 1.37 2000/06/30 18:22:54 jwise Exp $");
47 #endif
48 #endif /* not lint */
49
50 /*
51 * syslogd -- log system messages
52 *
53 * This program implements a system log. It takes a series of lines.
54 * Each line may have a priority, signified as "<n>" as
55 * the first characters of the line. If this is
56 * not present, a default priority is used.
57 *
58 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
59 * cause it to reread its configuration file.
60 *
61 * Defined Constants:
62 *
63 * MAXLINE -- the maximimum line length that can be handled.
64 * DEFUPRI -- the default priority for user messages
65 * DEFSPRI -- the default priority for kernel messages
66 *
67 * Author: Eric Allman
68 * extensive changes by Ralph Campbell
69 * more extensive changes by Eric Allman (again)
70 */
71
72 #define MAXLINE 1024 /* maximum line length */
73 #define MAXSVLINE 120 /* maximum saved line length */
74 #define DEFUPRI (LOG_USER|LOG_NOTICE)
75 #define DEFSPRI (LOG_KERN|LOG_CRIT)
76 #define TIMERINTVL 30 /* interval for checking flush, mark */
77 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
78
79 #include <sys/param.h>
80 #include <sys/ioctl.h>
81 #include <sys/stat.h>
82 #include <sys/wait.h>
83 #include <sys/socket.h>
84 #include <sys/msgbuf.h>
85 #include <sys/uio.h>
86 #include <sys/poll.h>
87 #include <sys/un.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/sysctl.h>
91
92 #include <netinet/in.h>
93 #include <netdb.h>
94 #include <arpa/inet.h>
95
96 #include <ctype.h>
97 #include <errno.h>
98 #include <fcntl.h>
99 #include <setjmp.h>
100 #include <signal.h>
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <string.h>
104 #include <unistd.h>
105 #include <utmp.h>
106 #include <util.h>
107 #include "pathnames.h"
108
109 #define SYSLOG_NAMES
110 #include <sys/syslog.h>
111
112 char *ConfFile = _PATH_LOGCONF;
113 char ctty[] = _PATH_CONSOLE;
114
115 #define FDMASK(fd) (1 << (fd))
116
117 #define dprintf if (Debug) printf
118
119 #define MAXUNAMES 20 /* maximum number of user names */
120
121 /*
122 * Flags to logmsg().
123 */
124
125 #define IGN_CONS 0x001 /* don't print on console */
126 #define SYNC_FILE 0x002 /* do fsync on file after printing */
127 #define ADDDATE 0x004 /* add a date to the message */
128 #define MARK 0x008 /* this message is a mark */
129
130 /*
131 * This structure represents the files that will have log
132 * copies printed.
133 */
134
135 struct filed {
136 struct filed *f_next; /* next in linked list */
137 short f_type; /* entry type, see below */
138 short f_file; /* file descriptor */
139 time_t f_time; /* time this was last written */
140 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
141 union {
142 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
143 struct {
144 char f_hname[MAXHOSTNAMELEN+1];
145 struct addrinfo *f_addr;
146 } f_forw; /* forwarding address */
147 char f_fname[MAXPATHLEN];
148 } f_un;
149 char f_prevline[MAXSVLINE]; /* last message logged */
150 char f_lasttime[16]; /* time of last occurrence */
151 char f_prevhost[MAXHOSTNAMELEN+1]; /* host from which recd. */
152 int f_prevpri; /* pri of f_prevline */
153 int f_prevlen; /* length of f_prevline */
154 int f_prevcount; /* repetition cnt of prevline */
155 int f_repeatcount; /* number of "repeated" msgs */
156 };
157
158 /*
159 * Intervals at which we flush out "message repeated" messages,
160 * in seconds after previous message is logged. After each flush,
161 * we move to the next interval until we reach the largest.
162 */
163 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
164 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
165 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
166 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
167 (f)->f_repeatcount = MAXREPEAT; \
168 }
169
170 /* values for f_type */
171 #define F_UNUSED 0 /* unused entry */
172 #define F_FILE 1 /* regular file */
173 #define F_TTY 2 /* terminal */
174 #define F_CONSOLE 3 /* console terminal */
175 #define F_FORW 4 /* remote machine */
176 #define F_USERS 5 /* list of users */
177 #define F_WALL 6 /* everyone logged on */
178
179 char *TypeNames[7] = {
180 "UNUSED", "FILE", "TTY", "CONSOLE",
181 "FORW", "USERS", "WALL"
182 };
183
184 struct filed *Files;
185 struct filed consfile;
186
187 int Debug; /* debug flag */
188 char LocalHostName[MAXHOSTNAMELEN+1]; /* our hostname */
189 char *LocalDomain; /* our local domain name */
190 int *finet; /* Internet datagram sockets */
191 int Initialized = 0; /* set when we have initialized ourselves */
192 int MarkInterval = 20 * 60; /* interval between marks in seconds */
193 int MarkSeq = 0; /* mark sequence number */
194 int SecureMode = 0; /* listen only on unix domain socks */
195 int NumForwards = 0; /* number of forwarding actions in conf file */
196 char **LogPaths; /* array of pathnames to read messages from */
197
198 void cfline __P((char *, struct filed *));
199 char *cvthname __P((struct sockaddr_storage *));
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 int* socksetup __P((int));
206 void init __P((int));
207 void logerror __P((char *));
208 void logmsg __P((int, char *, char *, int));
209 void printline __P((char *, char *));
210 void printsys __P((char *));
211 void reapchild __P((int));
212 void usage __P((void));
213 void wallmsg __P((struct filed *, struct iovec *));
214 int main __P((int, char *[]));
215 void logpath_add __P((char ***, int *, int *, char *));
216 void logpath_fileadd __P((char ***, int *, int *, char *));
217
218 int
219 main(argc, argv)
220 int argc;
221 char *argv[];
222 {
223 int ch, *funix, i, j, fklog, len, linesize;
224 int *nfinetix, nfklogix, nfunixbaseix, nfds;
225 int funixsize = 0, funixmaxsize = 0;
226 struct sockaddr_un sunx, fromunix;
227 struct sockaddr_storage frominet;
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 listen 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 dprintf("making unix dgram socket %s\n", *pp);
303 unlink(*pp);
304 memset(&sunx, 0, sizeof(sunx));
305 sunx.sun_family = AF_LOCAL;
306 (void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
307 funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
308 if (funix[j] < 0 || bind(funix[j],
309 (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
310 chmod(*pp, 0666) < 0) {
311 int serrno = errno;
312 (void)snprintf(line, sizeof line,
313 "cannot create %s", *pp);
314 errno = serrno;
315 logerror(line);
316 errno = serrno;
317 dprintf("cannot create %s (%d)\n", *pp, errno);
318 die(0);
319 }
320 dprintf("listening on unix dgram socket %s\n", *pp);
321 }
322
323 init(0);
324 finet = socksetup(PF_UNSPEC);
325 if (finet) {
326 if (SecureMode) {
327 for (j = 0; j < *finet; j++) {
328 if (shutdown(finet[j+1], SHUT_RD) < 0) {
329 logerror("shutdown");
330 die(0);
331 }
332 }
333 } else
334 dprintf("listening on inet and/or inet6 socket\n");
335 dprintf("sending on inet and/or inet6 socket\n");
336 }
337
338 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
339 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
340 } else {
341 dprintf("listening on kernel log %s\n", _PATH_KLOG);
342 }
343
344 /* tuck my process id away, if i'm not in debug mode */
345 if (Debug == 0)
346 pidfile(NULL);
347
348 dprintf("off & running....\n");
349
350 (void)signal(SIGHUP, init);
351
352 /* setup pollfd set. */
353 readfds = (struct pollfd *)malloc(sizeof(struct pollfd) *
354 (funixsize + (finet ? *finet : 0) + 1));
355 if (readfds == NULL) {
356 logerror("couldn't allocate pollfds");
357 die(0);
358 }
359 nfds = 0;
360 if (fklog >= 0) {
361 nfklogix = nfds++;
362 readfds[nfklogix].fd = fklog;
363 readfds[nfklogix].events = POLLIN | POLLPRI;
364 }
365 if (finet && !SecureMode) {
366 nfinetix = malloc(*finet * sizeof(*nfinetix));
367 for (j = 0; j < *finet; j++) {
368 nfinetix[j] = nfds++;
369 readfds[nfinetix[j]].fd = finet[j+1];
370 readfds[nfinetix[j]].events = POLLIN | POLLPRI;
371 }
372 }
373 nfunixbaseix = nfds;
374 for (j = 0, pp = LogPaths; *pp; pp++) {
375 readfds[nfds].fd = funix[j++];
376 readfds[nfds++].events = POLLIN | POLLPRI;
377 }
378
379 for (;;) {
380 int rv;
381
382 rv = poll(readfds, nfds, INFTIM);
383 if (rv == 0)
384 continue;
385 if (rv < 0) {
386 if (errno != EINTR)
387 logerror("poll");
388 continue;
389 }
390 dprintf("got a message (%d)\n", rv);
391 if (fklog >= 0 &&
392 (readfds[nfklogix].revents & (POLLIN | POLLPRI))) {
393 dprintf("kernel log active\n");
394 i = read(fklog, line, linesize - 1);
395 if (i > 0) {
396 line[i] = '\0';
397 printsys(line);
398 } else if (i < 0 && errno != EINTR) {
399 logerror("klog");
400 fklog = -1;
401 }
402 }
403 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
404 if ((readfds[nfunixbaseix + j].revents &
405 (POLLIN | POLLPRI)) == 0)
406 continue;
407
408 dprintf("unix socket (%s) active\n", *pp);
409 len = sizeof(fromunix);
410 i = recvfrom(funix[j], line, MAXLINE, 0,
411 (struct sockaddr *)&fromunix, &len);
412 if (i > 0) {
413 line[i] = '\0';
414 printline(LocalHostName, line);
415 } else if (i < 0 && errno != EINTR) {
416 char buf[MAXPATHLEN];
417 int serrno = errno;
418
419 (void)snprintf(buf, sizeof buf,
420 "recvfrom unix %s", *pp);
421 errno = serrno;
422 logerror(buf);
423 }
424 }
425 if (finet && !SecureMode) {
426 for (j = 0; j < *finet; j++) {
427 if (readfds[nfinetix[j]].revents &
428 (POLLIN | POLLPRI)) {
429 dprintf("inet socket active\n");
430 len = sizeof(frominet);
431 i = recvfrom(finet[j+1], line, MAXLINE,
432 0, (struct sockaddr *)&frominet,
433 &len);
434 if (i > 0) {
435 line[i] = '\0';
436 printline(cvthname(&frominet),
437 line);
438 } else if (i < 0 && errno != EINTR)
439 logerror("recvfrom inet");
440 }
441 }
442 }
443 }
444 }
445
446 void
447 usage()
448 {
449 extern char *__progname;
450
451 (void)fprintf(stderr,
452 "usage: %s [-ds] [-f conffile] [-m markinterval] [-P logpathfile] [-p logpath1] [-p logpath2 ..]\n",
453 __progname);
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 dprintf("adding %s to the %p logpath list\n", new, *lp);
471 if (*szp == *maxszp) {
472 if (*maxszp == 0) {
473 *maxszp = 4; /* start of with enough for now */
474 *lp = NULL;
475 }
476 else
477 *maxszp *= 2;
478 *lp = realloc(*lp, sizeof(char *) * (*maxszp + 1));
479 if (*lp == NULL) {
480 logerror("couldn't allocate line buffer");
481 die(0);
482 }
483 }
484 (*lp)[(*szp)++] = new;
485 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
486 }
487
488 /* do a file of log sockets */
489 void
490 logpath_fileadd(lp, szp, maxszp, file)
491 char ***lp;
492 int *szp;
493 int *maxszp;
494 char *file;
495 {
496 FILE *fp;
497 char *line;
498 size_t len;
499
500 fp = fopen(file, "r");
501 if (fp == NULL) {
502 int serrno = errno;
503
504 dprintf("can't open %s (%d)\n", file, errno);
505 errno = serrno;
506 logerror("could not open socket file list");
507 die(0);
508 }
509
510 while ((line = fgetln(fp, &len))) {
511 line[len - 1] = 0;
512 logpath_add(lp, szp, maxszp, line);
513 }
514 fclose(fp);
515 }
516
517 /*
518 * Take a raw input line, decode the message, and print the message
519 * on the appropriate log files.
520 */
521 void
522 printline(hname, msg)
523 char *hname;
524 char *msg;
525 {
526 int c, pri;
527 char *p, *q, line[MAXLINE + 1];
528
529 /* test for special codes */
530 pri = DEFUPRI;
531 p = msg;
532 if (*p == '<') {
533 pri = 0;
534 while (isdigit(*++p))
535 pri = 10 * pri + (*p - '0');
536 if (*p == '>')
537 ++p;
538 }
539 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
540 pri = DEFUPRI;
541
542 /* don't allow users to log kernel messages */
543 if (LOG_FAC(pri) == LOG_KERN)
544 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
545
546 q = line;
547
548 while ((c = *p++ & 0177) != '\0' &&
549 q < &line[sizeof(line) - 1])
550 if (iscntrl(c))
551 if (c == '\n')
552 *q++ = ' ';
553 else if (c == '\t')
554 *q++ = '\t';
555 else {
556 *q++ = '^';
557 *q++ = c ^ 0100;
558 }
559 else
560 *q++ = c;
561 *q = '\0';
562
563 logmsg(pri, line, hname, 0);
564 }
565
566 /*
567 * Take a raw input line from /dev/klog, split and format similar to syslog().
568 */
569 void
570 printsys(msg)
571 char *msg;
572 {
573 int c, pri, flags;
574 char *lp, *p, *q, line[MAXLINE + 1];
575
576 (void)strcpy(line, _PATH_UNIX);
577 (void)strcat(line, ": ");
578 lp = line + strlen(line);
579 for (p = msg; *p != '\0'; ) {
580 flags = SYNC_FILE | ADDDATE; /* fsync file after write */
581 pri = DEFSPRI;
582 if (*p == '<') {
583 pri = 0;
584 while (isdigit(*++p))
585 pri = 10 * pri + (*p - '0');
586 if (*p == '>')
587 ++p;
588 } else {
589 /* kernel printf's come out on console */
590 flags |= IGN_CONS;
591 }
592 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
593 pri = DEFSPRI;
594 q = lp;
595 while (*p != '\0' && (c = *p++) != '\n' &&
596 q < &line[MAXLINE])
597 *q++ = c;
598 *q = '\0';
599 logmsg(pri, line, LocalHostName, flags);
600 }
601 }
602
603 time_t now;
604
605 /*
606 * Log a message to the appropriate log files, users, etc. based on
607 * the priority.
608 */
609 void
610 logmsg(pri, msg, from, flags)
611 int pri;
612 char *msg, *from;
613 int flags;
614 {
615 struct filed *f;
616 int fac, msglen, omask, prilev;
617 char *timestamp;
618
619 dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
620 pri, flags, from, msg);
621
622 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
623
624 /*
625 * Check to see if msg looks non-standard.
626 */
627 msglen = strlen(msg);
628 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
629 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
630 flags |= ADDDATE;
631
632 (void)time(&now);
633 if (flags & ADDDATE)
634 timestamp = ctime(&now) + 4;
635 else {
636 timestamp = msg;
637 msg += 16;
638 msglen -= 16;
639 }
640
641 /* extract facility and priority level */
642 if (flags & MARK)
643 fac = LOG_NFACILITIES;
644 else
645 fac = LOG_FAC(pri);
646 prilev = LOG_PRI(pri);
647
648 /* log the message to the particular outputs */
649 if (!Initialized) {
650 f = &consfile;
651 f->f_file = open(ctty, O_WRONLY, 0);
652
653 if (f->f_file >= 0) {
654 fprintlog(f, flags, msg);
655 (void)close(f->f_file);
656 }
657 (void)sigsetmask(omask);
658 return;
659 }
660 for (f = Files; f; f = f->f_next) {
661 /* skip messages that are incorrect priority */
662 if (f->f_pmask[fac] < prilev ||
663 f->f_pmask[fac] == INTERNAL_NOPRI)
664 continue;
665
666 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
667 continue;
668
669 /* don't output marks to recently written files */
670 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
671 continue;
672
673 /*
674 * suppress duplicate lines to this file
675 */
676 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
677 !strcmp(msg, f->f_prevline) &&
678 !strcmp(from, f->f_prevhost)) {
679 (void)strncpy(f->f_lasttime, timestamp, 15);
680 f->f_prevcount++;
681 dprintf("msg repeated %d times, %ld sec of %d\n",
682 f->f_prevcount, (long)(now - f->f_time),
683 repeatinterval[f->f_repeatcount]);
684 /*
685 * If domark would have logged this by now,
686 * flush it now (so we don't hold isolated messages),
687 * but back off so we'll flush less often
688 * in the future.
689 */
690 if (now > REPEATTIME(f)) {
691 fprintlog(f, flags, (char *)NULL);
692 BACKOFF(f);
693 }
694 } else {
695 /* new line, save it */
696 if (f->f_prevcount)
697 fprintlog(f, 0, (char *)NULL);
698 f->f_repeatcount = 0;
699 f->f_prevpri = pri;
700 (void)strncpy(f->f_lasttime, timestamp, 15);
701 (void)strncpy(f->f_prevhost, from,
702 sizeof(f->f_prevhost));
703 if (msglen < MAXSVLINE) {
704 f->f_prevlen = msglen;
705 (void)strcpy(f->f_prevline, msg);
706 fprintlog(f, flags, (char *)NULL);
707 } else {
708 f->f_prevline[0] = 0;
709 f->f_prevlen = 0;
710 fprintlog(f, flags, msg);
711 }
712 }
713 }
714 (void)sigsetmask(omask);
715 }
716
717 void
718 fprintlog(f, flags, msg)
719 struct filed *f;
720 int flags;
721 char *msg;
722 {
723 struct iovec iov[6];
724 struct iovec *v;
725 struct addrinfo *r;
726 int j, l, lsent;
727 char line[MAXLINE + 1], repbuf[80], greetings[200];
728
729 v = iov;
730 if (f->f_type == F_WALL) {
731 v->iov_base = greetings;
732 v->iov_len = snprintf(greetings, sizeof greetings,
733 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
734 f->f_prevhost, ctime(&now));
735 v++;
736 v->iov_base = "";
737 v->iov_len = 0;
738 v++;
739 } else {
740 v->iov_base = f->f_lasttime;
741 v->iov_len = 15;
742 v++;
743 v->iov_base = " ";
744 v->iov_len = 1;
745 v++;
746 }
747 v->iov_base = f->f_prevhost;
748 v->iov_len = strlen(v->iov_base);
749 v++;
750 v->iov_base = " ";
751 v->iov_len = 1;
752 v++;
753
754 if (msg) {
755 v->iov_base = msg;
756 v->iov_len = strlen(msg);
757 } else if (f->f_prevcount > 1) {
758 v->iov_base = repbuf;
759 v->iov_len = snprintf(repbuf, sizeof repbuf,
760 "last message repeated %d times", f->f_prevcount);
761 } else {
762 v->iov_base = f->f_prevline;
763 v->iov_len = f->f_prevlen;
764 }
765 v++;
766
767 dprintf("Logging to %s", TypeNames[f->f_type]);
768 f->f_time = now;
769
770 switch (f->f_type) {
771 case F_UNUSED:
772 dprintf("\n");
773 break;
774
775 case F_FORW:
776 dprintf(" %s\n", f->f_un.f_forw.f_hname);
777 /*
778 * check for local vs remote messages
779 * (from FreeBSD PR#bin/7055)
780 */
781 if (strcmp(f->f_prevhost, LocalHostName)) {
782 l = snprintf(line, sizeof(line) - 1,
783 "<%d>%.15s [%s]: %s",
784 f->f_prevpri, (char *) iov[0].iov_base,
785 f->f_prevhost, (char *) iov[4].iov_base);
786 } else {
787 l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
788 f->f_prevpri, (char *) iov[0].iov_base,
789 (char *) iov[4].iov_base);
790 }
791 if (l > MAXLINE)
792 l = MAXLINE;
793 if (finet) {
794 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
795 for (j = 0; j < *finet; j++) {
796 #if 0
797 /*
798 * should we check AF first, or just
799 * trial and error? FWD
800 */
801 if (r->ai_family ==
802 address_family_of(finet[j+1]))
803 #endif
804 lsent = sendto(finet[j+1], line, l, 0,
805 r->ai_addr, r->ai_addrlen);
806 if (lsent == l)
807 break;
808 }
809 }
810 if (lsent != l) {
811 f->f_type = F_UNUSED;
812 logerror("sendto");
813 }
814 }
815 break;
816
817 case F_CONSOLE:
818 if (flags & IGN_CONS) {
819 dprintf(" (ignored)\n");
820 break;
821 }
822 /* FALLTHROUGH */
823
824 case F_TTY:
825 case F_FILE:
826 dprintf(" %s\n", f->f_un.f_fname);
827 if (f->f_type != F_FILE) {
828 v->iov_base = "\r\n";
829 v->iov_len = 2;
830 } else {
831 v->iov_base = "\n";
832 v->iov_len = 1;
833 }
834 again:
835 if (writev(f->f_file, iov, 6) < 0) {
836 int e = errno;
837 (void)close(f->f_file);
838 /*
839 * Check for errors on TTY's due to loss of tty
840 */
841 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
842 f->f_file = open(f->f_un.f_fname,
843 O_WRONLY|O_APPEND, 0);
844 if (f->f_file < 0) {
845 f->f_type = F_UNUSED;
846 logerror(f->f_un.f_fname);
847 } else
848 goto again;
849 } else {
850 f->f_type = F_UNUSED;
851 errno = e;
852 logerror(f->f_un.f_fname);
853 }
854 } else if (flags & SYNC_FILE)
855 (void)fsync(f->f_file);
856 break;
857
858 case F_USERS:
859 case F_WALL:
860 dprintf("\n");
861 v->iov_base = "\r\n";
862 v->iov_len = 2;
863 wallmsg(f, iov);
864 break;
865 }
866 f->f_prevcount = 0;
867 }
868
869 /*
870 * WALLMSG -- Write a message to the world at large
871 *
872 * Write the specified message to either the entire
873 * world, or a list of approved users.
874 */
875 void
876 wallmsg(f, iov)
877 struct filed *f;
878 struct iovec *iov;
879 {
880 static int reenter; /* avoid calling ourselves */
881 FILE *uf;
882 struct utmp ut;
883 int i;
884 char *p;
885 char line[sizeof(ut.ut_line) + 1];
886
887 if (reenter++)
888 return;
889 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
890 logerror(_PATH_UTMP);
891 reenter = 0;
892 return;
893 }
894 /* NOSTRICT */
895 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
896 if (ut.ut_name[0] == '\0')
897 continue;
898 strncpy(line, ut.ut_line, sizeof(ut.ut_line));
899 line[sizeof(ut.ut_line)] = '\0';
900 if (f->f_type == F_WALL) {
901 if ((p = ttymsg(iov, 6, line, TTYMSGTIME)) != NULL) {
902 errno = 0; /* already in msg */
903 logerror(p);
904 }
905 continue;
906 }
907 /* should we send the message to this user? */
908 for (i = 0; i < MAXUNAMES; i++) {
909 if (!f->f_un.f_uname[i][0])
910 break;
911 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
912 UT_NAMESIZE)) {
913 if ((p = ttymsg(iov, 6, line, TTYMSGTIME))
914 != NULL) {
915 errno = 0; /* already in msg */
916 logerror(p);
917 }
918 break;
919 }
920 }
921 }
922 (void)fclose(uf);
923 reenter = 0;
924 }
925
926 void
927 reapchild(signo)
928 int signo;
929 {
930 union wait status;
931
932 while (wait3((int *)&status, WNOHANG, (struct rusage *)NULL) > 0)
933 ;
934 }
935
936 /*
937 * Return a printable representation of a host address.
938 */
939 char *
940 cvthname(f)
941 struct sockaddr_storage *f;
942 {
943 int error;
944 char *p;
945 #ifdef KAME_SCOPEID
946 const int niflag = NI_DGRAM | NI_WITHSCOPEID;
947 #else
948 const int niflag = NI_DGRAM;
949 #endif
950 static char host[NI_MAXHOST], ip[NI_MAXHOST];
951
952 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
953 ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
954
955 dprintf("cvthname(%s)\n", ip);
956
957 if (error) {
958 dprintf("Malformed from address %s\n", gai_strerror(error));
959 return ("???");
960 }
961
962 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
963 host, sizeof host, NULL, 0, niflag);
964 if (error) {
965 dprintf("Host name for your address (%s) unknown\n", ip);
966 return (ip);
967 }
968 if ((p = strchr(host, '.')) && strcmp(p + 1, LocalDomain) == 0)
969 *p = '\0';
970 return (host);
971 }
972
973 void
974 domark(signo)
975 int signo;
976 {
977 struct filed *f;
978
979 now = time((time_t *)NULL);
980 MarkSeq += TIMERINTVL;
981 if (MarkSeq >= MarkInterval) {
982 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
983 MarkSeq = 0;
984 }
985
986 for (f = Files; f; f = f->f_next) {
987 if (f->f_prevcount && now >= REPEATTIME(f)) {
988 dprintf("flush %s: repeated %d times, %d sec.\n",
989 TypeNames[f->f_type], f->f_prevcount,
990 repeatinterval[f->f_repeatcount]);
991 fprintlog(f, 0, (char *)NULL);
992 BACKOFF(f);
993 }
994 }
995 (void)alarm(TIMERINTVL);
996 }
997
998 /*
999 * Print syslogd errors some place.
1000 */
1001 void
1002 logerror(type)
1003 char *type;
1004 {
1005 char buf[100];
1006
1007 if (errno)
1008 (void)snprintf(buf,
1009 sizeof(buf), "syslogd: %s: %s", type, strerror(errno));
1010 else
1011 (void)snprintf(buf, sizeof(buf), "syslogd: %s", type);
1012 errno = 0;
1013 dprintf("%s\n", buf);
1014 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1015 }
1016
1017 void
1018 die(signo)
1019 int signo;
1020 {
1021 struct filed *f;
1022 char buf[100], **p;
1023
1024 for (f = Files; f != NULL; f = f->f_next) {
1025 /* flush any pending output */
1026 if (f->f_prevcount)
1027 fprintlog(f, 0, (char *)NULL);
1028 }
1029 if (signo) {
1030 dprintf("syslogd: exiting on signal %d\n", signo);
1031 (void)snprintf(buf, sizeof buf, "exiting on signal %d", signo);
1032 errno = 0;
1033 logerror(buf);
1034 }
1035 for (p = LogPaths; p && *p; p++)
1036 unlink(*p);
1037 exit(0);
1038 }
1039
1040 /*
1041 * INIT -- Initialize syslogd from configuration table
1042 */
1043 void
1044 init(signo)
1045 int signo;
1046 {
1047 int i;
1048 FILE *cf;
1049 struct filed *f, *next, **nextp;
1050 char *p;
1051 char cline[LINE_MAX];
1052
1053 dprintf("init\n");
1054
1055 /*
1056 * Close all open log files.
1057 */
1058 Initialized = 0;
1059 for (f = Files; f != NULL; f = next) {
1060 /* flush any pending output */
1061 if (f->f_prevcount)
1062 fprintlog(f, 0, (char *)NULL);
1063
1064 switch (f->f_type) {
1065 case F_FILE:
1066 case F_TTY:
1067 case F_CONSOLE:
1068 (void)close(f->f_file);
1069 break;
1070 }
1071 next = f->f_next;
1072 free((char *)f);
1073 }
1074 Files = NULL;
1075 nextp = &Files;
1076
1077 /* open the configuration file */
1078 if ((cf = fopen(ConfFile, "r")) == NULL) {
1079 dprintf("cannot open %s\n", ConfFile);
1080 *nextp = (struct filed *)calloc(1, sizeof(*f));
1081 cfline("*.ERR\t/dev/console", *nextp);
1082 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1083 cfline("*.PANIC\t*", (*nextp)->f_next);
1084 Initialized = 1;
1085 return;
1086 }
1087
1088 /*
1089 * Foreach line in the conf table, open that file.
1090 */
1091 f = NULL;
1092 while (fgets(cline, sizeof(cline), cf) != NULL) {
1093 /*
1094 * check for end-of-section, comments, strip off trailing
1095 * spaces and newline character.
1096 */
1097 for (p = cline; isspace(*p); ++p)
1098 continue;
1099 if (*p == '\0' || *p == '#')
1100 continue;
1101 for (p = strchr(cline, '\0'); isspace(*--p);)
1102 continue;
1103 *++p = '\0';
1104 f = (struct filed *)calloc(1, sizeof(*f));
1105 *nextp = f;
1106 nextp = &f->f_next;
1107 cfline(cline, f);
1108 }
1109
1110 /* close the configuration file */
1111 (void)fclose(cf);
1112
1113 Initialized = 1;
1114
1115 if (Debug) {
1116 for (f = Files; f; f = f->f_next) {
1117 for (i = 0; i <= LOG_NFACILITIES; i++)
1118 if (f->f_pmask[i] == INTERNAL_NOPRI)
1119 printf("X ");
1120 else
1121 printf("%d ", f->f_pmask[i]);
1122 printf("%s: ", TypeNames[f->f_type]);
1123 switch (f->f_type) {
1124 case F_FILE:
1125 case F_TTY:
1126 case F_CONSOLE:
1127 printf("%s", f->f_un.f_fname);
1128 break;
1129
1130 case F_FORW:
1131 printf("%s", f->f_un.f_forw.f_hname);
1132 break;
1133
1134 case F_USERS:
1135 for (i = 0;
1136 i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1137 printf("%s, ", f->f_un.f_uname[i]);
1138 break;
1139 }
1140 printf("\n");
1141 }
1142 }
1143
1144 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1145 dprintf("syslogd: restarted\n");
1146 }
1147
1148 /*
1149 * Crack a configuration file line
1150 */
1151 void
1152 cfline(line, f)
1153 char *line;
1154 struct filed *f;
1155 {
1156 struct addrinfo hints, *res;
1157 int error, i, pri;
1158 char *bp, *p, *q;
1159 char buf[MAXLINE], ebuf[100];
1160
1161 dprintf("cfline(%s)\n", line);
1162
1163 errno = 0; /* keep strerror() stuff out of logerror messages */
1164
1165 /* clear out file entry */
1166 memset(f, 0, sizeof(*f));
1167 for (i = 0; i <= LOG_NFACILITIES; i++)
1168 f->f_pmask[i] = INTERNAL_NOPRI;
1169
1170 /* scan through the list of selectors */
1171 for (p = line; *p && *p != '\t';) {
1172
1173 /* find the end of this facility name list */
1174 for (q = p; *q && *q != '\t' && *q++ != '.'; )
1175 continue;
1176
1177 /* collect priority name */
1178 for (bp = buf; *q && !strchr("\t,;", *q); )
1179 *bp++ = *q++;
1180 *bp = '\0';
1181
1182 /* skip cruft */
1183 while (strchr(", ;", *q))
1184 q++;
1185
1186 /* decode priority name */
1187 if (*buf == '*')
1188 pri = LOG_PRIMASK + 1;
1189 else {
1190 pri = decode(buf, prioritynames);
1191 if (pri < 0) {
1192 (void)snprintf(ebuf, sizeof ebuf,
1193 "unknown priority name \"%s\"", buf);
1194 logerror(ebuf);
1195 return;
1196 }
1197 }
1198
1199 /* scan facilities */
1200 while (*p && !strchr("\t.;", *p)) {
1201 for (bp = buf; *p && !strchr("\t,;.", *p); )
1202 *bp++ = *p++;
1203 *bp = '\0';
1204 if (*buf == '*')
1205 for (i = 0; i < LOG_NFACILITIES; i++)
1206 f->f_pmask[i] = pri;
1207 else {
1208 i = decode(buf, facilitynames);
1209 if (i < 0) {
1210 (void)snprintf(ebuf, sizeof ebuf,
1211 "unknown facility name \"%s\"",
1212 buf);
1213 logerror(ebuf);
1214 return;
1215 }
1216 f->f_pmask[i >> 3] = pri;
1217 }
1218 while (*p == ',' || *p == ' ')
1219 p++;
1220 }
1221
1222 p = q;
1223 }
1224
1225 /* skip to action part */
1226 while (*p == '\t')
1227 p++;
1228
1229 switch (*p)
1230 {
1231 case '@':
1232 (void)strcpy(f->f_un.f_forw.f_hname, ++p);
1233 memset(&hints, 0, sizeof(hints));
1234 hints.ai_family = AF_UNSPEC;
1235 hints.ai_socktype = SOCK_DGRAM;
1236 hints.ai_protocol = 0;
1237 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
1238 &res);
1239 if (error) {
1240 logerror(gai_strerror(error));
1241 break;
1242 }
1243 f->f_un.f_forw.f_addr = res;
1244 f->f_type = F_FORW;
1245 NumForwards++;
1246 break;
1247
1248 case '/':
1249 (void)strcpy(f->f_un.f_fname, p);
1250 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1251 f->f_type = F_UNUSED;
1252 logerror(p);
1253 break;
1254 }
1255 if (isatty(f->f_file))
1256 f->f_type = F_TTY;
1257 else
1258 f->f_type = F_FILE;
1259 if (strcmp(p, ctty) == 0)
1260 f->f_type = F_CONSOLE;
1261 break;
1262
1263 case '*':
1264 f->f_type = F_WALL;
1265 break;
1266
1267 default:
1268 for (i = 0; i < MAXUNAMES && *p; i++) {
1269 for (q = p; *q && *q != ','; )
1270 q++;
1271 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1272 if ((q - p) > UT_NAMESIZE)
1273 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1274 else
1275 f->f_un.f_uname[i][q - p] = '\0';
1276 while (*q == ',' || *q == ' ')
1277 q++;
1278 p = q;
1279 }
1280 f->f_type = F_USERS;
1281 break;
1282 }
1283 }
1284
1285
1286 /*
1287 * Decode a symbolic name to a numeric value
1288 */
1289 int
1290 decode(name, codetab)
1291 const char *name;
1292 CODE *codetab;
1293 {
1294 CODE *c;
1295 char *p, buf[40];
1296
1297 if (isdigit(*name))
1298 return (atoi(name));
1299
1300 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1301 if (isupper(*name))
1302 *p = tolower(*name);
1303 else
1304 *p = *name;
1305 }
1306 *p = '\0';
1307 for (c = codetab; c->c_name; c++)
1308 if (!strcmp(buf, c->c_name))
1309 return (c->c_val);
1310
1311 return (-1);
1312 }
1313
1314 /*
1315 * Retrieve the size of the kernel message buffer, via sysctl.
1316 */
1317 int
1318 getmsgbufsize()
1319 {
1320 int msgbufsize, mib[2];
1321 size_t size;
1322
1323 mib[0] = CTL_KERN;
1324 mib[1] = KERN_MSGBUFSIZE;
1325 size = sizeof msgbufsize;
1326 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
1327 dprintf("couldn't get kern.msgbufsize\n");
1328 return (0);
1329 }
1330 return (msgbufsize);
1331 }
1332
1333 int *
1334 socksetup(af)
1335 int af;
1336 {
1337 struct addrinfo hints, *res, *r;
1338 int error, maxs, *s, *socks;
1339
1340 if(SecureMode && !NumForwards)
1341 return(NULL);
1342
1343 memset(&hints, 0, sizeof(hints));
1344 hints.ai_flags = AI_PASSIVE;
1345 hints.ai_family = af;
1346 hints.ai_socktype = SOCK_DGRAM;
1347 error = getaddrinfo(NULL, "syslog", &hints, &res);
1348 if (error) {
1349 logerror(gai_strerror(error));
1350 errno = 0;
1351 die(0);
1352 }
1353
1354 /* Count max number of sockets we may open */
1355 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
1356 continue;
1357 socks = malloc ((maxs+1) * sizeof(int));
1358 if (!socks) {
1359 logerror("couldn't allocate memory for sockets");
1360 die(0);
1361 }
1362
1363 *socks = 0; /* num of sockets counter at start of array */
1364 s = socks+1;
1365 for (r = res; r; r = r->ai_next) {
1366 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
1367 if (*s < 0) {
1368 logerror("socket");
1369 continue;
1370 }
1371 if (!SecureMode && bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
1372 close (*s);
1373 logerror("bind");
1374 continue;
1375 }
1376
1377 *socks = *socks + 1;
1378 s++;
1379 }
1380
1381 if (*socks == 0) {
1382 free (socks);
1383 if(Debug)
1384 return(NULL);
1385 else
1386 die(0);
1387 }
1388 if (res)
1389 freeaddrinfo(res);
1390
1391 return(socks);
1392 }
1393