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