2 * dmesg.c -- Print out the contents of the kernel ring buffer
4 * Copyright (C) 1993 Theodore Ts'o <tytso@athena.mit.edu>
5 * Copyright (C) 2011 Karel Zak <kzak@redhat.com>
7 * This program comes with ABSOLUTELY NO WARRANTY.
13 #include <sys/syslog.h>
15 #include <sys/sysinfo.h>
19 #include <sys/types.h>
32 #include "closestream.h"
34 #include "timeutils.h"
35 #include "monotonic.h"
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
66 const char *scheme
; /* name used in termina-colors.d/dmesg.scheme */
67 const char *dflt
; /* default color ESC sequence */
73 DMESG_COLOR_TIMEBREAK
,
81 static const struct dmesg_color colors
[] =
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
}
93 #define dmesg_enable_color(_id) \
94 color_scheme_enable(colors[_id].scheme, colors[_id].dflt);
97 * Priority and facility names
105 * Priority names -- based on sys/syslog.h
107 static const struct dmesg_name level_names
[] =
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") }
120 * sys/syslog.h uses (f << 3) for all facility codes.
121 * We want to use the codes as array indexes, so shift back...
123 * Note that libc LOG_FAC() macro returns the base codes, not the
126 #define FAC_BASE(f) ((f) >> 3)
128 static const struct dmesg_name facility_names
[] =
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") },
144 /* supported methods to read message buffer
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) */
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 */
162 #define is_timefmt(c, f) ((c)->time_fmt == (DMESG_TIMEFTM_ ##f))
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];
169 struct timeval lasttime
; /* last printed timestamp */
170 struct tm lasttm
; /* last localtime */
171 struct timeval boot_time
; /* system boot time */
173 int action
; /* SYSLOG_ACTION_* */
174 int method
; /* DMESG_METHOD_* */
176 size_t bufsize
; /* size of syslog buffer */
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 */
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).
190 unsigned int time_fmt
; /* time format */
192 unsigned int follow
:1, /* wait for new messages */
193 raw
:1, /* raw mode */
194 noesc
:1, /* no escape */
195 fltr_lev
:1, /* filter out by levels[] */
196 fltr_fac
:1, /* filter out by facilities[] */
197 decode
:1, /* use "facility: level: " prefix */
198 pager
:1, /* pipe output into a pager */
199 color
:1, /* colorize messages */
200 force_prefix
:1; /* force timestamp and decode prefix
202 int indent
; /* due to timestamps if newline */
205 struct dmesg_record
{
213 const char *next
; /* buffer with next unparsed record */
214 size_t next_size
; /* size of the next buffer */
217 #define INIT_DMESG_RECORD(_r) do { \
219 (_r)->mesg_size = 0; \
220 (_r)->facility = -1; \
222 (_r)->tv.tv_sec = 0; \
223 (_r)->tv.tv_usec = 0; \
226 static int read_kmsg(struct dmesg_control
*ctl
);
228 static int set_level_color(int log_level
, const char *mesg
, size_t mesgsz
)
234 id
= DMESG_COLOR_ALERT
;
237 id
= DMESG_COLOR_CRIT
;
240 id
= DMESG_COLOR_ERR
;
243 id
= DMESG_COLOR_WARN
;
249 /* well, sometimes the messages contains important keywords, but in
250 * non-warning/error messages
252 if (id
< 0 && memmem(mesg
, mesgsz
, "segfault at", 11))
253 id
= DMESG_COLOR_SEGFAULT
;
256 dmesg_enable_color(id
);
258 return id
>= 0 ? 0 : -1;
261 static void __attribute__((__noreturn__
)) usage(void)
266 fputs(USAGE_HEADER
, out
);
267 fprintf(out
, _(" %s [options]\n"), program_invocation_short_name
);
269 fputs(USAGE_SEPARATOR
, out
);
270 fputs(_("Display or control the kernel ring buffer.\n"), out
);
272 fputs(USAGE_OPTIONS
, out
);
273 fputs(_(" -C, --clear clear the kernel ring buffer\n"), out
);
274 fputs(_(" -c, --read-clear read and clear all messages\n"), out
);
275 fputs(_(" -D, --console-off disable printing messages to console\n"), out
);
276 fputs(_(" -E, --console-on enable printing messages to console\n"), out
);
277 fputs(_(" -F, --file <file> use the file instead of the kernel log buffer\n"), out
);
278 fputs(_(" -f, --facility <list> restrict output to defined facilities\n"), out
);
279 fputs(_(" -H, --human human readable output\n"), out
);
280 fputs(_(" -k, --kernel display kernel messages\n"), out
);
282 _(" -L, --color[=<when>] colorize messages (%s, %s or %s)\n"), "auto", "always", "never");
284 " %s\n", USAGE_COLORS_DEFAULT
);
285 fputs(_(" -l, --level <list> restrict output to defined levels\n"), out
);
286 fputs(_(" -n, --console-level <level> set level of messages printed to console\n"), out
);
287 fputs(_(" -P, --nopager do not pipe output into a pager\n"), out
);
288 fputs(_(" -p, --force-prefix force timestamp output on each line of multi-line messages\n"), out
);
289 fputs(_(" -r, --raw print the raw message buffer\n"), out
);
290 fputs(_(" --noescape don't escape unprintable character\n"), out
);
291 fputs(_(" -S, --syslog force to use syslog(2) rather than /dev/kmsg\n"), out
);
292 fputs(_(" -s, --buffer-size <size> buffer size to query the kernel ring buffer\n"), out
);
293 fputs(_(" -u, --userspace display userspace messages\n"), out
);
294 fputs(_(" -w, --follow wait for new messages\n"), out
);
295 fputs(_(" -x, --decode decode facility and level to readable string\n"), out
);
296 fputs(_(" -d, --show-delta show time delta between printed messages\n"), out
);
297 fputs(_(" -e, --reltime show local time and time delta in readable format\n"), out
);
298 fputs(_(" -T, --ctime show human-readable timestamp (may be inaccurate!)\n"), out
);
299 fputs(_(" -t, --notime don't show any timestamp with messages\n"), out
);
300 fputs(_(" --time-format <format> show timestamp using the given format:\n"
301 " [delta|reltime|ctime|notime|iso]\n"
302 "Suspending/resume will make ctime and iso timestamps inaccurate.\n"), out
);
303 fputs(USAGE_SEPARATOR
, out
);
304 printf(USAGE_HELP_OPTIONS(29));
305 fputs(_("\nSupported log facilities:\n"), out
);
306 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++)
307 fprintf(out
, " %7s - %s\n",
308 facility_names
[i
].name
,
309 _(facility_names
[i
].help
));
311 fputs(_("\nSupported log levels (priorities):\n"), out
);
312 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++)
313 fprintf(out
, " %7s - %s\n",
315 _(level_names
[i
].help
));
317 printf(USAGE_MAN_TAIL("dmesg(1)"));
322 * LEVEL ::= <number> | <name>
323 * <number> ::= @len is set: number in range <0..N>, where N < ARRAY_SIZE(level_names)
324 * ::= @len not set: number in range <1..N>, where N <= ARRAY_SIZE(level_names)
325 * <name> ::= case-insensitive text
327 * Note that @len argument is not set when parsing "-n <level>" command line
328 * option. The console_level is interpreted as "log level less than the value".
330 * For example "dmesg -n 8" or "dmesg -n debug" enables debug console log
331 * level by klogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL, 8). The @str argument
332 * has to be parsed to number in range <1..8>.
334 static int parse_level(const char *str
, size_t len
)
348 long x
= strtol(str
, &end
, 10) - offset
;
350 if (!errno
&& end
&& end
> str
&& (size_t) (end
- str
) == len
&&
351 x
>= 0 && (size_t) x
< ARRAY_SIZE(level_names
))
356 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++) {
357 const char *n
= level_names
[i
].name
;
359 if (strncasecmp(str
, n
, len
) == 0 && *(n
+ len
) == '\0')
365 err(EXIT_FAILURE
, _("failed to parse level '%s'"), str
);
367 errx(EXIT_FAILURE
, _("unknown level '%s'"), str
);
372 * FACILITY ::= <number> | <name>
373 * <number> ::= number in range <0..N>, where N < ARRAY_SIZE(facility_names)
374 * <name> ::= case-insensitive text
376 static int parse_facility(const char *str
, size_t len
)
386 long x
= strtol(str
, &end
, 10);
388 if (!errno
&& end
&& end
> str
&& (size_t) (end
- str
) == len
&&
389 x
>= 0 && (size_t) x
< ARRAY_SIZE(facility_names
))
394 for (i
= 0; i
< ARRAY_SIZE(facility_names
); i
++) {
395 const char *n
= facility_names
[i
].name
;
397 if (strncasecmp(str
, n
, len
) == 0 && *(n
+ len
) == '\0')
403 err(EXIT_FAILURE
, _("failed to parse facility '%s'"), str
);
405 errx(EXIT_FAILURE
, _("unknown facility '%s'"), str
);
410 * Parses numerical prefix used for all messages in kernel ring buffer.
412 * Priorities/facilities are encoded into a single 32-bit quantity, where the
413 * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
416 * Note that the number has to end with '>' or ',' char.
418 static const char *parse_faclev(const char *str
, int *fac
, int *lev
)
427 num
= strtol(str
, &end
, 10);
429 if (!errno
&& end
&& end
> str
) {
433 if (*lev
< 0 || (size_t) *lev
> ARRAY_SIZE(level_names
))
435 if (*fac
< 0 || (size_t) *fac
> ARRAY_SIZE(facility_names
))
437 return end
+ 1; /* skip '<' or ',' */
444 * Parses timestamp from syslog message prefix, expected format:
446 * seconds.microseconds]
448 * the ']' is the timestamp field terminator.
450 static const char *parse_syslog_timestamp(const char *str0
, struct timeval
*tv
)
452 const char *str
= str0
;
459 tv
->tv_sec
= strtol(str
, &end
, 10);
461 if (!errno
&& end
&& *end
== '.' && *(end
+ 1)) {
464 tv
->tv_usec
= strtol(str
, &end
, 10);
466 if (errno
|| !end
|| end
== str
|| *end
!= ']')
469 return end
+ 1; /* skip ']' */
473 * Parses timestamp from /dev/kmsg, expected formats:
478 * the ',' is fields separators and ';' items terminator (for the last item)
480 static const char *parse_kmsg_timestamp(const char *str0
, struct timeval
*tv
)
482 const char *str
= str0
;
490 usec
= strtoumax(str
, &end
, 10);
492 if (!errno
&& end
&& (*end
== ';' || *end
== ',')) {
493 tv
->tv_usec
= usec
% 1000000;
494 tv
->tv_sec
= usec
/ 1000000;
498 return end
+ 1; /* skip separator */
502 static double time_diff(struct timeval
*a
, struct timeval
*b
)
504 return (a
->tv_sec
- b
->tv_sec
) + (a
->tv_usec
- b
->tv_usec
) / 1E6
;
507 static int get_syslog_buffer_size(void)
509 int n
= klogctl(SYSLOG_ACTION_SIZE_BUFFER
, NULL
, 0);
511 return n
> 0 ? n
: 0;
515 * Reads messages from regular file by mmap
517 static ssize_t
mmap_file_buffer(struct dmesg_control
*ctl
, char **buf
)
525 fd
= open(ctl
->filename
, O_RDONLY
);
527 err(EXIT_FAILURE
, _("cannot open %s"), ctl
->filename
);
529 err(EXIT_FAILURE
, _("stat of %s failed"), ctl
->filename
);
531 *buf
= mmap(NULL
, st
.st_size
, PROT_READ
, MAP_SHARED
, fd
, 0);
532 if (*buf
== MAP_FAILED
)
533 err(EXIT_FAILURE
, _("cannot mmap: %s"), ctl
->filename
);
534 ctl
->mmap_buff
= *buf
;
535 ctl
->pagesize
= getpagesize();
542 * Reads messages from kernel ring buffer by klogctl()
544 static ssize_t
read_syslog_buffer(struct dmesg_control
*ctl
, char **buf
)
550 sz
= ctl
->bufsize
+ 8;
551 *buf
= xmalloc(sz
* sizeof(char));
552 rc
= klogctl(ctl
->action
, *buf
, sz
);
556 *buf
= xmalloc(sz
* sizeof(char));
557 rc
= klogctl(SYSLOG_ACTION_READ_ALL
, *buf
, sz
);
560 if ((size_t) rc
!= sz
|| sz
> (1 << 28))
567 if (rc
> 0 && ctl
->action
== SYSLOG_ACTION_READ_CLEAR
)
568 rc
= klogctl(SYSLOG_ACTION_READ_CLEAR
, *buf
, sz
);
575 * Top level function to read messages
577 static ssize_t
read_buffer(struct dmesg_control
*ctl
, char **buf
)
581 switch (ctl
->method
) {
582 case DMESG_METHOD_MMAP
:
583 n
= mmap_file_buffer(ctl
, buf
);
585 case DMESG_METHOD_SYSLOG
:
587 ctl
->bufsize
= get_syslog_buffer_size();
589 n
= read_syslog_buffer(ctl
, buf
);
591 case DMESG_METHOD_KMSG
:
596 if (n
== 0 && ctl
->action
== SYSLOG_ACTION_READ_CLEAR
)
597 n
= klogctl(SYSLOG_ACTION_CLEAR
, NULL
, 0);
600 abort(); /* impossible method -> drop core */
606 static int fwrite_hex(const char *buf
, size_t size
, FILE *out
)
610 for (i
= 0; i
< size
; i
++) {
611 int rc
= fprintf(out
, "\\x%02hhx", buf
[i
]);
619 * Prints to 'out' and non-printable chars are replaced with \x<hex> sequences.
621 static void safe_fwrite(struct dmesg_control
*ctl
, const char *buf
, size_t size
, int indent
, FILE *out
)
627 memset(&s
, 0, sizeof (s
));
629 for (i
= 0; i
< size
; i
++) {
630 const char *p
= buf
+ i
;
640 len
= mbrtowc(&wc
, p
, size
- i
, &s
);
642 if (len
== 0) /* L'\0' */
645 if (len
== (size_t)-1 || len
== (size_t)-2) { /* invalid sequence */
646 memset(&s
, 0, sizeof (s
));
649 } else if (len
> 1) {
650 if (!iswprint(wc
) && !iswspace(wc
)) /* non-printable multibyte */
657 if (!isprint((unsigned char) *p
) &&
658 !isspace((unsigned char) *p
)) /* non-printable */
665 rc
= fwrite_hex(p
, len
, out
);
666 else if (*p
== '\n' && *(p
+ 1) && indent
) {
667 rc
= fwrite(p
, 1, len
, out
) != len
;
668 if (fprintf(out
, "%*s", indent
, "") != indent
)
671 rc
= fwrite(p
, 1, len
, out
) != len
;
675 err(EXIT_FAILURE
, _("write failed"));
681 static const char *skip_item(const char *begin
, const char *end
, const char *sep
)
683 while (begin
< end
) {
686 if (c
== '\0' || strchr(sep
, c
))
694 * Parses one record from syslog(2) buffer
696 static int get_next_syslog_record(struct dmesg_control
*ctl
,
697 struct dmesg_record
*rec
)
700 const char *begin
= NULL
;
702 if (ctl
->method
!= DMESG_METHOD_MMAP
&&
703 ctl
->method
!= DMESG_METHOD_SYSLOG
)
706 if (!rec
->next
|| !rec
->next_size
)
709 INIT_DMESG_RECORD(rec
);
712 * Unmap already printed file data from memory
714 if (ctl
->mmap_buff
&& (size_t) (rec
->next
- ctl
->mmap_buff
) > ctl
->pagesize
) {
715 void *x
= ctl
->mmap_buff
;
717 ctl
->mmap_buff
+= ctl
->pagesize
;
718 munmap(x
, ctl
->pagesize
);
721 for (i
= 0; i
< rec
->next_size
; i
++) {
722 const char *p
= rec
->next
+ i
;
723 const char *end
= NULL
;
727 if (i
+ 1 == rec
->next_size
) {
730 } else if (*p
== '\n' && *(p
+ 1) == '<')
733 if (begin
&& !*begin
)
734 begin
= NULL
; /* zero(s) at the end of the buffer? */
738 continue; /* error or empty line? */
741 if (ctl
->fltr_lev
|| ctl
->fltr_fac
|| ctl
->decode
|| ctl
->color
)
742 begin
= parse_faclev(begin
+ 1, &rec
->facility
,
745 begin
= skip_item(begin
, end
, ">");
748 if (*begin
== '[' && (*(begin
+ 1) == ' ' ||
749 isdigit(*(begin
+ 1)))) {
751 if (!is_timefmt(ctl
, NONE
))
752 begin
= parse_syslog_timestamp(begin
+ 1, &rec
->tv
);
754 begin
= skip_item(begin
, end
, "]");
756 if (begin
< end
&& *begin
== ' ')
761 rec
->mesg_size
= end
- begin
;
763 /* Don't count \n from the last message to the message size */
764 if (*end
!= '\n' && *(end
- 1) == '\n')
767 rec
->next_size
-= end
- rec
->next
;
768 rec
->next
= rec
->next_size
> 0 ? end
+ 1 : NULL
;
769 if (rec
->next_size
> 0)
778 static int accept_record(struct dmesg_control
*ctl
, struct dmesg_record
*rec
)
780 if (ctl
->fltr_lev
&& (rec
->facility
< 0 ||
781 !isset(ctl
->levels
, rec
->level
)))
784 if (ctl
->fltr_fac
&& (rec
->facility
< 0 ||
785 !isset(ctl
->facilities
, rec
->facility
)))
791 static void raw_print(struct dmesg_control
*ctl
, const char *buf
, size_t size
)
795 if (!ctl
->mmap_buff
) {
797 * Print whole ring buffer
799 safe_fwrite(ctl
, buf
, size
, 0, stdout
);
800 lastc
= buf
[size
- 1];
803 * Print file in small chunks to save memory
806 size_t sz
= size
> ctl
->pagesize
? ctl
->pagesize
: size
;
807 char *x
= ctl
->mmap_buff
;
809 safe_fwrite(ctl
, x
, sz
, 0, stdout
);
812 ctl
->mmap_buff
+= sz
;
821 static struct tm
*record_localtime(struct dmesg_control
*ctl
,
822 struct dmesg_record
*rec
,
825 time_t t
= ctl
->boot_time
.tv_sec
+ rec
->tv
.tv_sec
;
826 return localtime_r(&t
, tm
);
829 static char *record_ctime(struct dmesg_control
*ctl
,
830 struct dmesg_record
*rec
,
831 char *buf
, size_t bufsiz
)
835 record_localtime(ctl
, rec
, &tm
);
837 if (strftime(buf
, bufsiz
, "%a %b %e %H:%M:%S %Y", &tm
) == 0)
842 static char *short_ctime(struct tm
*tm
, char *buf
, size_t bufsiz
)
844 if (strftime(buf
, bufsiz
, "%b%e %H:%M", tm
) == 0)
849 static char *iso_8601_time(struct dmesg_control
*ctl
, struct dmesg_record
*rec
,
850 char *buf
, size_t bufsz
)
852 struct timeval tv
= {
853 .tv_sec
= ctl
->boot_time
.tv_sec
+ rec
->tv
.tv_sec
,
854 .tv_usec
= rec
->tv
.tv_usec
857 if (strtimeval_iso(&tv
, ISO_TIMESTAMP_COMMA_T
, buf
, bufsz
) != 0)
863 static double record_count_delta(struct dmesg_control
*ctl
,
864 struct dmesg_record
*rec
)
868 if (timerisset(&ctl
->lasttime
))
869 delta
= time_diff(&rec
->tv
, &ctl
->lasttime
);
871 ctl
->lasttime
= rec
->tv
;
875 static const char *get_subsys_delimiter(const char *mesg
, size_t mesg_size
)
877 const char *p
= mesg
;
878 size_t sz
= mesg_size
;
881 const char *d
= strnchr(p
, sz
, ':');
886 if (isblank(*(d
+ 1)))
894 static void print_record(struct dmesg_control
*ctl
,
895 struct dmesg_record
*rec
)
898 char fpbuf
[32] = "\0";
899 char tsbuf
[64] = "\0";
900 size_t mesg_size
= rec
->mesg_size
;
902 char *mesg_copy
= NULL
;
903 const char *line
= NULL
;
905 if (!accept_record(ctl
, rec
))
908 if (!rec
->mesg_size
) {
914 * Compose syslog(2) compatible raw output -- used for /dev/kmsg for
915 * backward compatibility with syslog(2) buffers only
918 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
),
920 LOG_MAKEPRI(rec
->facility
, rec
->level
),
921 (long) rec
->tv
.tv_sec
,
922 (long) rec
->tv
.tv_usec
);
926 /* Store decode information (facility & priority level) in a buffer */
928 (rec
->level
> -1) && (rec
->level
< (int) ARRAY_SIZE(level_names
)) &&
929 (rec
->facility
> -1) &&
930 (rec
->facility
< (int) ARRAY_SIZE(facility_names
)))
931 snprintf(fpbuf
, sizeof(fpbuf
), "%-6s:%-6s: ",
932 facility_names
[rec
->facility
].name
,
933 level_names
[rec
->level
].name
);
935 /* Store the timestamp in a buffer */
936 switch (ctl
->time_fmt
) {
939 case DMESG_TIMEFTM_NONE
:
942 case DMESG_TIMEFTM_CTIME
:
943 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "[%s] ",
944 record_ctime(ctl
, rec
, buf
, sizeof(buf
)));
946 case DMESG_TIMEFTM_CTIME_DELTA
:
947 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "[%s <%12.06f>] ",
948 record_ctime(ctl
, rec
, buf
, sizeof(buf
)),
949 record_count_delta(ctl
, rec
));
951 case DMESG_TIMEFTM_DELTA
:
952 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "[<%12.06f>] ",
953 record_count_delta(ctl
, rec
));
955 case DMESG_TIMEFTM_RELTIME
:
956 record_localtime(ctl
, rec
, &cur
);
957 delta
= record_count_delta(ctl
, rec
);
958 if (cur
.tm_min
!= ctl
->lasttm
.tm_min
||
959 cur
.tm_hour
!= ctl
->lasttm
.tm_hour
||
960 cur
.tm_yday
!= ctl
->lasttm
.tm_yday
) {
962 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "[%s] ",
963 short_ctime(&cur
, buf
,
967 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
),
968 "[ %+8.06f] ", delta
);
970 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
),
971 "[ %+9.06f] ", delta
);
975 case DMESG_TIMEFTM_TIME
:
976 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "[%5ld.%06ld] ",
977 (long)rec
->tv
.tv_sec
,
978 (long)rec
->tv
.tv_usec
);
980 case DMESG_TIMEFTM_TIME_DELTA
:
981 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "[%5ld.%06ld <%12.06f>] ",
982 (long)rec
->tv
.tv_sec
,
983 (long)rec
->tv
.tv_usec
,
984 record_count_delta(ctl
, rec
));
986 case DMESG_TIMEFTM_ISO8601
:
987 ctl
->indent
= snprintf(tsbuf
, sizeof(tsbuf
), "%s ",
988 iso_8601_time(ctl
, rec
, buf
,
995 ctl
->indent
+= strlen(fpbuf
);
998 /* Output the decode information */
1000 fputs(fpbuf
, stdout
);
1002 /* Output the timestamp buffer */
1004 /* Colorize the timestamp */
1006 dmesg_enable_color(timebreak
? DMESG_COLOR_TIMEBREAK
:
1008 if (ctl
->time_fmt
!= DMESG_TIMEFTM_RELTIME
) {
1009 fputs(tsbuf
, stdout
);
1012 * For relative timestamping, the first line's
1013 * timestamp is the offset and all other lines will
1014 * report an offset of 0.000000.
1017 fputs(tsbuf
, stdout
);
1019 printf("[ +0.000000] ");
1026 * A kernel message may contain several lines of output, separated
1027 * by '\n'. If the timestamp and decode outputs are forced then each
1028 * line of the message must be displayed with that information.
1030 if (ctl
->force_prefix
) {
1032 mesg_copy
= xstrdup(rec
->mesg
);
1033 line
= strtok(mesg_copy
, "\n");
1035 goto done
; /* only when something is wrong */
1036 mesg_size
= strlen(line
);
1040 mesg_size
= rec
->mesg_size
;
1043 /* Colorize kernel message output */
1045 /* Subsystem prefix */
1046 const char *subsys
= get_subsys_delimiter(line
, mesg_size
);
1050 dmesg_enable_color(DMESG_COLOR_SUBSYS
);
1051 safe_fwrite(ctl
, line
, subsys
- line
, ctl
->indent
, stdout
);
1054 mesg_size
-= subsys
- line
;
1057 /* Error, alert .. etc. colors */
1058 has_color
= set_level_color(rec
->level
, line
, mesg_size
) == 0;
1059 safe_fwrite(ctl
, line
, mesg_size
, ctl
->indent
, stdout
);
1063 safe_fwrite(ctl
, line
, mesg_size
, ctl
->indent
, stdout
);
1065 /* Get the next line */
1066 if (ctl
->force_prefix
) {
1067 line
= strtok(NULL
, "\n");
1068 if (line
&& *line
) {
1070 mesg_size
= strlen(line
);
1081 * Prints the 'buf' kernel ring buffer; the messages are filtered out according
1082 * to 'levels' and 'facilities' bitarrays.
1084 static void print_buffer(struct dmesg_control
*ctl
,
1085 const char *buf
, size_t size
)
1087 struct dmesg_record rec
= { .next
= buf
, .next_size
= size
};
1090 raw_print(ctl
, buf
, size
);
1094 while (get_next_syslog_record(ctl
, &rec
) == 0)
1095 print_record(ctl
, &rec
);
1098 static ssize_t
read_kmsg_one(struct dmesg_control
*ctl
)
1102 /* kmsg returns EPIPE if record was modified while reading */
1104 size
= read(ctl
->kmsg
, ctl
->kmsg_buf
,
1105 sizeof(ctl
->kmsg_buf
) - 1);
1106 } while (size
< 0 && errno
== EPIPE
);
1111 static int init_kmsg(struct dmesg_control
*ctl
)
1113 int mode
= O_RDONLY
;
1120 ctl
->kmsg
= open("/dev/kmsg", mode
);
1125 * Seek after the last record available at the time
1126 * the last SYSLOG_ACTION_CLEAR was issued.
1128 * ... otherwise SYSLOG_ACTION_CLEAR will have no effect for kmsg.
1130 lseek(ctl
->kmsg
, 0, SEEK_DATA
);
1133 * Old kernels (<3.5) allow to successfully open /dev/kmsg for
1134 * read-only, but read() returns -EINVAL :-(((
1136 * Let's try to read the first record. The record is later processed in
1139 ctl
->kmsg_first_read
= read_kmsg_one(ctl
);
1140 if (ctl
->kmsg_first_read
< 0) {
1150 * /dev/kmsg record format:
1152 * faclev,seqnum,timestamp[optional, ...];message\n
1156 * - fields are separated by ','
1157 * - last field is terminated by ';'
1160 #define LAST_KMSG_FIELD(s) (!s || !*s || *(s - 1) == ';')
1162 static int parse_kmsg_record(struct dmesg_control
*ctl
,
1163 struct dmesg_record
*rec
,
1167 const char *p
= buf
, *end
;
1169 if (sz
== 0 || !buf
|| !*buf
)
1172 end
= buf
+ (sz
- 1);
1173 INIT_DMESG_RECORD(rec
);
1175 while (p
< end
&& isspace(*p
))
1178 /* A) priority and facility */
1179 if (ctl
->fltr_lev
|| ctl
->fltr_fac
|| ctl
->decode
||
1180 ctl
->raw
|| ctl
->color
)
1181 p
= parse_faclev(p
, &rec
->facility
, &rec
->level
);
1183 p
= skip_item(p
, end
, ",");
1184 if (LAST_KMSG_FIELD(p
))
1187 /* B) sequence number */
1188 p
= skip_item(p
, end
, ",;");
1189 if (LAST_KMSG_FIELD(p
))
1193 if (is_timefmt(ctl
, NONE
))
1194 p
= skip_item(p
, end
, ",;");
1196 p
= parse_kmsg_timestamp(p
, &rec
->tv
);
1197 if (LAST_KMSG_FIELD(p
))
1200 /* D) optional fields (ignore) */
1201 p
= skip_item(p
, end
, ";");
1204 /* E) message text */
1206 p
= skip_item(p
, end
, "\n");
1210 /* The message text is terminated by \n, but it's possible that the
1211 * message contains another stuff behind this linebreak; in this case
1212 * the previous skip_item() returns pointer to the stuff behind \n.
1213 * Let's normalize all these situations and make sure we always point to
1216 * Note that the next unhexmangle_to_buffer() will replace \n by \0.
1218 if (*p
&& *p
!= '\n')
1222 * Kernel escapes non-printable characters, unfortunately kernel
1223 * definition of "non-printable" is too strict. On UTF8 console we can
1224 * print many chars, so let's decode from kernel.
1226 rec
->mesg_size
= unhexmangle_to_buffer(rec
->mesg
,
1227 (char *) rec
->mesg
, p
- rec
->mesg
+ 1);
1229 rec
->mesg_size
--; /* don't count \0 */
1231 /* F) message tags (ignore) */
1237 * Note that each read() call for /dev/kmsg returns always one record. It means
1238 * that we don't have to read whole message buffer before the records parsing.
1240 * So this function does not compose one huge buffer (like read_syslog_buffer())
1241 * and print_buffer() is unnecessary. All is done in this function.
1243 * Returns 0 on success, -1 on error.
1245 static int read_kmsg(struct dmesg_control
*ctl
)
1247 struct dmesg_record rec
;
1250 if (ctl
->method
!= DMESG_METHOD_KMSG
|| ctl
->kmsg
< 0)
1254 * The very first read() call is done in kmsg_init() where we test
1255 * /dev/kmsg usability. The return code from the initial read() is
1256 * stored in ctl->kmsg_first_read;
1258 sz
= ctl
->kmsg_first_read
;
1261 *(ctl
->kmsg_buf
+ sz
) = '\0'; /* for debug messages */
1263 if (parse_kmsg_record(ctl
, &rec
,
1264 ctl
->kmsg_buf
, (size_t) sz
) == 0)
1265 print_record(ctl
, &rec
);
1267 sz
= read_kmsg_one(ctl
);
1273 static int which_time_format(const char *s
)
1275 if (!strcmp(s
, "notime"))
1276 return DMESG_TIMEFTM_NONE
;
1277 if (!strcmp(s
, "ctime"))
1278 return DMESG_TIMEFTM_CTIME
;
1279 if (!strcmp(s
, "delta"))
1280 return DMESG_TIMEFTM_DELTA
;
1281 if (!strcmp(s
, "reltime"))
1282 return DMESG_TIMEFTM_RELTIME
;
1283 if (!strcmp(s
, "iso"))
1284 return DMESG_TIMEFTM_ISO8601
;
1285 errx(EXIT_FAILURE
, _("unknown time format: %s"), s
);
1289 static inline int dmesg_get_boot_time(struct timeval
*tv
)
1291 char *str
= getenv("DMESG_TEST_BOOTIME");
1292 uintmax_t sec
, usec
;
1294 if (str
&& sscanf(str
, "%ju.%ju", &sec
, &usec
) == 2) {
1297 return tv
->tv_sec
>= 0 && tv
->tv_usec
>= 0 ? 0 : -EINVAL
;
1300 return get_boot_time(tv
);
1303 # define dmesg_get_boot_time get_boot_time
1306 int main(int argc
, char *argv
[])
1310 int console_level
= 0;
1314 static struct dmesg_control ctl
= {
1316 .action
= SYSLOG_ACTION_READ_ALL
,
1317 .method
= DMESG_METHOD_KMSG
,
1319 .time_fmt
= DMESG_TIMEFTM_TIME
,
1322 int colormode
= UL_COLORMODE_UNDEF
;
1324 OPT_TIME_FORMAT
= CHAR_MAX
+ 1,
1328 static const struct option longopts
[] = {
1329 { "buffer-size", required_argument
, NULL
, 's' },
1330 { "clear", no_argument
, NULL
, 'C' },
1331 { "color", optional_argument
, NULL
, 'L' },
1332 { "console-level", required_argument
, NULL
, 'n' },
1333 { "console-off", no_argument
, NULL
, 'D' },
1334 { "console-on", no_argument
, NULL
, 'E' },
1335 { "decode", no_argument
, NULL
, 'x' },
1336 { "file", required_argument
, NULL
, 'F' },
1337 { "facility", required_argument
, NULL
, 'f' },
1338 { "follow", no_argument
, NULL
, 'w' },
1339 { "human", no_argument
, NULL
, 'H' },
1340 { "help", no_argument
, NULL
, 'h' },
1341 { "kernel", no_argument
, NULL
, 'k' },
1342 { "level", required_argument
, NULL
, 'l' },
1343 { "syslog", no_argument
, NULL
, 'S' },
1344 { "raw", no_argument
, NULL
, 'r' },
1345 { "read-clear", no_argument
, NULL
, 'c' },
1346 { "reltime", no_argument
, NULL
, 'e' },
1347 { "show-delta", no_argument
, NULL
, 'd' },
1348 { "ctime", no_argument
, NULL
, 'T' },
1349 { "noescape", no_argument
, NULL
, OPT_NOESC
},
1350 { "notime", no_argument
, NULL
, 't' },
1351 { "nopager", no_argument
, NULL
, 'P' },
1352 { "userspace", no_argument
, NULL
, 'u' },
1353 { "version", no_argument
, NULL
, 'V' },
1354 { "time-format", required_argument
, NULL
, OPT_TIME_FORMAT
},
1355 { "force-prefix", no_argument
, NULL
, 'p' },
1356 { NULL
, 0, NULL
, 0 }
1359 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
1360 { 'C','D','E','c','n','r' }, /* clear,off,on,read-clear,level,raw*/
1361 { 'H','r' }, /* human, raw */
1362 { 'L','r' }, /* color, raw */
1363 { 'S','w' }, /* syslog,follow */
1364 { 'T','r' }, /* ctime, raw */
1365 { 'd','r' }, /* delta, raw */
1366 { 'e','r' }, /* reltime, raw */
1367 { 'r','x' }, /* raw, decode */
1368 { 'r','t' }, /* notime, raw */
1371 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1373 setlocale(LC_ALL
, "");
1374 bindtextdomain(PACKAGE
, LOCALEDIR
);
1375 textdomain(PACKAGE
);
1376 close_stdout_atexit();
1378 while ((c
= getopt_long(argc
, argv
, "CcDdEeF:f:HhkL::l:n:iPprSs:TtuVwx",
1379 longopts
, NULL
)) != -1) {
1381 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1385 ctl
.action
= SYSLOG_ACTION_CLEAR
;
1388 ctl
.action
= SYSLOG_ACTION_READ_CLEAR
;
1391 ctl
.action
= SYSLOG_ACTION_CONSOLE_OFF
;
1397 ctl
.action
= SYSLOG_ACTION_CONSOLE_ON
;
1400 ctl
.time_fmt
= DMESG_TIMEFTM_RELTIME
;
1403 ctl
.filename
= optarg
;
1404 ctl
.method
= DMESG_METHOD_MMAP
;
1408 if (string_to_bitarray(optarg
,
1409 ctl
.facilities
, parse_facility
) < 0)
1410 return EXIT_FAILURE
;
1413 ctl
.time_fmt
= DMESG_TIMEFTM_RELTIME
;
1414 colormode
= UL_COLORMODE_AUTO
;
1419 setbit(ctl
.facilities
, FAC_BASE(LOG_KERN
));
1422 colormode
= UL_COLORMODE_AUTO
;
1424 colormode
= colormode_or_err(optarg
,
1425 _("unsupported color mode"));
1429 if (string_to_bitarray(optarg
,
1430 ctl
.levels
, parse_level
) < 0)
1431 return EXIT_FAILURE
;
1434 ctl
.action
= SYSLOG_ACTION_CONSOLE_LEVEL
;
1435 console_level
= parse_level(optarg
, 0);
1441 ctl
.force_prefix
= 1;
1447 ctl
.method
= DMESG_METHOD_SYSLOG
;
1450 ctl
.bufsize
= strtou32_or_err(optarg
,
1451 _("invalid buffer size argument"));
1452 if (ctl
.bufsize
< 4096)
1456 ctl
.time_fmt
= DMESG_TIMEFTM_CTIME
;
1459 ctl
.time_fmt
= DMESG_TIMEFTM_NONE
;
1463 for (n
= 1; (size_t) n
< ARRAY_SIZE(facility_names
); n
++)
1464 setbit(ctl
.facilities
, n
);
1472 case OPT_TIME_FORMAT
:
1473 ctl
.time_fmt
= which_time_format(optarg
);
1482 print_version(EXIT_SUCCESS
);
1484 errtryhelp(EXIT_FAILURE
);
1488 if (argc
!= optind
) {
1489 warnx(_("bad usage"));
1490 errtryhelp(EXIT_FAILURE
);
1493 if ((is_timefmt(&ctl
, RELTIME
) ||
1494 is_timefmt(&ctl
, CTIME
) ||
1495 is_timefmt(&ctl
, ISO8601
))
1496 && dmesg_get_boot_time(&ctl
.boot_time
) != 0)
1497 ctl
.time_fmt
= DMESG_TIMEFTM_NONE
;
1500 switch (ctl
.time_fmt
) {
1501 case DMESG_TIMEFTM_CTIME
:
1502 ctl
.time_fmt
= DMESG_TIMEFTM_CTIME_DELTA
;
1504 case DMESG_TIMEFTM_TIME
:
1505 ctl
.time_fmt
= DMESG_TIMEFTM_TIME_DELTA
;
1507 case DMESG_TIMEFTM_ISO8601
:
1508 warnx(_("--show-delta is ignored when used together with iso8601 time format"));
1511 ctl
.time_fmt
= DMESG_TIMEFTM_DELTA
;
1515 ctl
.color
= colors_init(colormode
, "dmesg") ? 1 : 0;
1518 ctl
.pager
= nopager
? 0 : ctl
.pager
;
1522 switch (ctl
.action
) {
1523 case SYSLOG_ACTION_READ_ALL
:
1524 case SYSLOG_ACTION_READ_CLEAR
:
1525 if (ctl
.method
== DMESG_METHOD_KMSG
&& init_kmsg(&ctl
) != 0)
1526 ctl
.method
= DMESG_METHOD_SYSLOG
;
1529 && ctl
.method
!= DMESG_METHOD_KMSG
1530 && (ctl
.fltr_lev
|| ctl
.fltr_fac
))
1531 errx(EXIT_FAILURE
, _("--raw can be used together with --level or "
1532 "--facility only when reading messages from /dev/kmsg"));
1534 /* only kmsg supports multi-line messages */
1535 if (ctl
.force_prefix
&& ctl
.method
!= DMESG_METHOD_KMSG
)
1536 ctl
.force_prefix
= 0;
1540 n
= read_buffer(&ctl
, &buf
);
1542 print_buffer(&ctl
, buf
, n
);
1546 err(EXIT_FAILURE
, _("read kernel buffer failed"));
1550 case SYSLOG_ACTION_CLEAR
:
1551 case SYSLOG_ACTION_CONSOLE_OFF
:
1552 case SYSLOG_ACTION_CONSOLE_ON
:
1553 klog_rc
= klogctl(ctl
.action
, NULL
, 0);
1555 case SYSLOG_ACTION_CONSOLE_LEVEL
:
1556 klog_rc
= klogctl(ctl
.action
, NULL
, console_level
);
1559 errx(EXIT_FAILURE
, _("unsupported command"));
1565 err(EXIT_FAILURE
, _("klogctl failed"));
1567 return EXIT_SUCCESS
;