More little stuff.
[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  * 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 ( (fd = device_open(logFilePath,
85                                  O_WRONLY | O_CREAT | O_NOCTTY | O_APPEND |
86                                  O_NONBLOCK)) >= 0) {
87                 va_start(arguments, fmt);
88                 vdprintf(fd, fmt, arguments);
89                 va_end(arguments);
90                 close(fd);
91         } else {
92                 /* Always send console messages to /dev/console so people will see them. */
93                 if ( (fd = device_open(_PATH_CONSOLE,
94                                          O_WRONLY | O_NOCTTY | O_NONBLOCK)) >= 0) {
95                         va_start(arguments, fmt);
96                         vdprintf(fd, fmt, arguments);
97                         va_end(arguments);
98                         close(fd);
99                 } else {
100                         fprintf(stderr, "Bummer, can't print: ");
101                         va_start(arguments, fmt);
102                         vfprintf(stderr, fmt, arguments);
103                         fflush(stderr);
104                         va_end(arguments);
105                 }
106         }
107 }
108
109 static void logMessage(int pri, char *msg)
110 {
111         time_t now;
112         char *timestamp;
113         static char res[20] = "";
114         CODE *c_pri, *c_fac;
115
116         if (pri != 0) {
117                 for (c_fac = facilitynames;
118                          c_fac->c_name && !(c_fac->c_val == LOG_FAC(pri) << 3); c_fac++);
119                 for (c_pri = prioritynames;
120                          c_pri->c_name && !(c_pri->c_val == LOG_PRI(pri)); c_pri++);
121                 if (*c_fac->c_name == '\0' || *c_pri->c_name == '\0')
122                         snprintf(res, sizeof(res), "<%d>", pri);
123                 else
124                         snprintf(res, sizeof(res), "%s.%s", c_fac->c_name, c_pri->c_name);
125         }
126
127         if (strlen(msg) < 16 || msg[3] != ' ' || msg[6] != ' ' ||
128                 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ') {
129                 time(&now);
130                 timestamp = ctime(&now) + 4;
131                 timestamp[15] = '\0';
132         } else {
133                 timestamp = msg;
134                 timestamp[15] = '\0';
135                 msg += 16;
136         }
137
138         /* todo: supress duplicates */
139
140         /* now spew out the message to wherever it is supposed to go */
141         message("%s %s %s %s\n", timestamp, LocalHostName, res, msg);
142 }
143
144 static void quit_signal(int sig)
145 {
146         logMessage(0, "System log daemon exiting.");
147         unlink(lfile);
148         exit(TRUE);
149 }
150
151 static void domark(int sig)
152 {
153         if (MarkInterval > 0) {
154                 logMessage(LOG_SYSLOG | LOG_INFO, "-- MARK --");
155                 alarm(MarkInterval);
156         }
157 }
158
159 static void doSyslogd (void) __attribute__ ((noreturn));
160 static void doSyslogd (void)
161 {
162         struct sockaddr_un sunx;
163         size_t addrLength;
164         int sock_fd;
165         fd_set readfds;
166         char lfile[PATH_MAX];
167
168         /* Set up sig handlers */
169         signal (SIGINT,  quit_signal);
170         signal (SIGTERM, quit_signal);
171         signal (SIGQUIT, quit_signal);
172         signal (SIGHUP,  SIG_IGN);
173         signal (SIGALRM, domark);
174         alarm (MarkInterval);
175
176         /* create the syslog file so realpath() can work */ 
177         close(open(_PATH_LOG, O_RDWR | O_CREAT, 0644));
178         if (realpath(_PATH_LOG, lfile) == NULL) {
179                 fatalError("Could not resolv path to " _PATH_LOG);
180         }
181
182         unlink (lfile);
183
184         memset (&sunx, 0, sizeof(sunx));
185
186         sunx.sun_family = AF_UNIX;
187         strncpy (sunx.sun_path, lfile, sizeof(sunx.sun_path));
188         if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
189                 fatalError ("Couldn't obtain descriptor for socket " _PATH_LOG);
190         }
191
192         addrLength = sizeof (sunx.sun_family) + strlen (sunx.sun_path);
193         if ((bind (sock_fd, (struct sockaddr *) &sunx, addrLength)) ||
194                 (listen (sock_fd, 5))) {
195                 fatalError ("Could not connect to socket " _PATH_LOG);
196         }
197
198         if (chmod (lfile, 0666) < 0) {
199                 fatalError ("Could not set permission on " _PATH_LOG);
200         }
201
202         FD_ZERO (&readfds);
203         FD_SET (sock_fd, &readfds);
204
205         logMessage (0, "syslogd started: BusyBox v" BB_VER " (" BB_BT ")");
206
207         for (;;) {
208                 int n_ready;
209                 int fd;
210
211                 if ((n_ready = select (FD_SETSIZE, &readfds, NULL, NULL, NULL)) < 0) {
212                         if (errno == EINTR) continue; /* alarm may have happened. */
213                         fatalError( "select error: %s\n", strerror(errno));
214                 }
215
216                 /* Skip stdin, stdout, stderr */
217                 for (fd = 3; fd < FD_SETSIZE; fd++) {
218                         if (FD_ISSET (fd, &readfds)) {
219                                 if (fd == sock_fd) {
220                                         int conn;
221                                         if ((conn = accept(sock_fd, (struct sockaddr *) &sunx,
222                                                                            &addrLength)) < 0) {
223                                                 fatalError( "accept error: %s\n", strerror(errno));
224                                         }
225                                         FD_SET (conn, &readfds);
226                                 }
227                                 else {
228 #define                   BUFSIZE 1024 + 1
229                                         char buf;
230                                         char *q, *p;
231                                         int n_read;
232                                         char line[BUFSIZE];
233                                         unsigned char c;
234                                         int pri;
235
236                                         /* Get set to read in a line */
237                                         memset (line, 0, sizeof(line));
238                                         pri = (LOG_USER | LOG_NOTICE);
239
240                                         /* Keep reading stuff till there is nothing else to read */
241                                         while( (n_read = read (fd, &buf, 1)) > 0) {
242                                                 p = &buf;
243                                                 q = line;
244                                                 while (p && (c = *p) && q < &line[sizeof(line) - 1]) {
245                                                         if (c == '<') {
246                                                                 /* Parse the magic priority number */
247                                                                 pri = 0;
248                                                                 while (isdigit(*(++p))) {
249                                                                         pri = 10 * pri + (*p - '0');
250                                                                 }
251                                                                 if (pri & ~(LOG_FACMASK | LOG_PRIMASK))
252                                                                         pri = (LOG_USER | LOG_NOTICE);
253                                                         } else if (c == '\n') {
254                                                                 *q++ = ' ';
255                                                         } else if (iscntrl(c) && (c < 0177)) {
256                                                                 *q++ = '^';
257                                                                 *q++ = c ^ 0100;
258                                                         } else {
259                                                                 *q++ = c;
260                                                         }
261                                                         p++;
262                                                 }
263                                                 *q = '\0';
264
265                                                 /* Now log it */
266                                                 logMessage(pri, line);
267                                                 break;
268                                         }
269                                         close (fd);
270                                         FD_CLR (fd, &readfds);
271                                 }
272                         }
273                 }
274         }
275 }
276
277 #ifdef BB_KLOGD
278
279 static void klogd_signal(int sig)
280 {
281         ksyslog(7, NULL, 0);
282         ksyslog(0, 0, 0);
283         logMessage(0, "Kernel log daemon exiting.");
284         exit(TRUE);
285 }
286
287 static void doKlogd (void) __attribute__ ((noreturn));
288 static void doKlogd (void)
289 {
290         int priority = LOG_INFO;
291         char log_buffer[4096];
292         char *logp;
293
294         /* Set up sig handlers */
295         signal(SIGINT, klogd_signal);
296         signal(SIGKILL, klogd_signal);
297         signal(SIGTERM, klogd_signal);
298         signal(SIGHUP, SIG_IGN);
299         logMessage(0, "klogd started: "
300                            "BusyBox v" BB_VER " (" BB_BT ")");
301
302         ksyslog(1, NULL, 0);
303
304         while (1) {
305                 /* Use kernel syscalls */
306                 memset(log_buffer, '\0', sizeof(log_buffer));
307                 if (ksyslog(2, log_buffer, sizeof(log_buffer)) < 0) {
308                         char message[80];
309
310                         if (errno == EINTR)
311                                 continue;
312                         snprintf(message, 79, "klogd: Error return from sys_sycall: " \
313                                          "%d - %s.\n", errno, strerror(errno));
314                         logMessage(LOG_SYSLOG | LOG_ERR, message);
315                         exit(1);
316                 }
317                 logp = log_buffer;
318                 if (*log_buffer == '<') {
319                         switch (*(log_buffer + 1)) {
320                         case '0':
321                                 priority = LOG_EMERG;
322                                 break;
323                         case '1':
324                                 priority = LOG_ALERT;
325                                 break;
326                         case '2':
327                                 priority = LOG_CRIT;
328                                 break;
329                         case '3':
330                                 priority = LOG_ERR;
331                                 break;
332                         case '4':
333                                 priority = LOG_WARNING;
334                                 break;
335                         case '5':
336                                 priority = LOG_NOTICE;
337                                 break;
338                         case '6':
339                                 priority = LOG_INFO;
340                                 break;
341                         case '7':
342                         default:
343                                 priority = LOG_DEBUG;
344                         }
345                         logp += 3;
346                 }
347                 logMessage(LOG_KERN | priority, logp);
348         }
349
350 }
351
352 #endif
353
354 static void daemon_init (char **argv, char *dz, void fn (void)) __attribute__ ((noreturn));
355 static void daemon_init (char **argv, char *dz, void fn (void))
356 {
357         setsid();
358         chdir ("/");
359         strncpy(argv[0], dz, strlen(argv[0]));
360         fn();
361         exit(0);
362 }
363
364 extern int syslogd_main(int argc, char **argv)
365 {
366         int pid, klogd_pid;
367         int doFork = TRUE;
368
369 #ifdef BB_KLOGD
370         int startKlogd = TRUE;
371 #endif
372         int stopDoingThat = FALSE;
373         char *p;
374         char **argv1 = argv;
375
376         while (--argc > 0 && **(++argv1) == '-') {
377                 stopDoingThat = FALSE;
378                 while (stopDoingThat == FALSE && *(++(*argv1))) {
379                         switch (**argv1) {
380                         case 'm':
381                                 if (--argc == 0) {
382                                         usage(syslogd_usage);
383                                 }
384                                 MarkInterval = atoi(*(++argv1)) * 60;
385                                 break;
386                         case 'n':
387                                 doFork = FALSE;
388                                 break;
389 #ifdef BB_KLOGD
390                         case 'K':
391                                 startKlogd = FALSE;
392                                 break;
393 #endif
394                         case 'O':
395                                 if (--argc == 0) {
396                                         usage(syslogd_usage);
397                                 }
398                                 logFilePath = *(++argv1);
399                                 stopDoingThat = TRUE;
400                                 break;
401                         default:
402                                 usage(syslogd_usage);
403                         }
404                 }
405         }
406
407         /* Store away localhost's name before the fork */
408         gethostname(LocalHostName, sizeof(LocalHostName));
409         if ((p = strchr(LocalHostName, '.'))) {
410                 *p++ = '\0';
411         }
412
413         umask(0);
414
415 #ifdef BB_KLOGD
416         /* Start up the klogd process */
417         if (startKlogd == TRUE) {
418                 klogd_pid = fork();
419                 if (klogd_pid == 0) {
420                         daemon_init (argv, "klogd", doKlogd);
421                 }
422         }
423 #endif
424
425         if (doFork == TRUE) {
426                 pid = fork();
427                 if (pid < 0)
428                         exit(pid);
429                 else if (pid == 0) {
430                         daemon_init (argv, "syslogd", doSyslogd);
431                 }
432         } else {
433                 doSyslogd();
434         }
435
436         exit(TRUE);
437 }
438
439 /*
440  * Local Variables
441  * c-file-style: "linux"
442  * c-basic-offset: 4
443  * tab-width: 4
444  * End:
445  */