OSDN Git Service

ec372fc56e85fe3f899e30daf96f758ad7cf257b
[android-x86/external-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  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21  *
22  */
23
24 #include "internal.h"
25 #include <ctype.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #include <paths.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <sys/klog.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/un.h>
38 #include <time.h>
39 #include <unistd.h>
40
41 #define ksyslog klogctl
42 extern int ksyslog(int type, char *buf, int len);
43
44
45 /* SYSLOG_NAMES defined to pull some extra junk from syslog.h */
46 #define SYSLOG_NAMES
47 #include <sys/syslog.h>
48
49 /* Path for the file where all log messages are written */
50 #define __LOG_FILE "/var/log/messages"
51
52 /* Path to the unix socket */
53 char lfile[PATH_MAX] = "";
54
55 static char *logFilePath = __LOG_FILE;
56
57 /* interval between marks in seconds */
58 static int MarkInterval = 20 * 60;
59
60 /* localhost's name */
61 static char LocalHostName[32];
62
63 static const char syslogd_usage[] =
64         "syslogd [OPTION]...\n\n"
65         "Linux system and kernel (provides klogd) logging utility.\n"
66         "Note that this version of syslogd/klogd ignores /etc/syslog.conf.\n\n"
67         "Options:\n"
68         "\t-m\tChange the mark timestamp interval. default=20min. 0=off\n"
69         "\t-n\tDo not fork into the background (for when run by init)\n"
70 #ifdef BB_KLOGD
71         "\t-K\tDo not start up the klogd process (by default syslogd spawns klogd).\n"
72 #endif
73         "\t-O\tSpecify an alternate log file.  default=/var/log/messages\n";
74
75 /* Note: There is also a function called "message()" in init.c */
76 /* Print a message to the log file. */
77 static void message(char *fmt, ...)
78         __attribute__ ((format (printf, 1, 2)));
79 static void message(char *fmt, ...)
80 {
81         int fd;
82         va_list arguments;
83
84         if (
85                 (fd =
86                  device_open(logFilePath,
87                                          O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
88                                          O_NONBLOCK)) >= 0) {
89                 va_start(arguments, fmt);
90                 vdprintf(fd, fmt, arguments);
91                 va_end(arguments);
92                 close(fd);
93         } else {
94                 /* Always send console messages to /dev/console so people will see them. */
95                 if (
96                         (fd =
97                          device_open(_PATH_CONSOLE,
98                                                  O_WRONLY | O_NOCTTY | O_NONBLOCK)) >= 0) {
99                         va_start(arguments, fmt);
100                         vdprintf(fd, fmt, arguments);
101                         va_end(arguments);
102                         close(fd);
103                 } else {
104                         fprintf(stderr, "Bummer, can't print: ");
105                         va_start(arguments, fmt);
106                         vfprintf(stderr, fmt, arguments);
107                         fflush(stderr);
108                         va_end(arguments);
109                 }
110         }
111 }
112
113 static void logMessage(int pri, char *msg)
114 {
115         time_t now;
116         char *timestamp;
117         static char res[20] = "";
118         CODE *c_pri, *c_fac;
119
120         if (pri != 0) {
121                 for (c_fac = facilitynames;
122                          c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
123                 for (c_pri = prioritynames;
124                          c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
125                 if (*c_fac->c_name == '\0' || *c_pri->c_name == '\0')
126                         snprintf(res, sizeof(res), "<%d>", pri);
127                 else
128                         snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
129         }
130
131         if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
132                 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
133                 time(&now);
134                 timestamp = ctime(&now) + 4;
135                 timestamp[15] = '\0';
136         } else {
137                 timestamp = msg;
138                 timestamp[15] = '\0';
139                 msg += 16;
140         }
141
142         /* todo: supress duplicates */
143
144         /* now spew out the message to wherever it is supposed to go */
145         message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
146 }
147
148 static void quit_signal(int sig)
149 {
150         logMessage(0, "System log daemon exiting.");
151         unlink(lfile);
152         exit(TRUE);
153 }
154
155 static void domark(int sig)
156 {
157         if (MarkInterval > 0) {
158                 logMessage(LOG_SYSLOG | LOG_INFO, "-- MARK --");
159                 alarm(MarkInterval);
160         }
161 }
162
163 static void doSyslogd (void) __attribute__ ((noreturn));
164 static void doSyslogd (void)
165 {
166         struct sockaddr_un sunx;
167         size_t addrLength;
168         int sock_fd;
169         fd_set readfds;
170         char lfile[PATH_MAX];
171
172         /* Set up sig handlers */
173         signal (SIGINT,  quit_signal);
174         signal (SIGTERM, quit_signal);
175         signal (SIGQUIT, quit_signal);
176         signal (SIGHUP,  SIG_IGN);
177         signal (SIGALRM, domark);
178         alarm (MarkInterval);
179
180         /* create the syslog file so realpath() can work 
181          * (the ugle close(open()) stuff is just a cheap
182          * touch command that avoids using system (system
183          * is always a bad thing to use) */
184         close(open("touch " _PATH_LOG, O_RDWR | O_CREAT, 0644));
185         if (realpath(_PATH_LOG, lfile) == NULL) {
186                 perror("Could not resolv path to " _PATH_LOG);
187                 exit (FALSE);
188         }
189
190         unlink (lfile);
191
192         memset (&sunx, 0, sizeof(sunx));
193
194         sunx.sun_family = AF_UNIX;
195         strncpy (sunx.sun_path, lfile, sizeof(sunx.sun_path));
196         if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
197                 perror ("Couldn't obtain descriptor for socket " _PATH_LOG);
198                 exit (FALSE);
199         }
200
201         addrLength = sizeof (sunx.sun_family) + strlen (sunx.sun_path);
202         if ((bind (sock_fd, (struct sockaddr *) &sunx, addrLength)) ||
203                 (listen (sock_fd, 5))) {
204                 perror ("Could not connect to socket " _PATH_LOG);
205                 exit (FALSE);
206         }
207
208         if (chmod (lfile, 0666) < 0) {
209                 perror ("Could not set permission on " _PATH_LOG);
210                 exit (FALSE);
211         }
212
213         FD_ZERO (&readfds);
214         FD_SET (sock_fd, &readfds);
215
216         logMessage (0, "syslogd started: BusyBox v" BB_VER " (" BB_BT ")");
217
218         for (;;) {
219                 int n_ready;
220                 int fd;
221
222                 if ((n_ready = select (FD_SETSIZE, &readfds, NULL, NULL, NULL)) < 0) {
223                         if (errno == EINTR) continue; /* alarm may have happened. */
224                         perror ("select");
225                         exit (FALSE);
226                 }
227
228                 /* Skip stdin, stdout, stderr */
229                 for (fd = 3; fd <= FD_SETSIZE; fd++) {
230                         if (FD_ISSET (fd, &readfds)) {
231                                 if (fd == sock_fd) {
232                                         int conn;
233                                         if ((conn = accept(sock_fd, (struct sockaddr *) &sunx,
234                                                                            &addrLength)) < 0) {
235                                                 perror ("accept");
236                                                 exit (FALSE); /* #### ??? */
237                                         }
238                                         FD_SET (conn, &readfds);
239                                 }
240                                 else {
241 #define                   BUFSIZE 1024 + 1
242                                         char buf[BUFSIZE];
243                                         char *q, *p;
244                                         int n_read;
245
246                                         n_read = read (fd, buf, BUFSIZE);
247
248                                         if (n_read < 0) {
249                                                 // FIXME .. fd isn't set 
250                                                 perror ("read error");
251                                                 goto close_fd;
252                                         }
253                                         else if (n_read > 0) {
254                                                 char line[BUFSIZE];
255                                                 unsigned char c;
256                                                 int pri = (LOG_USER | LOG_NOTICE);
257
258                                                 memset (line, 0, sizeof(line));
259                                                 p = buf;
260                                                 q = line;
261                                                 while (p && (c = *p) && q < &line[sizeof(line) - 1]) {
262                                                         if (c == '<') {
263                                                                 /* Parse the magic priority number */
264                                                                 pri = 0;
265                                                                 while (isdigit(*(++p))) {
266                                                                         pri = 10 * pri + (*p - '0');
267                                                                 }
268                                                                 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
269                                                                         pri = (LOG_USER | LOG_NOTICE);
270                                                         } else if (c == '\n') {
271                                                                 *q++ = ' ';
272                                                         } else if (iscntrl(c) && (c < 0177)) {
273                                                                 *q++ = '^';
274                                                                 *q++ = c ^ 0100;
275                                                         } else {
276                                                                 *q++ = c;
277                                                         }
278                                                         p++;
279                                                 }
280                                                 *q = '\0';
281
282                                                 /* Now log it */
283                                                 logMessage(pri, line);
284
285                                         close_fd:
286                                                 close (fd);
287                                                 FD_CLR (fd, &readfds);
288                                         }
289                                         else {          /* EOF */
290                                                 goto close_fd;
291                                         }
292                                 }
293                         }
294                 }
295         }
296 }
297
298 #ifdef BB_KLOGD
299
300 static void klogd_signal(int sig)
301 {
302         ksyslog(7, NULL, 0);
303         ksyslog(0, 0, 0);
304         logMessage(0, "Kernel log daemon exiting.");
305         exit(TRUE);
306 }
307
308 static void doKlogd (void) __attribute__ ((noreturn));
309 static void doKlogd (void)
310 {
311         int priority = LOG_INFO;
312         char log_buffer[4096];
313         char *logp;
314
315         /* Set up sig handlers */
316         signal(SIGINT, klogd_signal);
317         signal(SIGKILL, klogd_signal);
318         signal(SIGTERM, klogd_signal);
319         signal(SIGHUP, SIG_IGN);
320         logMessage(0, "klogd started: "
321                            "BusyBox v" BB_VER " (" BB_BT ")");
322
323         ksyslog(1, NULL, 0);
324
325         while (1) {
326                 /* Use kernel syscalls */
327                 memset(log_buffer, '\0', sizeof(log_buffer));
328                 if (ksyslog(2, log_buffer, sizeof(log_buffer)) < 0) {
329                         char message[80];
330
331                         if (errno == EINTR)
332                                 continue;
333                         snprintf(message, 79, "klogd: Error return from sys_sycall: " \
334                                          "%d - %s.\n", errno, strerror(errno));
335                         logMessage(LOG_SYSLOG | LOG_ERR, message);
336                         exit(1);
337                 }
338                 logp = log_buffer;
339                 if (*log_buffer == '<') {
340                         switch (*(log_buffer + 1)) {
341                         case '0':
342                                 priority = LOG_EMERG;
343                                 break;
344                         case '1':
345                                 priority = LOG_ALERT;
346                                 break;
347                         case '2':
348                                 priority = LOG_CRIT;
349                                 break;
350                         case '3':
351                                 priority = LOG_ERR;
352                                 break;
353                         case '4':
354                                 priority = LOG_WARNING;
355                                 break;
356                         case '5':
357                                 priority = LOG_NOTICE;
358                                 break;
359                         case '6':
360                                 priority = LOG_INFO;
361                                 break;
362                         case '7':
363                         default:
364                                 priority = LOG_DEBUG;
365                         }
366                         logp += 3;
367                 }
368                 logMessage(LOG_KERN | priority, logp);
369         }
370
371 }
372
373 #endif
374
375 static void daemon_init (char **argv, char *dz, void fn (void)) __attribute__ ((noreturn));
376 static void daemon_init (char **argv, char *dz, void fn (void))
377 {
378         setsid();
379         chdir ("/");
380         strncpy(argv[0], dz, strlen(argv[0]));
381         fn();
382         exit(0);
383 }
384
385 extern int syslogd_main(int argc, char **argv)
386 {
387         int pid, klogd_pid;
388         int doFork = TRUE;
389
390 #ifdef BB_KLOGD
391         int startKlogd = TRUE;
392 #endif
393         int stopDoingThat = FALSE;
394         char *p;
395         char **argv1 = argv;
396
397         while (--argc > 0 && **(++argv1) == '-') {
398                 stopDoingThat = FALSE;
399                 while (stopDoingThat == FALSE && *(++(*argv1))) {
400                         switch (**argv1) {
401                         case 'm':
402                                 if (--argc == 0) {
403                                         usage(syslogd_usage);
404                                 }
405                                 MarkInterval = atoi(*(++argv1)) * 60;
406                                 break;
407                         case 'n':
408                                 doFork = FALSE;
409                                 break;
410 #ifdef BB_KLOGD
411                         case 'K':
412                                 startKlogd = FALSE;
413                                 break;
414 #endif
415                         case 'O':
416                                 if (--argc == 0) {
417                                         usage(syslogd_usage);
418                                 }
419                                 logFilePath = *(++argv1);
420                                 stopDoingThat = TRUE;
421                                 break;
422                         default:
423                                 usage(syslogd_usage);
424                         }
425                 }
426         }
427
428         /* Store away localhost's name before the fork */
429         gethostname(LocalHostName, sizeof(LocalHostName));
430         if ((p = strchr(LocalHostName, '.'))) {
431                 *p++ = '\0';
432         }
433
434         umask(0);
435
436 #ifdef BB_KLOGD
437         /* Start up the klogd process */
438         if (startKlogd == TRUE) {
439                 klogd_pid = fork();
440                 if (klogd_pid == 0) {
441                         daemon_init (argv, "klogd", doKlogd);
442                 }
443         }
444 #endif
445
446         if (doFork == TRUE) {
447                 pid = fork();
448                 if (pid < 0)
449                         exit(pid);
450                 else if (pid == 0) {
451                         daemon_init (argv, "syslogd", doSyslogd);
452                 }
453         } else {
454                 doSyslogd();
455         }
456
457         exit(TRUE);
458 }
459
460 /*
461  * Local Variables
462  * c-file-style: "linux"
463  * c-basic-offset: 4
464  * tab-width: 4
465  * End:
466  */