1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use crate::common;
use crate::entry::{Entry, EntryParsingError};
/// This crate provides a klogctl interface from Rust.
/// klogctl is a Linux syscall that allows reading the Linux Kernel Log buffer.
/// https://elinux.org/Debugging_by_printing
///
/// This is a crate/library version of the popular Linux utility 'dmesg'
/// https://en.wikipedia.org/wiki/Dmesg
///
/// This allows Rust programs to consume dmesg-like output programmatically.
///
use crate::error::RMesgError;

use lazy_static::lazy_static;
use nonblock::NonBlockingReader;
use regex::Regex;
use std::fs as stdfs;

#[cfg(feature = "sync")]
use std::io as stdio;
#[cfg(feature = "sync")]
use std::io::BufRead;
#[cfg(feature = "sync")]
use std::iter::Iterator;

#[cfg(feature = "async")]
use core::pin::Pin;
#[cfg(feature = "async")]
use futures::stream::Stream;
#[cfg(feature = "async")]
use futures::task::{Context, Poll};
#[cfg(feature = "async")]
use tokio::fs as tokiofs;
#[cfg(feature = "async")]
use tokio::io as tokioio;
#[cfg(feature = "async")]
use tokio::io::AsyncBufReadExt;

const DEV_KMSG_PATH: &str = "/dev/kmsg";

/// While reading the kernel log buffer is very useful in and of itself (expecially when running the CLI),
/// a lot more value is unlocked when it can be tailed line-by-line.
///
/// This struct provides the facilities to do that. It implements an iterator to easily iterate
/// indefinitely over the lines.
///
/// Implements the synchronous std::iter::Iterator trait
///
#[cfg(feature = "sync")]
pub struct KMsgEntriesIter {
    raw: bool,
    lines_iter: stdio::Lines<stdio::BufReader<stdfs::File>>,
}

#[cfg(feature = "sync")]
impl KMsgEntriesIter {
    /// Create a new KMsgEntries with two specific options
    /// `file_override`: When `Some`, overrides the path from where to read the kernel logs
    /// `raw: bool` When set, does not parse the message and instead sets the entire log entry in the "message" field
    pub fn with_options(file_override: Option<String>, raw: bool) -> Result<Self, RMesgError> {
        let path = file_override.unwrap_or_else(|| DEV_KMSG_PATH.to_owned());

        let file = match stdfs::File::open(path.clone()) {
            Ok(fc) => fc,
            Err(e) => {
                return Err(RMesgError::DevKMsgFileOpenError(format!(
                    "Unable to open file {}: {}",
                    path, e
                )))
            }
        };

        let lines_iter = stdio::BufReader::new(file).lines();

        Ok(Self { raw, lines_iter })
    }
}

/// Trait to iterate over lines of the kernel log buffer.
#[cfg(feature = "sync")]
impl Iterator for KMsgEntriesIter {
    type Item = Result<Entry, RMesgError>;

    /// This is a blocking call, and will use the calling thread to perform polling
    /// NOT a thread-safe method either. It is suggested this method be always
    /// blocked on to ensure no messages are missed.
    fn next(&mut self) -> Option<Self::Item> {
        match self.lines_iter.next() {
            None => None,
            Some(Err(e)) => Some(Err(RMesgError::IOError(format!(
                "Error reading next line from kernel log device file: {}",
                e
            )))),
            Some(Ok(line)) => {
                if self.raw {
                    Some(Ok(Entry {
                        facility: None,
                        level: None,
                        timestamp_from_system_start: None,
                        sequence_num: None,
                        message: line,
                    }))
                } else {
                    Some(entry_from_line(&line).map_err(|e| e.into()))
                }
            }
        }
    }
}

/// While reading the kernel log buffer is very useful in and of itself (expecially when running the CLI),
/// a lot more value is unlocked when it can be tailed line-by-line.
///
/// This struct provides the facilities to do that. It implements an iterator to easily iterate
/// indefinitely over the lines.
///
/// Implements the tokio::stream::Stream trait
///
#[cfg(feature = "async")]
pub struct KMsgEntriesStream {
    raw: bool,

    lines_stream: Pin<Box<tokioio::Lines<tokioio::BufReader<tokiofs::File>>>>,
}

