]> git.ipfire.org Git - thirdparty/util-linux.git/blame - sys-utils/dmesg.c
tests: check commands needed for running a test exist
[thirdparty/util-linux.git] / sys-utils / dmesg.c
CommitLineData
5ef05369
KZ
1/*
2 * dmesg.c -- Print out the contents of the kernel ring buffer
7eda085c 3 *
5ef05369
KZ
4 * Copyright (C) 1993 Theodore Ts'o <tytso@athena.mit.edu>
5 * Copyright (C) 2011 Karel Zak <kzak@redhat.com>
6 *
7 * This program comes with ABSOLUTELY NO WARRANTY.
6dbe3af9 8 */
6dbe3af9
KZ
9#include <linux/unistd.h>
10#include <stdio.h>
11#include <getopt.h>
fd6b7a7f 12#include <stdlib.h>
15673c15 13#include <sys/klog.h>
f06ec64f 14#include <sys/syslog.h>
bd304d92 15#include <sys/time.h>
42fac79a 16#include <sys/sysinfo.h>
15103c4b 17#include <ctype.h>
bd304d92 18#include <time.h>
c672220f
KZ
19#include <sys/mman.h>
20#include <sys/types.h>
21#include <sys/stat.h>
22#include <unistd.h>
23#include <fcntl.h>
5423ccb1 24
15103c4b 25#include "c.h"
098ce273 26#include "colors.h"
5423ccb1 27#include "nls.h"
15673c15 28#include "strutils.h"
15103c4b 29#include "xalloc.h"
b8300c0a 30#include "widechar.h"
e12c9866 31#include "all-io.h"
636a6207 32#include "bitops.h"
efb8854f 33#include "closestream.h"
94920134 34#include "optutils.h"
ddca870a 35#include "mangle.h"
aa192520 36#include "pager.h"
6dbe3af9 37
59a14899
KZ
38/* Close the log. Currently a NOP. */
39#define SYSLOG_ACTION_CLOSE 0
40/* Open the log. Currently a NOP. */
41#define SYSLOG_ACTION_OPEN 1
42/* Read from the log. */
43#define SYSLOG_ACTION_READ 2
44/* Read all messages remaining in the ring buffer. (allowed for non-root) */
45#define SYSLOG_ACTION_READ_ALL 3
46/* Read and clear all messages remaining in the ring buffer */
47#define SYSLOG_ACTION_READ_CLEAR 4
48/* Clear ring buffer. */
49#define SYSLOG_ACTION_CLEAR 5
50/* Disable printk's to console */
51#define SYSLOG_ACTION_CONSOLE_OFF 6
52/* Enable printk's to console */
53#define SYSLOG_ACTION_CONSOLE_ON 7
54/* Set level of messages printed to console */
55#define SYSLOG_ACTION_CONSOLE_LEVEL 8
56/* Return number of unread characters in the log buffer */
57#define SYSLOG_ACTION_SIZE_UNREAD 9
58/* Return size of the log buffer */
59#define SYSLOG_ACTION_SIZE_BUFFER 10
60
5aaee63c
KZ
61/*
62 * Colors
63 */
64#define DMESG_COLOR_SUBSYS UL_COLOR_BROWN
65#define DMESG_COLOR_TIME UL_COLOR_GREEN
66#define DMESG_COLOR_RELTIME UL_COLOR_BOLD_GREEN
67#define DMESG_COLOR_ALERT UL_COLOR_REVERSE UL_COLOR_RED
68#define DMESG_COLOR_CRIT UL_COLOR_BOLD_RED
69#define DMESG_COLOR_ERR UL_COLOR_RED
70#define DMESG_COLOR_WARN UL_COLOR_BOLD
71#define DMESG_COLOR_SEGFAULT UL_COLOR_HALFBRIGHT UL_COLOR_RED
72
f06ec64f 73/*
5ef05369 74 * Priority and facility names
f06ec64f
KZ
75 */
76struct dmesg_name {
77 const char *name;
78 const char *help;
79};
80
5ef05369
KZ
81/*
82 * Priority names -- based on sys/syslog.h
83 */
f06ec64f
KZ
84static const struct dmesg_name level_names[] =
85{
86 [LOG_EMERG] = { "emerg", N_("system is unusable") },
87 [LOG_ALERT] = { "alert", N_("action must be taken immediately") },
88 [LOG_CRIT] = { "crit", N_("critical conditions") },
89 [LOG_ERR] = { "err", N_("error conditions") },
90 [LOG_WARNING] = { "warn", N_("warning conditions") },
91 [LOG_NOTICE] = { "notice",N_("normal but significant condition") },
92 [LOG_INFO] = { "info", N_("informational") },
93 [LOG_DEBUG] = { "debug", N_("debug-level messages") }
94};
95
85f3cc55
KZ
96/*
97 * sys/syslog.h uses (f << 3) for all facility codes.
98 * We want to use the codes as array idexes, so shift back...
99 *
100 * Note that libc LOG_FAC() macro returns the base codes, not the
101 * shifted code :-)
102 */
103#define FAC_BASE(f) ((f) >> 3)
104
105static const struct dmesg_name facility_names[] =
106{
107 [FAC_BASE(LOG_KERN)] = { "kern", N_("kernel messages") },
108 [FAC_BASE(LOG_USER)] = { "user", N_("random user-level messages") },
109 [FAC_BASE(LOG_MAIL)] = { "mail", N_("mail system") },
110 [FAC_BASE(LOG_DAEMON)] = { "daemon", N_("system daemons") },
111 [FAC_BASE(LOG_AUTH)] = { "auth", N_("security/authorization messages") },
112 [FAC_BASE(LOG_SYSLOG)] = { "syslog", N_("messages generated internally by syslogd") },
113 [FAC_BASE(LOG_LPR)] = { "lpr", N_("line printer subsystem") },
114 [FAC_BASE(LOG_NEWS)] = { "news", N_("network news subsystem") },
115 [FAC_BASE(LOG_UUCP)] = { "uucp", N_("UUCP subsystem") },
116 [FAC_BASE(LOG_CRON)] = { "cron", N_("clock daemon") },
117 [FAC_BASE(LOG_AUTHPRIV)] = { "authpriv", N_("security/authorization messages (private)") },
4df28845 118 [FAC_BASE(LOG_FTP)] = { "ftp", N_("FTP daemon") },
85f3cc55
KZ
119};
120
e6471b9f
KZ
121/* supported methods to read message buffer
122 */
123enum {
7af23060 124 DMESG_METHOD_KMSG, /* read messages from /dev/kmsg (default) */
e6471b9f
KZ
125 DMESG_METHOD_SYSLOG, /* klogctl() buffer */
126 DMESG_METHOD_MMAP /* mmap file with records (see --file) */
127};
128
776eabe7
SK
129enum {
130 DMESG_TIMEFTM_NONE = 0,
131 DMESG_TIMEFTM_CTIME, /* [ctime] */
132 DMESG_TIMEFTM_CTIME_DELTA, /* [ctime <delta>] */
133 DMESG_TIMEFTM_DELTA, /* [<delta>] */
134 DMESG_TIMEFTM_RELTIME, /* [relative] */
135 DMESG_TIMEFTM_TIME, /* [time] */
8a8be309
SK
136 DMESG_TIMEFTM_TIME_DELTA, /* [time <delta>] */
137 DMESG_TIMEFTM_ISO8601 /* 2013-06-13T22:11:00,123456+0100 */
776eabe7 138};
15a1e371 139#define is_timefmt(c, f) ((c)->time_fmt == (DMESG_TIMEFTM_ ##f))
776eabe7 140
aca1633a
KZ
141struct dmesg_control {
142 /* bit arrays -- see include/bitops.h */
143 char levels[ARRAY_SIZE(level_names) / NBBY + 1];
144 char facilities[ARRAY_SIZE(facility_names) / NBBY + 1];
145
bd304d92 146 struct timeval lasttime; /* last printed timestamp */
60464b1f 147 struct tm lasttm; /* last localtime */
3c5384d0 148 struct timeval boot_time; /* system boot time */
bd304d92 149
e6471b9f
KZ
150 int action; /* SYSLOG_ACTION_* */
151 int method; /* DMESG_METHOD_* */
298a073c
KZ
152
153 size_t bufsize; /* size of syslog buffer */
154
7af23060 155 int kmsg; /* /dev/kmsg file descriptor */
298a073c
KZ
156 ssize_t kmsg_first_read;/* initial read() return code */
157 char kmsg_buf[BUFSIZ];/* buffer to read kmsg data */
e6471b9f 158
c672220f
KZ
159 /*
160 * For the --file option we mmap whole file. The unnecessary (already
161 * printed) pages are always unmapped. The result is that we have in
455fe9a0 162 * memory only the currently used page(s).
c672220f 163 */
9b3a6984 164 char *filename;
c672220f
KZ
165 char *mmap_buff;
166 size_t pagesize;
776eabe7 167 unsigned int time_fmt; /* time format */
c672220f 168
0fd12a96
KZ
169 unsigned int follow:1, /* wait for new messages */
170 raw:1, /* raw mode */
9feec79c
KZ
171 fltr_lev:1, /* filter out by levels[] */
172 fltr_fac:1, /* filter out by facilities[] */
173 decode:1, /* use "facility: level: " prefix */
aa192520 174 pager:1, /* pipe output into a pager */
098ce273 175 color:1; /* colorize messages */
aca1633a 176};
f4fa5b44 177
a7ee94f2
KZ
178struct dmesg_record {
179 const char *mesg;
180 size_t mesg_size;
181
182 int level;
183 int facility;
bd304d92 184 struct timeval tv;
a7ee94f2
KZ
185
186 const char *next; /* buffer with next unparsed record */
187 size_t next_size; /* size of the next buffer */
188};
189
ddca870a
KZ
190#define INIT_DMESG_RECORD(_r) do { \
191 (_r)->mesg = NULL; \
192 (_r)->mesg_size = 0; \
193 (_r)->facility = -1; \
194 (_r)->level = -1; \
195 (_r)->tv.tv_sec = 0; \
196 (_r)->tv.tv_usec = 0; \
197 } while (0)
198
199static int read_kmsg(struct dmesg_control *ctl);
200
5aaee63c 201static int set_level_color(int log_level, const char *mesg, size_t mesgsz)
098ce273
OO
202{
203 switch (log_level) {
204 case LOG_ALERT:
5aaee63c 205 color_enable(DMESG_COLOR_ALERT);
098ce273
OO
206 return 0;
207 case LOG_CRIT:
5aaee63c 208 color_enable(DMESG_COLOR_CRIT);
098ce273
OO
209 return 0;
210 case LOG_ERR:
5aaee63c
KZ
211 color_enable(DMESG_COLOR_ERR);
212 return 0;
213 case LOG_WARNING:
214 color_enable(DMESG_COLOR_WARN);
098ce273
OO
215 return 0;
216 default:
217 break;
218 }
219
5aaee63c
KZ
220 /* well, sometimes the messges contains important keywords, but in
221 * non-warning/error messages
222 */
223 if (memmem(mesg, mesgsz, "segfault at", 11)) {
224 color_enable(DMESG_COLOR_SEGFAULT);
225 return 0;
226 }
227
098ce273
OO
228 return 1;
229}
ddca870a 230
4a3b7949 231static void __attribute__((__noreturn__)) usage(FILE *out)
15103c4b 232{
738767b9 233 size_t i;
f06ec64f 234
fbbc4c88
SK
235 fputs(USAGE_HEADER, out);
236 fprintf(out, _(" %s [options]\n"), program_invocation_short_name);
237 fputs(USAGE_OPTIONS, out);
238 fputs(_(" -C, --clear clear the kernel ring buffer\n"), out);
239 fputs(_(" -c, --read-clear read and clear all messages\n"), out);
240 fputs(_(" -D, --console-off disable printing messages to console\n"), out);
fbbc4c88
SK
241 fputs(_(" -E, --console-on enable printing messages to console\n"), out);
242 fputs(_(" -F, --file <file> use the file instead of the kernel log buffer\n"), out);
243 fputs(_(" -f, --facility <list> restrict output to defined facilities\n"), out);
f0a3a1ca 244 fputs(_(" -H, --human human readable output\n"), out);
fbbc4c88 245 fputs(_(" -k, --kernel display kernel messages\n"), out);
9bc2b51a 246 fputs(_(" -L, --color[=<when>] colorize messages (auto, always or never)\n"), out);
fbbc4c88
SK
247 fputs(_(" -l, --level <list> restrict output to defined levels\n"), out);
248 fputs(_(" -n, --console-level <level> set level of messages printed to console\n"), out);
aa192520 249 fputs(_(" -P, --nopager do not pipe output into a pager\n"), out);
fbbc4c88
SK
250 fputs(_(" -r, --raw print the raw message buffer\n"), out);
251 fputs(_(" -S, --syslog force to use syslog(2) rather than /dev/kmsg\n"), out);
252 fputs(_(" -s, --buffer-size <size> buffer size to query the kernel ring buffer\n"), out);
fbbc4c88
SK
253 fputs(_(" -u, --userspace display userspace messages\n"), out);
254 fputs(_(" -w, --follow wait for new messages\n"), out);
255 fputs(_(" -x, --decode decode facility and level to readable string\n"), out);
06dd56f9
SK
256 fputs(_(" -d, --show-delta show time delta between printed messages\n"), out);
257 fputs(_(" -e, --reltime show local time and time delta in readable format\n"), out);
258 fputs(_(" -T, --ctime show human readable timestamp\n"), out);
259 fputs(_(" -t, --notime don't print messages timestamp\n"), out);
babf605d 260 fputs(_(" --time-format <format> show time stamp using format:\n"
06dd56f9
SK
261 " [delta|reltime|ctime|notime|iso]\n"
262 "Suspending/resume will make ctime and iso timestamps inaccurate.\n"), out);
fbbc4c88
SK
263 fputs(USAGE_SEPARATOR, out);
264 fputs(USAGE_HELP, out);
265 fputs(USAGE_VERSION, out);
dcd16b0f 266 fputs(_("\nSupported log facilities:\n"), out);
fbbc4c88 267 for (i = 0; i < ARRAY_SIZE(level_names); i++)
963ac507 268 fprintf(out, " %7s - %s\n",
fbbc4c88
SK
269 facility_names[i].name,
270 _(facility_names[i].help));
85f3cc55 271
dcd16b0f 272 fputs(_("\nSupported log levels (priorities):\n"), out);
fbbc4c88 273 for (i = 0; i < ARRAY_SIZE(level_names); i++)
963ac507 274 fprintf(out, " %7s - %s\n",
fbbc4c88
SK
275 level_names[i].name,
276 _(level_names[i].help));
0a86a1a6 277 fputs(USAGE_SEPARATOR, out);
30b44cf1 278 fprintf(out, USAGE_MAN_TAIL("dmesg(1)"));
4a3b7949 279 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
6dbe3af9
KZ
280}
281
5ef05369
KZ
282/*
283 * LEVEL ::= <number> | <name>
8c8fa302
BM
284 * <number> ::= @len is set: number in range <0..N>, where N < ARRAY_SIZE(level_names)
285 * ::= @len not set: number in range <1..N>, where N <= ARRAY_SIZE(level_names)
5ef05369 286 * <name> ::= case-insensitive text
8c8fa302
BM
287 *
288 * Note that @len argument is not set when parsing "-n <level>" command line
289 * option. The console_level is intepreted as "log level less than the value".
290 *
291 * For example "dmesg -n 8" or "dmesg -n debug" enables debug console log
292 * level by klogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL, 8). The @str argument
293 * has to be parsed to number in range <1..8>.
5ef05369 294 */
5c8f6bc6 295static int parse_level(const char *str, size_t len)
f06ec64f 296{
8c8fa302
BM
297 int offset = 0;
298
5c8f6bc6 299 if (!str)
f06ec64f 300 return -1;
8c8fa302 301 if (!len) {
5c8f6bc6 302 len = strlen(str);
8c8fa302
BM
303 offset = 1;
304 }
5c8f6bc6 305 errno = 0;
f06ec64f 306
5c8f6bc6
KZ
307 if (isdigit(*str)) {
308 char *end = NULL;
8c8fa302 309 long x = strtol(str, &end, 10) - offset;
5c8f6bc6 310
738767b9
KZ
311 if (!errno && end && end > str && (size_t) (end - str) == len &&
312 x >= 0 && (size_t) x < ARRAY_SIZE(level_names))
8c8fa302 313 return x + offset;
5c8f6bc6 314 } else {
738767b9
KZ
315 size_t i;
316
5c8f6bc6
KZ
317 for (i = 0; i < ARRAY_SIZE(level_names); i++) {
318 const char *n = level_names[i].name;
319
320 if (strncasecmp(str, n, len) == 0 && *(n + len) == '\0')
8c8fa302 321 return i + offset;
5c8f6bc6
KZ
322 }
323 }
324
325 if (errno)
326 err(EXIT_FAILURE, _("failed to parse level '%s'"), str);
327
328 errx(EXIT_FAILURE, _("unknown level '%s'"), str);
f06ec64f
KZ
329 return -1;
330}
331
5ef05369
KZ
332/*
333 * FACILITY ::= <number> | <name>
334 * <number> ::= number in range <0..N>, where N < ARRAY_SIZE(facility_names)
335 * <name> ::= case-insensitive text
336 */
0e24df3b
KZ
337static int parse_facility(const char *str, size_t len)
338{
0e24df3b
KZ
339 if (!str)
340 return -1;
341 if (!len)
342 len = strlen(str);
343 errno = 0;
344
345 if (isdigit(*str)) {
346 char *end = NULL;
738767b9 347 long x = strtol(str, &end, 10);
0e24df3b 348
738767b9
KZ
349 if (!errno && end && end > str && (size_t) (end - str) == len &&
350 x >= 0 && (size_t) x < ARRAY_SIZE(facility_names))
351 return x;
0e24df3b 352 } else {
738767b9
KZ
353 size_t i;
354
0e24df3b
KZ
355 for (i = 0; i < ARRAY_SIZE(facility_names); i++) {
356 const char *n = facility_names[i].name;
357
358 if (strncasecmp(str, n, len) == 0 && *(n + len) == '\0')
359 return i;
360 }
361 }
362
363 if (errno)
364 err(EXIT_FAILURE, _("failed to parse facility '%s'"), str);
365
366 errx(EXIT_FAILURE, _("unknown facility '%s'"), str);
367 return -1;
368}
369
5ef05369
KZ
370/*
371 * Parses numerical prefix used for all messages in kernel ring buffer.
372 *
373 * Priorities/facilities are encoded into a single 32-bit quantity, where the
374 * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
375 * (0-big number).
376 *
ddca870a 377 * Note that the number has to end with '>' or ',' char.
5ef05369 378 */
636a6207
KZ
379static const char *parse_faclev(const char *str, int *fac, int *lev)
380{
381 long num;
382 char *end = NULL;
383
384 if (!str)
385 return str;
386
387 errno = 0;
388 num = strtol(str, &end, 10);
389
390 if (!errno && end && end > str) {
391 *fac = LOG_FAC(num);
392 *lev = LOG_PRI(num);
85f3cc55 393
738767b9 394 if (*lev < 0 || (size_t) *lev > ARRAY_SIZE(level_names))
85f3cc55 395 *lev = -1;
738767b9 396 if (*fac < 0 || (size_t) *fac > ARRAY_SIZE(facility_names))
85f3cc55 397 *fac = -1;
ddca870a 398 return end + 1; /* skip '<' or ',' */
636a6207
KZ
399 }
400
401 return str;
402}
403
ddca870a
KZ
404/*
405 * Parses timestamp from syslog message prefix, expected format:
406 *
407 * seconds.microseconds]
408 *
409 * the ']' is the timestamp field terminator.
410 */
411static const char *parse_syslog_timestamp(const char *str0, struct timeval *tv)
bd304d92
KZ
412{
413 const char *str = str0;
414 char *end = NULL;
415
416 if (!str0)
417 return str0;
418
419 errno = 0;
420 tv->tv_sec = strtol(str, &end, 10);
421
422 if (!errno && end && *end == '.' && *(end + 1)) {
423 str = end + 1;
424 end = NULL;
425 tv->tv_usec = strtol(str, &end, 10);
426 }
427 if (errno || !end || end == str || *end != ']')
428 return str0;
429
430 return end + 1; /* skip ']' */
431}
432
ddca870a
KZ
433/*
434 * Parses timestamp from /dev/kmsg, expected formats:
435 *
436 * microseconds,
437 * microseconds;
438 *
439 * the ',' is fields separators and ';' items terminator (for the last item)
440 */
441static const char *parse_kmsg_timestamp(const char *str0, struct timeval *tv)
442{
443 const char *str = str0;
444 char *end = NULL;
445 uint64_t usec;
446
447 if (!str0)
448 return str0;
449
450 errno = 0;
451 usec = strtoumax(str, &end, 10);
452
453 if (!errno && end && (*end == ';' || *end == ',')) {
454 tv->tv_usec = usec % 1000000;
455 tv->tv_sec = usec / 1000000;
456 } else
457 return str0;
458
459 return end + 1; /* skip separator */
460}
461
bd304d92
KZ
462
463static double time_diff(struct timeval *a, struct timeval *b)
464{
465 return (a->tv_sec - b->tv_sec) + (a->tv_usec - b->tv_usec) / 1E6;
466}
467
7ff1f63f 468static int get_syslog_buffer_size(void)
eed99b2a
KZ
469{
470 int n = klogctl(SYSLOG_ACTION_SIZE_BUFFER, NULL, 0);
471
472 return n > 0 ? n : 0;
473}
474
3c5384d0 475static int get_boot_time(struct timeval *boot_time)
42fac79a 476{
3c5384d0
SK
477 struct timespec hires_uptime;
478 struct timeval lores_uptime, now;
42fac79a 479 struct sysinfo info;
42fac79a 480
3c5384d0
SK
481 if (gettimeofday(&now, NULL) != 0) {
482 warn(_("gettimeofday failed"));
483 return -errno;
484 }
485
486#ifdef CLOCK_BOOTTIME
487 if (clock_gettime(CLOCK_BOOTTIME, &hires_uptime) == 0) {
488 TIMESPEC_TO_TIMEVAL(&lores_uptime, &hires_uptime);
489 timersub(&now, &lores_uptime, boot_time);
490 return 0;
491 }
492#endif
493 /* fallback */
42fac79a
KZ
494 if (sysinfo(&info) != 0)
495 warn(_("sysinfo failed"));
3c5384d0
SK
496
497 boot_time->tv_sec = now.tv_sec - info.uptime;
498 boot_time->tv_usec = 0;
42fac79a
KZ
499 return 0;
500}
501
c672220f 502/*
7ff1f63f 503 * Reads messages from regular file by mmap
c672220f 504 */
7ff1f63f 505static ssize_t mmap_file_buffer(struct dmesg_control *ctl, char **buf)
c672220f
KZ
506{
507 struct stat st;
9b3a6984 508 int fd;
c672220f 509
9b3a6984
KZ
510 if (!ctl->filename)
511 return -1;
512
513 fd = open(ctl->filename, O_RDONLY);
c672220f 514 if (fd < 0)
9b3a6984 515 err(EXIT_FAILURE, _("cannot open %s"), ctl->filename);
c672220f 516 if (fstat(fd, &st))
9b3a6984 517 err(EXIT_FAILURE, _("stat failed %s"), ctl->filename);
c672220f
KZ
518
519 *buf = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
520 if (*buf == MAP_FAILED)
9b3a6984 521 err(EXIT_FAILURE, _("cannot mmap: %s"), ctl->filename);
c672220f
KZ
522 ctl->mmap_buff = *buf;
523 ctl->pagesize = getpagesize();
524 close(fd);
525
526 return st.st_size;
527}
528
5ef05369 529/*
7ff1f63f 530 * Reads messages from kernel ring buffer by klogctl()
5ef05369 531 */
7ff1f63f 532static ssize_t read_syslog_buffer(struct dmesg_control *ctl, char **buf)
65e3eed9
KZ
533{
534 size_t sz;
535 int rc = -1;
65e3eed9 536
e6471b9f
KZ
537 if (ctl->bufsize) {
538 sz = ctl->bufsize + 8;
65e3eed9 539 *buf = xmalloc(sz * sizeof(char));
e6471b9f 540 rc = klogctl(ctl->action, *buf, sz);
65e3eed9
KZ
541 } else {
542 sz = 16392;
543 while (1) {
544 *buf = xmalloc(sz * sizeof(char));
545 rc = klogctl(SYSLOG_ACTION_READ_ALL, *buf, sz);
738767b9
KZ
546 if (rc < 0)
547 break;
548 if ((size_t) rc != sz || sz > (1 << 28))
65e3eed9
KZ
549 break;
550 free(*buf);
551 *buf = NULL;
552 sz *= 4;
553 }
554
e6471b9f 555 if (rc > 0 && ctl->action == SYSLOG_ACTION_READ_CLEAR)
65e3eed9
KZ
556 rc = klogctl(SYSLOG_ACTION_READ_CLEAR, *buf, sz);
557 }
558
559 return rc;
560}
561
7ff1f63f
KZ
562/*
563 * Top level function to read messages
564 */
e6471b9f
KZ
565static ssize_t read_buffer(struct dmesg_control *ctl, char **buf)
566{
567 ssize_t n = -1;
568
569 switch (ctl->method) {
570 case DMESG_METHOD_MMAP:
7ff1f63f 571 n = mmap_file_buffer(ctl, buf);
e6471b9f
KZ
572 break;
573 case DMESG_METHOD_SYSLOG:
574 if (!ctl->bufsize)
7ff1f63f 575 ctl->bufsize = get_syslog_buffer_size();
e6471b9f 576
7ff1f63f 577 n = read_syslog_buffer(ctl, buf);
e6471b9f 578 break;
ddca870a
KZ
579 case DMESG_METHOD_KMSG:
580 /*
581 * Since kernel 3.5.0
582 */
583 n = read_kmsg(ctl);
c677ffba
KZ
584 if (n == 0 && ctl->action == SYSLOG_ACTION_READ_CLEAR)
585 n = klogctl(SYSLOG_ACTION_CLEAR, NULL, 0);
ddca870a 586 break;
e6471b9f
KZ
587 }
588
589 return n;
590}
591
b8300c0a
KZ
592static int fwrite_hex(const char *buf, size_t size, FILE *out)
593{
738767b9 594 size_t i;
b8300c0a
KZ
595
596 for (i = 0; i < size; i++) {
597 int rc = fprintf(out, "\\x%02x", buf[i]);
598 if (rc < 0)
599 return rc;
600 }
601 return 0;
602}
603
5ef05369
KZ
604/*
605 * Prints to 'out' and non-printable chars are replaced with \x<hex> sequences.
606 */
b8300c0a
KZ
607static void safe_fwrite(const char *buf, size_t size, FILE *out)
608{
738767b9 609 size_t i;
b8300c0a
KZ
610#ifdef HAVE_WIDECHAR
611 mbstate_t s;
612 memset(&s, 0, sizeof (s));
613#endif
614 for (i = 0; i < size; i++) {
615 const char *p = buf + i;
616 int rc, hex = 0;
ddca870a 617 size_t len = 1;
b8300c0a
KZ
618
619#ifdef HAVE_WIDECHAR
620 wchar_t wc;
0720766e 621 len = mbrtowc(&wc, p, size - i, &s);
b8300c0a
KZ
622
623 if (len == 0) /* L'\0' */
624 return;
625
730d5e77 626 if (len == (size_t)-1 || len == (size_t)-2) { /* invalid sequence */
b8300c0a
KZ
627 memset(&s, 0, sizeof (s));
628 len = hex = 1;
b8300c0a
KZ
629 } else if (len > 1 && !iswprint(wc)) { /* non-printable multibyte */
630 hex = 1;
b8300c0a 631 }
0720766e
PU
632 i += len - 1;
633#else
634 if (!isprint((unsigned int) *p) &&
635 !isspace((unsigned int) *p)) /* non-printable */
636 hex = 1;
637#endif
b8300c0a
KZ
638 if (hex)
639 rc = fwrite_hex(p, len, out);
640 else
85f3cc55 641 rc = fwrite(p, 1, len, out) != len;
b8300c0a
KZ
642 if (rc != 0)
643 err(EXIT_FAILURE, _("write failed"));
644 }
645}
646
ddca870a
KZ
647static const char *skip_item(const char *begin, const char *end, const char *sep)
648{
649 while (begin < end) {
650 int c = *begin++;
651
652 if (c == '\0' || strchr(sep, c))
653 break;
654 }
655
656 return begin;
657}
658
60464b1f
KZ
659/*
660 * Parses one record from syslog(2) buffer
661 */
7af23060
KZ
662static int get_next_syslog_record(struct dmesg_control *ctl,
663 struct dmesg_record *rec)
f4fa5b44 664{
738767b9 665 size_t i;
b8300c0a
KZ
666 const char *begin = NULL;
667
7af23060
KZ
668 if (ctl->method != DMESG_METHOD_MMAP &&
669 ctl->method != DMESG_METHOD_SYSLOG)
670 return -1;
671
a7ee94f2
KZ
672 if (!rec->next || !rec->next_size)
673 return 1;
f4fa5b44 674
ddca870a 675 INIT_DMESG_RECORD(rec);
a7ee94f2 676
c672220f
KZ
677 /*
678 * Unmap already printed file data from memory
679 */
680 if (ctl->mmap_buff && (size_t) (rec->next - ctl->mmap_buff) > ctl->pagesize) {
681 void *x = ctl->mmap_buff;
682
683 ctl->mmap_buff += ctl->pagesize;
684 munmap(x, ctl->pagesize);
685 }
686
a7ee94f2
KZ
687 for (i = 0; i < rec->next_size; i++) {
688 const char *p = rec->next + i;
689 const char *end = NULL;
b8300c0a
KZ
690
691 if (!begin)
692 begin = p;
a7ee94f2 693 if (i + 1 == rec->next_size) {
b8300c0a 694 end = p + 1;
f4fa5b44 695 i++;
22f69825
KZ
696 } else if (*p == '\n' && *(p + 1) == '<')
697 end = p;
698
a7ee94f2
KZ
699 if (begin && !*begin)
700 begin = NULL; /* zero(s) at the end of the buffer? */
b8300c0a
KZ
701 if (!begin || !end)
702 continue;
703 if (end <= begin)
704 continue; /* error or empty line? */
705
636a6207 706 if (*begin == '<') {
bb901317 707 if (ctl->fltr_lev || ctl->fltr_fac || ctl->decode || ctl->color)
a7ee94f2
KZ
708 begin = parse_faclev(begin + 1, &rec->facility,
709 &rec->level);
ddca870a
KZ
710 else
711 begin = skip_item(begin, end, ">");
b8300c0a
KZ
712 }
713
bd304d92
KZ
714 if (*begin == '[' && (*(begin + 1) == ' ' ||
715 isdigit(*(begin + 1)))) {
776eabe7
SK
716
717 if (!is_timefmt(ctl, NONE))
ddca870a 718 begin = parse_syslog_timestamp(begin + 1, &rec->tv);
776eabe7 719 else
ddca870a
KZ
720 begin = skip_item(begin, end, "]");
721
31c9099a
KZ
722 if (begin < end && *begin == ' ')
723 begin++;
a7ee94f2 724 }
d74b8dfc 725
a7ee94f2
KZ
726 rec->mesg = begin;
727 rec->mesg_size = end - begin;
b8300c0a 728
a7ee94f2
KZ
729 rec->next_size -= end - rec->next;
730 rec->next = rec->next_size > 0 ? end + 1 : NULL;
59202950
PU
731 if (rec->next_size > 0)
732 rec->next_size--;
a7ee94f2
KZ
733
734 return 0;
735 }
736
737 return 1;
738}
739
740static int accept_record(struct dmesg_control *ctl, struct dmesg_record *rec)
741{
742 if (ctl->fltr_lev && (rec->facility < 0 ||
743 !isset(ctl->levels, rec->level)))
744 return 0;
745
746 if (ctl->fltr_fac && (rec->facility < 0 ||
747 !isset(ctl->facilities, rec->facility)))
748 return 0;
749
750 return 1;
751}
752
7ff1f63f 753static void raw_print(struct dmesg_control *ctl, const char *buf, size_t size)
c672220f
KZ
754{
755 int lastc = '\n';
756
757 if (!ctl->mmap_buff) {
758 /*
759 * Print whole ring buffer
760 */
761 safe_fwrite(buf, size, stdout);
762 lastc = buf[size - 1];
763 } else {
764 /*
765 * Print file in small chunks to save memory
766 */
767 while (size) {
768 size_t sz = size > ctl->pagesize ? ctl->pagesize : size;
769 char *x = ctl->mmap_buff;
770
771 safe_fwrite(x, sz, stdout);
772 lastc = x[sz - 1];
773 size -= sz;
774 ctl->mmap_buff += sz;
775 munmap(x, sz);
776 }
777 }
778
779 if (lastc != '\n')
780 putchar('\n');
781}
782
60464b1f
KZ
783static struct tm *record_localtime(struct dmesg_control *ctl,
784 struct dmesg_record *rec,
785 struct tm *tm)
786{
3c5384d0 787 time_t t = ctl->boot_time.tv_sec + rec->tv.tv_sec;
60464b1f
KZ
788 return localtime_r(&t, tm);
789}
790
0d1b3300
KZ
791static char *record_ctime(struct dmesg_control *ctl,
792 struct dmesg_record *rec,
793 char *buf, size_t bufsiz)
794{
60464b1f 795 struct tm tm;
0d1b3300 796
60464b1f 797 record_localtime(ctl, rec, &tm);
0d1b3300 798
60464b1f 799 if (strftime(buf, bufsiz, "%a %b %e %H:%M:%S %Y", &tm) == 0)
0d1b3300
KZ
800 *buf = '\0';
801 return buf;
802}
803
60464b1f
KZ
804static char *short_ctime(struct tm *tm, char *buf, size_t bufsiz)
805{
806 if (strftime(buf, bufsiz, "%b%e %H:%M", tm) == 0)
807 *buf = '\0';
808 return buf;
809}
810
8a8be309
SK
811static char *iso_8601_time(struct dmesg_control *ctl, struct dmesg_record *rec,
812 char *buf, size_t bufsiz)
813{
814 struct tm tm;
815 size_t len;
816 record_localtime(ctl, rec, &tm);
817 if (strftime(buf, bufsiz, "%Y-%m-%dT%H:%M:%S", &tm) == 0) {
818 *buf = '\0';
819 return buf;
820 }
821 len = strlen(buf);
822 snprintf(buf + len, bufsiz - len, ",%06d", (int)rec->tv.tv_usec);
823 len = strlen(buf);
824 strftime(buf + len, bufsiz - len, "%z", &tm);
825 return buf;
826}
827
60464b1f
KZ
828static double record_count_delta(struct dmesg_control *ctl,
829 struct dmesg_record *rec)
830{
831 double delta = 0;
832
833 if (timerisset(&ctl->lasttime))
834 delta = time_diff(&rec->tv, &ctl->lasttime);
835
836 ctl->lasttime = rec->tv;
837 return delta;
838}
839
5aaee63c
KZ
840static const char *get_subsys_delimiter(const char *mesg, size_t mesg_size)
841{
842 const char *p = mesg;
843 size_t sz = mesg_size;
844
845 while (sz > 0) {
846 const char *d = strnchr(p, sz, ':');
847 if (!d)
848 return NULL;
849 sz -= d - p;
850 if (sz) {
851 if (isblank(*(d + 1)))
852 return d;
853 p = d + 1;
854 }
855 }
856 return NULL;
857}
858
60464b1f
KZ
859static void print_record(struct dmesg_control *ctl,
860 struct dmesg_record *rec)
7af23060 861{
0d1b3300 862 char buf[256];
098ce273 863 int has_color = 0;
5aaee63c
KZ
864 const char *mesg;
865 size_t mesg_size;
7af23060
KZ
866
867 if (!accept_record(ctl, rec))
868 return;
869
870 if (!rec->mesg_size) {
871 putchar('\n');
872 return;
873 }
874
0d1b3300
KZ
875 /*
876 * compose syslog(2) compatible raw output -- used for /dev/kmsg for
877 * backward compatibility with syslog(2) buffers only
878 */
37b04d6c 879 if (ctl->raw) {
37b04d6c
KZ
880 printf("<%d>[%5d.%06d] ",
881 LOG_MAKEPRI(rec->facility, rec->level),
882 (int) rec->tv.tv_sec,
883 (int) rec->tv.tv_usec);
884
885 goto mesg;
886 }
887
0d1b3300
KZ
888 /*
889 * facility : priority :
890 */
ae6288da
SK
891 if (ctl->decode &&
892 -1 < rec->level && rec->level < (int) ARRAY_SIZE(level_names) &&
893 -1 < rec->facility && rec->facility < (int) ARRAY_SIZE(facility_names))
7af23060
KZ
894 printf("%-6s:%-6s: ", facility_names[rec->facility].name,
895 level_names[rec->level].name);
896
776eabe7
SK
897 if (ctl->color)
898 color_enable(DMESG_COLOR_TIME);
0d1b3300 899
776eabe7 900 switch (ctl->time_fmt) {
60464b1f
KZ
901 double delta;
902 struct tm cur;
776eabe7
SK
903 case DMESG_TIMEFTM_NONE:
904 break;
905 case DMESG_TIMEFTM_CTIME:
906 printf("[%s] ", record_ctime(ctl, rec, buf, sizeof(buf)));
907 break;
908 case DMESG_TIMEFTM_CTIME_DELTA:
909 printf("[%s <%12.06f>] ",
910 record_ctime(ctl, rec, buf, sizeof(buf)),
911 record_count_delta(ctl, rec));
912 break;
913 case DMESG_TIMEFTM_DELTA:
914 printf("[<%12.06f>] ", record_count_delta(ctl, rec));
915 break;
916 case DMESG_TIMEFTM_RELTIME:
60464b1f
KZ
917 record_localtime(ctl, rec, &cur);
918 delta = record_count_delta(ctl, rec);
776eabe7 919 if (cur.tm_min != ctl->lasttm.tm_min ||
60464b1f 920 cur.tm_hour != ctl->lasttm.tm_hour ||
5aaee63c 921 cur.tm_yday != ctl->lasttm.tm_yday) {
60464b1f 922 printf("[%s] ", short_ctime(&cur, buf, sizeof(buf)));
5aaee63c 923 } else {
5aaee63c
KZ
924 if (delta < 10)
925 printf("[ %+8.06f] ", delta);
926 else
927 printf("[ %+9.06f] ", delta);
928 }
60464b1f 929 ctl->lasttm = cur;
776eabe7
SK
930 break;
931 case DMESG_TIMEFTM_TIME:
932 printf("[%5d.%06d] ", (int)rec->tv.tv_sec, (int)rec->tv.tv_usec);
933 break;
934 case DMESG_TIMEFTM_TIME_DELTA:
935 printf("[%5d.%06d <%12.06f>] ", (int)rec->tv.tv_sec,
936 (int)rec->tv.tv_usec, record_count_delta(ctl, rec));
937 break;
8a8be309
SK
938 case DMESG_TIMEFTM_ISO8601:
939 printf("%s ", iso_8601_time(ctl, rec, buf, sizeof(buf)));
940 break;
776eabe7
SK
941 default:
942 abort();
60464b1f 943 }
7af23060 944
776eabe7
SK
945 if (ctl->color)
946 color_disable();
ddca870a 947
37b04d6c 948mesg:
5aaee63c
KZ
949 mesg = rec->mesg;
950 mesg_size = rec->mesg_size;
951
952 /* Colorize output */
953 if (ctl->color) {
954 /* subsystem prefix */
955 const char *subsys = get_subsys_delimiter(mesg, mesg_size);
956 if (subsys) {
957 color_enable(DMESG_COLOR_SUBSYS);
958 safe_fwrite(mesg, subsys - mesg, stdout);
959 color_disable();
960
961 mesg_size -= subsys - mesg;
962 mesg = subsys;
963 }
964 /* error, alert .. etc. colors */
965 has_color = set_level_color(rec->level, mesg, mesg_size) == 0;
966 safe_fwrite(mesg, mesg_size, stdout);
967 if (has_color)
968 color_disable();
969 } else
970 safe_fwrite(mesg, mesg_size, stdout);
098ce273 971
5aaee63c 972 if (*(mesg + mesg_size - 1) != '\n')
7af23060
KZ
973 putchar('\n');
974}
975
a7ee94f2
KZ
976/*
977 * Prints the 'buf' kernel ring buffer; the messages are filtered out according
978 * to 'levels' and 'facilities' bitarrays.
979 */
7ff1f63f
KZ
980static void print_buffer(struct dmesg_control *ctl,
981 const char *buf, size_t size)
a7ee94f2
KZ
982{
983 struct dmesg_record rec = { .next = buf, .next_size = size };
984
985 if (ctl->raw) {
7ff1f63f 986 raw_print(ctl, buf, size);
a7ee94f2
KZ
987 return;
988 }
989
7af23060
KZ
990 while (get_next_syslog_record(ctl, &rec) == 0)
991 print_record(ctl, &rec);
992}
a7ee94f2 993
4ceb601d
MB
994static ssize_t read_kmsg_one(struct dmesg_control *ctl)
995{
996 ssize_t size;
997
998 /* kmsg returns EPIPE if record was modified while reading */
999 do {
1000 size = read(ctl->kmsg, ctl->kmsg_buf,
1001 sizeof(ctl->kmsg_buf) - 1);
1002 } while (size < 0 && errno == EPIPE);
1003
1004 return size;
1005}
1006
7af23060
KZ
1007static int init_kmsg(struct dmesg_control *ctl)
1008{
0fd12a96
KZ
1009 int mode = O_RDONLY;
1010
1011 if (!ctl->follow)
1012 mode |= O_NONBLOCK;
3938c08c
KZ
1013 else
1014 setlinebuf(stdout);
0fd12a96
KZ
1015
1016 ctl->kmsg = open("/dev/kmsg", mode);
c677ffba
KZ
1017 if (ctl->kmsg < 0)
1018 return -1;
1019
1020 /*
1021 * Seek after the last record available at the time
1022 * the last SYSLOG_ACTION_CLEAR was issued.
1023 *
1024 * ... otherwise SYSLOG_ACTION_CLEAR will have no effect for kmsg.
1025 */
1026 lseek(ctl->kmsg, 0, SEEK_DATA);
298a073c
KZ
1027
1028 /*
1029 * Old kernels (<3.5) allow to successfully open /dev/kmsg for
1030 * read-only, but read() returns -EINVAL :-(((
1031 *
1032 * Let's try to read the first record. The record is later processed in
1033 * read_kmsg().
1034 */
4ceb601d 1035 ctl->kmsg_first_read = read_kmsg_one(ctl);
298a073c
KZ
1036 if (ctl->kmsg_first_read < 0) {
1037 close(ctl->kmsg);
1038 ctl->kmsg = -1;
1039 return -1;
1040 }
1041
c677ffba 1042 return 0;
f4fa5b44
KZ
1043}
1044
ddca870a
KZ
1045/*
1046 * /dev/kmsg record format:
1047 *
1048 * faclev,seqnum,timestamp[optional, ...];messgage\n
1049 * TAGNAME=value
1050 * ...
1051 *
1052 * - fields are separated by ','
1053 * - last field is terminated by ';'
1054 *
1055 */
1056#define LAST_KMSG_FIELD(s) (!s || !*s || *(s - 1) == ';')
1057
1058static int parse_kmsg_record(struct dmesg_control *ctl,
1059 struct dmesg_record *rec,
1060 char *buf,
1061 size_t sz)
1062{
1063 const char *p = buf, *end;
1064
1065 if (sz == 0 || !buf || !*buf)
1066 return -1;
1067
1068 end = buf + (sz - 1);
1069 INIT_DMESG_RECORD(rec);
1070
1071 while (p < end && isspace(*p))
1072 p++;
1073
1074 /* A) priority and facility */
098ce273
OO
1075 if (ctl->fltr_lev || ctl->fltr_fac || ctl->decode ||
1076 ctl->raw || ctl->color)
ddca870a
KZ
1077 p = parse_faclev(p, &rec->facility, &rec->level);
1078 else
1079 p = skip_item(p, end, ",");
1080 if (LAST_KMSG_FIELD(p))
1081 goto mesg;
1082
1083 /* B) sequence number */
1084 p = skip_item(p, end, ",;");
1085 if (LAST_KMSG_FIELD(p))
1086 goto mesg;
1087
1088 /* C) timestamp */
776eabe7 1089 if (is_timefmt(ctl, NONE))
ddca870a
KZ
1090 p = skip_item(p, end, ",;");
1091 else
1092 p = parse_kmsg_timestamp(p, &rec->tv);
1093 if (LAST_KMSG_FIELD(p))
1094 goto mesg;
1095
1096 /* D) optional fields (ignore) */
1097 p = skip_item(p, end, ";");
1098 if (LAST_KMSG_FIELD(p))
1099 goto mesg;
1100
1101mesg:
1102 /* E) message text */
1103 rec->mesg = p;
1104 p = skip_item(p, end, "\n");
1105
1106 if (!p)
1107 return -1;
1108
1109 rec->mesg_size = p - rec->mesg;
1110
1111 /*
1112 * Kernel escapes non-printable characters, unfortuately kernel
1113 * definition of "non-printable" is too strict. On UTF8 console we can
1114 * print many chars, so let's decode from kernel.
1115 */
1116 unhexmangle_to_buffer(rec->mesg, (char *) rec->mesg, rec->mesg_size + 1);
1117
1118 /* F) message tags (ignore) */
1119
1120 return 0;
1121}
1122
1123/*
1124 * Note that each read() call for /dev/kmsg returns always one record. It means
1125 * that we don't have to read whole message buffer before the records parsing.
1126 *
1127 * So this function does not compose one huge buffer (like read_syslog_buffer())
1128 * and print_buffer() is unnecessary. All is done in this function.
1129 *
1130 * Returns 0 on success, -1 on error.
1131 */
1132static int read_kmsg(struct dmesg_control *ctl)
1133{
ddca870a 1134 struct dmesg_record rec;
298a073c 1135 ssize_t sz;
ddca870a
KZ
1136
1137 if (ctl->method != DMESG_METHOD_KMSG || ctl->kmsg < 0)
1138 return -1;
1139
298a073c
KZ
1140 /*
1141 * The very first read() call is done in kmsg_init() where we test
1142 * /dev/kmsg usability. The return code from the initial read() is
1143 * stored in ctl->kmsg_first_read;
1144 */
1145 sz = ctl->kmsg_first_read;
ddca870a 1146
298a073c
KZ
1147 while (sz > 0) {
1148 *(ctl->kmsg_buf + sz) = '\0'; /* for debug messages */
ddca870a 1149
298a073c
KZ
1150 if (parse_kmsg_record(ctl, &rec,
1151 ctl->kmsg_buf, (size_t) sz) == 0)
1152 print_record(ctl, &rec);
37b04d6c 1153
4ceb601d 1154 sz = read_kmsg_one(ctl);
298a073c 1155 }
ddca870a
KZ
1156
1157 return 0;
1158}
1159
babf605d
SK
1160static int which_time_format(const char *optarg)
1161{
1162 if (!strcmp(optarg, "notime"))
1163 return DMESG_TIMEFTM_NONE;
1164 if (!strcmp(optarg, "ctime"))
1165 return DMESG_TIMEFTM_CTIME;
1166 if (!strcmp(optarg, "delta"))
1167 return DMESG_TIMEFTM_DELTA;
1168 if (!strcmp(optarg, "reltime"))
1169 return DMESG_TIMEFTM_RELTIME;
8a8be309
SK
1170 if (!strcmp(optarg, "iso"))
1171 return DMESG_TIMEFTM_ISO8601;
babf605d
SK
1172 errx(EXIT_FAILURE, _("unknown time format: %s"), optarg);
1173}
1174
15103c4b
MP
1175int main(int argc, char *argv[])
1176{
1177 char *buf = NULL;
aa192520 1178 int c, nopager = 0;
48c5c662 1179 int console_level = 0;
6e9b06cc 1180 int klog_rc = 0;
776eabe7 1181 int delta = 0;
6e9b06cc 1182 ssize_t n;
9b3a6984 1183 static struct dmesg_control ctl = {
e6471b9f 1184 .filename = NULL,
7ff1f63f 1185 .action = SYSLOG_ACTION_READ_ALL,
ed61acc2 1186 .method = DMESG_METHOD_KMSG,
7af23060 1187 .kmsg = -1,
776eabe7 1188 .time_fmt = DMESG_TIMEFTM_TIME,
9b3a6984 1189 };
9bc2b51a 1190 int colormode = UL_COLORMODE_NEVER;
babf605d
SK
1191 enum {
1192 OPT_TIME_FORMAT = CHAR_MAX + 1,
1193 };
6dbe3af9 1194
4a3b7949 1195 static const struct option longopts[] = {
4a3b7949 1196 { "buffer-size", required_argument, NULL, 's' },
5ef05369 1197 { "clear", no_argument, NULL, 'C' },
9bc2b51a 1198 { "color", optional_argument, NULL, 'L' },
4a3b7949 1199 { "console-level", required_argument, NULL, 'n' },
bd304d92
KZ
1200 { "console-off", no_argument, NULL, 'D' },
1201 { "console-on", no_argument, NULL, 'E' },
5ef05369 1202 { "decode", no_argument, NULL, 'x' },
c672220f 1203 { "file", required_argument, NULL, 'F' },
0e24df3b 1204 { "facility", required_argument, NULL, 'f' },
0fd12a96 1205 { "follow", no_argument, NULL, 'w' },
f0a3a1ca 1206 { "human", no_argument, NULL, 'H' },
4a3b7949 1207 { "help", no_argument, NULL, 'h' },
25000180 1208 { "kernel", no_argument, NULL, 'k' },
5ef05369 1209 { "level", required_argument, NULL, 'l' },
ed61acc2 1210 { "syslog", no_argument, NULL, 'S' },
5ef05369
KZ
1211 { "raw", no_argument, NULL, 'r' },
1212 { "read-clear", no_argument, NULL, 'c' },
60464b1f 1213 { "reltime", no_argument, NULL, 'e' },
bd304d92 1214 { "show-delta", no_argument, NULL, 'd' },
42fac79a 1215 { "ctime", no_argument, NULL, 'T' },
d74b8dfc 1216 { "notime", no_argument, NULL, 't' },
aa192520 1217 { "nopager", no_argument, NULL, 'P' },
25000180 1218 { "userspace", no_argument, NULL, 'u' },
5ef05369 1219 { "version", no_argument, NULL, 'V' },
babf605d 1220 { "time-format", required_argument, NULL, OPT_TIME_FORMAT },
4a3b7949
KZ
1221 { NULL, 0, NULL, 0 }
1222 };
1223
43d2eeef 1224 static const ul_excl_t excl[] = { /* rows and cols in in ASCII order */
1a38ad5c 1225 { 'C','D','E','c','n','r' }, /* clear,off,on,read-clear,level,raw*/
f0a3a1ca 1226 { 'H','r' }, /* human, raw */
5aaee63c 1227 { 'L','r' }, /* color, raw */
43d2eeef 1228 { 'S','w' }, /* syslog,follow */
1a38ad5c
KZ
1229 { 'T','r' }, /* ctime, raw */
1230 { 'd','r' }, /* delta, raw */
1231 { 'e','r' }, /* reltime, raw */
1232 { 'r','x' }, /* raw, decode */
1233 { 'r','t' }, /* notime, raw */
43d2eeef
KZ
1234 { 0 }
1235 };
1236 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
1237
df1dddf9
KZ
1238 setlocale(LC_ALL, "");
1239 bindtextdomain(PACKAGE, LOCALEDIR);
1240 textdomain(PACKAGE);
efb8854f 1241 atexit(close_stdout);
7eda085c 1242
9bc2b51a 1243 while ((c = getopt_long(argc, argv, "CcDdEeF:f:HhkL::l:n:iPrSs:TtuVwx",
aca1633a 1244 longopts, NULL)) != -1) {
43d2eeef
KZ
1245
1246 err_exclusive_options(c, longopts, excl, excl_st);
1247
df1dddf9 1248 switch (c) {
04199860 1249 case 'C':
e6471b9f 1250 ctl.action = SYSLOG_ACTION_CLEAR;
04199860 1251 break;
df1dddf9 1252 case 'c':
e6471b9f 1253 ctl.action = SYSLOG_ACTION_READ_CLEAR;
df1dddf9 1254 break;
bd304d92 1255 case 'D':
e6471b9f 1256 ctl.action = SYSLOG_ACTION_CONSOLE_OFF;
2170174e 1257 break;
bd304d92 1258 case 'd':
776eabe7 1259 delta = 1;
bd304d92
KZ
1260 break;
1261 case 'E':
e6471b9f 1262 ctl.action = SYSLOG_ACTION_CONSOLE_ON;
2170174e 1263 break;
60464b1f 1264 case 'e':
776eabe7 1265 ctl.time_fmt = DMESG_TIMEFTM_RELTIME;
60464b1f 1266 break;
c672220f 1267 case 'F':
9b3a6984 1268 ctl.filename = optarg;
e6471b9f 1269 ctl.method = DMESG_METHOD_MMAP;
c672220f 1270 break;
0e24df3b 1271 case 'f':
aca1633a 1272 ctl.fltr_fac = 1;
c87638ad
KZ
1273 if (string_to_bitarray(optarg,
1274 ctl.facilities, parse_facility) < 0)
1275 return EXIT_FAILURE;
0e24df3b 1276 break;
f0a3a1ca 1277 case 'H':
776eabe7 1278 ctl.time_fmt = DMESG_TIMEFTM_RELTIME;
81bd88e4 1279 colormode = UL_COLORMODE_AUTO;
aa192520 1280 ctl.pager = 1;
f0a3a1ca 1281 break;
5ef05369
KZ
1282 case 'h':
1283 usage(stdout);
df1dddf9 1284 break;
25000180 1285 case 'k':
aca1633a
KZ
1286 ctl.fltr_fac = 1;
1287 setbit(ctl.facilities, FAC_BASE(LOG_KERN));
25000180 1288 break;
098ce273 1289 case 'L':
9bc2b51a 1290 colormode = UL_COLORMODE_AUTO;
b7faf991
KZ
1291 if (optarg)
1292 colormode = colormode_or_err(optarg,
1293 _("unsupported color mode"));
098ce273 1294 break;
636a6207 1295 case 'l':
aca1633a 1296 ctl.fltr_lev= 1;
c87638ad
KZ
1297 if (string_to_bitarray(optarg,
1298 ctl.levels, parse_level) < 0)
1299 return EXIT_FAILURE;
636a6207 1300 break;
5ef05369 1301 case 'n':
e6471b9f 1302 ctl.action = SYSLOG_ACTION_CONSOLE_LEVEL;
5ef05369
KZ
1303 console_level = parse_level(optarg, 0);
1304 break;
aa192520
KZ
1305 case 'P':
1306 nopager = 1;
1307 break;
11ea22d5 1308 case 'r':
aca1633a 1309 ctl.raw = 1;
11ea22d5 1310 break;
ed61acc2
KZ
1311 case 'S':
1312 ctl.method = DMESG_METHOD_SYSLOG;
1313 break;
df1dddf9 1314 case 's':
e6471b9f
KZ
1315 ctl.bufsize = strtou32_or_err(optarg,
1316 _("invalid buffer size argument"));
1317 if (ctl.bufsize < 4096)
1318 ctl.bufsize = 4096;
df1dddf9 1319 break;
42fac79a 1320 case 'T':
776eabe7 1321 ctl.time_fmt = DMESG_TIMEFTM_CTIME;
42fac79a 1322 break;
d74b8dfc 1323 case 't':
776eabe7
SK
1324 ctl.time_fmt = DMESG_TIMEFTM_NONE;
1325 delta = 0;
d74b8dfc 1326 break;
25000180 1327 case 'u':
aca1633a 1328 ctl.fltr_fac = 1;
738767b9 1329 for (n = 1; (size_t) n < ARRAY_SIZE(facility_names); n++)
aca1633a 1330 setbit(ctl.facilities, n);
25000180 1331 break;
4a3b7949
KZ
1332 case 'V':
1333 printf(_("%s from %s\n"), program_invocation_short_name,
1334 PACKAGE_STRING);
1335 return EXIT_SUCCESS;
0fd12a96 1336 case 'w':
0fd12a96
KZ
1337 ctl.follow = 1;
1338 break;
5ef05369 1339 case 'x':
aca1633a 1340 ctl.decode = 1;
4a3b7949 1341 break;
babf605d
SK
1342 case OPT_TIME_FORMAT:
1343 ctl.time_fmt = which_time_format(optarg);
1344 break;
df1dddf9
KZ
1345 case '?':
1346 default:
4a3b7949 1347 usage(stderr);
df1dddf9
KZ
1348 }
1349 }
1350 argc -= optind;
1351 argv += optind;
e6c379eb 1352
15103c4b 1353 if (argc > 1)
4a3b7949 1354 usage(stderr);
6dbe3af9 1355
15a1e371
KZ
1356 if (is_timefmt(&ctl, RELTIME) ||
1357 is_timefmt(&ctl, CTIME) ||
1358 is_timefmt(&ctl, ISO8601)) {
1359
3c5384d0 1360 if (get_boot_time(&ctl.boot_time) != 0)
776eabe7 1361 ctl.time_fmt = DMESG_TIMEFTM_NONE;
f0a3a1ca 1362 }
9bc2b51a 1363
776eabe7
SK
1364 if (delta)
1365 switch (ctl.time_fmt) {
1366 case DMESG_TIMEFTM_CTIME:
1367 ctl.time_fmt = DMESG_TIMEFTM_CTIME_DELTA;
1368 break;
1369 case DMESG_TIMEFTM_TIME:
1370 ctl.time_fmt = DMESG_TIMEFTM_TIME_DELTA;
1371 break;
e7ba987a
SK
1372 case DMESG_TIMEFTM_ISO8601:
1373 warnx(_("--show-delta is ignored when used together with iso8601 time format"));
1374 break;
776eabe7
SK
1375 default:
1376 ctl.time_fmt = DMESG_TIMEFTM_DELTA;
1377 }
1378
776eabe7 1379
9bc2b51a 1380 ctl.color = colors_init(colormode) ? 1 : 0;
5042cdcf
KZ
1381 if (ctl.follow)
1382 nopager = 1;
aa192520
KZ
1383 ctl.pager = nopager ? 0 : ctl.pager;
1384 if (ctl.pager)
1385 setup_pager();
1386
e6471b9f 1387 switch (ctl.action) {
48c5c662
KZ
1388 case SYSLOG_ACTION_READ_ALL:
1389 case SYSLOG_ACTION_READ_CLEAR:
7af23060
KZ
1390 if (ctl.method == DMESG_METHOD_KMSG && init_kmsg(&ctl) != 0)
1391 ctl.method = DMESG_METHOD_SYSLOG;
1a38ad5c
KZ
1392
1393 if (ctl.raw
1394 && ctl.method != DMESG_METHOD_KMSG
1395 && (ctl.fltr_lev || ctl.fltr_fac))
1396 errx(EXIT_FAILURE, _("--raw could be used together with --level or "
1397 "--facility only when read messages from /dev/kmsg"));
aa192520
KZ
1398 if (ctl.pager)
1399 setup_pager();
6e9b06cc
KZ
1400 n = read_buffer(&ctl, &buf);
1401 if (n > 0)
1402 print_buffer(&ctl, buf, n);
7ff1f63f 1403 if (!ctl.mmap_buff)
c672220f 1404 free(buf);
6e9b06cc
KZ
1405 if (n < 0)
1406 err(EXIT_FAILURE, _("read kernel buffer failed"));
1407 if (ctl.kmsg >= 0)
1408 close(ctl.kmsg);
48c5c662 1409 break;
04199860 1410 case SYSLOG_ACTION_CLEAR:
2170174e
KZ
1411 case SYSLOG_ACTION_CONSOLE_OFF:
1412 case SYSLOG_ACTION_CONSOLE_ON:
6e9b06cc 1413 klog_rc = klogctl(ctl.action, NULL, 0);
04199860 1414 break;
48c5c662 1415 case SYSLOG_ACTION_CONSOLE_LEVEL:
6e9b06cc 1416 klog_rc = klogctl(ctl.action, NULL, console_level);
48c5c662
KZ
1417 break;
1418 default:
1419 errx(EXIT_FAILURE, _("unsupported command"));
1420 break;
df1dddf9 1421 }
6dbe3af9 1422
7af23060 1423
6e9b06cc 1424 if (klog_rc)
15103c4b 1425 err(EXIT_FAILURE, _("klogctl failed"));
6dbe3af9 1426
15103c4b 1427 return EXIT_SUCCESS;
6dbe3af9 1428}