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