#[cfg(feature = "async")]
impl KMsgEntriesStream {
    /// Create a new KMsgEntries with two specific options
    /// `file_override`: When `Some`, overrides the path from where to read the kernel logs
    /// `raw: bool` When set, does not parse the message and instead sets the entire log entry in the "message" field
    pub async fn with_options(
        file_override: Option<String>,
        raw: bool,
    ) -> Result<Self, RMesgError> {
        let path = file_override.unwrap_or_else(|| DEV_KMSG_PATH.to_owned());

        let file = match tokiofs::File::open(path.clone()).await {
            Ok(fc) => fc,
            Err(e) => {
                return Err(RMesgError::DevKMsgFileOpenError(format!(
                    "Unable to open file {}: {}",
                    path, e
                )))
            }
        };

        let lines_stream = Box::pin(tokioio::BufReader::new(file).lines());

        Ok(Self { raw, lines_stream })
    }
}

/// Trait to iterate over lines of the kernel log buffer.
#[cfg(feature = "async")]
impl Stream for KMsgEntriesStream {
    type Item = Result<Entry, RMesgError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match self.lines_stream.as_mut().poll_next_line(cx) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e.into()))),
            Poll::Ready(Ok(None)) => Poll::Ready(None),
            Poll::Ready(Ok(Some(line))) => {
                let value = if self.raw {
                    Some(Ok(Entry {
                        facility: None,
                        level: None,
                        timestamp_from_system_start: None,
                        sequence_num: None,
                        message: line,
                    }))
                } else {
                    Some(entry_from_line(&line).map_err(|e| e.into()))
                };

                Poll::Ready(value)
            }
        }
    }
}

pub fn kmsg_raw(file_override: Option<String>) -> Result<String, RMesgError> {
    let path = file_override.unwrap_or_else(|| DEV_KMSG_PATH.to_owned());

    let file = match stdfs::File::open(path.clone()) {
        Ok(fc) => fc,
        Err(e) => {
            return Err(RMesgError::DevKMsgFileOpenError(format!(
                "Unable to open file {}: {}",
                path, e
            )))
        }
    };

    let mut noblock_file = NonBlockingReader::from_fd(file)?;

    let mut file_contents = String::new();
    match noblock_file.read_available_to_string(&mut file_contents) {
        Ok(_) => {}
        Err(e) => {
            return Err(RMesgError::DevKMsgFileOpenError(format!(
                "Unable to open file {}: {}",
                path, e
            )))
        }
    }

    Ok(file_contents)
}

/// This is the key safe function that makes the klogctl syslog call with parameters.
/// While the internally used function supports all klogctl parameters, this function
/// only provides one bool parameter which indicates whether the buffer is to be cleared
/// or not, after its contents have been read.
///
/// Note that this is a by-definition synchronous function. So it is available
/// whether or not "async" feature is enabled
///
pub fn kmsg(file_override: Option<String>) -> Result<Vec<Entry>, RMesgError> {
    let file_contents = kmsg_raw(file_override)?;

    let lines = file_contents.as_str().lines();

    let mut entries = Vec::<Entry>::new();
    for line in lines {
        entries.push(entry_from_line(line)?)
    }
    Ok(entries)
}

