fd56aad97a399a8dfe35f2d18551401383d84770
[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 "busybox.h"
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <netdb.h>
33 #include <paths.h>
34 #include <signal.h>
35 #include <stdarg.h>
36 #include <time.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <sys/types.h>
40 #include <sys/un.h>
41 #include <sys/param.h>
42
43 #if ! defined __GLIBC__ && ! defined __UCLIBC__
44
45 typedef unsigned int socklen_t;
46
47 #ifndef __alpha__
48 # define __NR_klogctl __NR_syslog
49 static inline _syscall3(int, klogctl, int, type, char *, b, int, len);
50 #else                                                   /* __alpha__ */
51 #define klogctl syslog
52 #endif
53
54 #else
55 # include <sys/klog.h>
56 #endif
57
58
59
60 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
61 #define SYSLOG_NAMES
62 #include <sys/syslog.h>
63 #include <sys/uio.h>
64
65 /* Path for the file where all log messages are written */
66 #define __LOG_FILE "/var/log/messages"
67
68 /* Path to the unix socket */
69 char lfile[BUFSIZ] = "";
70
71 static char *logFilePath = __LOG_FILE;
72
73 /* interval between marks in seconds */
74 static int MarkInterval = 20 * 60;
75
76 /* localhost's name */
77 static char LocalHostName[32];
78
79 #ifdef BB_FEATURE_REMOTE_LOG
80 #include <netinet/in.h>
81 /* udp socket for logging to remote host */
82 static int remotefd = -1;
83 /* where do we log? */
84 static char *RemoteHost;
85 /* what port to log to? */
86 static int RemotePort = 514;
87 /* To remote log or not to remote log, that is the question. */
88 static int doRemoteLog = FALSE;
89 static int local_logging = FALSE;
90 #endif
91
92 /* Note: There is also a function called "message()" in init.c */
93 /* Print a message to the log file. */
94 static void message (char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
95 static void message (char *fmt, ...)
96 {
97         int fd;
98         struct flock fl;
99         va_list arguments;
100
101         fl.l_whence = SEEK_SET;
102         fl.l_start  = 0;
103         fl.l_len    = 1;
104
105         if ((fd = device_open (logFilePath,
106                                                    O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
107                                                    O_NONBLOCK)) >= 0) {
108                 fl.l_type = F_WRLCK;
109                 fcntl (fd, F_SETLKW, &fl);
110                 va_start (arguments, fmt);
111                 vdprintf (fd, fmt, arguments);
112                 va_end (arguments);
113                 fl.l_type = F_UNLCK;
114                 fcntl (fd, F_SETLKW, &fl);
115                 close (fd);
116         } else {
117                 /* Always send console messages to /dev/console so people will see them. */
118                 if ((fd = device_open (_PATH_CONSOLE,
119                                                            O_WRONLY | O_NOCTTY | O_NONBLOCK)) >= 0) {
120                         va_start (arguments, fmt);
121                         vdprintf (fd, fmt, arguments);
122                         va_end (arguments);
123                         close (fd);
124                 } else {
125                         fprintf (stderr, "Bummer, can't print: ");
126                         va_start (arguments, fmt);
127                         vfprintf (stderr, fmt, arguments);
128                         fflush (stderr);
129                         va_end (arguments);
130                 }
131         }
132 }
133
134 static void logMessage (int pri, char *msg)
135 {
136         time_t now;
137         char *timestamp;
138         static char res[20] = "";
139         CODE *c_pri, *c_fac;
140
141         if (pri != 0) {
142                 for (c_fac = facilitynames;
143                                 c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
144                 for (c_pri = prioritynames;
145                                 c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
146                 if (*c_fac->c_name == '\0' || *c_pri->c_name == '\0')
147                         snprintf(res, sizeof(res), "<%d>", pri);
148                 else
149                         snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
150         }
151
152         if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
153                         msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
154                 time(&now);
155                 timestamp = ctime(&now) + 4;
156                 timestamp[15] = '\0';
157         } else {
158                 timestamp = msg;
159                 timestamp[15] = '\0';
160                 msg += 16;
161         }
162
163         /* todo: supress duplicates */
164
165 #ifdef BB_FEATURE_REMOTE_LOG
166         /* send message to remote logger */
167         if ( -1 != remotefd){
168 #define IOV_COUNT 2
169                 struct iovec iov[IOV_COUNT];
170                 struct iovec *v = iov;
171
172                 bzero(&res, sizeof(res));
173                 snprintf(res, sizeof(res), "<%d>", pri);
174                 v->iov_base = res ;
175                 v->iov_len = strlen(res);          
176                 v++;
177
178                 v->iov_base = msg;
179                 v->iov_len = strlen(msg);          
180
181                 if ( -1 == writev(remotefd,iov, IOV_COUNT)){
182                         error_msg_and_die("syslogd: cannot write to remote file handle on" 
183                                         "%s:%d\n",RemoteHost,RemotePort);
184                 }
185         }
186         if (local_logging == TRUE)
187 #endif
188                 /* now spew out the message to wherever it is supposed to go */
189                 message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
190
191
192 }
193
194 static void quit_signal(int sig)
195 {
196         logMessage(0, "System log daemon exiting.");
197         unlink(lfile);
198         exit(TRUE);
199 }
200
201 static void domark(int sig)
202 {
203         if (MarkInterval > 0) {
204                 logMessage(LOG_SYSLOG | LOG_INFO, "-- MARK --");
205                 alarm(MarkInterval);
206         }
207 }
208
209 #define BUFSIZE 1023
210 static int serveConnection (int conn)
211 {
212         char   buf[ BUFSIZE + 1 ];
213         int    n_read;
214
215         while ((n_read = read (conn, buf, BUFSIZE )) > 0) {
216
217                 int           pri = (LOG_USER | LOG_NOTICE);
218                 char          line[ BUFSIZE + 1 ];
219                 unsigned char c;
220
221                 char *p = buf, *q = line;
222
223                 buf[ n_read - 1 ] = '\0';
224
225                 while (p && (c = *p) && q < &line[ sizeof (line) - 1 ]) {
226                         if (c == '<') {
227                         /* Parse the magic priority number. */
228                                 pri = 0;
229                                 while (isdigit (*(++p))) {
230                                         pri = 10 * pri + (*p - '0');
231                                 }
232                                 if (pri & ~(LOG_FACMASK | LOG_PRIMASK)){
233                                         pri = (LOG_USER | LOG_NOTICE);
234                                 }
235                         } else if (c == '\n') {
236                                 *q++ = ' ';
237                         } else if (iscntrl (c) && (c < 0177)) {
238                                 *q++ = '^';
239                                 *q++ = c ^ 0100;
240                         } else {
241                                 *q++ = c;
242                         }
243                         p++;
244                 }
245                 *q = '\0';
246                 /* Now log it */
247                 logMessage (pri, line);
248         }
249         return (0);
250 }
251
252
253 #ifdef BB_FEATURE_REMOTE_LOG
254 static void init_RemoteLog (void){
255
256   struct sockaddr_in remoteaddr;
257   struct hostent *hostinfo;
258   int len = sizeof(remoteaddr);
259
260   bzero(&remoteaddr, len);
261   
262   remotefd = socket(AF_INET, SOCK_DGRAM, 0);
263
264   if (remotefd < 0) {
265     error_msg_and_die("syslogd: cannot create socket\n");
266   }
267
268   hostinfo = (struct hostent *) gethostbyname(RemoteHost);
269
270   if (!hostinfo) {
271     error_msg_and_die("syslogd: cannot resolve remote host name [%s]\n", RemoteHost);
272   }
273
274   remoteaddr.sin_family = AF_INET;
275   remoteaddr.sin_addr = *(struct in_addr *) *hostinfo->h_addr_list;
276   remoteaddr.sin_port = htons(RemotePort);
277
278   /* 
279      Since we are using UDP sockets, connect just sets the default host and port 
280      for future operations
281   */
282   if ( 0 != (connect(remotefd, (struct sockaddr *) &remoteaddr, len))){
283     error_msg_and_die("syslogd: cannot connect to remote host %s:%d\n", RemoteHost, RemotePort);
284   }
285
286 }
287 #endif
288
289 static void doSyslogd (void) __attribute__ ((noreturn));
290 static void doSyslogd (void)
291 {
292         struct sockaddr_un sunx;
293         socklen_t addrLength;
294
295
296         int sock_fd;
297         fd_set fds;
298
299         char lfile[BUFSIZ];
300
301         /* Set up signal handlers. */
302         signal (SIGINT,  quit_signal);
303         signal (SIGTERM, quit_signal);
304         signal (SIGQUIT, quit_signal);
305         signal (SIGHUP,  SIG_IGN);
306         signal (SIGCHLD,  SIG_IGN);
307 #ifdef SIGCLD
308         signal (SIGCLD,  SIG_IGN);
309 #endif
310         signal (SIGALRM, domark);
311         alarm (MarkInterval);
312
313         /* Create the syslog file so realpath() can work. */
314         close (open (_PATH_LOG, O_RDWR | O_CREAT, 0644));
315         if (realpath (_PATH_LOG, lfile) == NULL)
316                 error_msg_and_die ("Could not resolve path to " _PATH_LOG ": %s\n", strerror (errno));
317
318         unlink (lfile);
319
320         memset (&sunx, 0, sizeof (sunx));
321         sunx.sun_family = AF_UNIX;
322         strncpy (sunx.sun_path, lfile, sizeof (sunx.sun_path));
323         if ((sock_fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
324                 error_msg_and_die ("Couldn't obtain descriptor for socket " _PATH_LOG ": %s\n", strerror (errno));
325
326         addrLength = sizeof (sunx.sun_family) + strlen (sunx.sun_path);
327         if ((bind (sock_fd, (struct sockaddr *) &sunx, addrLength)) || (listen (sock_fd, 5)))
328                 error_msg_and_die ("Could not connect to socket " _PATH_LOG ": %s\n", strerror (errno));
329
330         if (chmod (lfile, 0666) < 0)
331                 error_msg_and_die ("Could not set permission on " _PATH_LOG ": %s\n", strerror (errno));
332
333         FD_ZERO (&fds);
334         FD_SET (sock_fd, &fds);
335
336         #ifdef BB_FEATURE_REMOTE_LOG
337         if (doRemoteLog == TRUE){
338           init_RemoteLog();
339         }
340         #endif
341
342         logMessage (0, "syslogd started: BusyBox v" BB_VER " (" BB_BT ")");
343
344         for (;;) {
345
346                 fd_set readfds;
347                 int    n_ready;
348                 int    fd;
349
350                 memcpy (&readfds, &fds, sizeof (fds));
351
352                 if ((n_ready = select (FD_SETSIZE, &readfds, NULL, NULL, NULL)) < 0) {
353                         if (errno == EINTR) continue; /* alarm may have happened. */
354                         error_msg_and_die ("select error: %s\n", strerror (errno));
355                 }
356
357                 for (fd = 0; (n_ready > 0) && (fd < FD_SETSIZE); fd++) {
358                         if (FD_ISSET (fd, &readfds)) {
359
360                                 --n_ready;
361
362                                 if (fd == sock_fd) {
363
364                                         int   conn;
365                                         pid_t pid;
366
367                                         if ((conn = accept (sock_fd, (struct sockaddr *) &sunx, &addrLength)) < 0) {
368                                                 error_msg_and_die ("accept error: %s\n", strerror (errno));
369                                         }
370
371                                         pid = fork();
372
373                                         if (pid < 0) {
374                                                 perror ("syslogd: fork");
375                                                 close (conn);
376                                                 continue;
377                                         }
378
379                                         if (pid == 0) {
380                                                 serveConnection (conn);
381                                                 close (conn);
382                                                 exit( TRUE);
383                                         }
384                                         close (conn);
385                                 }
386                         }
387                 }
388         }
389 }
390
391 #ifdef BB_FEATURE_KLOGD
392
393 static void klogd_signal(int sig)
394 {
395         klogctl(7, NULL, 0);
396         klogctl(0, 0, 0);
397         logMessage(0, "Kernel log daemon exiting.");
398         exit(TRUE);
399 }
400
401 static void doKlogd (void) __attribute__ ((noreturn));
402 static void doKlogd (void)
403 {
404         int priority = LOG_INFO;
405         char log_buffer[4096];
406         char *logp;
407
408         /* Set up sig handlers */
409         signal(SIGINT, klogd_signal);
410         signal(SIGKILL, klogd_signal);
411         signal(SIGTERM, klogd_signal);
412         signal(SIGHUP, SIG_IGN);
413
414 #ifdef BB_FEATURE_REMOTE_LOG
415         if (doRemoteLog == TRUE){
416           init_RemoteLog();
417         }
418 #endif
419
420         logMessage(0, "klogd started: "
421                            "BusyBox v" BB_VER " (" BB_BT ")");
422
423         klogctl(1, NULL, 0);
424
425         while (1) {
426                 /* Use kernel syscalls */
427                 memset(log_buffer, '\0', sizeof(log_buffer));
428                 if (klogctl(2, log_buffer, sizeof(log_buffer)) < 0) {
429                         char message[80];
430
431                         if (errno == EINTR)
432                                 continue;
433                         snprintf(message, 79, "klogd: Error return from sys_sycall: " \
434                                          "%d - %s.\n", errno, strerror(errno));
435                         logMessage(LOG_SYSLOG | LOG_ERR, message);
436                         exit(1);
437                 }
438                 logp = log_buffer;
439                 if (*log_buffer == '<') {
440                         switch (*(log_buffer + 1)) {
441                         case '0':
442                                 priority = LOG_EMERG;
443                                 break;
444                         case '1':
445                                 priority = LOG_ALERT;
446                                 break;
447                         case '2':
448                                 priority = LOG_CRIT;
449                                 break;
450                         case '3':
451                                 priority = LOG_ERR;
452                                 break;
453                         case '4':
454                                 priority = LOG_WARNING;
455                                 break;
456                         case '5':
457                                 priority = LOG_NOTICE;
458                                 break;
459                         case '6':
460                                 priority = LOG_INFO;
461                                 break;
462                         case '7':
463                         default:
464                                 priority = LOG_DEBUG;
465                         }
466                         logp += 3;
467                 }
468                 logMessage(LOG_KERN | priority, logp);
469         }
470
471 }
472
473 #endif
474
475 static void daemon_init (char **argv, char *dz, void fn (void))
476 {
477         setsid();
478         chdir ("/");
479         strncpy(argv[0], dz, strlen(argv[0]));
480         fn();
481         exit(0);
482 }
483
484 extern int syslogd_main(int argc, char **argv)
485 {
486         int pid, klogd_pid;
487         int doFork = TRUE;
488
489 #ifdef BB_FEATURE_KLOGD
490         int startKlogd = TRUE;
491 #endif
492         int stopDoingThat = FALSE;
493         char *p;
494         char **argv1 = argv;
495
496         while (--argc > 0 && **(++argv1) == '-') {
497                 stopDoingThat = FALSE;
498                 while (stopDoingThat == FALSE && *(++(*argv1))) {
499                         switch (**argv1) {
500                         case 'm':
501                                 if (--argc == 0) {
502                                         usage(syslogd_usage);
503                                 }
504                                 MarkInterval = atoi(*(++argv1)) * 60;
505                                 break;
506                         case 'n':
507                                 doFork = FALSE;
508                                 break;
509 #ifdef BB_FEATURE_KLOGD
510                         case 'K':
511                                 startKlogd = FALSE;
512                                 break;
513 #endif
514                         case 'O':
515                                 if (--argc == 0) {
516                                         usage(syslogd_usage);
517                                 }
518                                 logFilePath = *(++argv1);
519                                 stopDoingThat = TRUE;
520                                 break;
521 #ifdef BB_FEATURE_REMOTE_LOG
522                         case 'R':
523                           if (--argc == 0) {
524                             usage(syslogd_usage);
525                           }
526                           RemoteHost = *(++argv1);
527                           if ( (p = strchr(RemoteHost, ':'))){
528                             RemotePort = atoi(p+1);
529                             *p = '\0';
530                           }          
531                           doRemoteLog = TRUE;
532                           stopDoingThat = TRUE;
533                           break;
534                         case 'L':
535                                 local_logging = TRUE;
536                                 break;
537 #endif
538                         default:
539                                 usage(syslogd_usage);
540                         }
541                 }
542         }
543
544         if (argc > 0)
545                 usage(syslogd_usage);
546
547         /* Store away localhost's name before the fork */
548         gethostname(LocalHostName, sizeof(LocalHostName));
549         if ((p = strchr(LocalHostName, '.'))) {
550                 *p++ = '\0';
551         }
552
553         umask(0);
554
555 #ifdef BB_FEATURE_KLOGD
556         /* Start up the klogd process */
557         if (startKlogd == TRUE) {
558                 klogd_pid = fork();
559                 if (klogd_pid == 0) {
560                         daemon_init (argv, "klogd", doKlogd);
561                 }
562         }
563 #endif
564
565         if (doFork == TRUE) {
566                 pid = fork();
567                 if (pid < 0)
568                         exit(pid);
569                 else if (pid == 0) {
570                         daemon_init (argv, "syslogd", doSyslogd);
571                 }
572         } else {
573                 doSyslogd();
574         }
575
576         return EXIT_SUCCESS;
577 }
578
579 /*
580 Local Variables
581 c-file-style: "linux"
582 c-basic-offset: 4
583 tab-width: 4
584 End:
585 */