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