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