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