syslogd and klogd work now.
[oweals/busybox.git] / syslogd.c
1 /*
2  * Mini syslogd implementation for busybox
3  *
4  * Copyright (C) 1999 by Lineo, inc.
5  * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 #include "internal.h"
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <sys/socket.h>
27 #include <sys/un.h>
28 #include <unistd.h>
29 #include <time.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <ctype.h>
35 #include <netdb.h>
36 #include <sys/klog.h>
37 #include <errno.h>
38 #include <paths.h>
39
40 #define ksyslog klogctl
41 extern int ksyslog(int type, char *buf, int len);
42
43
44 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
45 #define SYSLOG_NAMES
46 #include <sys/syslog.h>
47
48 /* Path for the file where all log messages are written */
49 #define __LOG_FILE              "/var/log/messages"
50
51
52 static char* logFilePath = __LOG_FILE;
53 /* interval between marks in seconds */
54 static int MarkInterval = 20*60;
55 /* localhost's name */
56 static char LocalHostName[32];
57
58 static const char syslogd_usage[] =
59     "syslogd [OPTION]...\n\n"
60     "Linux system logging utility.\n\n"
61     "Options:\n"
62     "\t-m\tChange the mark timestamp interval. default=20min. 0=off\n"
63     "\t-n\tDo not fork into the background (for when run by init)\n"
64     "\t-O\tSpecify an alternate log file.  default=/var/log/messages\n";
65
66 static int kmsg;
67
68 /* try to open up the specified device */
69 static int device_open(char *device, int mode)
70 {
71     int m, f, fd = -1;
72
73     m = mode | O_NONBLOCK;
74
75     /* Retry up to 5 times */
76     for (f = 0; f < 5; f++)
77         if ((fd = open(device, m)) >= 0)
78             break;
79     if (fd < 0)
80         return fd;
81     /* Reset original flags. */
82     if (m != mode)
83         fcntl(fd, F_SETFL, mode);
84     return fd;
85 }
86
87 /* print a message to the log file */
88 static void message(char *fmt, ...)
89 {
90     int fd;
91     va_list arguments;
92
93     if ((fd = device_open(logFilePath, O_WRONLY|O_CREAT|O_NOCTTY|O_APPEND|O_NONBLOCK)) >= 0) {
94         va_start(arguments, fmt);
95         vdprintf(fd, fmt, arguments);
96         va_end(arguments);
97         close(fd);
98     } else {
99         /* Always send console messages to /dev/console so people will see them. */
100         if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NONBLOCK)) >= 0) {
101             va_start(arguments, fmt);
102             vdprintf(fd, fmt, arguments);
103             va_end(arguments);
104             close(fd);
105         } else {
106             fprintf(stderr, "Bummer, can't print: ");
107             va_start(arguments, fmt);
108             vfprintf(stderr, fmt, arguments);
109             fflush(stderr);
110             va_end(arguments);
111         }
112     }
113 }
114
115 static void logMessage( int pri, char* msg) 
116 {
117     time_t  now;
118     char *timestamp;
119     static char res[20];
120     CODE *c_pri, *c_fac;
121
122     for (c_fac=facilitynames; c_fac->c_name && !(c_fac->c_val==LOG_FAC(pri)<<3); c_fac++);
123     for (c_pri=prioritynames; c_pri->c_name && !(c_pri->c_val==LOG_PRI(pri)); c_pri++);
124     if (*c_fac->c_name=='\0' || *c_pri->c_name=='\0')
125         snprintf (res, sizeof(res), "<%d>", pri);
126     else
127         snprintf (res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
128
129     if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' || 
130             msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') 
131     {
132         time(&now);
133         timestamp = ctime(&now) + 4;
134         timestamp[15] = '\0';
135     } else {
136         timestamp = msg;
137         timestamp[15] = '\0';
138         msg += 16;
139     }
140
141     /* todo: supress duplicates */
142
143     /* now spew out the message to wherever it is supposed to go */
144     message( "%s %s %s %s\n", timestamp, LocalHostName, res, msg);
145 }
146
147 static void quit_signal(int sig)
148 {
149     logMessage(LOG_SYSLOG|LOG_INFO, "System log daemon exiting.");
150     unlink( _PATH_LOG);
151     exit( TRUE);
152 }
153
154 static void restart_signal(int sig)
155 {
156     /* pretend to restart */
157     logMessage(LOG_SYSLOG|LOG_INFO, "syslogd restarting");
158 }
159
160 static void domark(int sig)
161 {
162     if (MarkInterval > 0) {
163         logMessage(LOG_SYSLOG|LOG_INFO, "-- MARK --");
164         signal(SIGALRM, domark);
165         alarm(MarkInterval);
166     }
167 }
168
169 static void doSyslogd(void)
170 {
171     struct sockaddr_un sunx;
172     int fd, conn;
173     size_t addrLength;
174     char buf[1024];
175     char *q, *p = buf;
176     int readSize;
177
178     /* Remove any preexisting socket/file */
179     unlink(_PATH_LOG);
180
181     /* Set up sig handlers */
182     signal(SIGINT,  quit_signal);
183     signal(SIGTERM, quit_signal);
184     signal(SIGQUIT, quit_signal);
185     signal(SIGHUP,  restart_signal);
186     signal(SIGALRM, domark);
187     alarm(MarkInterval);
188
189
190     unlink( _PATH_LOG);
191     memset(&sunx, 0, sizeof(sunx));
192     sunx.sun_family = AF_UNIX;  /* Unix domain socket */
193     strncpy(sunx.sun_path, _PATH_LOG, sizeof(sunx.sun_path));
194     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 ) {
195         perror("Couldn't obtain descriptor for socket " _PATH_LOG);
196         exit( FALSE);
197     }
198
199     addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
200     if ( (bind(fd, (struct sockaddr *) &sunx, addrLength)) ||
201             (fchmod(fd, 0666) < 0) || (listen(fd, 5)) ) 
202     {
203         perror("Could not connect to socket " _PATH_LOG);
204         exit( FALSE);
205     }
206     
207     
208     logMessage(LOG_SYSLOG|LOG_INFO, "syslogd started: "
209             "BusyBox v" BB_VER " (" BB_BT ")");
210
211
212     while ((conn = accept(fd, (struct sockaddr *) &sunx, 
213                           &addrLength)) >= 0) 
214     {
215         while ((readSize=read(conn, buf, sizeof(buf))) > 0)
216         {
217             char line[1025];
218             unsigned char c;
219             int pri = (LOG_USER|LOG_NOTICE);
220
221             memset (line, 0, sizeof(line));
222             p = buf;
223             q = line;
224             while ( p && (c = *p) && q < &line[sizeof(line) - 1]) {
225                 if (c == '<') {
226                     /* Parse the magic priority number */
227                     pri = 0;
228                     while (isdigit(*(++p))) {
229                         pri = 10 * pri + (*p - '0');
230                     }
231                     if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
232                         pri = (LOG_USER|LOG_NOTICE);
233                 } else if (c == '\n') {
234                     *q++ = ' ';
235                 } else if (iscntrl(c)&&(c<0177)) {
236                     *q++ = '^';
237                     *q++ = c ^ 0100;
238                 } else {
239                     *q++ = c;
240                 }
241                 p++;
242             }
243             *q = '\0';
244
245             /* Now log it */
246             logMessage( pri, line);
247         }
248         close(conn);
249     }
250
251     close(fd);
252 }
253
254 static void klogd_signal(int sig)
255 {
256     //ksyslog(7, NULL, 0);
257     //ksyslog(0, 0, 0);
258     logMessage(LOG_SYSLOG|LOG_INFO, "Kernel log daemon exiting.");
259     close( kmsg);
260     exit( TRUE);
261 }
262
263
264 static void doKlogd(void)
265 {
266     int priority=LOG_INFO;
267     struct stat sb;
268     char log_buffer[4096];
269     char *logp;
270
271     /* Set up sig handlers */
272     signal(SIGINT,  klogd_signal);
273     signal(SIGKILL, klogd_signal);
274     signal(SIGTERM, klogd_signal);
275     signal(SIGHUP,  klogd_signal);
276     logMessage(LOG_SYSLOG|LOG_INFO, "klogd started: "
277             "BusyBox v" BB_VER " (" BB_BT ")");
278
279     ksyslog(1, NULL, 0);
280     if ( ((stat(_PATH_KLOG, &sb) < 0) && (errno == ENOENT)) ||
281             ( (kmsg = open(_PATH_KLOG, O_RDONLY)) < 0 ) ) {
282         char message[80];
283         snprintf(message, 79, "klogd: Cannot open %s, " \
284                 "%d - %s.\n", _PATH_KLOG, errno, strerror(errno));
285         logMessage(LOG_SYSLOG|LOG_ERR, message);
286         klogd_signal(0);
287     }
288     while (1) {
289         memset(log_buffer, '\0', sizeof(log_buffer));
290         if ( read(kmsg, log_buffer, sizeof(log_buffer)-1) < 0 ) {
291             char message[80];
292             if ( errno == EINTR )
293                 continue;
294             snprintf(message, 79, "klogd: Cannot read proc file system: %d - %s.\n", 
295                     errno, strerror(errno));
296             logMessage(LOG_SYSLOG|LOG_ERR, message);
297             klogd_signal(0);
298         }
299 #if 0
300         if ( ksyslog(2, log_buffer, sizeof(log_buffer)) < 0 ) {
301             char message[80];
302             if ( errno == EINTR )
303                 continue;
304             snprintf(message, 79, "klogd: Error return from sys_sycall: " \
305                     "%d - %s.\n", errno, strerror(errno));
306             logMessage(LOG_SYSLOG|LOG_ERR, message);
307             exit(1);
308         }
309 #endif
310         logp=log_buffer;
311         if ( *log_buffer == '<' )
312         {
313             switch ( *(log_buffer+1) )
314             {
315                 case '0':
316                     priority = LOG_EMERG;
317                     break;
318                 case '1':
319                     priority = LOG_ALERT;
320                     break;
321                 case '2':
322                     priority = LOG_CRIT;
323                     break;
324                 case '3':
325                     priority = LOG_ERR;
326                     break;
327                 case '4':
328                     priority = LOG_WARNING;
329                     break;
330                 case '5':
331                     priority = LOG_NOTICE;
332                     break;
333                 case '6':
334                     priority = LOG_INFO;
335                     break;
336                 case '7':
337                 default:
338                     priority = LOG_DEBUG;
339             }
340             logp+=3;
341         }
342         logMessage(LOG_KERN|priority, logp);
343     }
344
345 }
346
347
348 extern int syslogd_main(int argc, char **argv)
349 {
350     int pid, klogd_pid;
351     int doFork = TRUE;
352     char *p;
353     char **argv1=argv;
354     
355     while (--argc > 0 && **(++argv1) == '-') {
356         while (*(++(*argv1))) {
357             switch (**argv1) {
358             case 'm':
359                 if (--argc == 0) {
360                     usage(syslogd_usage);
361                 }
362                 MarkInterval = atoi(*(++argv1))*60;
363                 break;
364             case 'n':
365                 doFork = FALSE;
366                 break;
367             case 'O':
368                 if (--argc == 0) {
369                     usage(syslogd_usage);
370                 }
371                 logFilePath = *(++argv1);
372                 break;
373             default:
374                 usage(syslogd_usage);
375             }
376         }
377     }
378     
379     /* Store away localhost's name before the fork */
380     gethostname(LocalHostName, sizeof(LocalHostName));
381     if ( (p = strchr(LocalHostName, '.')) ) {
382         *p++ = '\0';
383     }
384
385     if (doFork == TRUE) {
386         pid = fork();
387         if ( pid < 0 )
388             exit( pid);
389         else if ( pid == 0 ) {
390             strncpy(argv[0], "syslogd",strlen(argv[0]));
391             doSyslogd();
392         }
393     } else {
394         doSyslogd();
395     }
396
397     /* Start up the klogd process */
398     klogd_pid = fork();
399     if (klogd_pid == 0 ) {
400             strncpy(argv[0], "klogd", strlen(argv[0]));
401             doKlogd();
402     }
403
404     exit( TRUE);
405 }
406
407