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