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