Fix compiling with musl's utmp stubs
[oweals/busybox.git] / sysklogd / klogd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini klogd implementation for busybox
4  *
5  * Copyright (C) 2001 by Gennady Feldman <gfeldman@gena01.com>.
6  * Changes: Made this a standalone busybox module which uses standalone
7  * syslog() client interface.
8  *
9  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
10  *
11  * Copyright (C) 2000 by Karl M. Hegbloom <karlheg@debian.org>
12  *
13  * "circular buffer" Copyright (C) 2000 by Gennady Feldman <gfeldman@gena01.com>
14  *
15  * Maintainer: Gennady Feldman <gfeldman@gena01.com> as of Mar 12, 2001
16  *
17  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
18  */
19 //config:config KLOGD
20 //config:       bool "klogd"
21 //config:       default y
22 //config:       help
23 //config:         klogd is a utility which intercepts and logs all
24 //config:         messages from the Linux kernel and sends the messages
25 //config:         out to the 'syslogd' utility so they can be logged. If
26 //config:         you wish to record the messages produced by the kernel,
27 //config:         you should enable this option.
28 //config:
29 //config:comment "klogd should not be used together with syslog to kernel printk buffer"
30 //config:       depends on KLOGD && FEATURE_KMSG_SYSLOG
31 //config:
32 //config:config FEATURE_KLOGD_KLOGCTL
33 //config:       bool "Use the klogctl() interface"
34 //config:       default y
35 //config:       depends on KLOGD
36 //config:       select PLATFORM_LINUX
37 //config:       help
38 //config:         The klogd applet supports two interfaces for reading
39 //config:         kernel messages. Linux provides the klogctl() interface
40 //config:         which allows reading messages from the kernel ring buffer
41 //config:         independently from the file system.
42 //config:
43 //config:         If you answer 'N' here, klogd will use the more portable
44 //config:         approach of reading them from /proc or a device node.
45 //config:         However, this method requires the file to be available.
46 //config:
47 //config:         If in doubt, say 'Y'.
48
49 //applet:IF_KLOGD(APPLET(klogd, BB_DIR_SBIN, BB_SUID_DROP))
50
51 //kbuild:lib-$(CONFIG_KLOGD) += klogd.o
52
53 //usage:#define klogd_trivial_usage
54 //usage:       "[-c N] [-n]"
55 //usage:#define klogd_full_usage "\n\n"
56 //usage:       "Kernel logger\n"
57 //usage:     "\n        -c N    Print to console messages more urgent than prio N (1-8)"
58 //usage:     "\n        -n      Run in foreground"
59
60 #include "libbb.h"
61 #include <syslog.h>
62
63
64 /* The Linux-specific klogctl(3) interface does not rely on the filesystem and
65  * allows us to change the console loglevel. Alternatively, we read the
66  * messages from _PATH_KLOG. */
67
68 #if ENABLE_FEATURE_KLOGD_KLOGCTL
69
70 # include <sys/klog.h>
71
72 static void klogd_open(void)
73 {
74         /* "Open the log. Currently a NOP" */
75         klogctl(1, NULL, 0);
76 }
77
78 static void klogd_setloglevel(int lvl)
79 {
80         /* "printk() prints a message on the console only if it has a loglevel
81          * less than console_loglevel". Here we set console_loglevel = lvl. */
82         klogctl(8, NULL, lvl);
83 }
84
85 static int klogd_read(char *bufp, int len)
86 {
87         return klogctl(2, bufp, len);
88 }
89 # define READ_ERROR "klogctl(2) error"
90
91 static void klogd_close(void)
92 {
93         /* FYI: cmd 7 is equivalent to setting console_loglevel to 7
94          * via klogctl(8, NULL, 7). */
95         klogctl(7, NULL, 0); /* "7 -- Enable printk's to console" */
96         klogctl(0, NULL, 0); /* "0 -- Close the log. Currently a NOP" */
97 }
98
99 #else
100
101 # ifndef _PATH_KLOG
102 #  ifdef __GNU__
103 #   define _PATH_KLOG "/dev/klog"
104 #  else
105 #   error "your system's _PATH_KLOG is unknown"
106 #  endif
107 # endif
108 # define PATH_PRINTK "/proc/sys/kernel/printk"
109
110 enum { klogfd = 3 };
111
112 static void klogd_open(void)
113 {
114         int fd = xopen(_PATH_KLOG, O_RDONLY);
115         xmove_fd(fd, klogfd);
116 }
117
118 static void klogd_setloglevel(int lvl)
119 {
120         FILE *fp = fopen_or_warn(PATH_PRINTK, "w");
121         if (fp) {
122                 /* This changes only first value:
123                  * "messages with a higher priority than this
124                  * [that is, with numerically lower value]
125                  * will be printed to the console".
126                  * The other three values in this pseudo-file aren't changed.
127                  */
128                 fprintf(fp, "%u\n", lvl);
129                 fclose(fp);
130         }
131 }
132
133 static int klogd_read(char *bufp, int len)
134 {
135         return read(klogfd, bufp, len);
136 }
137 # define READ_ERROR "read error"
138
139 static void klogd_close(void)
140 {
141         klogd_setloglevel(7);
142         if (ENABLE_FEATURE_CLEAN_UP)
143                 close(klogfd);
144 }
145
146 #endif
147
148 #define log_buffer bb_common_bufsiz1
149 enum {
150         KLOGD_LOGBUF_SIZE = sizeof(log_buffer),
151         OPT_LEVEL      = (1 << 0),
152         OPT_FOREGROUND = (1 << 1),
153 };
154
155 /* TODO: glibc openlog(LOG_KERN) reverts to LOG_USER instead,
156  * because that's how they interpret word "default"
157  * in the openlog() manpage:
158  *      LOG_USER (default)
159  *              generic user-level messages
160  * and the fact that LOG_KERN is a constant 0.
161  * glibc interprets it as "0 in openlog() call means 'use default'".
162  * I think it means "if openlog wasn't called before syslog() is called,
163  * use default".
164  * Convincing glibc maintainers otherwise is, as usual, nearly impossible.
165  * Should we open-code syslog() here to use correct facility?
166  */
167
168 int klogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
169 int klogd_main(int argc UNUSED_PARAM, char **argv)
170 {
171         int i = 0;
172         char *opt_c;
173         int opt;
174         int used;
175
176         opt = getopt32(argv, "c:n", &opt_c);
177         if (opt & OPT_LEVEL) {
178                 /* Valid levels are between 1 and 8 */
179                 i = xatou_range(opt_c, 1, 8);
180         }
181         if (!(opt & OPT_FOREGROUND)) {
182                 bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv);
183         }
184
185         logmode = LOGMODE_SYSLOG;
186
187         /* klogd_open() before openlog(), since it might use fixed fd 3,
188          * and openlog() also may use the same fd 3 if we swap them:
189          */
190         klogd_open();
191         openlog("kernel", 0, LOG_KERN);
192         /*
193          * glibc problem: for some reason, glibc changes LOG_KERN to LOG_USER
194          * above. The logic behind this is that standard
195          * http://pubs.opengroup.org/onlinepubs/9699919799/functions/syslog.html
196          * says the following about openlog and syslog:
197          * "LOG_USER
198          *  Messages generated by arbitrary processes.
199          *  This is the default facility identifier if none is specified."
200          *
201          * I believe glibc misinterpreted this text as "if openlog's
202          * third parameter is 0 (=LOG_KERN), treat it as LOG_USER".
203          * Whereas it was meant to say "if *syslog* is called with facility
204          * 0 in its 1st parameter without prior call to openlog, then perform
205          * implicit openlog(LOG_USER)".
206          *
207          * As a result of this, eh, feature, standard klogd was forced
208          * to open-code its own openlog and syslog implementation (!).
209          *
210          * Note that prohibiting openlog(LOG_KERN) on libc level does not
211          * add any security: any process can open a socket to "/dev/log"
212          * and write a string "<0>Voila, a LOG_KERN + LOG_EMERG message"
213          *
214          * Google code search tells me there is no widespread use of
215          * openlog("foo", 0, 0), thus fixing glibc won't break userspace.
216          *
217          * The bug against glibc was filed:
218          * bugzilla.redhat.com/show_bug.cgi?id=547000
219          */
220
221         if (i)
222                 klogd_setloglevel(i);
223
224         signal(SIGHUP, SIG_IGN);
225         /* We want klogd_read to not be restarted, thus _norestart: */
226         bb_signals_recursive_norestart(BB_FATAL_SIGS, record_signo);
227
228         syslog(LOG_NOTICE, "klogd started: %s", bb_banner);
229
230         write_pidfile(CONFIG_PID_FILE_PATH "/klogd.pid");
231
232         used = 0;
233         while (!bb_got_signal) {
234                 int n;
235                 int priority;
236                 char *start;
237
238                 /* "2 -- Read from the log." */
239                 start = log_buffer + used;
240                 n = klogd_read(start, KLOGD_LOGBUF_SIZE-1 - used);
241                 if (n < 0) {
242                         if (errno == EINTR)
243                                 continue;
244                         bb_perror_msg(READ_ERROR);
245                         break;
246                 }
247                 start[n] = '\0';
248
249                 /* Process each newline-terminated line in the buffer */
250                 start = log_buffer;
251                 while (1) {
252                         char *newline = strchrnul(start, '\n');
253
254                         if (*newline == '\0') {
255                                 /* This line is incomplete */
256
257                                 /* move it to the front of the buffer */
258                                 overlapping_strcpy(log_buffer, start);
259                                 used = newline - start;
260                                 if (used < KLOGD_LOGBUF_SIZE-1) {
261                                         /* buffer isn't full */
262                                         break;
263                                 }
264                                 /* buffer is full, log it anyway */
265                                 used = 0;
266                                 newline = NULL;
267                         } else {
268                                 *newline++ = '\0';
269                         }
270
271                         /* Extract the priority */
272                         priority = LOG_INFO;
273                         if (*start == '<') {
274                                 start++;
275                                 if (*start)
276                                         priority = strtoul(start, &start, 10);
277                                 if (*start == '>')
278                                         start++;
279                         }
280                         /* Log (only non-empty lines) */
281                         if (*start)
282                                 syslog(priority, "%s", start);
283
284                         if (!newline)
285                                 break;
286                         start = newline;
287                 }
288         }
289
290         klogd_close();
291         syslog(LOG_NOTICE, "klogd: exiting");
292         remove_pidfile(CONFIG_PID_FILE_PATH "/klogd.pid");
293         if (bb_got_signal)
294                 kill_myself_with_sig(bb_got_signal);
295         return EXIT_FAILURE;
296 }