Shutdown sending on the socket when stdin closes.
[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 "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 == NULL || c_pri->c_name == NULL)
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         int i, n, lastc;
407         char *start;
408
409         /* Set up sig handlers */
410         signal(SIGINT, klogd_signal);
411         signal(SIGKILL, klogd_signal);
412         signal(SIGTERM, klogd_signal);
413         signal(SIGHUP, SIG_IGN);
414
415 #ifdef BB_FEATURE_REMOTE_LOG
416         if (doRemoteLog == TRUE){
417           init_RemoteLog();
418         }
419 #endif
420
421         logMessage(0, "klogd started: "
422                            "BusyBox v" BB_VER " (" BB_BT ")");
423
424         /* "Open the log. Currently a NOP." */
425         klogctl(1, NULL, 0);
426
427         while (1) {
428                 /* Use kernel syscalls */
429                 memset(log_buffer, '\0', sizeof(log_buffer));
430                 n = klogctl(2, log_buffer, sizeof(log_buffer));
431                 if (n < 0) {
432                         char message[80];
433
434                         if (errno == EINTR)
435                                 continue;
436                         snprintf(message, 79, "klogd: Error return from sys_sycall: " \
437                                          "%d - %s.\n", errno, strerror(errno));
438                         logMessage(LOG_SYSLOG | LOG_ERR, message);
439                         exit(1);
440                 }
441
442                 /* klogctl buffer parsing modelled after code in dmesg.c */
443                 start=&log_buffer[0];
444                 lastc='\0';
445                 for (i=0; i<n; i++) {
446                         if (lastc == '\0' && log_buffer[i] == '<') {
447                                 priority = 0;
448                                 i++;
449                                 while (isdigit(log_buffer[i])) {
450                                         priority = priority*10+(log_buffer[i]-'0');
451                                         i++;
452                                 }
453                                 if (log_buffer[i] == '>') i++;
454                                 start = &log_buffer[i];
455                         }
456                         if (log_buffer[i] == '\n') {
457                                 log_buffer[i] = '\0';  /* zero terminate this message */
458                                 logMessage(LOG_KERN | priority, start);
459                                 start = &log_buffer[i+1];
460                                 priority = LOG_INFO;
461                         }
462                         lastc = log_buffer[i];
463                 }
464         }
465
466 }
467
468 #endif
469
470 static void daemon_init (char **argv, char *dz, void fn (void))
471 {
472         setsid();
473         chdir ("/");
474         strncpy(argv[0], dz, strlen(argv[0]));
475         fn();
476         exit(0);
477 }
478
479 extern int syslogd_main(int argc, char **argv)
480 {
481         int opt, pid, klogd_pid;
482         int doFork = TRUE;
483
484 #ifdef BB_FEATURE_KLOGD
485         int startKlogd = TRUE;
486 #endif
487         char *p;
488
489         /* do normal option parsing */
490         while ((opt = getopt(argc, argv, "m:nKO:R:L")) > 0) {
491                 switch (opt) {
492                         case 'm':
493                                 MarkInterval = atoi(optarg) * 60;
494                                 break;
495                         case 'n':
496                                 doFork = FALSE;
497                                 break;
498 #ifdef BB_FEATURE_KLOGD
499                         case 'K':
500                                 startKlogd = FALSE;
501                                 break;
502 #endif
503                         case 'O':
504                                 logFilePath = strdup(optarg);
505                                 break;
506 #ifdef BB_FEATURE_REMOTE_LOG
507                         case 'R':
508                                 RemoteHost = strdup(optarg);
509                                 if ( (p = strchr(RemoteHost, ':'))){
510                                         RemotePort = atoi(p+1);
511                                         *p = '\0';
512                                 }          
513                                 doRemoteLog = TRUE;
514                                 break;
515                         case 'L':
516                                 local_logging = TRUE;
517                                 break;
518 #endif
519                         default:
520                                 usage(syslogd_usage);
521                 }
522         }
523
524 #ifdef BB_FEATURE_REMOTE_LOG
525         /* If they have not specified remote logging, then log locally */
526         if (doRemoteLog == FALSE)
527                 local_logging = TRUE;
528 #endif
529
530         /* Store away localhost's name before the fork */
531         gethostname(LocalHostName, sizeof(LocalHostName));
532         if ((p = strchr(LocalHostName, '.'))) {
533                 *p++ = '\0';
534         }
535
536         umask(0);
537
538 #ifdef BB_FEATURE_KLOGD
539         /* Start up the klogd process */
540         if (startKlogd == TRUE) {
541                 klogd_pid = fork();
542                 if (klogd_pid == 0) {
543                         daemon_init (argv, "klogd", doKlogd);
544                 }
545         }
546 #endif
547
548         if (doFork == TRUE) {
549                 pid = fork();
550                 if (pid < 0)
551                         exit(pid);
552                 else if (pid == 0) {
553                         daemon_init (argv, "syslogd", doSyslogd);
554                 }
555         } else {
556                 doSyslogd();
557         }
558
559         return EXIT_SUCCESS;
560 }
561
562 /*
563 Local Variables
564 c-file-style: "linux"
565 c-basic-offset: 4
566 tab-width: 4
567 End:
568 */