2 * Copyright (c) 1983, 1988, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
37 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
44 static const char rcsid[] =
49 * syslogd -- log system messages
51 * This program implements a system log. It takes a series of lines.
52 * Each line may have a priority, signified as "<n>" as
53 * the first characters of the line. If this is
54 * not present, a default priority is used.
56 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
57 * cause it to reread its configuration file.
61 * MAXLINE -- the maximimum line length that can be handled.
62 * DEFUPRI -- the default priority for user messages
63 * DEFSPRI -- the default priority for kernel messages
66 * extensive changes by Ralph Campbell
67 * more extensive changes by Eric Allman (again)
68 * Extension to log by program name as well as facility and priority
70 * -u and -v by Harlan Stenn.
71 * Priority comparison code by Harlan Stenn.
74 #define MAXLINE 1024 /* maximum line length */
75 #define MAXSVLINE 120 /* maximum saved line length */
76 #define DEFUPRI (LOG_USER|LOG_NOTICE)
77 #define DEFSPRI (LOG_KERN|LOG_CRIT)
78 #define TIMERINTVL 30 /* interval for checking flush, mark */
79 #define TTYMSGTIME 1 /* timed out passed to ttymsg */
81 #include <sys/param.h>
82 #include <sys/ioctl.h>
85 #include <sys/socket.h>
86 #include <sys/queue.h>
90 #include <sys/resource.h>
91 #include <sys/syslimits.h>
94 #include <netinet/in.h>
96 #include <arpa/inet.h>
108 #include <sysexits.h>
111 #include "pathnames.h"
114 #include <sys/syslog.h>
116 const char *ConfFile = _PATH_LOGCONF;
117 const char *PidFile = _PATH_LOGPID;
118 const char ctty[] = _PATH_CONSOLE;
120 #define dprintf if (Debug) printf
122 #define MAXUNAMES 20 /* maximum number of user names */
127 char *funixn[MAXFUNIX] = { _PATH_LOG };
134 #define IGN_CONS 0x001 /* don't print on console */
135 #define SYNC_FILE 0x002 /* do fsync on file after printing */
136 #define ADDDATE 0x004 /* add a date to the message */
137 #define MARK 0x008 /* this message is a mark */
138 #define ISKERNEL 0x010 /* kernel generated message */
141 * This structure represents the files that will have log
146 struct filed *f_next; /* next in linked list */
147 short f_type; /* entry type, see below */
148 short f_file; /* file descriptor */
149 time_t f_time; /* time this was last written */
150 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
151 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
155 char *f_program; /* program this applies to */
157 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
159 char f_hname[MAXHOSTNAMELEN+1];
160 struct sockaddr_in f_addr;
161 } f_forw; /* forwarding address */
162 char f_fname[MAXPATHLEN];
164 char f_pname[MAXPATHLEN];
168 char f_prevline[MAXSVLINE]; /* last message logged */
169 char f_lasttime[16]; /* time of last occurrence */
170 char f_prevhost[MAXHOSTNAMELEN+1]; /* host from which recd. */
171 int f_prevpri; /* pri of f_prevline */
172 int f_prevlen; /* length of f_prevline */
173 int f_prevcount; /* repetition cnt of prevline */
174 int f_repeatcount; /* number of "repeated" msgs */
178 * Queue of about-to-be dead processes we should watch out for.
181 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
182 struct stailhead *deadq_headp;
187 TAILQ_ENTRY(deadq_entry) dq_entries;
191 * The timeout to apply to processes waiting on the dead queue. Unit
192 * of measure is `mark intervals', i.e. 20 minutes by default.
193 * Processes on the dead queue will be terminated after that time.
196 #define DQ_TIMO_INIT 2
198 typedef struct deadq_entry *dq_t;
202 * Struct to hold records of network addresses that are allowed to log
215 #define a_addr u.numeric.addr
216 #define a_mask u.numeric.mask
217 #define a_name u.name
222 * Intervals at which we flush out "message repeated" messages,
223 * in seconds after previous message is logged. After each flush,
224 * we move to the next interval until we reach the largest.
226 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
227 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
228 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
229 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
230 (f)->f_repeatcount = MAXREPEAT; \
233 /* values for f_type */
234 #define F_UNUSED 0 /* unused entry */
235 #define F_FILE 1 /* regular file */
236 #define F_TTY 2 /* terminal */
237 #define F_CONSOLE 3 /* console terminal */
238 #define F_FORW 4 /* remote machine */
239 #define F_USERS 5 /* list of users */
240 #define F_WALL 6 /* everyone logged on */
241 #define F_PIPE 7 /* pipe to program */
243 char *TypeNames[8] = {
244 "UNUSED", "FILE", "TTY", "CONSOLE",
245 "FORW", "USERS", "WALL", "PIPE"
249 struct filed consfile;
251 int Debug; /* debug flag */
252 char LocalHostName[MAXHOSTNAMELEN+1]; /* our hostname */
253 char *LocalDomain; /* our local domain name */
254 int finet = -1; /* Internet datagram socket */
255 int fklog = -1; /* /dev/klog */
256 int LogPort; /* port number for INET connections */
257 int Initialized = 0; /* set when we have initialized ourselves */
258 int MarkInterval = 20 * 60; /* interval between marks in seconds */
259 int MarkSeq = 0; /* mark sequence number */
260 int SecureMode = 0; /* when true, receive only unix domain socks */
262 char bootfile[MAXLINE+1]; /* booted kernel file */
264 struct allowedpeer *AllowedPeers;
265 int NumAllowed = 0; /* # of AllowedPeer entries */
267 int UniquePriority = 0; /* Only log specified priority? */
268 int LogFacPri = 0; /* Put facility and priority in log message: */
269 /* 0=no, 1=numeric, 2=names */
271 int allowaddr __P((char *));
272 void cfline __P((char *, struct filed *, char *));
273 char *cvthname __P((struct sockaddr_in *));
274 void deadq_enter __P((pid_t, const char *));
275 int deadq_remove __P((pid_t));
276 int decode __P((const char *, CODE *));
278 void domark __P((int));
279 void fprintlog __P((struct filed *, int, char *));
280 void init __P((int));
281 void logerror __P((const char *));
282 void logmsg __P((int, char *, char *, int));
283 void log_deadchild __P((pid_t, int, const char *));
284 void printline __P((char *, char *));
285 void printsys __P((char *));
286 int p_open __P((char *, pid_t *));
287 void readklog __P((void));
288 void reapchild __P((int));
289 char *ttymsg __P((struct iovec *, int, char *, int));
290 static void usage __P((void));
291 int validate __P((struct sockaddr_in *, const char *));
292 void wallmsg __P((struct filed *, struct iovec *));
293 int waitdaemon __P((int, int, int));
294 void timedout __P((int));
302 struct sockaddr_un sunx, fromunix;
303 struct sockaddr_in sin, frominet;
305 char *p, *hname, line[MAXLINE + 1];
306 struct timeval tv, *tvp;
307 struct sigaction sact;
312 while ((ch = getopt(argc, argv, "a:dl:f:m:p:suv")) != -1)
314 case 'd': /* debug */
317 case 'a': /* allow specific network addresses only */
318 if (allowaddr(optarg) == -1)
321 case 'f': /* configuration file */
324 case 'm': /* mark interval */
325 MarkInterval = atoi(optarg) * 60;
330 case 's': /* no network mode */
334 if (nfunix < MAXFUNIX)
335 funixn[nfunix++] = optarg;
337 warnx("out of descriptors, ignoring %s",
340 case 'u': /* only log specified priority */
343 case 'v': /* log facility and priority */
350 if ((argc -= optind) != 0)
354 ppid = waitdaemon(0, 0, 30);
356 err(1, "could not become daemon");
363 consfile.f_type = F_CONSOLE;
364 (void)strcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1);
365 (void)gethostname(LocalHostName, sizeof(LocalHostName));
366 if ((p = strchr(LocalHostName, '.')) != NULL) {
371 (void)strcpy(bootfile, getbootfile());
372 (void)signal(SIGTERM, die);
373 (void)signal(SIGINT, Debug ? die : SIG_IGN);
374 (void)signal(SIGQUIT, Debug ? die : SIG_IGN);
376 * We don't want the SIGCHLD and SIGHUP handlers to interfere
377 * with each other; they are likely candidates for being called
378 * simultaneously (SIGHUP closes pipe descriptor, process dies,
382 sigaddset(&mask, SIGHUP);
383 sact.sa_handler = reapchild;
385 sact.sa_flags = SA_RESTART;
386 (void)sigaction(SIGCHLD, &sact, NULL);
387 (void)signal(SIGALRM, domark);
388 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
389 (void)alarm(TIMERINTVL);
391 TAILQ_INIT(&deadq_head);
394 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
396 for (i = 0; i < nfunix; i++) {
397 memset(&sunx, 0, sizeof(sunx));
398 sunx.sun_family = AF_UNIX;
399 (void)strncpy(sunx.sun_path, funixn[i], sizeof(sunx.sun_path));
400 funix[i] = socket(AF_UNIX, SOCK_DGRAM, 0);
402 bind(funix[i], (struct sockaddr *)&sunx,
403 SUN_LEN(&sunx)) < 0 ||
404 chmod(funixn[i], 0666) < 0) {
405 (void) snprintf(line, sizeof line,
406 "cannot create %s", funixn[i]);
408 dprintf("cannot create %s (%d)\n", funixn[i], errno);
414 finet = socket(AF_INET, SOCK_DGRAM, 0);
418 sp = getservbyname("syslog", "udp");
421 logerror("syslog/udp: unknown service");
424 memset(&sin, 0, sizeof(sin));
425 sin.sin_family = AF_INET;
426 sin.sin_port = LogPort = sp->s_port;
428 if (bind(finet, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
434 if (finet >= 0 && SecureMode) {
435 if (shutdown(finet, SHUT_RD) < 0) {
436 logerror("shutdown");
442 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
443 if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
446 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
448 /* tuck my process id away */
449 fp = fopen(PidFile, "w");
451 fprintf(fp, "%d\n", getpid());
455 dprintf("off & running....\n");
458 /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
460 sigaddset(&mask, SIGCHLD);
461 sact.sa_handler = init;
463 sact.sa_flags = SA_RESTART;
464 (void)sigaction(SIGHUP, &sact, NULL);
467 tv.tv_sec = tv.tv_usec = 0;
475 FD_SET(fklog, &readfds);
479 if (finet != -1 && !SecureMode) {
480 FD_SET(finet, &readfds);
484 for (i = 0; i < nfunix; i++) {
485 if (funix[i] != -1) {
486 FD_SET(funix[i], &readfds);
492 /*dprintf("readfds = %#x\n", readfds);*/
493 nfds = select(nfds+1, &readfds, (fd_set *)NULL,
494 (fd_set *)NULL, tvp);
508 /*dprintf("got a message (%d, %#x)\n", nfds, readfds);*/
509 if (fklog != -1 && FD_ISSET(fklog, &readfds))
511 if (finet != -1 && FD_ISSET(finet, &readfds)) {
512 len = sizeof(frominet);
513 l = recvfrom(finet, line, MAXLINE, 0,
514 (struct sockaddr *)&frominet, &len);
517 hname = cvthname(&frominet);
518 if (validate(&frominet, hname))
519 printline(hname, line);
520 } else if (l < 0 && errno != EINTR)
521 logerror("recvfrom inet");
523 for (i = 0; i < nfunix; i++) {
524 if (funix[i] != -1 && FD_ISSET(funix[i], &readfds)) {
525 len = sizeof(fromunix);
526 l = recvfrom(funix[i], line, MAXLINE, 0,
527 (struct sockaddr *)&fromunix, &len);
530 printline(LocalHostName, line);
531 } else if (l < 0 && errno != EINTR)
532 logerror("recvfrom unix");
542 fprintf(stderr, "%s\n%s\n%s\n",
543 "usage: syslogd [-dsuv] [-a allowed_peer] [-f config_file]",
544 " [-m mark_interval] [-p log_socket]",
550 * Take a raw input line, decode the message, and print the message
551 * on the appropriate log files.
554 printline(hname, msg)
559 char *p, *q, line[MAXLINE + 1];
561 /* test for special codes */
566 while (isdigit(*++p))
567 pri = 10 * pri + (*p - '0');
571 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
574 /* don't allow users to log kernel messages */
575 if (LOG_FAC(pri) == LOG_KERN)
576 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
580 while ((c = *p++ & 0177) != '\0' &&
581 q < &line[sizeof(line) - 1])
595 logmsg(pri, line, hname, 0);
599 * Read /dev/klog while data are available, split into lines.
604 char *p, *q, line[MAXLINE + 1];
609 i = read(fklog, line + len, MAXLINE - 1 - len);
611 line[i + len] = '\0';
612 else if (i < 0 && errno != EINTR && errno != EAGAIN) {
619 for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
624 if (len >= MAXLINE - 1) {
629 memmove(line, p, len + 1);
636 * Take a raw input line from /dev/klog, format similar to syslog().
644 flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
648 while (isdigit(*++p))
649 pri = 10 * pri + (*p - '0');
653 /* kernel printf's come out on console */
656 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
658 logmsg(pri, p, LocalHostName, flags);
664 * Log a message to the appropriate log files, users, etc. based on
668 logmsg(pri, msg, from, flags)
674 int i, fac, msglen, omask, prilev;
676 char prog[NAME_MAX+1];
679 dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
680 pri, flags, from, msg);
682 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
685 * Check to see if msg looks non-standard.
687 msglen = strlen(msg);
688 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
689 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
694 timestamp = ctime(&now) + 4;
701 /* skip leading blanks */
702 while(isspace(*msg)) {
707 /* extract facility and priority level */
709 fac = LOG_NFACILITIES;
712 prilev = LOG_PRI(pri);
714 /* extract program name */
715 for(i = 0; i < NAME_MAX; i++) {
722 /* add kernel prefix for kernel messages */
723 if (flags & ISKERNEL) {
724 snprintf(buf, sizeof(buf), "%s: %s", bootfile, msg);
726 msglen = strlen(buf);
729 /* log the message to the particular outputs */
732 f->f_file = open(ctty, O_WRONLY, 0);
734 if (f->f_file >= 0) {
735 fprintlog(f, flags, msg);
736 (void)close(f->f_file);
738 (void)sigsetmask(omask);
741 for (f = Files; f; f = f->f_next) {
742 /* skip messages that are incorrect priority */
743 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
744 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
745 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
747 || f->f_pmask[fac] == INTERNAL_NOPRI)
749 /* skip messages with the incorrect program name */
751 if(strcmp(prog, f->f_program) != 0)
754 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
757 /* don't output marks to recently written files */
758 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
762 * suppress duplicate lines to this file
764 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
765 !strcmp(msg, f->f_prevline) &&
766 !strcasecmp(from, f->f_prevhost)) {
767 (void)strncpy(f->f_lasttime, timestamp, 15);
769 dprintf("msg repeated %d times, %ld sec of %d\n",
770 f->f_prevcount, (long)(now - f->f_time),
771 repeatinterval[f->f_repeatcount]);
773 * If domark would have logged this by now,
774 * flush it now (so we don't hold isolated messages),
775 * but back off so we'll flush less often
778 if (now > REPEATTIME(f)) {
779 fprintlog(f, flags, (char *)NULL);
783 /* new line, save it */
785 fprintlog(f, 0, (char *)NULL);
786 f->f_repeatcount = 0;
788 (void)strncpy(f->f_lasttime, timestamp, 15);
789 (void)strncpy(f->f_prevhost, from,
790 sizeof(f->f_prevhost)-1);
791 f->f_prevhost[sizeof(f->f_prevhost)-1] = '\0';
792 if (msglen < MAXSVLINE) {
793 f->f_prevlen = msglen;
794 (void)strcpy(f->f_prevline, msg);
795 fprintlog(f, flags, (char *)NULL);
797 f->f_prevline[0] = 0;
799 fprintlog(f, flags, msg);
803 (void)sigsetmask(omask);
807 fprintlog(f, flags, msg)
815 char line[MAXLINE + 1], repbuf[80], greetings[200];
819 if (f->f_type == F_WALL) {
820 v->iov_base = greetings;
821 v->iov_len = snprintf(greetings, sizeof greetings,
822 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
823 f->f_prevhost, ctime(&now));
829 v->iov_base = f->f_lasttime;
838 static char fp_buf[30]; /* Hollow laugh */
839 int fac = f->f_prevpri & LOG_FACMASK;
840 int pri = LOG_PRI(f->f_prevpri);
842 char f_n[5]; /* Hollow laugh */
844 char p_n[5]; /* Hollow laugh */
849 for (c = facilitynames; c->c_name; c++) {
850 if (c->c_val == fac) {
855 for (c = prioritynames; c->c_name; c++) {
856 if (c->c_val == pri) {
863 snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
867 snprintf(p_n, sizeof p_n, "%d", pri);
870 snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
871 v->iov_base = fp_buf;
872 v->iov_len = strlen(fp_buf);
879 v->iov_base = f->f_prevhost;
880 v->iov_len = strlen(v->iov_base);
888 v->iov_len = strlen(msg);
889 } else if (f->f_prevcount > 1) {
890 v->iov_base = repbuf;
891 v->iov_len = sprintf(repbuf, "last message repeated %d times",
894 v->iov_base = f->f_prevline;
895 v->iov_len = f->f_prevlen;
899 dprintf("Logging to %s", TypeNames[f->f_type]);
908 dprintf(" %s\n", f->f_un.f_forw.f_hname);
909 /* check for local vs remote messages */
910 if (strcasecmp(f->f_prevhost, LocalHostName))
911 l = snprintf(line, sizeof line - 1,
912 "<%d>%.15s Forwarded from %s: %s",
913 f->f_prevpri, iov[0].iov_base, f->f_prevhost,
916 l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
917 f->f_prevpri, iov[0].iov_base, iov[5].iov_base);
921 (sendto(finet, line, l, 0,
922 (struct sockaddr *)&f->f_un.f_forw.f_addr,
923 sizeof(f->f_un.f_forw.f_addr)) != l)) {
925 (void)close(f->f_file);
926 f->f_type = F_UNUSED;
933 dprintf(" %s\n", f->f_un.f_fname);
936 if (writev(f->f_file, iov, 7) < 0) {
938 (void)close(f->f_file);
939 f->f_type = F_UNUSED;
941 logerror(f->f_un.f_fname);
942 } else if (flags & SYNC_FILE)
943 (void)fsync(f->f_file);
947 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
950 if (f->f_un.f_pipe.f_pid == 0) {
951 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
952 &f->f_un.f_pipe.f_pid)) < 0) {
953 f->f_type = F_UNUSED;
954 logerror(f->f_un.f_pipe.f_pname);
958 if (writev(f->f_file, iov, 7) < 0) {
960 (void)close(f->f_file);
961 if (f->f_un.f_pipe.f_pid > 0)
962 deadq_enter(f->f_un.f_pipe.f_pid,
963 f->f_un.f_pipe.f_pname);
964 f->f_un.f_pipe.f_pid = 0;
966 logerror(f->f_un.f_pipe.f_pname);
971 if (flags & IGN_CONS) {
972 dprintf(" (ignored)\n");
978 dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
979 v->iov_base = "\r\n";
982 errno = 0; /* ttymsg() only sometimes returns an errno */
983 if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
984 f->f_type = F_UNUSED;
992 v->iov_base = "\r\n";
1001 * WALLMSG -- Write a message to the world at large
1003 * Write the specified message to either the entire
1004 * world, or a list of approved users.
1011 static int reenter; /* avoid calling ourselves */
1016 char line[sizeof(ut.ut_line) + 1];
1020 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1021 logerror(_PATH_UTMP);
1026 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
1027 if (ut.ut_name[0] == '\0')
1029 strncpy(line, ut.ut_line, sizeof(ut.ut_line));
1030 line[sizeof(ut.ut_line)] = '\0';
1031 if (f->f_type == F_WALL) {
1032 if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
1033 errno = 0; /* already in msg */
1038 /* should we send the message to this user? */
1039 for (i = 0; i < MAXUNAMES; i++) {
1040 if (!f->f_un.f_uname[i][0])
1042 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
1044 if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
1046 errno = 0; /* already in msg */
1065 while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1067 /* Don't tell while we are initting. */
1070 /* First, look if it's a process from the dead queue. */
1071 if (deadq_remove(pid))
1074 /* Now, look in list of active processes. */
1075 for (f = Files; f; f = f->f_next)
1076 if (f->f_type == F_PIPE &&
1077 f->f_un.f_pipe.f_pid == pid) {
1078 (void)close(f->f_file);
1079 f->f_un.f_pipe.f_pid = 0;
1080 log_deadchild(pid, status,
1081 f->f_un.f_pipe.f_pname);
1090 * Return a printable representation of a host address.
1094 struct sockaddr_in *f;
1097 sigset_t omask, nmask;
1100 dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
1102 if (f->sin_family != AF_INET) {
1103 dprintf("Malformed from address\n");
1106 sigemptyset(&nmask);
1107 sigaddset(&nmask, SIGHUP);
1108 sigprocmask(SIG_BLOCK, &nmask, &omask);
1109 hp = gethostbyaddr((char *)&f->sin_addr,
1110 sizeof(struct in_addr), f->sin_family);
1111 sigprocmask(SIG_SETMASK, &omask, NULL);
1113 dprintf("Host name for your address (%s) unknown\n",
1114 inet_ntoa(f->sin_addr));
1115 return (inet_ntoa(f->sin_addr));
1117 if ((p = strchr(hp->h_name, '.')) &&
1118 strcasecmp(p + 1, LocalDomain) == 0)
1120 return (hp->h_name);
1130 now = time((time_t *)NULL);
1131 MarkSeq += TIMERINTVL;
1132 if (MarkSeq >= MarkInterval) {
1133 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1137 for (f = Files; f; f = f->f_next) {
1138 if (f->f_prevcount && now >= REPEATTIME(f)) {
1139 dprintf("flush %s: repeated %d times, %d sec.\n",
1140 TypeNames[f->f_type], f->f_prevcount,
1141 repeatinterval[f->f_repeatcount]);
1142 fprintlog(f, 0, (char *)NULL);
1147 /* Walk the dead queue, and see if we should signal somebody. */
1148 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1149 switch (q->dq_timeout) {
1151 /* Already signalled once, try harder now. */
1152 if (kill(q->dq_pid, SIGKILL) != 0)
1153 (void)deadq_remove(q->dq_pid);
1158 * Timed out on dead queue, send terminate
1159 * signal. Note that we leave the removal
1160 * from the dead queue to reapchild(), which
1161 * will also log the event (unless the process
1162 * didn't even really exist, in case we simply
1163 * drop it from the dead queue).
1165 if (kill(q->dq_pid, SIGTERM) != 0)
1166 (void)deadq_remove(q->dq_pid);
1173 (void)alarm(TIMERINTVL);
1177 * Print syslogd errors some place.
1187 sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1189 (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1191 dprintf("%s\n", buf);
1192 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1200 int was_initialized;
1204 was_initialized = Initialized;
1205 Initialized = 0; /* Don't log SIGCHLDs. */
1206 for (f = Files; f != NULL; f = f->f_next) {
1207 /* flush any pending output */
1209 fprintlog(f, 0, (char *)NULL);
1210 if (f->f_type == F_PIPE)
1211 (void)close(f->f_file);
1213 Initialized = was_initialized;
1215 dprintf("syslogd: exiting on signal %d\n", signo);
1216 (void)sprintf(buf, "exiting on signal %d", signo);
1220 for (i = 0; i < nfunix; i++)
1221 if (funixn[i] && funix[i] != -1)
1222 (void)unlink(funixn[i]);
1227 * INIT -- Initialize syslogd from configuration table
1235 struct filed *f, *next, **nextp;
1237 char cline[LINE_MAX];
1238 char prog[NAME_MAX+1];
1243 * Close all open log files.
1246 for (f = Files; f != NULL; f = next) {
1247 /* flush any pending output */
1249 fprintlog(f, 0, (char *)NULL);
1251 switch (f->f_type) {
1256 (void)close(f->f_file);
1259 (void)close(f->f_file);
1260 if (f->f_un.f_pipe.f_pid > 0)
1261 deadq_enter(f->f_un.f_pipe.f_pid,
1262 f->f_un.f_pipe.f_pname);
1263 f->f_un.f_pipe.f_pid = 0;
1267 if(f->f_program) free(f->f_program);
1273 /* open the configuration file */
1274 if ((cf = fopen(ConfFile, "r")) == NULL) {
1275 dprintf("cannot open %s\n", ConfFile);
1276 *nextp = (struct filed *)calloc(1, sizeof(*f));
1277 cfline("*.ERR\t/dev/console", *nextp, "*");
1278 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1279 cfline("*.PANIC\t*", (*nextp)->f_next, "*");
1285 * Foreach line in the conf table, open that file.
1289 while (fgets(cline, sizeof(cline), cf) != NULL) {
1291 * check for end-of-section, comments, strip off trailing
1292 * spaces and newline character. #!prog is treated specially:
1293 * following lines apply only to that program.
1295 for (p = cline; isspace(*p); ++p)
1306 while(isspace(*p)) p++;
1307 if((!*p) || (*p == '*')) {
1311 for(i = 0; i < NAME_MAX; i++) {
1319 for (p = strchr(cline, '\0'); isspace(*--p);)
1322 f = (struct filed *)calloc(1, sizeof(*f));
1325 cfline(cline, f, prog);
1328 /* close the configuration file */
1334 for (f = Files; f; f = f->f_next) {
1335 for (i = 0; i <= LOG_NFACILITIES; i++)
1336 if (f->f_pmask[i] == INTERNAL_NOPRI)
1339 printf("%d ", f->f_pmask[i]);
1340 printf("%s: ", TypeNames[f->f_type]);
1341 switch (f->f_type) {
1343 printf("%s", f->f_un.f_fname);
1348 printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1352 printf("%s", f->f_un.f_forw.f_hname);
1356 printf("%s", f->f_un.f_pipe.f_pname);
1360 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1361 printf("%s, ", f->f_un.f_uname[i]);
1365 printf(" (%s)", f->f_program);
1371 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1372 dprintf("syslogd: restarted\n");
1376 * Crack a configuration file line
1379 cfline(line, f, prog)
1387 char buf[MAXLINE], ebuf[100];
1389 dprintf("cfline(\"%s\", f, \"%s\")\n", line, prog);
1391 errno = 0; /* keep strerror() stuff out of logerror messages */
1393 /* clear out file entry */
1394 memset(f, 0, sizeof(*f));
1395 for (i = 0; i <= LOG_NFACILITIES; i++)
1396 f->f_pmask[i] = INTERNAL_NOPRI;
1398 /* save program name if any */
1399 if(prog && *prog=='*') prog = NULL;
1401 f->f_program = calloc(1, strlen(prog)+1);
1403 strcpy(f->f_program, prog);
1407 /* scan through the list of selectors */
1408 for (p = line; *p && *p != '\t' && *p != ' ';) {
1412 /* find the end of this facility name list */
1413 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1416 /* get the priority comparison */
1439 pri_cmp = (UniquePriority)
1444 /* collect priority name */
1445 for (bp = buf; *q && !strchr("\t,; ", *q); )
1450 while (strchr(",;", *q))
1453 /* decode priority name */
1455 pri = LOG_PRIMASK + 1;
1457 pri = decode(buf, prioritynames);
1459 (void)snprintf(ebuf, sizeof ebuf,
1460 "unknown priority name \"%s\"", buf);
1466 /* scan facilities */
1467 while (*p && !strchr("\t.; ", *p)) {
1468 for (bp = buf; *p && !strchr("\t,;. ", *p); )
1473 for (i = 0; i < LOG_NFACILITIES; i++) {
1474 f->f_pmask[i] = pri;
1475 f->f_pcmp[i] = pri_cmp;
1478 i = decode(buf, facilitynames);
1480 (void)snprintf(ebuf, sizeof ebuf,
1481 "unknown facility name \"%s\"",
1486 f->f_pmask[i >> 3] = pri;
1487 f->f_pcmp[i >> 3] = pri_cmp;
1489 while (*p == ',' || *p == ' ')
1496 /* skip to action part */
1497 while (*p == '\t' || *p == ' ')
1503 (void)strncpy(f->f_un.f_forw.f_hname, ++p,
1504 sizeof(f->f_un.f_forw.f_hname)-1);
1505 f->f_un.f_forw.f_hname[sizeof(f->f_un.f_forw.f_hname)-1] = '\0';
1506 hp = gethostbyname(f->f_un.f_forw.f_hname);
1510 logerror(hstrerror(h_errno));
1513 memset(&f->f_un.f_forw.f_addr, 0,
1514 sizeof(f->f_un.f_forw.f_addr));
1515 f->f_un.f_forw.f_addr.sin_family = AF_INET;
1516 f->f_un.f_forw.f_addr.sin_port = LogPort;
1517 memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1522 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1523 f->f_type = F_UNUSED;
1527 if (isatty(f->f_file)) {
1528 if (strcmp(p, ctty) == 0)
1529 f->f_type = F_CONSOLE;
1532 (void)strcpy(f->f_un.f_fname, p + sizeof _PATH_DEV - 1);
1534 (void)strcpy(f->f_un.f_fname, p);
1540 f->f_un.f_pipe.f_pid = 0;
1541 (void)strcpy(f->f_un.f_pipe.f_pname, p + 1);
1550 for (i = 0; i < MAXUNAMES && *p; i++) {
1551 for (q = p; *q && *q != ','; )
1553 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1554 if ((q - p) > UT_NAMESIZE)
1555 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1557 f->f_un.f_uname[i][q - p] = '\0';
1558 while (*q == ',' || *q == ' ')
1562 f->f_type = F_USERS;
1569 * Decode a symbolic name to a numeric value
1572 decode(name, codetab)
1580 return (atoi(name));
1582 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1584 *p = tolower(*name);
1589 for (c = codetab; c->c_name; c++)
1590 if (!strcmp(buf, c->c_name))
1597 * fork off and become a daemon, but wait for the child to come online
1598 * before returing to the parent, or we get disk thrashing at boot etc.
1599 * Set a timer so we don't hang forever if it wedges.
1602 waitdaemon(nochdir, noclose, maxwait)
1603 int nochdir, noclose, maxwait;
1607 pid_t pid, childpid;
1609 switch (childpid = fork()) {
1615 signal(SIGALRM, timedout);
1617 while ((pid = wait3(&status, 0, NULL)) != -1) {
1618 if (WIFEXITED(status))
1619 errx(1, "child pid %d exited with return code %d",
1620 pid, WEXITSTATUS(status));
1621 if (WIFSIGNALED(status))
1622 errx(1, "child pid %d exited on signal %d%s",
1623 pid, WTERMSIG(status),
1624 WCOREDUMP(status) ? " (core dumped)" :
1626 if (pid == childpid) /* it's gone... */
1638 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1639 (void)dup2(fd, STDIN_FILENO);
1640 (void)dup2(fd, STDOUT_FILENO);
1641 (void)dup2(fd, STDERR_FILENO);
1649 * We get a SIGALRM from the child when it's running and finished doing it's
1650 * fsync()'s or O_SYNC writes for all the boot messages.
1652 * We also get a signal from the kernel if the timer expires, so check to
1653 * see what happened.
1661 signal(SIGALRM, SIG_DFL);
1663 errx(1, "timed out waiting for child");
1669 * Add `s' to the list of allowable peer addresses to accept messages
1672 * `s' is a string in the form:
1674 * [*]domainname[:{servicename|portnumber|*}]
1678 * netaddr/maskbits[:{servicename|portnumber|*}]
1680 * Returns -1 on error, 0 if the argument was valid.
1687 struct allowedpeer ap;
1692 if ((cp1 = strrchr(s, ':'))) {
1693 /* service/port provided */
1695 if (strlen(cp1) == 1 && *cp1 == '*')
1696 /* any port allowed */
1698 else if ((se = getservbyname(cp1, "udp")))
1699 ap.port = se->s_port;
1701 ap.port = htons((int)strtol(cp1, &cp2, 0));
1703 return -1; /* port not numeric */
1706 if ((se = getservbyname("syslog", "udp")))
1707 ap.port = se->s_port;
1709 /* sanity, should not happen */
1710 ap.port = htons(514);
1713 /* the regexp's are ugly, but the cleanest way */
1715 if (regcomp(&re, "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+(/[0-9]+)?$",
1717 /* if RE compilation fails, that's an internal error */
1719 if (regexec(&re, s, 0, 0, 0) == 0) {
1720 /* arg `s' is numeric */
1722 if ((cp1 = strchr(s, '/')) != NULL) {
1725 if (i < 0 || i > 32)
1727 /* convert masklen to netmask */
1728 ap.a_mask.s_addr = htonl(~((1 << (32 - i)) - 1));
1730 if (ascii2addr(AF_INET, s, &ap.a_addr) == -1)
1733 /* use default netmask */
1734 if (IN_CLASSA(ntohl(ap.a_addr.s_addr)))
1735 ap.a_mask.s_addr = htonl(IN_CLASSA_NET);
1736 else if (IN_CLASSB(ntohl(ap.a_addr.s_addr)))
1737 ap.a_mask.s_addr = htonl(IN_CLASSB_NET);
1739 ap.a_mask.s_addr = htonl(IN_CLASSC_NET);
1742 /* arg `s' is domain name */
1749 printf("allowaddr: rule %d: ", NumAllowed);
1751 printf("numeric, ");
1752 printf("addr = %s, ",
1753 addr2ascii(AF_INET, &ap.a_addr, sizeof(struct in_addr), 0));
1754 printf("mask = %s; ",
1755 addr2ascii(AF_INET, &ap.a_mask, sizeof(struct in_addr), 0));
1757 printf("domainname = %s; ", ap.a_name);
1758 printf("port = %d\n", ntohs(ap.port));
1761 if ((AllowedPeers = realloc(AllowedPeers,
1762 ++NumAllowed * sizeof(struct allowedpeer)))
1764 fprintf(stderr, "Out of memory!\n");
1767 memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
1772 * Validate that the remote peer has permission to log to us.
1775 validate(sin, hname)
1776 struct sockaddr_in *sin;
1781 char *cp, name[MAXHOSTNAMELEN];
1782 struct allowedpeer *ap;
1784 if (NumAllowed == 0)
1785 /* traditional behaviour, allow everything */
1788 strncpy(name, hname, sizeof name);
1789 if (strchr(name, '.') == NULL) {
1790 strncat(name, ".", sizeof name - strlen(name) - 1);
1791 strncat(name, LocalDomain, sizeof name - strlen(name) - 1);
1793 dprintf("validate: dgram from IP %s, port %d, name %s;\n",
1794 addr2ascii(AF_INET, &sin->sin_addr, sizeof(struct in_addr), 0),
1795 ntohs(sin->sin_port), name);
1797 /* now, walk down the list */
1798 for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
1799 if (ntohs(ap->port) != 0 && ap->port != sin->sin_port) {
1800 dprintf("rejected in rule %d due to port mismatch.\n", i);
1804 if (ap->isnumeric) {
1805 if ((sin->sin_addr.s_addr & ap->a_mask.s_addr)
1806 != ap->a_addr.s_addr) {
1807 dprintf("rejected in rule %d due to IP mismatch.\n", i);
1814 /* allow wildmatch */
1817 if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
1818 dprintf("rejected in rule %d due to name mismatch.\n", i);
1824 if (l2 != l1 || memcmp(cp, name, l1) != 0) {
1825 dprintf("rejected in rule %d due to name mismatch.\n", i);
1830 dprintf("accepted in rule %d.\n", i);
1831 return 1; /* hooray! */
1837 * Fairly similar to popen(3), but returns an open descriptor, as
1838 * opposed to a FILE *.
1845 int pfd[2], nulldesc, i;
1846 sigset_t omask, mask;
1847 char *argv[4]; /* sh -c cmd NULL */
1850 if (pipe(pfd) == -1)
1852 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
1853 /* we are royally screwed anyway */
1857 sigaddset(&mask, SIGALRM);
1858 sigaddset(&mask, SIGHUP);
1859 sigprocmask(SIG_BLOCK, &mask, &omask);
1860 switch ((*pid = fork())) {
1862 sigprocmask(SIG_SETMASK, &omask, 0);
1873 (void)setsid(); /* Avoid catching SIGHUPs. */
1876 * Throw away pending signals, and reset signal
1877 * behaviour to standard values.
1879 signal(SIGALRM, SIG_IGN);
1880 signal(SIGHUP, SIG_IGN);
1881 sigprocmask(SIG_SETMASK, &omask, 0);
1882 signal(SIGPIPE, SIG_DFL);
1883 signal(SIGQUIT, SIG_DFL);
1884 signal(SIGALRM, SIG_DFL);
1885 signal(SIGHUP, SIG_DFL);
1887 dup2(pfd[0], STDIN_FILENO);
1888 dup2(nulldesc, STDOUT_FILENO);
1889 dup2(nulldesc, STDERR_FILENO);
1890 for (i = getdtablesize(); i > 2; i--)
1893 (void) execvp(_PATH_BSHELL, argv);
1897 sigprocmask(SIG_SETMASK, &omask, 0);
1901 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
1902 * supposed to get an EWOULDBLOCK on writev(2), which is
1903 * caught by the logic above anyway, which will in turn close
1904 * the pipe, and fork a new logging subprocess if necessary.
1905 * The stale subprocess will be killed some time later unless
1906 * it terminated itself due to closing its input pipe (so we
1907 * get rid of really dead puppies).
1909 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
1911 (void)snprintf(errmsg, sizeof errmsg,
1912 "Warning: cannot change pipe to PID %d to "
1913 "non-blocking behaviour.",
1921 deadq_enter(pid, name)
1929 * Be paranoid, if we can't signal the process, don't enter it
1930 * into the dead queue (perhaps it's already dead). If possible,
1931 * we try to fetch and log the child's status.
1933 if (kill(pid, 0) != 0) {
1934 if (waitpid(pid, &status, WNOHANG) > 0)
1935 log_deadchild(pid, status, name);
1939 p = malloc(sizeof(struct deadq_entry));
1942 logerror("panic: out of virtual memory!");
1947 p->dq_timeout = DQ_TIMO_INIT;
1948 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
1957 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1958 if (q->dq_pid == pid) {
1959 TAILQ_REMOVE(&deadq_head, q, dq_entries);
1968 log_deadchild(pid, status, name)
1977 errno = 0; /* Keep strerror() stuff out of logerror messages. */
1978 if (WIFSIGNALED(status)) {
1979 reason = "due to signal";
1980 code = WTERMSIG(status);
1982 reason = "with status";
1983 code = WEXITSTATUS(status);
1987 (void)snprintf(buf, sizeof buf,
1988 "Logging subprocess %d (%s) exited %s %d.",
1989 pid, name, reason, code);