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>
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 indexes, 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 */
182 char kmsg_saved
[BUFSIZ
];/* buffer to save line after fragment */
183 ssize_t kmsg_saved_size
; /* if nonzero, read from kmsg_saved */
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).
193 unsigned int time_fmt
; /* time format */
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 */
205 struct dmesg_record
{
214 const char *next
; /* buffer with next unparsed record */
215 size_t next_size
; /* size of the next buffer */
218 #define INIT_DMESG_RECORD(_r) do { \
220 (_r)->mesg_size = 0; \
221 (_r)->facility = -1; \
223 (_r)->tv.tv_sec = 0; \
224 (_r)->tv.tv_usec = 0; \
227 static int read_kmsg(struct dmesg_control
*ctl
);
230 static int parse_kmsg_record(struct dmesg_control
*ctl
,
231 struct dmesg_record
*rec
,
236 static int set_level_color(int log_level
, const char *mesg
, size_t mesgsz
)
242 id
= DMESG_COLOR_ALERT
;
245 id
= DMESG_COLOR_CRIT
;
248 id
= DMESG_COLOR_ERR
;
251 id
= DMESG_COLOR_WARN
;
257 /* well, sometimes the messages contains important keywords, but in
258 * non-warning/error messages
260 if (id
< 0 && memmem(mesg
, mesgsz
, "segfault at", 11))
261 id
= DMESG_COLOR_SEGFAULT
;
264 dmesg_enable_color(id
);
266 return id
>= 0 ? 0 : -1;
269 static void __attribute__((__noreturn__
)) usage(void)
274 fputs(USAGE_HEADER
, out
);
275 fprintf(out
, _(" %s [options]\n"), program_invocation_short_name
);
277 fputs(USAGE_SEPARATOR
, out
);
278 fputs(_("Display or control the kernel ring buffer.\n"), out
);
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
);
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
));
316 fputs(_("\nSupported log levels (priorities):\n"), out
);
317 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++)
318 fprintf(out
, " %7s - %s\n",
320 _(level_names
[i
].help
));
322 printf(USAGE_MAN_TAIL("dmesg(1)"));
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
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".
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>.
339 static int parse_level(const char *str
, size_t len
)
353 long x
= strtol(str
, &end
, 10) - offset
;
355 if (!errno
&& end
&& end
> str
&& (size_t) (end
- str
) == len
&&
356 x
>= 0 && (size_t) x
< ARRAY_SIZE(level_names
))
361 for (i
= 0; i
< ARRAY_SIZE(level_names
); i
++) {
362 const char *n
= level_names
[i
].name
;
364 if (strncasecmp(str
, n
, len
) == 0 && *(n
+ len
) == '\0')
370 err(EXIT_FAILURE
, _("failed to parse level '%s'"), str
);
372 errx(EXIT_FAILURE
, _("unknown level '%s'"), str
);
377 * FACILITY ::= <number> | <name>
378 * <number> ::= number in range <0..N>, where N < ARRAY_SIZE(facility_names)
379 * <name> ::= case-insensitive text
381 static int parse_facility(const char *str
, size_t len
)
391 long x
= strtol(str
, &end
, 10);
393 if (!errno
&& end
&& end
> str
&& (size_t) (end
- str
) == len
&&
394 x
>= 0 && (size_t) x
< ARRAY_SIZE(facility_names
))
399 for (i
= 0; i
< ARRAY_SIZE(facility_names
); i
++) {
400 const char *n
= facility_names
[i
].name
;
402 if (strncasecmp(str
, n
, len
) == 0 && *(n
+ len
) == '\0')
408 err(EXIT_FAILURE
, _("failed to parse facility '%s'"), str
);
410 errx(EXIT_FAILURE
, _("unknown facility '%s'"), str
);
415 * Parses numerical prefix used for all messages in kernel ring buffer.
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
421 * Note that the number has to end with '>' or ',' char.
423 static const char *parse_faclev(const char *str
, int *fac
, int *lev
)
432 num
= strtol(str
, &end
, 10);
434 if (!errno
&& end
&& end
> str
) {
438 if (*lev
< 0 || (size_t) *lev
> ARRAY_SIZE(level_names
))
440 if (*fac
< 0 || (size_t) *fac
> ARRAY_SIZE(facility_names
))
442 return end
+ 1; /* skip '<' or ',' */
449 * Parses timestamp from syslog message prefix, expected format:
451 * seconds.microseconds]
453 * the ']' is the timestamp field terminator.
455 static const char *parse_syslog_timestamp(const char *str0
, struct timeval
*tv
)
457 const char *str
= str0
;
464 tv
->tv_sec
= strtol(str
, &end
, 10);
466 if (!errno
&& end
&& *end
== '.' && *(end
+ 1)) {
469 tv
->tv_usec
= strtol(str
, &end
, 10);
471 if (errno
|| !end
|| end
== str
|| *end
!= ']')
474 return end
+ 1; /* skip ']' */
478 * Parses timestamp from /dev/kmsg, expected formats:
483 * the ',' is fields separators and ';' items terminator (for the last item)
485 static const char *parse_kmsg_timestamp(const char *str0
, struct timeval
*tv
)
487 const char *str
= str0
;
495 usec
= strtoumax(str
, &end
, 10);
497 if (!errno
&& end
&& (*end
== ';' || *end
== ',')) {
498 tv
->tv_usec
= usec
% 1000000;
499 tv
->tv_sec
= usec
/ 1000000;
503 return end
+ 1; /* skip separator */
507 static double time_diff(struct timeval
*a
, struct timeval
*b
)
509 return (a
->tv_sec
- b
->tv_sec
) + (a
->tv_usec
- b
->tv_usec
) / 1E6
;
512 static int get_syslog_buffer_size(void)
514 int n
= klogctl(SYSLOG_ACTION_SIZE_BUFFER
, NULL
, 0);
516 return n
> 0 ? n
: 0;
520 * Reads messages from regular file by mmap
522 static ssize_t
mmap_file_buffer(struct dmesg_control
*ctl
, char **buf
)
530 fd
= open(ctl
->filename
, O_RDONLY
);
532 err(EXIT_FAILURE
, _("cannot open %s"), ctl
->filename
);
534 err(EXIT_FAILURE
, _("stat of %s failed"), ctl
->filename
);
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();
547 * Reads messages from kernel ring buffer by klogctl()
549 static ssize_t
read_syslog_buffer(struct dmesg_control
*ctl
, char **buf
)
555 sz
= ctl
->bufsize
+ 8;
556 *buf
= xmalloc(sz
* sizeof(char));
557 rc
= klogctl(ctl
->action
, *buf
, sz
);
561 *buf
= xmalloc(sz
* sizeof(char));
562 rc
= klogctl(SYSLOG_ACTION_READ_ALL
, *buf
, sz
);
565 if ((size_t) rc
!= sz
|| sz
> (1 << 28))
572 if (rc
> 0 && ctl
->action
== SYSLOG_ACTION_READ_CLEAR
)
573 rc
= klogctl(SYSLOG_ACTION_READ_CLEAR
, *buf
, sz
);
580 * Top level function to read messages
582 static ssize_t
read_buffer(struct dmesg_control
*ctl
, char **buf
)
586 switch (ctl
->method
) {
587 case DMESG_METHOD_MMAP
:
588 n
= mmap_file_buffer(ctl
, buf
);
590 case DMESG_METHOD_SYSLOG
:
592 ctl
->bufsize
= get_syslog_buffer_size();
594 n
= read_syslog_buffer(ctl
, buf
);
596 case DMESG_METHOD_KMSG
:
601 if (n
== 0 && ctl
->action
== SYSLOG_ACTION_READ_CLEAR
)
602 n
= klogctl(SYSLOG_ACTION_CLEAR
, NULL
, 0);
605 abort(); /* impossible method -> drop core */
611 static int fwrite_hex(const char *buf
, size_t size
, FILE *out
)
615 for (i
= 0; i
< size
; i
++) {
616 int rc
= fprintf(out
, "\\x%02hhx", buf
[i
]);
624 * Prints to 'out' and non-printable chars are replaced with \x<hex> sequences.
626 static void safe_fwrite(const char *buf
, size_t size
, int indent
, FILE *out
)
631 memset(&s
, 0, sizeof (s
));
633 for (i
= 0; i
< size
; i
++) {
634 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
));
648 } else if (len
> 1 && !iswprint(wc
)) { /* non-printable multibyte */
654 if (!isprint((unsigned char) *p
) &&
655 !isspace((unsigned char) *p
)) /* non-printable */
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
)
666 rc
= fwrite(p
, 1, len
, out
) != len
;
669 err(EXIT_FAILURE
, _("write failed"));
675 static const char *skip_item(const char *begin
, const char *end
, const char *sep
)
677 while (begin
< end
) {
680 if (c
== '\0' || strchr(sep
, c
))
688 * Parses one record from syslog(2) buffer
690 static int get_next_syslog_record(struct dmesg_control
*ctl
,
691 struct dmesg_record
*rec
)
694 const char *begin
= NULL
;
696 if (ctl
->method
!= DMESG_METHOD_MMAP
&&
697 ctl
->method
!= DMESG_METHOD_SYSLOG
)
700 if (!rec
->next
|| !rec
->next_size
)
703 INIT_DMESG_RECORD(rec
);
706 * Unmap already printed file data from memory
708 if (ctl
->mmap_buff
&& (size_t) (rec
->next
- ctl
->mmap_buff
) > ctl
->pagesize
) {
709 void *x
= ctl
->mmap_buff
;
711 ctl
->mmap_buff
+= ctl
->pagesize
;
712 munmap(x
, ctl
->pagesize
);
715 for (i
= 0; i
< rec
->next_size
; i
++) {
716 const char *p
= rec
->next
+ i
;
717 const char *end
= NULL
;
721 if (i
+ 1 == rec
->next_size
) {
724 } else if (*p
== '\n' && *(p
+ 1) == '<')
727 if (begin
&& !*begin
)
728 begin
= NULL
; /* zero(s) at the end of the buffer? */
732 continue; /* error or empty line? */
735 if (ctl
->fltr_lev
|| ctl
->fltr_fac
|| ctl
->decode
|| ctl
->color
)
736 begin
= parse_faclev(begin
+ 1, &rec
->facility
,
739 begin
= skip_item(begin
, end
, ">");
742 if (*begin
== '[' && (*(begin
+ 1) == ' ' ||
743 isdigit(*(begin
+ 1)))) {
745 if (!is_timefmt(ctl
, NONE
))
746 begin
= parse_syslog_timestamp(begin
+ 1, &rec
->tv
);
748 begin
= skip_item(begin
, end
, "]");
750 if (begin
< end
&& *begin
== ' ')
755 rec
->mesg_size
= end
- begin
;
757 rec
->next_size
-= end
- rec
->next
;
758 rec
->next
= rec
->next_size
> 0 ? end
+ 1 : NULL
;
759 if (rec
->next_size
> 0)
768 static int accept_record(struct dmesg_control
*ctl
, struct dmesg_record
*rec
)
770 if (ctl
->fltr_lev
&& (rec
->facility
< 0 ||
771 !isset(ctl
->levels
, rec
->level
)))
774 if (ctl
->fltr_fac
&& (rec
->facility
< 0 ||
775 !isset(ctl
->facilities
, rec
->facility
)))
781 static void raw_print(struct dmesg_control
*ctl
, const char *buf
, size_t size
)
785 if (!ctl
->mmap_buff
) {
787 * Print whole ring buffer
789 safe_fwrite(buf
, size
, 0, stdout
);
790 lastc
= buf
[size
- 1];
793 * Print file in small chunks to save memory
796 size_t sz
= size
> ctl
->pagesize
? ctl
->pagesize
: size
;
797 char *x
= ctl
->mmap_buff
;
799 safe_fwrite(x
, sz
, 0, stdout
);
802 ctl
->mmap_buff
+= sz
;
811 static struct tm
*record_localtime(struct dmesg_control
*ctl
,
812 struct dmesg_record
*rec
,
815 time_t t
= ctl
->boot_time
.tv_sec
+ rec
->tv
.tv_sec
;
816 return localtime_r(&t
, tm
);
819 static char *record_ctime(struct dmesg_control
*ctl
,
820 struct dmesg_record
*rec
,
821 char *buf
, size_t bufsiz
)
825 record_localtime(ctl
, rec
, &tm
);
827 if (strftime(buf
, bufsiz
, "%a %b %e %H:%M:%S %Y", &tm
) == 0)
832 static char *short_ctime(struct tm
*tm
, char *buf
, size_t bufsiz
)
834 if (strftime(buf
, bufsiz
, "%b%e %H:%M", tm
) == 0)
839 static char *iso_8601_time(struct dmesg_control
*ctl
, struct dmesg_record
*rec
,
840 char *buf
, size_t bufsz
)
842 struct timeval tv
= {
843 .tv_sec
= ctl
->boot_time
.tv_sec
+ rec
->tv
.tv_sec
,
844 .tv_usec
= rec
->tv
.tv_usec
847 if (strtimeval_iso(&tv
, ISO_8601_DATE
|ISO_8601_TIME
|ISO_8601_COMMAUSEC
|
855 static double record_count_delta(struct dmesg_control
*ctl
,
856 struct dmesg_record
*rec
)
860 if (timerisset(&ctl
->lasttime
))
861 delta
= time_diff(&rec
->tv
, &ctl
->lasttime
);
863 ctl
->lasttime
= rec
->tv
;
867 static const char *get_subsys_delimiter(const char *mesg
, size_t mesg_size
)
869 const char *p
= mesg
;
870 size_t sz
= mesg_size
;
873 const char *d
= strnchr(p
, sz
, ':');
878 if (isblank(*(d
+ 1)))
886 static void print_record(struct dmesg_control
*ctl
,
887 struct dmesg_record
*rec
)
895 if (!accept_record(ctl
, rec
))
898 if (!rec
->mesg_size
) {
904 * compose syslog(2) compatible raw output -- used for /dev/kmsg for
905 * backward compatibility with syslog(2) buffers only
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
);
917 * facility : priority :
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
);
926 dmesg_enable_color(DMESG_COLOR_TIME
);
928 switch (ctl
->time_fmt
) {
931 case DMESG_TIMEFTM_NONE
:
934 case DMESG_TIMEFTM_CTIME
:
935 ctl
->indent
= printf("[%s] ", record_ctime(ctl
, rec
, buf
, sizeof(buf
)));
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
));
942 case DMESG_TIMEFTM_DELTA
:
943 ctl
->indent
= printf("[<%12.06f>] ", record_count_delta(ctl
, rec
));
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
)));
955 ctl
->indent
= printf("[ %+8.06f] ", delta
);
957 ctl
->indent
= printf("[ %+9.06f] ", delta
);
961 case DMESG_TIMEFTM_TIME
:
962 ctl
->indent
= printf("[%5ld.%06ld] ",
963 (long)rec
->tv
.tv_sec
, (long)rec
->tv
.tv_usec
);
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
));
969 case DMESG_TIMEFTM_ISO8601
:
970 ctl
->indent
= printf("%s ", iso_8601_time(ctl
, rec
, buf
, sizeof(buf
)));
976 ctl
->indent
+= indent
;
983 mesg_size
= rec
->mesg_size
;
985 /* Colorize output */
987 /* subsystem prefix */
988 const char *subsys
= get_subsys_delimiter(mesg
, mesg_size
);
990 dmesg_enable_color(DMESG_COLOR_SUBSYS
);
991 safe_fwrite(mesg
, subsys
- mesg
, ctl
->indent
, stdout
);
994 mesg_size
-= subsys
- mesg
;
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
);
1003 safe_fwrite(mesg
, mesg_size
, ctl
->indent
, stdout
);
1005 if (*(mesg
+ mesg_size
- 1) != '\n')
1010 * Prints the 'buf' kernel ring buffer; the messages are filtered out according
1011 * to 'levels' and 'facilities' bitarrays.
1013 static void print_buffer(struct dmesg_control
*ctl
,
1014 const char *buf
, size_t size
)
1016 struct dmesg_record rec
= { .next
= buf
, .next_size
= size
};
1019 raw_print(ctl
, buf
, size
);
1023 while (get_next_syslog_record(ctl
, &rec
) == 0)
1024 print_record(ctl
, &rec
);
1028 * Read one record from kmsg, automatically concatenating message fragments
1030 static ssize_t
read_kmsg_one(struct dmesg_control
*ctl
)
1033 struct dmesg_record rec
= { .flags
= 0 };
1034 char fragment_buf
[BUFSIZ
] = { 0 };
1035 ssize_t fragment_offset
= 0;
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;
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.
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
1056 if (ctl
->follow
&& fragment_offset
) {
1057 struct pollfd pfd
= {.fd
= ctl
->kmsg
, .events
= POLLIN
};
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;
1065 size
= read(ctl
->kmsg
, ctl
->kmsg_buf
, sizeof(ctl
->kmsg_buf
) - 1);
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.
1073 if (errno
== EAGAIN
&& fragment_offset
) {
1074 memcpy(ctl
->kmsg_buf
, fragment_buf
, fragment_offset
);
1075 return fragment_offset
+ 1;
1078 if (parse_kmsg_record(ctl
, &rec
, ctl
->kmsg_buf
,
1079 (size_t) size
) == 0) {
1081 * 'c' can indicate a start of a fragment or a
1082 * continuation, '+' is used in older kernels to
1083 * indicate a continuation.
1085 if (rec
.flags
== 'c' || rec
.flags
== '+') {
1086 if (!fragment_offset
) {
1087 memcpy(fragment_buf
, ctl
->kmsg_buf
, size
);
1088 fragment_offset
= size
- 1;
1091 * In case of a buffer overflow, just
1092 * truncate the fragment - no one should
1093 * be logging this much anyway
1095 ssize_t truncate_size
= min(
1096 fragment_offset
+ rec
.mesg_size
,
1097 sizeof(fragment_buf
));
1099 memcpy(fragment_buf
+ fragment_offset
,
1100 rec
.mesg
, truncate_size
);
1101 fragment_offset
+= rec
.mesg_size
;
1104 } else if (rec
.flags
== '-') {
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.
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;
1120 } while ((size
< 0 && errno
== EPIPE
) ||
1121 (rec
.flags
== 'c' || rec
.flags
== '+'));
1126 static int init_kmsg(struct dmesg_control
*ctl
)
1128 int mode
= O_RDONLY
;
1135 ctl
->kmsg
= open("/dev/kmsg", mode
);
1140 * Seek after the last record available at the time
1141 * the last SYSLOG_ACTION_CLEAR was issued.
1143 * ... otherwise SYSLOG_ACTION_CLEAR will have no effect for kmsg.
1145 lseek(ctl
->kmsg
, 0, SEEK_DATA
);
1148 * Old kernels (<3.5) allow to successfully open /dev/kmsg for
1149 * read-only, but read() returns -EINVAL :-(((
1151 * Let's try to read the first record. The record is later processed in
1154 ctl
->kmsg_first_read
= read_kmsg_one(ctl
);
1155 if (ctl
->kmsg_first_read
< 0) {
1165 * /dev/kmsg record format:
1167 * faclev,seqnum,timestamp[optional, ...];message\n
1171 * - fields are separated by ','
1172 * - last field is terminated by ';'
1175 #define LAST_KMSG_FIELD(s) (!s || !*s || *(s - 1) == ';')
1177 static int parse_kmsg_record(struct dmesg_control
*ctl
,
1178 struct dmesg_record
*rec
,
1182 const char *p
= buf
, *end
;
1184 if (sz
== 0 || !buf
|| !*buf
)
1187 end
= buf
+ (sz
- 1);
1188 INIT_DMESG_RECORD(rec
);
1190 while (p
< end
&& isspace(*p
))
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
);
1198 p
= skip_item(p
, end
, ",");
1199 if (LAST_KMSG_FIELD(p
))
1202 /* B) sequence number */
1203 p
= skip_item(p
, end
, ",;");
1204 if (LAST_KMSG_FIELD(p
))
1208 if (is_timefmt(ctl
, NONE
))
1209 p
= skip_item(p
, end
, ",;");
1211 p
= parse_kmsg_timestamp(p
, &rec
->tv
);
1212 if (LAST_KMSG_FIELD(p
))
1216 rec
->flags
= *p
; // flag is one char
1218 if (LAST_KMSG_FIELD(p
))
1221 /* E) optional fields (ignore) */
1222 p
= skip_item(p
, end
, ";");
1225 /* F) message text */
1227 p
= skip_item(p
, end
, "\n");
1232 rec
->mesg_size
= p
- rec
->mesg
;
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.
1239 unhexmangle_to_buffer(rec
->mesg
, (char *) rec
->mesg
, rec
->mesg_size
+ 1);
1241 /* G) message tags (ignore) */
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.
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.
1253 * Returns 0 on success, -1 on error.
1255 static int read_kmsg(struct dmesg_control
*ctl
)
1257 struct dmesg_record rec
;
1260 if (ctl
->method
!= DMESG_METHOD_KMSG
|| ctl
->kmsg
< 0)
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;
1268 sz
= ctl
->kmsg_first_read
;
1271 *(ctl
->kmsg_buf
+ sz
) = '\0'; /* for debug messages */
1273 if (parse_kmsg_record(ctl
, &rec
,
1274 ctl
->kmsg_buf
, (size_t) sz
) == 0)
1275 print_record(ctl
, &rec
);
1277 sz
= read_kmsg_one(ctl
);
1283 static int which_time_format(const char *s
)
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
);
1299 static inline int dmesg_get_boot_time(struct timeval
*tv
)
1301 char *str
= getenv("DMESG_TEST_BOOTIME");
1302 uintmax_t sec
, usec
;
1304 if (str
&& sscanf(str
, "%ju.%ju", &sec
, &usec
) == 2) {
1307 return tv
->tv_sec
>= 0 && tv
->tv_usec
>= 0 ? 0 : -EINVAL
;
1310 return get_boot_time(tv
);
1313 # define dmesg_get_boot_time get_boot_time
1316 int main(int argc
, char *argv
[])
1320 int console_level
= 0;
1324 static struct dmesg_control ctl
= {
1326 .action
= SYSLOG_ACTION_READ_ALL
,
1327 .method
= DMESG_METHOD_KMSG
,
1329 .time_fmt
= DMESG_TIMEFTM_TIME
,
1332 int colormode
= UL_COLORMODE_UNDEF
;
1334 OPT_TIME_FORMAT
= CHAR_MAX
+ 1,
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 }
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 */
1378 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
1380 setlocale(LC_ALL
, "");
1381 bindtextdomain(PACKAGE
, LOCALEDIR
);
1382 textdomain(PACKAGE
);
1383 atexit(close_stdout
);
1385 while ((c
= getopt_long(argc
, argv
, "CcDdEeF:f:HhkL::l:n:iPrSs:TtuVwx",
1386 longopts
, NULL
)) != -1) {
1388 err_exclusive_options(c
, longopts
, excl
, excl_st
);
1392 ctl
.action
= SYSLOG_ACTION_CLEAR
;
1395 ctl
.action
= SYSLOG_ACTION_READ_CLEAR
;
1398 ctl
.action
= SYSLOG_ACTION_CONSOLE_OFF
;
1404 ctl
.action
= SYSLOG_ACTION_CONSOLE_ON
;
1407 ctl
.time_fmt
= DMESG_TIMEFTM_RELTIME
;
1410 ctl
.filename
= optarg
;
1411 ctl
.method
= DMESG_METHOD_MMAP
;
1415 if (string_to_bitarray(optarg
,
1416 ctl
.facilities
, parse_facility
) < 0)
1417 return EXIT_FAILURE
;
1420 ctl
.time_fmt
= DMESG_TIMEFTM_RELTIME
;
1421 colormode
= UL_COLORMODE_AUTO
;
1429 setbit(ctl
.facilities
, FAC_BASE(LOG_KERN
));
1432 colormode
= UL_COLORMODE_AUTO
;
1434 colormode
= colormode_or_err(optarg
,
1435 _("unsupported color mode"));
1439 if (string_to_bitarray(optarg
,
1440 ctl
.levels
, parse_level
) < 0)
1441 return EXIT_FAILURE
;
1444 ctl
.action
= SYSLOG_ACTION_CONSOLE_LEVEL
;
1445 console_level
= parse_level(optarg
, 0);
1454 ctl
.method
= DMESG_METHOD_SYSLOG
;
1457 ctl
.bufsize
= strtou32_or_err(optarg
,
1458 _("invalid buffer size argument"));
1459 if (ctl
.bufsize
< 4096)
1463 ctl
.time_fmt
= DMESG_TIMEFTM_CTIME
;
1466 ctl
.time_fmt
= DMESG_TIMEFTM_NONE
;
1470 for (n
= 1; (size_t) n
< ARRAY_SIZE(facility_names
); n
++)
1471 setbit(ctl
.facilities
, n
);
1474 printf(UTIL_LINUX_VERSION
);
1475 return EXIT_SUCCESS
;
1482 case OPT_TIME_FORMAT
:
1483 ctl
.time_fmt
= which_time_format(optarg
);
1486 errtryhelp(EXIT_FAILURE
);
1490 if (argc
!= optind
) {
1491 warnx(_("bad usage"));
1492 errtryhelp(EXIT_FAILURE
);
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
;
1502 switch (ctl
.time_fmt
) {
1503 case DMESG_TIMEFTM_CTIME
:
1504 ctl
.time_fmt
= DMESG_TIMEFTM_CTIME_DELTA
;
1506 case DMESG_TIMEFTM_TIME
:
1507 ctl
.time_fmt
= DMESG_TIMEFTM_TIME_DELTA
;
1509 case DMESG_TIMEFTM_ISO8601
:
1510 warnx(_("--show-delta is ignored when used together with iso8601 time format"));
1513 ctl
.time_fmt
= DMESG_TIMEFTM_DELTA
;
1517 ctl
.color
= colors_init(colormode
, "dmesg") ? 1 : 0;
1520 ctl
.pager
= nopager
? 0 : ctl
.pager
;
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
;
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"));
1537 n
= read_buffer(&ctl
, &buf
);
1539 print_buffer(&ctl
, buf
, n
);
1543 err(EXIT_FAILURE
, _("read kernel buffer failed"));
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);
1552 case SYSLOG_ACTION_CONSOLE_LEVEL
:
1553 klog_rc
= klogctl(ctl
.action
, NULL
, console_level
);
1556 errx(EXIT_FAILURE
, _("unsupported command"));
1562 err(EXIT_FAILURE
, _("klogctl failed"));
1564 return EXIT_SUCCESS
;