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