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
use crate::{UtmpEntry, UtmpError};
use std::convert::TryFrom;
use std::fs::File;
use std::io::{self, BufReader, Read};
use std::path::Path;
use thiserror::Error;
use utmp_raw::utmp;
use zerocopy::LayoutVerified;
const UTMP_SIZE: usize = std::mem::size_of::<utmp>();
#[repr(align(4))]
struct UtmpBuffer([u8; UTMP_SIZE]);
pub fn parse_from_path<P: AsRef<Path>>(path: P) -> Result<Vec<UtmpEntry>, ParseError> {
parse_from_file(File::open(path)?)
}
pub fn parse_from_file(file: File) -> Result<Vec<UtmpEntry>, ParseError> {
parse_from_reader(BufReader::new(file))
}
pub fn parse_from_reader<R: Read>(mut reader: R) -> Result<Vec<UtmpEntry>, ParseError> {
let mut result = Vec::new();
let mut buffer = UtmpBuffer([0; UTMP_SIZE]);
'outer: loop {
let mut buf = buffer.0.as_mut();
loop {
match reader.read(buf) {
Ok(0) if buf.len() == UTMP_SIZE => break 'outer,
Ok(0) => {
let inner = io::Error::new(io::ErrorKind::UnexpectedEof, "size not aligned");
return Err(inner.into());
}
Ok(n) => {
buf = &mut buf[n..];
if buf.is_empty() {
break;
}
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e.into()),
}
}
let buffer = buffer.0.as_ref();
let entry = LayoutVerified::<_, utmp>::new(buffer).unwrap().into_ref();
result.push(UtmpEntry::try_from(entry)?);
}
Ok(result)
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ParseError {
#[error(transparent)]
Utmp(#[from] UtmpError),
#[error(transparent)]
Io(#[from] io::Error),
}