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