0d400e5353f699b74d0e03b5b95d92e579b04b36
[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         socklen_t addrLength;
175
176
177         int sock_fd;
178         fd_set fds;
179
180         char lfile[PATH_MAX];
181
182         /* Set up signal handlers. */
183         signal (SIGINT,  quit_signal);
184         signal (SIGTERM, quit_signal);
185         signal (SIGQUIT, quit_signal);
186         signal (SIGHUP,  SIG_IGN);
187         signal (SIGCLD,  SIG_IGN);
188         signal (SIGALRM, domark);
189         alarm (MarkInterval);
190
191         /* Create the syslog file so realpath() can work. */
192         close (open (_PATH_LOG, O_RDWR | O_CREAT, 0644));
193         if (realpath (_PATH_LOG, lfile) == NULL)
194                 fatalError ("Could not resolv path to " _PATH_LOG ": %s", strerror (errno));
195
196         unlink (lfile);
197
198         memset (&sunx, 0, sizeof (sunx));
199         sunx.sun_family = AF_UNIX;
200         strncpy (sunx.sun_path, lfile, sizeof (sunx.sun_path));
201         if ((sock_fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
202                 fatalError ("Couldn't obtain descriptor for socket " _PATH_LOG ": %s", strerror (errno));
203
204         addrLength = sizeof (sunx.sun_family) + strlen (sunx.sun_path);
205         if ((bind (sock_fd, (struct sockaddr *) &sunx, addrLength)) || (listen (sock_fd, 5)))
206                 fatalError ("Could not connect to socket " _PATH_LOG ": %s", strerror (errno));
207
208         if (chmod (lfile, 0666) < 0)
209                 fatalError ("Could not set permission on " _PATH_LOG ": %s", strerror (errno));
210
211         FD_ZERO (&fds);
212         FD_SET (sock_fd, &fds);
213
214         logMessage (0, "syslogd started: BusyBox v" BB_VER " (" BB_BT ")");
215
216         for (;;) {
217
218                 fd_set readfds;
219                 int    n_ready;
220                 int    fd;
221
222                 memcpy (&readfds, &fds, sizeof (fds));
223
224                 if ((n_ready = select (FD_SETSIZE, &readfds, NULL, NULL, NULL)) < 0) {
225                         if (errno == EINTR) continue; /* alarm may have happened. */
226                         fatalError ("select error: %s\n", strerror (errno));
227                 }
228
229                 for (fd = 0; (n_ready > 0) && (fd < FD_SETSIZE); fd++) {
230                         if (FD_ISSET (fd, &readfds)) {
231
232                                 --n_ready;
233
234                                 if (fd == sock_fd) {
235
236                                         int   conn;
237                                         pid_t pid;
238
239                                         if ((conn = accept (sock_fd, (struct sockaddr *) &sunx, &addrLength)) < 0) {
240                                                 fatalError ("accept error: %s\n", strerror (errno));
241                                         }
242
243                                         pid = fork();
244
245                                         if (pid < 0) {
246                                                 perror ("syslogd: fork");
247                                                 close (conn);
248                                                 continue;
249                                         }
250
251                                         if (pid > 0) {
252
253 #                                               define BUFSIZE 1023
254                                                 char   buf[ BUFSIZE + 1 ];
255                                                 int    n_read;
256
257                                                 while ((n_read = read (conn, buf, BUFSIZE )) > 0) {
258
259                                                         int           pri = (LOG_USER | LOG_NOTICE);
260                                                         char          line[ BUFSIZE + 1 ];
261                                                         unsigned char c;
262
263                                                         char *p = buf, *q = line;
264
265                                                         buf[ n_read - 1 ] = '\0';
266
267                                                         while (p && (c = *p) && q < &line[ sizeof (line) - 1 ]) {
268                                                                 if (c == '<') {
269                                                                 /* Parse the magic priority number. */
270                                                                         pri = 0;
271                                                                         while (isdigit (*(++p))) {
272                                                                                 pri = 10 * pri + (*p - '0');
273                                                                         }
274                                                                         if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
275                                                                                 pri = (LOG_USER | LOG_NOTICE);
276                                                                 } else if (c == '\n') {
277                                                                         *q++ = ' ';
278                                                                 } else if (iscntrl (c) && (c < 0177)) {
279                                                                         *q++ = '^';
280                                                                         *q++ = c ^ 0100;
281                                                                 } else {
282                                                                         *q++ = c;
283                                                                 }
284                                                                 p++;
285                                                         }
286                                                         *q = '\0';
287                                                         /* Now log it */
288                                                         logMessage (pri, line);
289                                                 }
290                                                 exit (0);
291                                         }
292                                         close (conn);
293                                 }
294                         }
295                 }
296         }
297 }
298
299 #ifdef BB_KLOGD
300
301 static void klogd_signal(int sig)
302 {
303         ksyslog(7, NULL, 0);
304         ksyslog(0, 0, 0);
305         logMessage(0, "Kernel log daemon exiting.");
306         exit(TRUE);
307 }
308
309 static void doKlogd (void) __attribute__ ((noreturn));
310 static void doKlogd (void)
311 {
312         int priority = LOG_INFO;
313         char log_buffer[4096];
314         char *logp;
315
316         /* Set up sig handlers */
317         signal(SIGINT, klogd_signal);
318         signal(SIGKILL, klogd_signal);
319         signal(SIGTERM, klogd_signal);
320         signal(SIGHUP, SIG_IGN);
321         logMessage(0, "klogd started: "
322                            "BusyBox v" BB_VER " (" BB_BT ")");
323
324         ksyslog(1, NULL, 0);
325
326         while (1) {
327                 /* Use kernel syscalls */
328                 memset(log_buffer, '\0', sizeof(log_buffer));
329                 if (ksyslog(2, log_buffer, sizeof(log_buffer)) < 0) {
330                         char message[80];
331
332                         if (errno == EINTR)
333                                 continue;
334                         snprintf(message, 79, "klogd: Error return from sys_sycall: " \
335                                          "%d - %s.\n", errno, strerror(errno));
336                         logMessage(LOG_SYSLOG | LOG_ERR, message);
337                         exit(1);
338                 }
339                 logp = log_buffer;
340                 if (*log_buffer == '<') {
341                         switch (*(log_buffer + 1)) {
342                         case '0':
343                                 priority = LOG_EMERG;
344                                 break;
345                         case '1':
346                                 priority = LOG_ALERT;
347                                 break;
348                         case '2':
349                                 priority = LOG_CRIT;
350                                 break;
351                         case '3':
352                                 priority = LOG_ERR;
353                                 break;
354                         case '4':
355                                 priority = LOG_WARNING;
356                                 break;
357                         case '5':
358                                 priority = LOG_NOTICE;
359                                 break;
360                         case '6':
361                                 priority = LOG_INFO;
362                                 break;
363                         case '7':
364                         default:
365                                 priority = LOG_DEBUG;
366                         }
367                         logp += 3;
368                 }
369                 logMessage(LOG_KERN | priority, logp);
370         }
371
372 }
373
374 #endif
375
376 static void daemon_init (char **argv, char *dz, void fn (void))
377 {
378         setsid();
379         chdir ("/");
380         strncpy(argv[0], dz, strlen(argv[0]));
381         fn();
382         exit(0);
383 }
384
385 extern int syslogd_main(int argc, char **argv)
386 {
387         int pid, klogd_pid;
388         int doFork = TRUE;
389
390 #ifdef BB_KLOGD
391         int startKlogd = TRUE;
392 #endif
393         int stopDoingThat = FALSE;
394         char *p;
395         char **argv1 = argv;
396
397         while (--argc > 0 && **(++argv1) == '-') {
398                 stopDoingThat = FALSE;
399                 while (stopDoingThat == FALSE && *(++(*argv1))) {
400                         switch (**argv1) {
401                         case 'm':
402                                 if (--argc == 0) {
403                                         usage(syslogd_usage);
404                                 }
405                                 MarkInterval = atoi(*(++argv1)) * 60;
406                                 break;
407                         case 'n':
408                                 doFork = FALSE;
409                                 break;
410 #ifdef BB_KLOGD
411                         case 'K':
412                                 startKlogd = FALSE;
413                                 break;
414 #endif
415                         case 'O':
416                                 if (--argc == 0) {
417                                         usage(syslogd_usage);
418                                 }
419                                 logFilePath = *(++argv1);
420                                 stopDoingThat = TRUE;
421                                 break;
422                         default:
423                                 usage(syslogd_usage);
424                         }
425                 }
426         }
427
428         /* Store away localhost's name before the fork */
429         gethostname(LocalHostName, sizeof(LocalHostName));
430         if ((p = strchr(LocalHostName, '.'))) {
431                 *p++ = '\0';
432         }
433
434         umask(0);
435
436 #ifdef BB_KLOGD
437         /* Start up the klogd process */
438         if (startKlogd == TRUE) {
439                 klogd_pid = fork();
440                 if (klogd_pid == 0) {
441                         daemon_init (argv, "klogd", doKlogd);
442                 }
443         }
444 #endif
445
446         if (doFork == TRUE) {
447                 pid = fork();
448                 if (pid < 0)
449                         exit(pid);
450                 else if (pid == 0) {
451                         daemon_init (argv, "syslogd", doSyslogd);
452                 }
453         } else {
454                 doSyslogd();
455         }
456
457         exit(TRUE);
458 }
459
460 /*
461 Local Variables
462 c-file-style: "linux"
463 c-basic-offset: 4
464 tab-width: 4
465 End:
466 */