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