t40c term[] count fix
[minix.git] / commands / syslogd / syslogd.c
blob49c9e2b44e6add4ce4fa924422e46cdd331c1e63
1 /*
2 ** Copyright (c) 1983, 1988
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.
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.
33 ** #ifndef lint
34 ** char copyright2[] =
35 ** "@(#) Copyright (c) 1983, 1988 Regents of the University of California.\n\
36 ** All rights reserved.\n";
37 ** #endif
39 ** #ifndef lint
40 ** static char sccsid[] = "@(#)syslogd.c 5.27 (Berkeley) 10/10/88";
41 ** #endif
43 ** -----------------------------------------------------------------------
45 ** SYSLOGD -- log system messages
46 ** This program implements a system log.
47 ** It takes a series of lines and outputs them according to the setup
48 ** defined in the configuration file.
49 ** Each line may have a priority, signified as "<n>" as
50 ** the first characters of the line. If this is
51 ** not present, a default priority is used.
53 ** To kill syslogd, send a signal 15 (terminate).
54 ** A signal 1 (hup) will cause it to reread its configuration file.
56 ** Defined Constants:
57 ** MAXLINE -- the maximimum line length that can be handled.
58 ** MAXSVLINE -- the length of saved messages (for filtering)
59 ** DEFUPRI -- the default priority for user messages
60 ** DEFSPRI -- the default priority for kernel messages
62 ** Author: Eric Allman
63 ** extensive changes by Ralph Campbell
64 ** more extensive changes by Eric Allman (again)
65 ** changes by Steve Lord
67 ** Extensive rewriting by G. Falzoni <gfalzoni@inwind.it> for porting to Minix
68 **
69 ** $Log$
70 ** Revision 1.3 2006/04/04 14:22:40 beng
71 ** Fix
73 ** Revision 1.2 2006/04/04 14:18:16 beng
74 ** Make syslogd work, even if it can only open klog and not udp or vice versa
75 ** (but not neither)
77 ** Revision 1.1 2006/04/03 13:07:42 beng
78 ** Kick out usyslogd in favour of syslogd Giovanni's syslogd port
80 ** Revision 1.3 2005/09/16 10:10:12 lsodgf0
81 ** Rework for Minix 3. Adds kernel logs from /dev/klogd
84 #include <sys/types.h>
85 #include <stdio.h>
86 #include <ctype.h>
87 #include <string.h>
88 #include <unistd.h>
89 #include <stdlib.h>
90 #include <signal.h>
91 #include <errno.h>
92 #include <fcntl.h>
93 #include <limits.h>
94 #include <time.h>
95 #include <sys/ioctl.h>
96 #include <sys/select.h>
97 #include <sys/wait.h>
98 #include <net/netlib.h>
99 #include <net/hton.h>
100 #include <net/gen/in.h>
101 #include <net/gen/udp.h>
102 #include <net/gen/udp_io.h>
103 #include <net/gen/netdb.h>
105 #define SYSLOG_NAMES
106 #include <syslog.h>
107 #define KLOGD 1
108 /** Define following values to your requirements **/
109 #define MAXLINE 512 /* maximum line length */
110 #define MAXSVLINE 256 /* maximum saved line length */
112 #define DEFUPRI (LOG_USER|LOG_NOTICE)
113 #define DEFSPRI (LOG_KERN|LOG_CRIT)
115 /* Flags to logmsg() */
116 #define IGN_CONS 0x001 /* don't print on console */
117 #define SYNC_FILE 0x002 /* do fsync on file after printing */
118 #define ADDDATE 0x004 /* add a date to the message */
119 #define MARK 0x008 /* this message is a mark */
121 #define CTTY "/dev/log" /* Minix log device (console) */
123 #define dprintf if(DbgOpt!=0)printf
124 #if debug == 0
125 #define DEBUG(statement)
126 #else
127 #define DEBUG(statement) statement
128 #endif
129 #if !defined PIDFILE
130 #define PIDFILE "/var/run/syslogd.pid"
131 #endif
133 #define UNAMESZ 8 /* length of a login name */
134 #define MAXUNAMES 20 /* maximum number of user names */
135 #define MAXFNAME 200 /* max file pathname length */
136 #define MAXHOSTNAMELEN 64 /* max length of FQDN host name */
138 /* Intervals at which we flush out "message repeated" messages,
139 * in seconds after previous message is logged. After each flush,
140 * we move to the next interval until we reach the largest. */
141 #define TIMERINTVL 30 /* interval for checking flush, mark */
142 #define INTERVAL1 30
143 #define INTERVAL2 60
144 #define MAXREPEAT ((sizeof(repeatinterval)/sizeof(repeatinterval[0]))-1)
145 #define REPEATTIME(f) ((f)->f_time+repeatinterval[(f)->f_repeatcount])
146 #define BACKOFF(f) {if(++(f)->f_repeatcount>MAXREPEAT)(f)->f_repeatcount=MAXREPEAT;}
148 /* Values for f_type */
149 #define F_UNUSED 0 /* unused entry */
150 #define F_FILE 1 /* regular file */
151 #define F_TTY 2 /* terminal */
152 #define F_CONSOLE 3 /* console terminal */
153 #define F_FORW 4 /* remote machine */
154 #define F_USERS 5 /* list of users */
155 #define F_WALL 6 /* everyone logged on */
157 #define max(a,b) ((a)>=(b)?(a):(b))
159 /* This structure represents the files that will have log copies printed */
160 struct filed {
161 struct filed *f_next; /* next in linked list */
162 short f_type; /* entry type, see below */
163 short f_file; /* file descriptor */
164 time_t f_time; /* time this was last written */
165 char f_pmask[LOG_NFACILITIES + 1]; /* priority mask */
166 union {
167 char f_uname[MAXUNAMES][UNAMESZ + 1];
168 char f_fname[MAXFNAME];
169 } f_un;
170 char f_prevline[MAXSVLINE]; /* last message logged */
171 char f_lasttime[16]; /* time of last occurrence */
172 char f_prevhost[MAXHOSTNAMELEN + 1]; /* host from which recd. */
173 int f_prevpri; /* pri of f_prevline */
174 int f_prevlen; /* length of f_prevline */
175 int f_prevcount; /* repetition cnt of prevline */
176 int f_repeatcount; /* number of "repeated" msgs */
177 int f_flags; /* store some additional flags */
180 static const char *const TypeNames[] =
182 "UNUSED", "FILE", "TTY", "CONSOLE", "FORW", "USERS", "WALL", NULL,
185 static struct filed *Files = NULL;
186 static struct filed consfile;
187 static int DbgOpt = 0; /* debug flag */
188 static char LocalHostName[MAXHOSTNAMELEN + 1]; /* our hostname */
189 static int Initialized = 0; /* set when we have initialized ourselves */
190 static int MarkInterval = 20 * 60; /* interval between marks in seconds */
191 static int MarkSeq = 0; /* mark sequence number */
192 static time_t now;
194 static const char *ConfFile = "/etc/syslog.conf";
195 static const char *PidFile = PIDFILE; /* "/var/run/syslogd.pid" */
196 static const char ctty[] = CTTY;
198 static const char ProgName[] = "syslogd:";
199 static const char version[] = "1.3 (Minix)";
200 static const char usage[] =
201 /* */ "usage:\tsyslogd [-d] [-m markinterval] [-f conf-file]\n"
202 "\t\t[-p listeningport] [-v] [-?]\n" ;
203 static const int repeatinterval[] =
204 /* */ {INTERVAL1, INTERVAL2,}; /* # of secs before flush */
207 ** Name: void wallmsg(struct filed *fLog, char *message);
208 ** Function: Write the specified message to either the entire
209 ** world, or a list of approved users.
211 void wallmsg(struct filed * fLog, char *message)
214 return;
218 ** Name: void fprintlog(struct filed *fLog, int flags, char *message);
219 ** Function:
221 void fprintlog(struct filed * fLog, int flags, char *message)
223 int len;
224 char line[MAXLINE + 1];
225 char repbuf[80];
227 if (message == NULL) {
228 if (fLog->f_prevcount > 1) {
229 sprintf(repbuf, "last message repeated %d times", fLog->f_prevcount);
230 message = repbuf;
231 } else
232 message = fLog->f_prevline;
234 snprintf(line, sizeof(line), "%s %s %s",
235 fLog->f_lasttime, fLog->f_prevhost, message);
236 DEBUG(dprintf("Logging to %s", TypeNames[fLog->f_type]);)
237 fLog->f_time = now;
238 switch (fLog->f_type) {
239 case F_UNUSED: /* */
240 DEBUG(dprintf("\n");)
241 break;
242 case F_CONSOLE:
243 if (flags & IGN_CONS) {
244 case F_FORW: /* */
245 DEBUG(dprintf(" (ignored)\n");)
246 break;
247 } /* else Fall Through */
248 case F_TTY:
249 case F_FILE:
250 DEBUG(dprintf(" %s\n", fLog->f_un.f_fname);)
251 strcat(line, fLog->f_type != F_FILE ? "\r\n" : "\n");
252 len = strlen(line);
253 if (write(fLog->f_file, line, len) != len) {
254 /* Handle errors */ ;
255 } else if (flags & SYNC_FILE)
256 sync();
257 break;
258 case F_USERS:
259 case F_WALL:
260 DEBUG(dprintf("\n");)
261 strcat(line, "\r\n");
262 wallmsg(fLog, line);
263 break;
265 fLog->f_prevcount = 0;
266 return;
270 ** Name: void logmsg(int pri, char *msg, char *from, int flags);
271 ** Function: Log a message to the appropriate log files, users, etc.
272 ** based on the priority.
274 void logmsg(int pri, char *msg, char *from, int flags)
276 struct filed *f;
277 int fac, prilev;
278 int /*omask,*/ msglen;
279 char *timestamp;
281 DEBUG(dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n", pri, flags, from, msg);)
283 omask = sigblock(__sigmask(SIGHUP) | __sigmask(SIGALRM));
285 /* Check to see if msg looks non-standard. */
286 msglen = strlen(msg);
287 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
288 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
289 flags |= ADDDATE;
291 time(&now);
292 if (flags & ADDDATE)
293 timestamp = ctime(&now) + 4;
294 else {
295 timestamp = msg;
296 msg += 16;
297 msglen -= 16;
300 /* Extract facility and priority level */
301 fac = (flags & MARK) ? LOG_NFACILITIES : LOG_FAC(pri);
302 prilev = LOG_PRI(pri);
304 /* Log the message to the particular outputs */
305 if (!Initialized) {
306 /* Not yet initialized. Every message goes to console */
307 f = &consfile;
308 f->f_file = open(ctty, O_WRONLY | O_NOCTTY);
309 if (f->f_file >= 0) {
310 if (!DbgOpt) setsid();
311 fprintlog(f, flags, msg);
312 close(f->f_file);
314 } else {
315 for (f = Files; f; f = f->f_next) {
317 /* Skip messages that are incorrect priority */
318 if (f->f_pmask[fac] < prilev || f->f_pmask[fac] == INTERNAL_NOPRI)
319 continue;
321 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) continue;
323 /* Don't output marks to recently written files */
324 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
325 continue;
327 /* Suppress duplicate lines to this file */
328 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
329 !strcmp(msg, f->f_prevline) &&
330 !strcmp(from, f->f_prevhost)) {
331 strncpy(f->f_lasttime, timestamp, 15);
332 f->f_prevcount += 1;
333 DEBUG(dprintf("msg repeated %d times, %ld sec of %d\n",
334 f->f_prevcount, now - f->f_time,
335 repeatinterval[f->f_repeatcount]);)
336 /* If domark would have logged this by now,
337 * flush it now (so we don't hold isolated
338 * messages), but back off so we'll flush
339 * less often in the future. */
340 if (now > REPEATTIME(f)) {
341 fprintlog(f, flags, (char *) NULL);
342 BACKOFF(f);
344 } else {
345 /* New line, save it */
346 if (f->f_prevcount) fprintlog(f, 0, (char *) NULL);
347 f->f_repeatcount = 0;
348 strncpy(f->f_lasttime, timestamp, 15);
349 strncpy(f->f_prevhost, from, sizeof(f->f_prevhost));
350 if (msglen < MAXSVLINE) {
351 f->f_prevlen = msglen;
352 f->f_prevpri = pri;
353 strcpy(f->f_prevline, msg);
354 fprintlog(f, flags, (char *) NULL);
355 } else {
356 f->f_prevline[0] = 0;
357 f->f_prevlen = 0;
358 fprintlog(f, flags, msg);
365 sigsetmask(omask);
367 return;
371 ** Name: void logerror(char *type);
372 ** Function: Prints syslogd errors in some place.
374 void logerror(char *type)
376 char buf[100];
378 if (errno == 0) sprintf(buf, "%s %s", ProgName, type);
380 sprintf(buf, "%s %s - %s", ProgName, type, strerror(errno));
382 errno = 0;
383 dprintf("%s\n", buf);
384 logmsg(LOG_SYSLOG | LOG_ERR, buf, LocalHostName, ADDDATE);
385 return;
389 ** Name: void die(int sig);
390 ** Function: Signal handler for kill signals.
392 void die(int sig)
394 struct filed *f;
395 char buf[100];
397 for (f = Files; f != NULL; f = f->f_next) {
398 /* Flush any pending output */
399 if (f->f_prevcount) fprintlog(f, 0, NULL);
401 if (sig >= 0) {
402 DEBUG(dprintf("%s exiting on signal %d\n", ProgName, sig);)
403 sprintf(buf, "exiting on signal %d", sig);
404 errno = 0;
405 logerror(buf);
407 unlink(PidFile);
408 exit(sig == (-1) ? EXIT_FAILURE : EXIT_SUCCESS);
412 ** Name: void domark(int sig);
413 ** Function: Signal handler for alarm.
414 ** Used for messages filtering and mark facility.
416 void domark(int sig)
418 struct filed *f;
420 now = time(NULL);
421 MarkSeq += TIMERINTVL;
422 if (MarkSeq >= MarkInterval) {
423 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE | MARK);
424 MarkSeq = 0;
426 for (f = Files; f; f = f->f_next) {
427 if (f->f_prevcount && now >= REPEATTIME(f)) {
428 DEBUG(dprintf("flush %s: repeated %d times, %d sec.\n",
429 TypeNames[f->f_type], f->f_prevcount,
430 repeatinterval[f->f_repeatcount]);)
431 fprintlog(f, 0, NULL);
432 BACKOFF(f);
435 signal(SIGALRM, domark);
436 alarm(TIMERINTVL);
437 return;
441 ** Name: int decode(char *name, struct _code *codetab);
442 ** Function: Decode a symbolic name to a numeric value
444 int decode(char *name, const struct _code *codetab)
446 const struct _code *c;
447 char *p;
448 char buf[40];
450 DEBUG(dprintf("symbolic name: %s", name);)
451 if (isdigit(*name)) return (atoi(name));
453 strcpy(buf, name);
454 for (p = buf; *p; p += 1) {
455 if (isupper(*p)) *p = tolower(*p);
457 for (c = codetab; c->c_name; c += 1) {
458 if (!strcmp(buf, c->c_name)) {
459 DEBUG(dprintf(" ==> %d\n", c->c_val);)
460 return (c->c_val);
463 return (-1);
467 ** Name: void cfline(char *line, struct filed *f);
468 ** Function: Parse a configuration file line
470 void cfline(char *line, struct filed * fLog)
472 char *p, *q, *bp;
473 int ix, pri;
474 char buf[MAXLINE];
475 char xbuf[200];
477 DEBUG(dprintf("cfline(%s)\n", line);)
479 /* Keep sys_errlist stuff out of logerror messages */
480 errno = 0;
482 /* Clear out file entry */
483 memset(fLog, 0, sizeof(*fLog));
484 for (ix = 0; ix <= LOG_NFACILITIES; ix += 1) /* */
485 fLog->f_pmask[ix] = INTERNAL_NOPRI;
487 /* Scan through the list of selectors */
488 for (p = line; *p && *p != '\t';) {
490 /* Find the end of this facility name list */
491 for (q = p; *q && *q != '\t' && *q++ != '.';) continue;
493 /* Collect priority name */
494 for (bp = buf; *q && !strchr("\t,;", *q);) *bp++ = *q++;
495 *bp = '\0';
497 /* Skip cruft */
498 while (strchr(", ;", *q)) q++;
500 /* Decode priority name */
501 #ifdef __NBSD_LIBC
502 pri = decode(buf, prioritynames);
503 #else
504 pri = decode(buf, PriNames);
505 #endif
506 if (pri < 0) {
507 sprintf(xbuf, "unknown priority name \"%s\"", buf);
508 logerror(xbuf);
509 return;
512 /* Scan facilities */
513 while (*p && !strchr("\t.;", *p)) {
514 for (bp = buf; *p && !strchr("\t,;.", *p);) *bp++ = *p++;
515 *bp = '\0';
516 if (*buf == '*') {
517 for (ix = 0; ix <= LOG_NFACILITIES; ix += 1)
518 if ((fLog->f_pmask[ix] < pri) ||
519 (fLog->f_pmask[ix] == INTERNAL_NOPRI)) {
520 fLog->f_pmask[ix] = pri;
522 } else {
523 #ifdef __NBSD_LIBC
524 ix = decode(buf, facilitynames);
525 #else
526 ix = decode(buf, FacNames);
527 #endif
528 if (ix < 0) {
529 sprintf(xbuf, "unknown facility name \"%s\"", buf);
530 logerror(xbuf);
531 return;
533 if ((fLog->f_pmask[ix >> 3] < pri) ||
534 (fLog->f_pmask[ix >> 3] == INTERNAL_NOPRI)) {
535 fLog->f_pmask[ix >> 3] = pri;
538 while (*p == ',' || *p == ' ') p++;
540 p = q;
543 /* Skip to action part */
544 while (*p == '\t' || *p == ' ') p++;
546 DEBUG(dprintf("leading char in action: %c\n", *p);)
547 switch (*p) {
548 case '@': /* Logging to a remote host */
549 break; /* NOT IMPLEMENTED */
551 case '/': /* Logging to a local file/device */
552 strcpy(fLog->f_un.f_fname, p);
553 DEBUG(dprintf("filename: %s\n", p); /* ASP */)
554 if ((fLog->f_file = open(p, O_WRONLY | O_APPEND | O_CREAT | O_NOCTTY, 0644)) < 0) {
555 fLog->f_file = F_UNUSED;
556 sprintf(xbuf, "unknown file/device (%s)", p);
557 logerror(xbuf);
558 break;
560 if (isatty(fLog->f_file)) {
561 if (!DbgOpt) setsid();
562 fLog->f_type = F_TTY;
563 } else
564 fLog->f_type = F_FILE;
565 if (strcmp(p, ctty) == 0) fLog->f_type = F_CONSOLE;
566 break;
568 case '*': /* Logging to all users */
569 DEBUG(dprintf("write-all\n");)
570 fLog->f_type = F_WALL;
571 break;
573 default: /* Logging to selected users */
574 DEBUG(dprintf("users: %s\n", p); /* ASP */)
575 for (ix = 0; ix < MAXUNAMES && *p; ix += 1) {
576 for (q = p; *q && *q != ',';) q += 1;
577 strncpy(fLog->f_un.f_uname[ix], p, UNAMESZ);
578 if ((q - p) > UNAMESZ)
579 fLog->f_un.f_uname[ix][UNAMESZ] = '\0';
580 else
581 fLog->f_un.f_uname[ix][q - p] = '\0';
582 while (*q == ',' || *q == ' ') q++;
583 p = q;
585 fLog->f_type = F_USERS;
586 break;
591 ** Name: void printline(char *hname, char *msg);
592 ** Function: Takes a raw input line, decodes the message and
593 ** prints the message on the appropriate log files.
595 void printline(char *hname, char *msg)
597 char line[MAXLINE + 1];
598 char *p = msg, *q = line;
599 int ch, pri = DEFUPRI;
601 /* Test for special codes */
602 if (*p == '<') {
603 pri = 0;
604 while (isdigit(*++p)) {
605 if ((*p - '0') < 8) {
606 /* Only 3 bits allocated for pri -- ASP */
607 pri = 10 * pri + (*p - '0');
608 } else
609 pri = 10 * pri + 7;
611 if (*p == '>') ++p;
613 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) pri = DEFUPRI;
615 /* Does not allow users to log kernel messages */
616 if (LOG_FAC(pri) == LOG_KERN) pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
618 /* Copies message to local buffer, translating control characters */
619 while ((ch = *p++ & 0177) != '\0' && q < &line[sizeof(line) - 1]) {
620 if (ch == '\n') /* Removes newlines */
621 *q++ = ' ';
622 else if (iscntrl(ch)) { /* Translates control characters */
623 *q++ = '^';
624 *q++ = ch ^ 0100;
625 } else
626 *q++ = ch;
628 *q = '\0';
630 logmsg(pri, line, hname, 0);
631 return;
635 ** Name: void printkline(char *hname, char *msg);
636 ** Function: Takes a raw input line from kernel and
637 ** prints the message on the appropriate log files.
639 void printkline(char *hname, char *msg)
641 char line[MAXLINE + 1];
643 /* Copies message to local buffer, adding source program tag */
644 snprintf(line, sizeof(line), "kernel: %s", msg);
646 logmsg(LOG_KERN | LOG_INFO, line, hname, ADDDATE);
647 return;
651 ** Name: void init(int sig);
652 ** Function: Initialize syslogd from configuration file.
653 ** Used at startup or after a SIGHUP signal.
655 void init(int sig)
657 FILE *cf;
658 struct filed *fLog, *next, **nextp;
659 char *p;
660 char cline[BUFSIZ];
662 DEBUG(dprintf("init\n");)
664 /* Close all open log files. */
665 Initialized = 0;
666 for (fLog = Files; fLog != NULL; fLog = next) {
668 /* Flush any pending output */
669 if (fLog->f_prevcount) fprintlog(fLog, 0, NULL);
671 switch (fLog->f_type) {
672 case F_FILE:
673 case F_TTY:
674 case F_CONSOLE: close(fLog->f_file); break;
676 next = fLog->f_next;
677 free((char *) fLog);
679 Files = NULL;
680 nextp = &Files;
682 /* Open the configuration file */
683 if ((cf = fopen(ConfFile, "r")) != NULL) {
684 /* Foreach line in the configuration table, open that file. */
685 fLog = NULL;
686 while (fgets(cline, sizeof(cline), cf) != NULL) {
687 /* Check for end-of-section, comments, strip off
688 * trailing spaces and newline character. */
689 for (p = cline; isspace(*p); p += 1);
690 if (*p == '\0' || *p == '#') continue;
691 for (p = strchr(cline, '\0'); isspace(*--p););
692 *++p = '\0';
693 fLog = (struct filed *) calloc(1, sizeof(*fLog));
694 *nextp = fLog;
695 nextp = &fLog->f_next;
696 cfline(cline, fLog);
699 /* Close the configuration file */
700 fclose(cf);
701 Initialized = 1;
702 DEBUG (
703 if (DbgOpt) {
704 for (fLog = Files; fLog; fLog = fLog->f_next) {
705 for (i = 0; i <= LOG_NFACILITIES; i += 1)
706 if (fLog->f_pmask[i] == INTERNAL_NOPRI)
707 printf("X ");
708 else
709 printf("%d ", fLog->f_pmask[i]);
710 printf("%s: ", TypeNames[fLog->f_type]);
711 switch (fLog->f_type) {
712 case F_FILE:
713 case F_TTY:
714 case F_CONSOLE:
715 printf("%s", fLog->f_un.f_fname);
716 break;
717 case F_FORW:
718 break;
719 case F_USERS:
720 for (i = 0; i < MAXUNAMES && *fLog->f_un.f_uname[i]; i += 1)
721 printf("%s, ", fLog->f_un.f_uname[i]);
722 break;
724 printf("\n");
728 logmsg(LOG_SYSLOG | LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
729 signal(SIGHUP, init);
730 DEBUG(dprintf("%s restarted\n", ProgName);)
731 } else {
732 DEBUG(dprintf("cannot open %s\n", ConfFile);)
733 *nextp = (struct filed *) calloc(1, sizeof(*fLog));
734 cfline("*.ERR\t" CTTY, *nextp);
735 (*nextp)->f_next = (struct filed *) calloc(1, sizeof(*fLog));
736 cfline("*.PANIC\t*", (*nextp)->f_next);
737 Initialized = 1;
739 return;
743 ** Name: void daemonize(char *line);
744 ** Function: Clone itself and becomes a daemon releasing unnecessay resources.
746 void daemonize(char *line)
748 int lfd, len, pid;
750 if ((lfd = open(PidFile, O_CREAT | O_RDWR, 0600)) > 0) {
751 len = read(lfd, line, 10);
752 line[len] = '\0';
753 close(lfd);
754 if ((kill(len = atoi(line), 0) < 0 && errno == ESRCH) || len == 0) {
755 if (!DbgOpt) {
756 /* Parent ends and child becomes a daemon */
757 if ((pid = fork()) > 0) {
758 /* Write process id. in pid file */
759 lfd = open(PidFile, O_TRUNC | O_WRONLY);
760 len = sprintf(line, "%5d", pid);
761 write(lfd, line, len);
762 close(lfd);
764 /* Wait for initialization to complete */
765 exit(EXIT_SUCCESS);
767 sleep(1);
768 setsid(); /* Set as session leader */
769 chdir("/"); /* Change to the root directory */
770 /* Get rid of all open files */
771 for (lfd = STDERR_FILENO + 1; lfd < OPEN_MAX; lfd += 1)
772 close(lfd);
774 } else {
775 fprintf(stderr, "\n%s already running\n", ProgName);
776 exit(EXIT_FAILURE);
778 } else {
779 fprintf(stderr, "\n%s can't open %s (%s)\n", ProgName, PidFile, strerror(errno));
780 exit(EXIT_FAILURE);
782 return;
786 ** Name: int main(int argc, char **argv);
787 ** Function: Syslog daemon entry point
789 int main(int argc, char **argv)
791 char *p, *udpdev, *eol;
792 int nfd, kfd, len, fdmax;
793 int ch, port = 0;
794 fd_set fdset;
795 struct nwio_udpopt udpopt;
796 struct servent *sp;
797 char line[MAXLINE + 1];
799 while ((ch = getopt(argc, argv, "df:m:p:v?")) != EOF) {
800 switch ((char) ch) {
801 case 'd': /* Debug */
802 DbgOpt += 1;
803 break;
804 case 'f': /* Set configuration file */
805 ConfFile = optarg;
806 break;
807 case 'm': /* Set mark interval */
808 MarkInterval = atoi(optarg) * 60;
809 break;
810 case 'p': /* Set listening port */
811 port = atoi(optarg);
812 break;
813 case 'v': /* Print version */
814 fprintf(stderr, "%s version %s\n", ProgName, version);
815 return EXIT_FAILURE;
816 case '?': /* Help */
817 default:
818 fprintf(stderr, usage);
819 return EXIT_FAILURE;
822 if (argc -= optind) {
823 fprintf(stderr, usage);
824 return EXIT_FAILURE;
827 daemonize(line);
829 /* Get the official name of local host. */
830 gethostname(LocalHostName, sizeof(LocalHostName) - 1);
831 if ((p = strchr(LocalHostName, '.'))) *p = '\0';
833 udpdev = (p = getenv("UDP_DEVICE")) ? p : UDP_DEVICE;
834 sp = getservbyname("syslog", "udp");
836 signal(SIGTERM, die);
837 signal(SIGINT, DbgOpt ? die : SIG_IGN);
838 signal(SIGQUIT, DbgOpt ? die : SIG_IGN);
839 signal(SIGALRM, domark);
841 alarm(TIMERINTVL);
843 /* Open UDP device */
844 nfd = open(udpdev, O_NONBLOCK | O_RDONLY);
846 /* Configures the UDP device */
847 udpopt.nwuo_flags = NWUO_SHARED | NWUO_LP_SET | NWUO_EN_LOC |
848 NWUO_DI_BROAD | NWUO_RP_SET | NWUO_RA_SET |
849 NWUO_RWDATONLY | NWUO_DI_IPOPT;
850 udpopt.nwuo_locport = udpopt.nwuo_remport =
851 port == 0 ? sp->s_port : htons(port);
852 udpopt.nwuo_remaddr = udpopt.nwuo_locaddr = htonl(0x7F000001L);
854 if(nfd >= 0) {
855 while (ioctl(nfd, NWIOSUDPOPT, &udpopt) < 0 ||
856 ioctl(nfd, NWIOGUDPOPT, &udpopt) < 0) {
857 if (errno == EAGAIN) {
858 sleep(1);
859 continue;
861 logerror("Set/Get UDP options failed");
862 return EXIT_FAILURE;
866 /* Open kernel log device */
867 kfd = open("/dev/klog", O_NONBLOCK | O_RDONLY);
869 if(kfd < 0 && nfd < 0) {
870 logerror("open /dev/klog and udp device failed - can't log anything");
871 return EXIT_FAILURE;
874 fdmax = max(nfd, kfd) + 1;
876 DEBUG(dprintf("off & running....\n");)
878 init(-1); /* Initilizes log data structures */
880 for (;;) { /* Main loop */
882 FD_ZERO(&fdset); /* Setup descriptors for select */
883 if(nfd >= 0) FD_SET(nfd, &fdset);
884 if(kfd >= 0) FD_SET(kfd, &fdset);
886 if (select(fdmax, &fdset, NULL, NULL, NULL) <= 0) {
887 sleep(1);
888 continue;
891 if (nfd >= 0 && FD_ISSET(nfd, &fdset)) {
893 /* Read a message from application programs */
894 len = read(nfd, line, MAXLINE);
895 if (len > 0) { /* Got a message */
896 line[len] = '\0';
897 dprintf("got a message (%d, %#x)\n", nfd, len);
898 printline(LocalHostName, line);
900 } else if (len < 0) { /* Got an error or signal while reading */
901 if (errno != EINTR) /* */
903 logerror("Receive error from UDP channel");
904 close(nfd);
905 nfd= -1;
908 } else { /* (len == 0) Channel has been closed */
909 logerror("UDP channel has closed");
910 close(nfd);
911 die(-1);
914 if (kfd >= 0 && FD_ISSET(kfd, &fdset)) {
915 static char linebuf[5*1024];
917 /* Read a message from kernel (klog) */
918 len = read(kfd, linebuf, sizeof(linebuf)-2);
919 dprintf("got a message (%d, %#x)\n", kfd, len);
920 for (ch = 0; ch < len; ch += 1)
921 if (linebuf[ch] == '\0') linebuf[ch] = ' ';
922 if (linebuf[len - 1] == '\n') len -= 1;
923 linebuf[len] = '\n';
924 linebuf[len + 1] = '\0';
925 p = linebuf;
926 while((eol = strchr(p, '\n'))) {
927 *eol = '\0';
928 printkline(LocalHostName, p);
929 p = eol+1;
933 /* Control never gets here */
936 /** syslogd.c **/