// Message spec: https://github.com/torvalds/linux/blob/master/Documentation/ABI/testing/dev-kmsg
// Parses a kernel log line that looks like this (we ignore lines wtihout the timestamp):
// 5,0,0,-;Linux version 4.14.131-linuxkit (root@6d384074ad24) (gcc version 8.3.0 (Alpine 8.3.0)) #1 SMP Fri Jul 19 12:31:17 UTC 2019
// 6,1,0,-;Command, line: BOOT_IMAGE=/boot/kernel console=ttyS0 console=ttyS1 page_poison=1 vsyscall=emulate panic=1 root=/dev/sr0 text
//  LINE2=foobar
//  LINE 3 = foobar ; with semicolon
// 6,2,0,-;x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'
// 6,3,0,-,more,deets;x86/fpu: Supporting XSAVE; feature 0x002: 'SSE registers'
pub fn entry_from_line(line: &str) -> Result<Entry, EntryParsingError> {
    lazy_static! {
        static ref RE_ENTRY_WITH_TIMESTAMP: Regex = Regex::new(
            r"(?x)^
            [[:space:]]*(?P<faclevstr>[[:digit:]]*)[[:space:]]*,
            # Sequence is a 64-bit integer: https://www.kernel.org/doc/Documentation/ABI/testing/dev-kmsg
            [[:space:]]*(?P<sequencenum>[[:digit:]]*)[[:space:]]*,
            [[:space:]]*(?P<timestampstr>[[:digit:]]*)[[:space:]]*,
            # Ignore everything until the semi-colon and then the semicolon
            [[^;]]*;
            (?P<message>.*)$"
        )
        .unwrap();
    }

    if line.trim() == "" {
        return Err(EntryParsingError::EmptyLine);
    }

    let (facility, level, sequence_num, timestamp_from_system_start, message) =
        if let Some(kmsgparts) = RE_ENTRY_WITH_TIMESTAMP.captures(&line) {
            let (facility, level) = match kmsgparts.name("faclevstr") {
                Some(faclevstr) => common::parse_favlecstr(faclevstr.as_str(), line)?,
                None => (None, None),
            };

            let sequence_num = match kmsgparts.name("sequencenum") {
                Some(sequencestr) => {
                    Some(common::parse_fragment::<usize>(sequencestr.as_str(), line)?)
                }
                None => None,
            };

            let timestamp_from_system_start = match kmsgparts.name("timestampstr") {
                Some(timestampstr) => {
                    common::parse_timestamp_microsecs(timestampstr.as_str(), line)?
                }
                None => None,
            };

            let message = kmsgparts["message"].to_owned();

            (
                facility,
                level,
                sequence_num,
                timestamp_from_system_start,
                message,
            )
        } else {
            (None, None, None, None, line.to_owned())
        };

    Ok(Entry {
        facility,
        level,
        sequence_num,
        timestamp_from_system_start,
        message,
    })
}

/**********************************************************************************/
// Tests! Tests! Tests!

#[cfg(all(test, target_os = "linux"))]
mod test {
    use super::*;
    #[cfg(feature = "async")]
    use tokio_stream::StreamExt;

    #[test]
    fn test_kmsg() {
        let entries = kmsg(None);
        assert!(entries.is_ok(), "Response from kmsg not Ok");
        assert!(!entries.unwrap().is_empty(), "Should have non-empty logs");
    }

    #[cfg(feature = "sync")]
    #[test]
    fn test_iterator() {
        // uncomment below if you want to be extra-sure
        //let enable_timestamp_result = kernel_log_timestamps_enable(true);
        //assert!(enable_timestamp_result.is_ok());

        // Don't clear the buffer. Poll every second.
        let iterator_result = KMsgEntriesIter::with_options(None, false);
        assert!(iterator_result.is_ok());

        let iterator = iterator_result.unwrap();

        // Read 10 lines and quit
        for (count, entry) in iterator.enumerate() {
            assert!(entry.is_ok());
            if count > 10 {
                break;
            }
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_stream() {
        // uncomment below if you want to be extra-sure
        //let enable_timestamp_result = kernel_log_timestamps_enable(true);
        //assert!(enable_timestamp_result.is_ok());

        // Don't clear the buffer. Poll every second.
        let stream_result = KMsgEntriesStream::with_options(None, false).await;
        assert!(stream_result.is_ok());

        let mut stream = stream_result.unwrap();

        // Read 10 lines and quit
        let mut count: u32 = 0;
        while let Some(entry) = stream.next().await {
            assert!(entry.is_ok());
            count += 1;
            if count > 10 {
                break;
            }
        }
    }

    #[test]
    fn test_parse_serialize() {
        let line1 = " LINE2=foobar";
        let e1r = entry_from_line(line1);
        assert!(e1r.is_ok());
        let line1again = e1r.unwrap().to_kmsg_str();
        assert_eq!(line1, line1again);

        let line2 = "6,779,91650777797,-;docker0: port 2(veth98d5024) entered disabled state";
        let e2r = entry_from_line(line2);
        assert!(e2r.is_ok());
        let line2again = e2r.unwrap().to_kmsg_str();
        assert_eq!(line2, line2again);
    }
}