c48d5a435e55031a474c142d26f35aab418a3399
[oweals/busybox.git] / sysklogd / 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 and kernel (provides klogd) logging utility.\n"
61     "Note that this version of syslogd/klogd ignores /etc/syslog.conf.\n\n"
62     "Options:\n"
63     "\t-m\tChange the mark timestamp interval. default=20min. 0=off\n"
64     "\t-n\tDo not fork into the background (for when run by init)\n"
65 #ifdef BB_KLOGD
66     "\t-K\tDo not start up the klogd process (by default syslogd spawns klogd).\n"
67 #endif
68     "\t-O\tSpecify an alternate log file.  default=/var/log/messages\n";
69
70
71 /* print a message to the log file */
72 static void message(char *fmt, ...)
73 {
74     int fd;
75     va_list arguments;
76
77     if ((fd = device_open(logFilePath, O_WRONLY|O_CREAT|O_NOCTTY|O_APPEND|O_NONBLOCK)) >= 0) {
78         va_start(arguments, fmt);
79         vdprintf(fd, fmt, arguments);
80         va_end(arguments);
81         close(fd);
82     } else {
83         /* Always send console messages to /dev/console so people will see them. */
84         if ((fd = device_open(_PATH_CONSOLE, O_WRONLY|O_NOCTTY|O_NONBLOCK)) >= 0) {
85             va_start(arguments, fmt);
86             vdprintf(fd, fmt, arguments);
87             va_end(arguments);
88             close(fd);
89         } else {
90             fprintf(stderr, "Bummer, can't print: ");
91             va_start(arguments, fmt);
92             vfprintf(stderr, fmt, arguments);
93             fflush(stderr);
94             va_end(arguments);
95         }
96     }
97 }
98
99 static void logMessage( int pri, char* msg) 
100 {
101     time_t  now;
102     char *timestamp;
103     static char res[20];
104     CODE *c_pri, *c_fac;
105
106     for (c_fac=facilitynames; c_fac->c_name && !(c_fac->c_val==LOG_FAC(pri)<<3); c_fac++);
107     for (c_pri=prioritynames; c_pri->c_name && !(c_pri->c_val==LOG_PRI(pri)); c_pri++);
108     if (*c_fac->c_name=='\0' || *c_pri->c_name=='\0')
109         snprintf (res, sizeof(res), "<%d>", pri);
110     else
111         snprintf (res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
112
113     if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' || 
114             msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') 
115     {
116         time(&now);
117         timestamp = ctime(&now) + 4;
118         timestamp[15] = '\0';
119     } else {
120         timestamp = msg;
121         timestamp[15] = '\0';
122         msg += 16;
123     }
124
125     /* todo: supress duplicates */
126
127     /* now spew out the message to wherever it is supposed to go */
128     message( "%s %s %s %s\n", timestamp, LocalHostName, res, msg);
129 }
130
131 static void quit_signal(int sig)
132 {
133     logMessage(LOG_SYSLOG|LOG_INFO, "System log daemon exiting.");
134     unlink( _PATH_LOG);
135     exit( TRUE);
136 }
137
138 static void restart_signal(int sig)
139 {
140     /* pretend to restart */
141     logMessage(LOG_SYSLOG|LOG_INFO, "syslogd restarting");
142 }
143
144 static void domark(int sig)
145 {
146     if (MarkInterval > 0) {
147         logMessage(LOG_SYSLOG|LOG_INFO, "-- MARK --");
148         alarm(MarkInterval);
149     }
150 }
151
152 static void doSyslogd(void)
153 {
154     struct sockaddr_un sunx;
155     int fd, conn;
156     size_t addrLength;
157     char buf[1024];
158     char *q, *p = buf;
159     int readSize;
160
161     /* Set up sig handlers */
162     signal(SIGINT,  quit_signal);
163     signal(SIGTERM, quit_signal);
164     signal(SIGQUIT, quit_signal);
165     signal(SIGHUP,  restart_signal);
166     signal(SIGALRM, domark);
167     alarm(MarkInterval);
168
169     /* Remove any preexisting socket/file */
170     unlink(_PATH_LOG);
171
172     memset(&sunx, 0, sizeof(sunx));
173     sunx.sun_family = AF_UNIX;  /* Unix domain socket */
174     strncpy(sunx.sun_path, _PATH_LOG, sizeof(sunx.sun_path));
175     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 ) {
176         perror("Couldn't obtain descriptor for socket " _PATH_LOG);
177         exit( FALSE);
178     }
179
180     addrLength = sizeof(sunx.sun_family) + strlen(sunx.sun_path);
181     if ( (bind(fd, (struct sockaddr *) &sunx, addrLength)) ||
182             (listen(fd, 5)) ) 
183     {
184         perror("Could not connect to socket " _PATH_LOG);
185         exit( FALSE);
186     }
187     
188     umask(0);
189     if (chmod(_PATH_LOG, 0666) < 0) {
190         perror("Could not set permission on " _PATH_LOG);
191         exit (FALSE);
192     }
193     
194     logMessage(LOG_SYSLOG|LOG_INFO, "syslogd started: "
195             "BusyBox v" BB_VER " (" BB_BT ")");
196
197
198     while ((conn = accept(fd, (struct sockaddr *) &sunx, 
199                           &addrLength)) >= 0) 
200     {
201         while ((readSize=read(conn, buf, sizeof(buf))) > 0)
202         {
203             char line[1025];
204             unsigned char c;
205             int pri = (LOG_USER|LOG_NOTICE);
206
207             memset (line, 0, sizeof(line));
208             p = buf;
209             q = line;
210             while ( p && (c = *p) && q < &line[sizeof(line) - 1]) {
211                 if (c == '<') {
212                     /* Parse the magic priority number */
213                     pri = 0;
214                     while (isdigit(*(++p))) {
215                         pri = 10 * pri + (*p - '0');
216                     }
217                     if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
218                         pri = (LOG_USER|LOG_NOTICE);
219                 } else if (c == '\n') {
220                     *q++ = ' ';
221                 } else if (iscntrl(c)&&(c<0177)) {
222                     *q++ = '^';
223                     *q++ = c ^ 0100;
224                 } else {
225                     *q++ = c;
226                 }
227                 p++;
228             }
229             *q = '\0';
230
231             /* Now log it */
232             logMessage( pri, line);
233         }
234         close(conn);
235     }
236
237     close(fd);
238 }
239
240 #ifdef BB_KLOGD
241
242 static void klogd_signal(int sig)
243 {
244     ksyslog(7, NULL, 0);
245     ksyslog(0, 0, 0);
246     logMessage(LOG_SYSLOG|LOG_INFO, "Kernel log daemon exiting.");
247     exit( TRUE);
248 }
249
250 static void doKlogd(void)
251 {
252     int priority=LOG_INFO;
253     char log_buffer[4096];
254     char *logp;
255
256     /* Set up sig handlers */
257     signal(SIGINT,  klogd_signal);
258     signal(SIGKILL, klogd_signal);
259     signal(SIGTERM, klogd_signal);
260     signal(SIGHUP,  klogd_signal);
261     logMessage(LOG_SYSLOG|LOG_INFO, "klogd started: "
262             "BusyBox v" BB_VER " (" BB_BT ")");
263
264     ksyslog(1, NULL, 0);
265
266     while (1) {
267         /* Use kernel syscalls */
268         memset(log_buffer, '\0', sizeof(log_buffer));
269         if ( ksyslog(2, log_buffer, sizeof(log_buffer)) < 0 ) {
270             char message[80];
271             if ( errno == EINTR )
272                 continue;
273             snprintf(message, 79, "klogd: Error return from sys_sycall: " \
274                     "%d - %s.\n", errno, strerror(errno));
275             logMessage(LOG_SYSLOG|LOG_ERR, message);
276             exit(1);
277         }
278         logp=log_buffer;
279         if ( *log_buffer == '<' )
280         {
281             switch ( *(log_buffer+1) )
282             {
283                 case '0':
284                     priority = LOG_EMERG;
285                     break;
286                 case '1':
287                     priority = LOG_ALERT;
288                     break;
289                 case '2':
290                     priority = LOG_CRIT;
291                     break;
292                 case '3':
293                     priority = LOG_ERR;
294                     break;
295                 case '4':
296                     priority = LOG_WARNING;
297                     break;
298                 case '5':
299                     priority = LOG_NOTICE;
300                     break;
301                 case '6':
302                     priority = LOG_INFO;
303                     break;
304                 case '7':
305                 default:
306                     priority = LOG_DEBUG;
307             }
308             logp+=3;
309         }
310         logMessage(LOG_KERN|priority, logp);
311     }
312
313 }
314
315 #endif
316
317 extern int syslogd_main(int argc, char **argv)
318 {
319     int pid, klogd_pid;
320     int doFork = TRUE;
321 #ifdef BB_KLOGD
322     int startKlogd = TRUE;
323 #endif
324     int stopDoingThat = FALSE;
325     char *p;
326     char **argv1=argv;
327     
328     while (--argc > 0 && **(++argv1) == '-') {
329         stopDoingThat = FALSE;
330         while (stopDoingThat == FALSE && *(++(*argv1))) {
331             switch (**argv1) {
332             case 'm':
333                 if (--argc == 0) {
334                     usage(syslogd_usage);
335                 }
336                 MarkInterval = atoi(*(++argv1))*60;
337                 break;
338             case 'n':
339                 doFork = FALSE;
340                 break;
341 #ifdef BB_KLOGD
342             case 'K':
343                 startKlogd = FALSE;
344                 break;
345 #endif
346             case 'O':
347                 if (--argc == 0) {
348                     usage(syslogd_usage);
349                 }
350                 logFilePath = *(++argv1);
351                 stopDoingThat = TRUE;
352                 break;
353             default:
354                 usage(syslogd_usage);
355             }
356         }
357     }
358     
359     /* Store away localhost's name before the fork */
360     gethostname(LocalHostName, sizeof(LocalHostName));
361     if ( (p = strchr(LocalHostName, '.')) ) {
362         *p++ = '\0';
363     }
364
365     if (doFork == TRUE) {
366         pid = fork();
367         if ( pid < 0 )
368             exit( pid);
369         else if ( pid == 0 ) {
370             strncpy(argv[0], "syslogd",strlen(argv[0]));
371             doSyslogd();
372         }
373     } else {
374         doSyslogd();
375     }
376
377 #ifdef BB_KLOGD
378     /* Start up the klogd process */
379     if (startKlogd == TRUE) {
380         klogd_pid = fork();
381         if (klogd_pid == 0 ) {
382                 strncpy(argv[0], "klogd", strlen(argv[0]));
383                 doKlogd();
384         }
385     }
386 #endif
387
388     exit( TRUE);
389 }
390
391