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