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