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