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.
9 #include <linux/unistd.h>
14 #include <sys/syslog.h>
16 #include <sys/sysinfo.h>
20 #include <sys/types.h>
33 #include "closestream.h"
35 #include "timeutils.h"
36 #include "monotonic.h"
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
67 const char *scheme
; /* name used in termina-colors.d/dmesg.scheme */
68 const char *dflt
; /* default color ESC sequence */
74 DMESG_COLOR_TIMEBREAK
,
82 static const struct dmesg_color colors
[] =
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
}
94 #define dmesg_enable_color(_id) \
95 color_scheme_enable(colors[_id].scheme, colors[_id].dflt);
98 * Priority and facility names
106 * Priority names -- based on sys/syslog.h
108 static const struct dmesg_name level_names
[] =
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") }
121 * sys/syslog.h uses (f << 3) for all facility codes.
122 * We want to use the codes as array idexes, so shift back...
124 * Note that libc LOG_FAC() macro returns the base codes, not the
127 #define FAC_BASE(f) ((f) >> 3)
129 static const struct dmesg_name facility_names
[] =
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") },
145 /* supported methods to read message buffer
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) */
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 */
163 #define is_timefmt(c, f) ((c)->time_fmt == (DMESG_TIMEFTM_ ##f))
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];
170 struct timeval lasttime
; /* last printed timestamp */
171 struct tm lasttm
; /* last localtime */
172 struct timeval boot_time
; /* system boot time */
174 int action
; /* SYSLOG_ACTION_* */
175 int method
; /* DMESG_METHOD_* */
177 size_t bufsize
; /* size of syslog buffer */
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 */
184 * For the --file option we mmap whole file. The unnecessary (already
185 * printed) pages are always unmapped. The result is that we have in
186 * memory only the currently used page(s).
191 unsigned int time_fmt
; /* time format */
193 unsigned int follow
:1, /* wait for new messages */
194 raw
:1, /* raw mode */
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 int indent
; /* due to timestamps if newline */
203 struct dmesg_record
{
211 const char *next
; /* buffer with next unparsed record */
212 size_t next_size
; /* size of the next buffer */
215 #define INIT_DMESG_RECORD(_r) do { \
217 (_r)->mesg_size = 0; \
218 (_r)->facility = -1; \
220 (_r)->tv.tv_sec = 0; \
221 (_r)->tv.tv_usec = 0; \
224 static int read_kmsg(struct dmesg_control
*ctl
);
226 static int set_level_color(int log_level
, const char *mesg
, size_t mesgsz
)
232 id
= DMESG_COLOR_ALERT
;
235 id
= DMESG_COLOR_CRIT
;
238 id
= DMESG_COLOR_ERR
;
241 id
= DMESG_COLOR_WARN
;
247 /* well, sometimes the messges contains important keywords, but in
248 * non-warning/error messages
250 if (id
< 0 && memmem(mesg
, mesgsz
, "segfault at", 11))
251 id
= DMESG_COLOR_SEGFAULT
;
254 dmesg_enable_color(id
);
256 return id
>= 0 ? 0 : -1;
259 static void __attribute__((__noreturn__
)) usage(FILE *out
)
263 fputs(USAGE_HEADER
, out
);
264 fprintf(out
, _(" %s [options]\n"), program_invocation_short_name
);
266 fputs(USAGE_SEPARATOR
, out
);
267 fputs(_("Display or control the kernel ring buffer.\n"), out
);
269 fputs(USAGE_OPTIONS
, out
);
270 fputs(_(" -C, --clear clear the kernel ring buffer\n"), out
);
271 fputs(_(" -c, --read-clear read and clear all messages\n"), out
);
272 fputs(_(" -D, --console-off disable printing messages to console\n"), out
);
273 fputs(_(" -E, --console-on enable printing messages to console\n"), out
);
274 fputs(_(" -F, --file <file> use the file instead of the kernel log buffer\n"), out
);
275 fputs(_(" -f, --facility <list> restrict output to defined facilities\n"), out
);
276 fputs(_(" -H, --human human readable output\n"), out
);
277 fputs(_(" -k, --kernel display kernel messages\n"), out
);
278 fputs(_(" -L, --color[=<when>] colorize messages (auto, always or never)\n"), out
);
280 " %s\n", USAGE_COLORS_DEFAULT
);
281 fputs(_(" -l, --level <list> restrict output to defined levels\n"), out
);
282 fputs(_(" -n, --console-level <level> set level of messages printed to console\n"), out
);
283 fputs(_(" -P, --nopager do not pipe output into a pager\n"), out
);
284 fputs(_(" -r, --raw print the raw message buffer\n"), out
);
285 fputs(_(" -S, --syslog force to use syslog(2) rather than /dev/kmsg\n"), out
);
286 fputs(_(" -s, --buffer-size <size> buffer size to query the kernel ring buffer\n"), out
);
287 fputs(_(" -u, --userspace display userspace messages\n"), out
);
288 fputs(_(" -w, --follow wait for new messages\n"), out
);
289 fputs(_(" -x, --decode decode facility and level to readable string\n"), out
);
290 fputs(_(" -d, --show-delta show time delta between printed messages\n"), out
);
291 fputs(_(" -e, --reltime show local time and time delta in readable format\n"), out
);
292 fputs(_(" -T, --ctime show human readable timestamp (may be inaccurate!)\n"), out
);
293 fputs(_(" -t, --notime don't print messages timestamp\n"), out
);
294 fputs(_(" --time-format <format> show time stamp using format:\n"
295 " [delta|reltime|ctime|notime|iso]\n"
296 "Suspending/resume will make ctime and iso timestamps inaccurate.\n"), out
);
297 fputs(USAGE_SEPARATOR
, out
);
298 fputs(USAGE_HELP
, out
);
299 fputs(USAGE_VERSION
, out
);
300 fputs(_("\nSupported log facilities:\n"), out
);
301 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++)
302 fprintf(out
, " %7s - %s\n",
303 facility_names
[i
].name
,
304 _(facility_names
[i
].help
));
306 fputs(_("\nSupported log levels (priorities):\n"), out
);
307 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++)
308 fprintf(out
, " %7s - %s\n",
310 _(level_names
[i
].help
));
311 fputs(USAGE_SEPARATOR
, out
);
312 fprintf(out
, USAGE_MAN_TAIL("dmesg(1)"));
313 exit(out
== stderr
? EXIT_FAILURE
: EXIT_SUCCESS
);
317 * LEVEL ::= <number> | <name>
318 * <number> ::= @len is set: number in range <0..N>, where N < ARRAY_SIZE(level_names)
319 * ::= @len not set: number in range <1..N>, where N <= ARRAY_SIZE(level_names)
320 * <name> ::= case-insensitive text
322 * Note that @len argument is not set when parsing "-n <level>" command line
323 * option. The console_level is intepreted as "log level less than the value".
325 * For example "dmesg -n 8" or "dmesg -n debug" enables debug console log
326 * level by klogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL, 8). The @str argument
327 * has to be parsed to number in range <1..8>.
329 static int parse_level(const char *str
, size_t len
)
343 long x
= strtol(str
, &end
, 10) - offset
;
345 if (!errno
&& end
&& end
> str
&& (size_t) (end
- str
) == len
&&
346 x
>= 0 && (size_t) x
< ARRAY_SIZE(level_names
))
351 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++) {
352 const char *n
= level_names
[i
].name
;
354 if (strncasecmp(str
, n
, len
) == 0 && *(n
+ len
) == '\0')
360 err(EXIT_FAILURE
, _("failed to parse level '%s'"), str
);
362 errx(EXIT_FAILURE
, _("unknown level '%s'"), str
);
367 * FACILITY ::= <number> | <name>
368 * <number> ::= number in range <0..N>, where N < ARRAY_SIZE(facility_names)
369 * <name> ::= case-insensitive text
371 static int parse_facility(const char *str
, size_t len
)
381 long x
= strtol(str
, &end
, 10);
383 if (!errno
&& end
&& end
> str
&& (size_t) (end
- str
) == len
&&
384 x
>= 0 && (size_t) x
< ARRAY_SIZE(facility_names
))
389 for (i
= 0; i
< ARRAY_SIZE(facility_names
); i
++) {
390 const char *n
= facility_names
[i
].name
;
392 if (strncasecmp(str
, n
, len
) == 0 && *(n
+ len
) == '\0')
398 err(EXIT_FAILURE
, _("failed to parse facility '%s'"), str
);
400 errx(EXIT_FAILURE
, _("unknown facility '%s'"), str
);
405 * Parses numerical prefix used for all messages in kernel ring buffer.
407 * Priorities/facilities are encoded into a single 32-bit quantity, where the
408 * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
411 * Note that the number has to end with '>' or ',' char.
413 static const char *parse_faclev(const char *str
, int *fac
, int *lev
)
422 num
= strtol(str
, &end
, 10);
424 if (!errno
&& end
&& end
> str
) {
428 if (*lev
< 0 || (size_t) *lev
> ARRAY_SIZE(level_names
))
430 if (*fac
< 0 || (size_t) *fac
> ARRAY_SIZE(facility_names
))
432 return end
+ 1; /* skip '<' or ',' */
439 * Parses timestamp from syslog message prefix, expected format:
441 * seconds.microseconds]
443 * the ']' is the timestamp field terminator.
445 static const char *parse_syslog_timestamp(const char *str0
, struct timeval
*tv
)
447 const char *str
= str0
;
454 tv
->tv_sec
= strtol(str
, &end
, 10);
456 if (!errno
&& end
&& *end
== '.' && *(end
+ 1)) {
459 tv
->tv_usec
= strtol(str
, &end
, 10);
461 if (errno
|| !end
|| end
== str
|| *end
!= ']')
464 return end
+ 1; /* skip ']' */
468 * Parses timestamp from /dev/kmsg, expected formats:
473 * the ',' is fields separators and ';' items terminator (for the last item)
475 static const char *parse_kmsg_timestamp(const char *str0
, struct timeval
*tv
)
477 const char *str
= str0
;
485 usec
= strtoumax(str
, &end
, 10);
487 if (!errno
&& end
&& (*end
== ';' || *end
== ',')) {
488 tv
->tv_usec
= usec
% 1000000;
489 tv
->tv_sec
= usec
/ 1000000;
493 return end
+ 1; /* skip separator */
497 static double time_diff(struct timeval
*a
, struct timeval
*b
)
499 return (a
->tv_sec
- b
->tv_sec
) + (a
->tv_usec
- b
->tv_usec
) / 1E6
;
502 static int get_syslog_buffer_size(void)
504 int n
= klogctl(SYSLOG_ACTION_SIZE_BUFFER
, NULL
, 0);
506 return n
> 0 ? n
: 0;
510 * Reads messages from regular file by mmap
512 static ssize_t
mmap_file_buffer(struct dmesg_control
*ctl
, char **buf
)
520 fd
= open(ctl
->filename
, O_RDONLY
);
522 err(EXIT_FAILURE
, _("cannot open %s"), ctl
->filename
);
524 err(EXIT_FAILURE
, _("stat of %s failed"), ctl
->filename
);
526 *buf
= mmap(NULL
, st
.st_size
, PROT_READ
, MAP_SHARED
, fd
, 0);
527 if (*buf
== MAP_FAILED
)
528 err(EXIT_FAILURE
, _("cannot mmap: %s"), ctl
->filename
);
529 ctl
->mmap_buff
= *buf
;
530 ctl
->pagesize
= getpagesize();
537 * Reads messages from kernel ring buffer by klogctl()
539 static ssize_t
read_syslog_buffer(struct dmesg_control
*ctl
, char **buf
)
545 sz
= ctl
->bufsize
+ 8;
546 *buf
= xmalloc(sz
* sizeof(char));
547 rc
= klogctl(ctl
->action
, *buf
, sz
);
551 *buf
= xmalloc(sz
* sizeof(char));
552 rc
= klogctl(SYSLOG_ACTION_READ_ALL
, *buf
, sz
);
555 if ((size_t) rc
!= sz
|| sz
> (1 << 28))
562 if (rc
> 0 && ctl
->action
== SYSLOG_ACTION_READ_CLEAR
)
563 rc
= klogctl(SYSLOG_ACTION_READ_CLEAR
, *buf
, sz
);
570 * Top level function to read messages
572 static ssize_t
read_buffer(struct dmesg_control
*ctl
, char **buf
)
576 switch (ctl
->method
) {
577 case DMESG_METHOD_MMAP
:
578 n
= mmap_file_buffer(ctl
, buf
);
580 case DMESG_METHOD_SYSLOG
:
582 ctl
->bufsize
= get_syslog_buffer_size();
584 n
= read_syslog_buffer(ctl
, buf
);
586 case DMESG_METHOD_KMSG
:
591 if (n
== 0 && ctl
->action
== SYSLOG_ACTION_READ_CLEAR
)
592 n
= klogctl(SYSLOG_ACTION_CLEAR
, NULL
, 0);
599 static int fwrite_hex(const char *buf
, size_t size
, FILE *out
)
603 for (i
= 0; i
< size
; i
++) {
604 int rc
= fprintf(out
, "\\x%02x", buf
[i
]);
612 * Prints to 'out' and non-printable chars are replaced with \x<hex> sequences.
614 static void safe_fwrite(const char *buf
, size_t size
, int indent
, FILE *out
)
619 memset(&s
, 0, sizeof (s
));
621 for (i
= 0; i
< size
; i
++) {
622 const char *p
= buf
+ i
;
628 len
= mbrtowc(&wc
, p
, size
- i
, &s
);
630 if (len
== 0) /* L'\0' */
633 if (len
== (size_t)-1 || len
== (size_t)-2) { /* invalid sequence */
634 memset(&s
, 0, sizeof (s
));
636 } else if (len
> 1 && !iswprint(wc
)) { /* non-printable multibyte */
642 if (!isprint((unsigned int) *p
) &&
643 !isspace((unsigned int) *p
)) /* non-printable */
647 rc
= fwrite_hex(p
, len
, out
);
648 else if (*p
== '\n' && *(p
+ 1) && indent
) {
649 rc
= fwrite(p
, 1, len
, out
) != len
;
650 if (fprintf(out
, "%*s", indent
, "") != indent
)
654 rc
= fwrite(p
, 1, len
, out
) != len
;
657 err(EXIT_FAILURE
, _("write failed"));
663 static const char *skip_item(const char *begin
, const char *end
, const char *sep
)
665 while (begin
< end
) {
668 if (c
== '\0' || strchr(sep
, c
))
676 * Parses one record from syslog(2) buffer
678 static int get_next_syslog_record(struct dmesg_control
*ctl
,
679 struct dmesg_record
*rec
)
682 const char *begin
= NULL
;
684 if (ctl
->method
!= DMESG_METHOD_MMAP
&&
685 ctl
->method
!= DMESG_METHOD_SYSLOG
)
688 if (!rec
->next
|| !rec
->next_size
)
691 INIT_DMESG_RECORD(rec
);
694 * Unmap already printed file data from memory
696 if (ctl
->mmap_buff
&& (size_t) (rec
->next
- ctl
->mmap_buff
) > ctl
->pagesize
) {
697 void *x
= ctl
->mmap_buff
;
699 ctl
->mmap_buff
+= ctl
->pagesize
;
700 munmap(x
, ctl
->pagesize
);
703 for (i
= 0; i
< rec
->next_size
; i
++) {
704 const char *p
= rec
->next
+ i
;
705 const char *end
= NULL
;
709 if (i
+ 1 == rec
->next_size
) {
712 } else if (*p
== '\n' && *(p
+ 1) == '<')
715 if (begin
&& !*begin
)
716 begin
= NULL
; /* zero(s) at the end of the buffer? */
720 continue; /* error or empty line? */
723 if (ctl
->fltr_lev
|| ctl
->fltr_fac
|| ctl
->decode
|| ctl
->color
)
724 begin
= parse_faclev(begin
+ 1, &rec
->facility
,
727 begin
= skip_item(begin
, end
, ">");
730 if (*begin
== '[' && (*(begin
+ 1) == ' ' ||
731 isdigit(*(begin
+ 1)))) {
733 if (!is_timefmt(ctl
, NONE
))
734 begin
= parse_syslog_timestamp(begin
+ 1, &rec
->tv
);
736 begin
= skip_item(begin
, end
, "]");
738 if (begin
< end
&& *begin
== ' ')
743 rec
->mesg_size
= end
- begin
;
745 rec
->next_size
-= end
- rec
->next
;
746 rec
->next
= rec
->next_size
> 0 ? end
+ 1 : NULL
;
747 if (rec
->next_size
> 0)
756 static int accept_record(struct dmesg_control
*ctl
, struct dmesg_record
*rec
)
758 if (ctl
->fltr_lev
&& (rec
->facility
< 0 ||
759 !isset(ctl
->levels
, rec
->level
)))
762 if (ctl
->fltr_fac
&& (rec
->facility
< 0 ||
763 !isset(ctl
->facilities
, rec
->facility
)))
769 static void raw_print(struct dmesg_control
*ctl
, const char *buf
, size_t size
)
773 if (!ctl
->mmap_buff
) {
775 * Print whole ring buffer
777 safe_fwrite(buf
, size
, 0, stdout
);
778 lastc
= buf
[size
- 1];
781 * Print file in small chunks to save memory
784 size_t sz
= size
> ctl
->pagesize
? ctl
->pagesize
: size
;
785 char *x
= ctl
->mmap_buff
;
787 safe_fwrite(x
, sz
, 0, stdout
);
790 ctl
->mmap_buff
+= sz
;
799 static struct tm
*record_localtime(struct dmesg_control
*ctl
,
800 struct dmesg_record
*rec
,
803 time_t t
= ctl
->boot_time
.tv_sec
+ rec
->tv
.tv_sec
;
804 return localtime_r(&t
, tm
);
807 static char *record_ctime(struct dmesg_control
*ctl
,
808 struct dmesg_record
*rec
,
809 char *buf
, size_t bufsiz
)
813 record_localtime(ctl
, rec
, &tm
);
815 if (strftime(buf
, bufsiz
, "%a %b %e %H:%M:%S %Y", &tm
) == 0)
820 static char *short_ctime(struct tm
*tm
, char *buf
, size_t bufsiz
)
822 if (strftime(buf
, bufsiz
, "%b%e %H:%M", tm
) == 0)
827 static char *iso_8601_time(struct dmesg_control
*ctl
, struct dmesg_record
*rec
,
828 char *buf
, size_t bufsiz
)
832 record_localtime(ctl
, rec
, &tm
);
833 if (strftime(buf
, bufsiz
, "%Y-%m-%dT%H:%M:%S", &tm
) == 0) {
838 snprintf(buf
+ len
, bufsiz
- len
, ",%06d", (int)rec
->tv
.tv_usec
);
840 strftime(buf
+ len
, bufsiz
- len
, "%z", &tm
);
844 static double record_count_delta(struct dmesg_control
*ctl
,
845 struct dmesg_record
*rec
)
849 if (timerisset(&ctl
->lasttime
))
850 delta
= time_diff(&rec
->tv
, &ctl
->lasttime
);
852 ctl
->lasttime
= rec
->tv
;
856 static const char *get_subsys_delimiter(const char *mesg
, size_t mesg_size
)
858 const char *p
= mesg
;
859 size_t sz
= mesg_size
;
862 const char *d
= strnchr(p
, sz
, ':');
867 if (isblank(*(d
+ 1)))
875 static void print_record(struct dmesg_control
*ctl
,
876 struct dmesg_record
*rec
)
884 if (!accept_record(ctl
, rec
))
887 if (!rec
->mesg_size
) {
893 * compose syslog(2) compatible raw output -- used for /dev/kmsg for
894 * backward compatibility with syslog(2) buffers only
897 ctl
->indent
= printf("<%d>[%5d.%06d] ",
898 LOG_MAKEPRI(rec
->facility
, rec
->level
),
899 (int) rec
->tv
.tv_sec
,
900 (int) rec
->tv
.tv_usec
);
906 * facility : priority :
909 -1 < rec
->level
&& rec
->level
< (int) ARRAY_SIZE(level_names
) &&
910 -1 < rec
->facility
&& rec
->facility
< (int) ARRAY_SIZE(facility_names
))
911 indent
= printf("%-6s:%-6s: ", facility_names
[rec
->facility
].name
,
912 level_names
[rec
->level
].name
);
915 dmesg_enable_color(DMESG_COLOR_TIME
);
917 switch (ctl
->time_fmt
) {
920 case DMESG_TIMEFTM_NONE
:
923 case DMESG_TIMEFTM_CTIME
:
924 ctl
->indent
= printf("[%s] ", record_ctime(ctl
, rec
, buf
, sizeof(buf
)));
926 case DMESG_TIMEFTM_CTIME_DELTA
:
927 ctl
->indent
= printf("[%s <%12.06f>] ",
928 record_ctime(ctl
, rec
, buf
, sizeof(buf
)),
929 record_count_delta(ctl
, rec
));
931 case DMESG_TIMEFTM_DELTA
:
932 ctl
->indent
= printf("[<%12.06f>] ", record_count_delta(ctl
, rec
));
934 case DMESG_TIMEFTM_RELTIME
:
935 record_localtime(ctl
, rec
, &cur
);
936 delta
= record_count_delta(ctl
, rec
);
937 if (cur
.tm_min
!= ctl
->lasttm
.tm_min
||
938 cur
.tm_hour
!= ctl
->lasttm
.tm_hour
||
939 cur
.tm_yday
!= ctl
->lasttm
.tm_yday
) {
940 dmesg_enable_color(DMESG_COLOR_TIMEBREAK
);
941 ctl
->indent
= printf("[%s] ", short_ctime(&cur
, buf
, sizeof(buf
)));
944 ctl
->indent
= printf("[ %+8.06f] ", delta
);
946 ctl
->indent
= printf("[ %+9.06f] ", delta
);
950 case DMESG_TIMEFTM_TIME
:
951 ctl
->indent
= printf("[%5d.%06d] ", (int)rec
->tv
.tv_sec
, (int)rec
->tv
.tv_usec
);
953 case DMESG_TIMEFTM_TIME_DELTA
:
954 ctl
->indent
= printf("[%5d.%06d <%12.06f>] ", (int)rec
->tv
.tv_sec
,
955 (int)rec
->tv
.tv_usec
, record_count_delta(ctl
, rec
));
957 case DMESG_TIMEFTM_ISO8601
:
958 ctl
->indent
= printf("%s ", iso_8601_time(ctl
, rec
, buf
, sizeof(buf
)));
964 ctl
->indent
+= indent
;
971 mesg_size
= rec
->mesg_size
;
973 /* Colorize output */
975 /* subsystem prefix */
976 const char *subsys
= get_subsys_delimiter(mesg
, mesg_size
);
978 dmesg_enable_color(DMESG_COLOR_SUBSYS
);
979 safe_fwrite(mesg
, subsys
- mesg
, ctl
->indent
, stdout
);
982 mesg_size
-= subsys
- mesg
;
985 /* error, alert .. etc. colors */
986 has_color
= set_level_color(rec
->level
, mesg
, mesg_size
) == 0;
987 safe_fwrite(mesg
, mesg_size
, ctl
->indent
, stdout
);
991 safe_fwrite(mesg
, mesg_size
, ctl
->indent
, stdout
);
993 if (*(mesg
+ mesg_size
- 1) != '\n')
998 * Prints the 'buf' kernel ring buffer; the messages are filtered out according
999 * to 'levels' and 'facilities' bitarrays.
1001 static void print_buffer(struct dmesg_control
*ctl
,
1002 const char *buf
, size_t size
)
1004 struct dmesg_record rec
= { .next
= buf
, .next_size
= size
};
1007 raw_print(ctl
, buf
, size
);
1011 while (get_next_syslog_record(ctl
, &rec
) == 0)
1012 print_record(ctl
, &rec
);
1015 static ssize_t
read_kmsg_one(struct dmesg_control
*ctl
)
1019 /* kmsg returns EPIPE if record was modified while reading */
1021 size
= read(ctl
->kmsg
, ctl
->kmsg_buf
,
1022 sizeof(ctl
->kmsg_buf
) - 1);
1023 } while (size
< 0 && errno
== EPIPE
);
1028 static int init_kmsg(struct dmesg_control
*ctl
)
1030 int mode
= O_RDONLY
;
1037 ctl
->kmsg
= open("/dev/kmsg", mode
);
1042 * Seek after the last record available at the time
1043 * the last SYSLOG_ACTION_CLEAR was issued.
1045 * ... otherwise SYSLOG_ACTION_CLEAR will have no effect for kmsg.
1047 lseek(ctl
->kmsg
, 0, SEEK_DATA
);
1050 * Old kernels (<3.5) allow to successfully open /dev/kmsg for
1051 * read-only, but read() returns -EINVAL :-(((
1053 * Let's try to read the first record. The record is later processed in
1056 ctl
->kmsg_first_read
= read_kmsg_one(ctl
);
1057 if (ctl
->kmsg_first_read
< 0) {
1067 * /dev/kmsg record format:
1069 * faclev,seqnum,timestamp[optional, ...];messgage\n
1073 * - fields are separated by ','
1074 * - last field is terminated by ';'
1077 #define LAST_KMSG_FIELD(s) (!s || !*s || *(s - 1) == ';')
1079 static int parse_kmsg_record(struct dmesg_control
*ctl
,
1080 struct dmesg_record
*rec
,
1084 const char *p
= buf
, *end
;
1086 if (sz
== 0 || !buf
|| !*buf
)
1089 end
= buf
+ (sz
- 1);
1090 INIT_DMESG_RECORD(rec
);
1092 while (p
< end
&& isspace(*p
))
1095 /* A) priority and facility */
1096 if (ctl
->fltr_lev
|| ctl
->fltr_fac
|| ctl
->decode
||
1097 ctl
->raw
|| ctl
->color
)
1098 p
= parse_faclev(p
, &rec
->facility
, &rec
->level
);
1100 p
= skip_item(p
, end
, ",");
1101 if (LAST_KMSG_FIELD(p
))
1104 /* B) sequence number */
1105 p
= skip_item(p
, end
, ",;");
1106 if (LAST_KMSG_FIELD(p
))
1110 if (is_timefmt(ctl
, NONE
))
1111 p
= skip_item(p
, end
, ",;");
1113 p
= parse_kmsg_timestamp(p
, &rec
->tv
);
1114 if (LAST_KMSG_FIELD(p
))
1117 /* D) optional fields (ignore) */
1118 p
= skip_item(p
, end
, ";");
1119 if (LAST_KMSG_FIELD(p
))
1123 /* E) message text */
1125 p
= skip_item(p
, end
, "\n");
1130 rec
->mesg_size
= p
- rec
->mesg
;
1133 * Kernel escapes non-printable characters, unfortuately kernel
1134 * definition of "non-printable" is too strict. On UTF8 console we can
1135 * print many chars, so let's decode from kernel.
1137 unhexmangle_to_buffer(rec
->mesg
, (char *) rec
->mesg
, rec
->mesg_size
+ 1);
1139 /* F) message tags (ignore) */
1145 * Note that each read() call for /dev/kmsg returns always one record. It means
1146 * that we don't have to read whole message buffer before the records parsing.
1148 * So this function does not compose one huge buffer (like read_syslog_buffer())
1149 * and print_buffer() is unnecessary. All is done in this function.
1151 * Returns 0 on success, -1 on error.
1153 static int read_kmsg(struct dmesg_control
*ctl
)
1155 struct dmesg_record rec
;
1158 if (ctl
->method
!= DMESG_METHOD_KMSG
|| ctl
->kmsg
< 0)
1162 * The very first read() call is done in kmsg_init() where we test
1163 * /dev/kmsg usability. The return code from the initial read() is
1164 * stored in ctl->kmsg_first_read;
1166 sz
= ctl
->kmsg_first_read
;
1169 *(ctl
->kmsg_buf
+ sz
) = '\0'; /* for debug messages */
1171 if (parse_kmsg_record(ctl
, &rec
,
1172 ctl
->kmsg_buf
, (size_t) sz
) == 0)
1173 print_record(ctl
, &rec
);
1175 sz
= read_kmsg_one(ctl
);
1181 static int which_time_format(const char *optarg
)
1183 if (!strcmp(optarg
, "notime"))
1184 return DMESG_TIMEFTM_NONE
;
1185 if (!strcmp(optarg
, "ctime"))
1186 return DMESG_TIMEFTM_CTIME
;
1187 if (!strcmp(optarg
, "delta"))
1188 return DMESG_TIMEFTM_DELTA
;
1189 if (!strcmp(optarg
, "reltime"))
1190 return DMESG_TIMEFTM_RELTIME
;
1191 if (!strcmp(optarg
, "iso"))
1192 return DMESG_TIMEFTM_ISO8601
;
1193 errx(EXIT_FAILURE
, _("unknown time format: %s"), optarg
);
1197 static inline int dmesg_get_boot_time(struct timeval
*tv
)
1199 char *str
= getenv("DMESG_TEST_BOOTIME");
1200 uintmax_t sec
, usec
;
1202 if (str
&& sscanf(str
, "%ju.%ju", &sec
, &usec
) == 2) {
1205 return tv
->tv_sec
>= 0 && tv
->tv_usec
>= 0 ? 0 : -EINVAL
;
1208 return get_boot_time(tv
);
1211 # define dmesg_get_boot_time get_boot_time
1214 int main(int argc
, char *argv
[])
1218 int console_level
= 0;
1222 static struct dmesg_control ctl
= {
1224 .action
= SYSLOG_ACTION_READ_ALL
,
1225 .method
= DMESG_METHOD_KMSG
,
1227 .time_fmt
= DMESG_TIMEFTM_TIME
,
1230 int colormode
= UL_COLORMODE_UNDEF
;
1232 OPT_TIME_FORMAT
= CHAR_MAX
+ 1,
1235 static const struct option longopts
[] = {
1236 { "buffer-size", required_argument
, NULL
, 's' },
1237 { "clear", no_argument
, NULL
, 'C' },
1238 { "color", optional_argument
, NULL
, 'L' },
1239 { "console-level", required_argument
, NULL
, 'n' },
1240 { "console-off", no_argument
, NULL
, 'D' },
1241 { "console-on", no_argument
, NULL
, 'E' },
1242 { "decode", no_argument
, NULL
, 'x' },
1243 { "file", required_argument
, NULL
, 'F' },
1244 { "facility", required_argument
, NULL
, 'f' },
1245 { "follow", no_argument
, NULL
, 'w' },
1246 { "human", no_argument
, NULL
, 'H' },
1247 { "help", no_argument
, NULL
, 'h' },
1248 { "kernel", no_argument
, NULL
, 'k' },
1249 { "level", required_argument
, NULL
, 'l' },
1250 { "syslog", no_argument
, NULL
, 'S' },
1251 { "raw", no_argument
, NULL
, 'r' },
1252 { "read-clear", no_argument
, NULL
, 'c' },
1253 { "reltime", no_argument
, NULL
, 'e' },
1254 { "show-delta", no_argument
, NULL
, 'd' },
1255 { "ctime", no_argument
, NULL
, 'T' },
1256 { "notime", no_argument
, NULL
, 't' },
1257 { "nopager", no_argument
, NULL
, 'P' },
1258 { "userspace", no_argument
, NULL
, 'u' },
1259 { "version", no_argument
, NULL
, 'V' },
1260 { "time-format", required_argument
, NULL
, OPT_TIME_FORMAT
},
1261 { NULL
, 0, NULL
, 0 }
1264 static const ul_excl_t excl
[] = { /* rows and cols in in ASCII order */
1265 { 'C','D','E','c','n','r' }, /* clear,off,on,read-clear,level,raw*/
1266 { 'H','r' }, /* human, raw */
1267 { 'L','r' }, /* color, raw */
1268 { 'S','w' }, /* syslog,follow */
1269 { 'T','r' }, /* ctime, raw */
1270 { 'd','r' }, /* delta, raw */
1271 { 'e','r' }, /* reltime, raw */
1272 { 'r','x' }, /* raw, decode */
1273 { 'r','t' }, /* notime, raw */
1276 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1278 setlocale(LC_ALL
, "");
1279 bindtextdomain(PACKAGE
, LOCALEDIR
);
1280 textdomain(PACKAGE
);
1281 atexit(close_stdout
);
1283 while ((c
= getopt_long(argc
, argv
, "CcDdEeF:f:HhkL::l:n:iPrSs:TtuVwx",
1284 longopts
, NULL
)) != -1) {
1286 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1290 ctl
.action
= SYSLOG_ACTION_CLEAR
;
1293 ctl
.action
= SYSLOG_ACTION_READ_CLEAR
;
1296 ctl
.action
= SYSLOG_ACTION_CONSOLE_OFF
;
1302 ctl
.action
= SYSLOG_ACTION_CONSOLE_ON
;
1305 ctl
.time_fmt
= DMESG_TIMEFTM_RELTIME
;
1308 ctl
.filename
= optarg
;
1309 ctl
.method
= DMESG_METHOD_MMAP
;
1313 if (string_to_bitarray(optarg
,
1314 ctl
.facilities
, parse_facility
) < 0)
1315 return EXIT_FAILURE
;
1318 ctl
.time_fmt
= DMESG_TIMEFTM_RELTIME
;
1319 colormode
= UL_COLORMODE_AUTO
;
1327 setbit(ctl
.facilities
, FAC_BASE(LOG_KERN
));
1330 colormode
= UL_COLORMODE_AUTO
;
1332 colormode
= colormode_or_err(optarg
,
1333 _("unsupported color mode"));
1337 if (string_to_bitarray(optarg
,
1338 ctl
.levels
, parse_level
) < 0)
1339 return EXIT_FAILURE
;
1342 ctl
.action
= SYSLOG_ACTION_CONSOLE_LEVEL
;
1343 console_level
= parse_level(optarg
, 0);
1352 ctl
.method
= DMESG_METHOD_SYSLOG
;
1355 ctl
.bufsize
= strtou32_or_err(optarg
,
1356 _("invalid buffer size argument"));
1357 if (ctl
.bufsize
< 4096)
1361 ctl
.time_fmt
= DMESG_TIMEFTM_CTIME
;
1364 ctl
.time_fmt
= DMESG_TIMEFTM_NONE
;
1369 for (n
= 1; (size_t) n
< ARRAY_SIZE(facility_names
); n
++)
1370 setbit(ctl
.facilities
, n
);
1373 printf(UTIL_LINUX_VERSION
);
1374 return EXIT_SUCCESS
;
1381 case OPT_TIME_FORMAT
:
1382 ctl
.time_fmt
= which_time_format(optarg
);
1395 if (is_timefmt(&ctl
, RELTIME
) ||
1396 is_timefmt(&ctl
, CTIME
) ||
1397 is_timefmt(&ctl
, ISO8601
)) {
1398 if (dmesg_get_boot_time(&ctl
.boot_time
) != 0)
1399 ctl
.time_fmt
= DMESG_TIMEFTM_NONE
;
1403 switch (ctl
.time_fmt
) {
1404 case DMESG_TIMEFTM_CTIME
:
1405 ctl
.time_fmt
= DMESG_TIMEFTM_CTIME_DELTA
;
1407 case DMESG_TIMEFTM_TIME
:
1408 ctl
.time_fmt
= DMESG_TIMEFTM_TIME_DELTA
;
1410 case DMESG_TIMEFTM_ISO8601
:
1411 warnx(_("--show-delta is ignored when used together with iso8601 time format"));
1414 ctl
.time_fmt
= DMESG_TIMEFTM_DELTA
;
1418 ctl
.color
= colors_init(colormode
, "dmesg") ? 1 : 0;
1421 ctl
.pager
= nopager
? 0 : ctl
.pager
;
1425 switch (ctl
.action
) {
1426 case SYSLOG_ACTION_READ_ALL
:
1427 case SYSLOG_ACTION_READ_CLEAR
:
1428 if (ctl
.method
== DMESG_METHOD_KMSG
&& init_kmsg(&ctl
) != 0)
1429 ctl
.method
= DMESG_METHOD_SYSLOG
;
1432 && ctl
.method
!= DMESG_METHOD_KMSG
1433 && (ctl
.fltr_lev
|| ctl
.fltr_fac
))
1434 errx(EXIT_FAILURE
, _("--raw can be used together with --level or "
1435 "--facility only when reading messages from /dev/kmsg"));
1438 n
= read_buffer(&ctl
, &buf
);
1440 print_buffer(&ctl
, buf
, n
);
1444 err(EXIT_FAILURE
, _("read kernel buffer failed"));
1448 case SYSLOG_ACTION_CLEAR
:
1449 case SYSLOG_ACTION_CONSOLE_OFF
:
1450 case SYSLOG_ACTION_CONSOLE_ON
:
1451 klog_rc
= klogctl(ctl
.action
, NULL
, 0);
1453 case SYSLOG_ACTION_CONSOLE_LEVEL
:
1454 klog_rc
= klogctl(ctl
.action
, NULL
, console_level
);
1457 errx(EXIT_FAILURE
, _("unsupported command"));
1463 err(EXIT_FAILURE
, _("klogctl failed"));
1465 return EXIT_SUCCESS
;