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