264d899f3377ad1b0b8d597b118ac09dcd840c32
[platform/upstream/busybox.git] / sysklogd / syslogd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini syslogd implementation for busybox
4  *
5  * Copyright (C) 1999,2000 by Lineo, inc.
6  * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
7  *
8  * Copyright (C) 2000 by Karl M. Hegbloom <karlheg@debian.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  *
24  */
25
26 #include "internal.h"
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <netdb.h>
33 #include <paths.h>
34 #include <signal.h>
35 #include <stdarg.h>
36 #include <time.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <sys/un.h>
42 #include <sys/param.h>
43
44 #if ! defined __GLIBC__ && ! defined __UCLIBC__
45
46 typedef unsigned int socklen_t;
47
48 #ifndef __alpha__
49 # define __NR_klogctl __NR_syslog
50 static inline _syscall3(int, klogctl, int, type, char *, b, int, len);
51 #else                                                   /* __alpha__ */
52 #define klogctl syslog
53 #endif
54
55 #else
56 # include <sys/klog.h>
57 #endif
58
59
60
61 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
62 #define SYSLOG_NAMES
63 #include <sys/syslog.h>
64
65 /* Path for the file where all log messages are written */
66 #define __LOG_FILE "/var/log/messages"
67
68 /* Path to the unix socket */
69 char lfile[BUFSIZ] = "";
70
71 static char *logFilePath = __LOG_FILE;
72
73 /* interval between marks in seconds */
74 static int MarkInterval = 20 * 60;
75
76 /* localhost's name */
77 static char LocalHostName[32];
78
79 /* Note: There is also a function called "message()" in init.c */
80 /* Print a message to the log file. */
81 static void message (char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
82 static void message (char *fmt, ...)
83 {
84         int fd;
85         struct flock fl;
86         va_list arguments;
87
88         fl.l_whence = SEEK_SET;
89         fl.l_start  = 0;
90         fl.l_len    = 1;
91
92         if ((fd = device_open (logFilePath,
93                                                    O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
94                                                    O_NONBLOCK)) >= 0) {
95                 fl.l_type = F_WRLCK;
96                 fcntl (fd, F_SETLKW, &fl);
97                 va_start (arguments, fmt);
98                 vdprintf (fd, fmt, arguments);
99                 va_end (arguments);
100                 fl.l_type = F_UNLCK;
101                 fcntl (fd, F_SETLKW, &fl);
102                 close (fd);
103         } else {
104                 /* Always send console messages to /dev/console so people will see them. */
105                 if ((fd = device_open (_PATH_CONSOLE,
106                                                            O_WRONLY | O_NOCTTY | O_NONBLOCK)) >= 0) {
107                         va_start (arguments, fmt);
108                         vdprintf (fd, fmt, arguments);
109                         va_end (arguments);
110                         close (fd);
111                 } else {
112                         fprintf (stderr, "Bummer, can't print: ");
113                         va_start (arguments, fmt);
114                         vfprintf (stderr, fmt, arguments);
115                         fflush (stderr);
116                         va_end (arguments);
117                 }
118         }
119 }
120
121 static void logMessage (int pri, char *msg)
122 {
123         time_t now;
124         char *timestamp;
125         static char res[20] = "";
126         CODE *c_pri, *c_fac;
127
128         if (pri != 0) {
129                 for (c_fac = facilitynames;
130                          c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
131                 for (c_pri = prioritynames;
132                          c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
133                 if (*c_fac->c_name == '\0' || *c_pri->c_name == '\0')
134                         snprintf(res, sizeof(res), "<%d>", pri);
135                 else
136                         snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
137         }
138
139         if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
140                 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
141                 time(&now);
142                 timestamp = ctime(&now) + 4;
143                 timestamp[15] = '\0';
144         } else {
145                 timestamp = msg;
146                 timestamp[15] = '\0';
147                 msg += 16;
148         }
149
150         /* todo: supress duplicates */
151
152         /* now spew out the message to wherever it is supposed to go */
153         message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
154 }
155
156 static void quit_signal(int sig)
157 {
158         logMessage(0, "System log daemon exiting.");
159         unlink(lfile);
160         exit(TRUE);
161 }
162
163 static void domark(int sig)
164 {
165         if (MarkInterval > 0) {
166                 logMessage(LOG_SYSLOG | LOG_INFO, "-- MARK --");
167                 alarm(MarkInterval);
168         }
169 }
170
171 #define BUFSIZE 1023
172 static int serveConnection (int conn)
173 {
174         char   buf[ BUFSIZE + 1 ];
175         int    n_read;
176
177         while ((n_read = read (conn, buf, BUFSIZE )) > 0) {
178
179                 int           pri = (LOG_USER | LOG_NOTICE);
180                 char          line[ BUFSIZE + 1 ];
181                 unsigned char c;
182
183                 char *p = buf, *q = line;
184
185                 buf[ n_read - 1 ] = '\0';
186
187                 while (p && (c = *p) && q < &line[ sizeof (line) - 1 ]) {
188                         if (c == '<') {
189                         /* Parse the magic priority number. */
190                                 pri = 0;
191                                 while (isdigit (*(++p))) {
192                                         pri = 10 * pri + (*p - '0');
193                                 }
194                                 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
195                                         pri = (LOG_USER | LOG_NOTICE);
196                         } else if (c == '\n') {
197                                 *q++ = ' ';
198                         } else if (iscntrl (c) && (c < 0177)) {
199                                 *q++ = '^';
200                                 *q++ = c ^ 0100;
201                         } else {
202                                 *q++ = c;
203                         }
204                         p++;
205                 }
206                 *q = '\0';
207                 /* Now log it */
208                 logMessage (pri, line);
209         }
210         return (0);
211 }
212
213 static void doSyslogd (void) __attribute__ ((noreturn));
214 static void doSyslogd (void)
215 {
216         struct sockaddr_un sunx;
217         socklen_t addrLength;
218
219
220         int sock_fd;
221         fd_set fds;
222
223         char lfile[BUFSIZ];
224
225         /* Set up signal handlers. */
226         signal (SIGINT,  quit_signal);
227         signal (SIGTERM, quit_signal);
228         signal (SIGQUIT, quit_signal);
229         signal (SIGHUP,  SIG_IGN);
230         signal (SIGCLD,  SIG_IGN);
231         signal (SIGALRM, domark);
232         alarm (MarkInterval);
233
234         /* Create the syslog file so realpath() can work. */
235         close (open (_PATH_LOG, O_RDWR | O_CREAT, 0644));
236         if (realpath (_PATH_LOG, lfile) == NULL)
237                 fatalError ("Could not resolv path to " _PATH_LOG ": %s\n", strerror (errno));
238
239         unlink (lfile);
240
241         memset (&sunx, 0, sizeof (sunx));
242         sunx.sun_family = AF_UNIX;
243         strncpy (sunx.sun_path, lfile, sizeof (sunx.sun_path));
244         if ((sock_fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
245                 fatalError ("Couldn't obtain descriptor for socket " _PATH_LOG ": %s\n", strerror (errno));
246
247         addrLength = sizeof (sunx.sun_family) + strlen (sunx.sun_path);
248         if ((bind (sock_fd, (struct sockaddr *) &sunx, addrLength)) || (listen (sock_fd, 5)))
249                 fatalError ("Could not connect to socket " _PATH_LOG ": %s\n", strerror (errno));
250
251         if (chmod (lfile, 0666) < 0)
252                 fatalError ("Could not set permission on " _PATH_LOG ": %s\n", strerror (errno));
253
254         FD_ZERO (&fds);
255         FD_SET (sock_fd, &fds);
256
257         logMessage (0, "syslogd started: BusyBox v" BB_VER " (" BB_BT ")");
258
259         for (;;) {
260
261                 fd_set readfds;
262                 int    n_ready;
263                 int    fd;
264
265                 memcpy (&readfds, &fds, sizeof (fds));
266
267                 if ((n_ready = select (FD_SETSIZE, &readfds, NULL, NULL, NULL)) < 0) {
268                         if (errno == EINTR) continue; /* alarm may have happened. */
269                         fatalError ("select error: %s\n", strerror (errno));
270                 }
271
272                 for (fd = 0; (n_ready > 0) && (fd < FD_SETSIZE); fd++) {
273                         if (FD_ISSET (fd, &readfds)) {
274
275                                 --n_ready;
276
277                                 if (fd == sock_fd) {
278
279                                         int   conn;
280                                         pid_t pid;
281
282                                         if ((conn = accept (sock_fd, (struct sockaddr *) &sunx, &addrLength)) < 0) {
283                                                 fatalError ("accept error: %s\n", strerror (errno));
284                                         }
285
286                                         pid = fork();
287
288                                         if (pid < 0) {
289                                                 perror ("syslogd: fork");
290                                                 close (conn);
291                                                 continue;
292                                         }
293
294                                         if (pid == 0)
295                                                 serveConnection (conn);
296                                         close (conn);
297                                 }
298                         }
299                 }
300         }
301 }
302
303 #ifdef BB_FEATURE_KLOGD
304
305 static void klogd_signal(int sig)
306 {
307         klogctl(7, NULL, 0);
308         klogctl(0, 0, 0);
309         logMessage(0, "Kernel log daemon exiting.");
310         exit(TRUE);
311 }
312
313 static void doKlogd (void) __attribute__ ((noreturn));
314 static void doKlogd (void)
315 {
316         int priority = LOG_INFO;
317         char log_buffer[4096];
318         char *logp;
319
320         /* Set up sig handlers */
321         signal(SIGINT, klogd_signal);
322         signal(SIGKILL, klogd_signal);
323         signal(SIGTERM, klogd_signal);
324         signal(SIGHUP, SIG_IGN);
325         logMessage(0, "klogd started: "
326                            "BusyBox v" BB_VER " (" BB_BT ")");
327
328         klogctl(1, NULL, 0);
329
330         while (1) {
331                 /* Use kernel syscalls */
332                 memset(log_buffer, '\0', sizeof(log_buffer));
333                 if (klogctl(2, log_buffer, sizeof(log_buffer)) < 0) {
334                         char message[80];
335
336                         if (errno == EINTR)
337                                 continue;
338                         snprintf(message, 79, "klogd: Error return from sys_sycall: " \
339                                          "%d - %s.\n", errno, strerror(errno));
340                         logMessage(LOG_SYSLOG | LOG_ERR, message);
341                         exit(1);
342                 }
343                 logp = log_buffer;
344                 if (*log_buffer == '<') {
345                         switch (*(log_buffer + 1)) {
346                         case '0':
347                                 priority = LOG_EMERG;
348                                 break;
349                         case '1':
350                                 priority = LOG_ALERT;
351                                 break;
352                         case '2':
353                                 priority = LOG_CRIT;
354                                 break;
355                         case '3':
356                                 priority = LOG_ERR;
357                                 break;
358                         case '4':
359                                 priority = LOG_WARNING;
360                                 break;
361                         case '5':
362                                 priority = LOG_NOTICE;
363                                 break;
364                         case '6':
365                                 priority = LOG_INFO;
366                                 break;
367                         case '7':
368                         default:
369                                 priority = LOG_DEBUG;
370                         }
371                         logp += 3;
372                 }
373                 logMessage(LOG_KERN | priority, logp);
374         }
375
376 }
377
378 #endif
379
380 static void daemon_init (char **argv, char *dz, void fn (void))
381 {
382         setsid();
383         chdir ("/");
384         strncpy(argv[0], dz, strlen(argv[0]));
385         fn();
386         exit(0);
387 }
388
389 extern int syslogd_main(int argc, char **argv)
390 {
391         int pid, klogd_pid;
392         int doFork = TRUE;
393
394 #ifdef BB_FEATURE_KLOGD
395         int startKlogd = TRUE;
396 #endif
397         int stopDoingThat = FALSE;
398         char *p;
399         char **argv1 = argv;
400
401         while (--argc > 0 && **(++argv1) == '-') {
402                 stopDoingThat = FALSE;
403                 while (stopDoingThat == FALSE && *(++(*argv1))) {
404                         switch (**argv1) {
405                         case 'm':
406                                 if (--argc == 0) {
407                                         usage(syslogd_usage);
408                                 }
409                                 MarkInterval = atoi(*(++argv1)) * 60;
410                                 break;
411                         case 'n':
412                                 doFork = FALSE;
413                                 break;
414 #ifdef BB_FEATURE_KLOGD
415                         case 'K':
416                                 startKlogd = FALSE;
417                                 break;
418 #endif
419                         case 'O':
420                                 if (--argc == 0) {
421                                         usage(syslogd_usage);
422                                 }
423                                 logFilePath = *(++argv1);
424                                 stopDoingThat = TRUE;
425                                 break;
426                         default:
427                                 usage(syslogd_usage);
428                         }
429                 }
430         }
431
432         if (argc > 0)
433                 usage(syslogd_usage);
434
435         /* Store away localhost's name before the fork */
436         gethostname(LocalHostName, sizeof(LocalHostName));
437         if ((p = strchr(LocalHostName, '.'))) {
438                 *p++ = '\0';
439         }
440
441         umask(0);
442
443 #ifdef BB_FEATURE_KLOGD
444         /* Start up the klogd process */
445         if (startKlogd == TRUE) {
446                 klogd_pid = fork();
447                 if (klogd_pid == 0) {
448                         daemon_init (argv, "klogd", doKlogd);
449                 }
450         }
451 #endif
452
453         if (doFork == TRUE) {
454                 pid = fork();
455                 if (pid < 0)
456                         exit(pid);
457                 else if (pid == 0) {
458                         daemon_init (argv, "syslogd", doSyslogd);
459                 }
460         } else {
461                 doSyslogd();
462         }
463
464         return(TRUE);
465 }
466
467 /*
468 Local Variables
469 c-file-style: "linux"
470 c-basic-offset: 4
471 tab-width: 4
472 End:
473 */