diff options
Diffstat (limited to 'third_party/rust/devd-rs/src')
-rw-r--r-- | third_party/rust/devd-rs/src/data.rs | 9 | ||||
-rw-r--r-- | third_party/rust/devd-rs/src/lib.rs | 93 | ||||
-rw-r--r-- | third_party/rust/devd-rs/src/parser.rs | 153 | ||||
-rw-r--r-- | third_party/rust/devd-rs/src/result.rs | 26 |
4 files changed, 281 insertions, 0 deletions
diff --git a/third_party/rust/devd-rs/src/data.rs b/third_party/rust/devd-rs/src/data.rs new file mode 100644 index 0000000000..52084362e5 --- /dev/null +++ b/third_party/rust/devd-rs/src/data.rs @@ -0,0 +1,9 @@ +pub use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + Notify { system: String, subsystem: String, kind: String, data: BTreeMap<String, String> }, + Attach { dev: String, parent: BTreeMap<String, String>, location: String }, + Detach { dev: String, parent: BTreeMap<String, String>, location: String }, + Nomatch { parent: BTreeMap<String, String>, location: String }, +} diff --git a/third_party/rust/devd-rs/src/lib.rs b/third_party/rust/devd-rs/src/lib.rs new file mode 100644 index 0000000000..8c863e856e --- /dev/null +++ b/third_party/rust/devd-rs/src/lib.rs @@ -0,0 +1,93 @@ +pub mod data; +pub mod parser; +pub mod result; + +use io::{BufRead, BufReader}; +use libc::{c_int, connect, nfds_t, poll, pollfd, sockaddr_un, socket, AF_UNIX, POLLIN, SOCK_SEQPACKET}; +use std::cmp::Ordering; +use std::os::unix::io::{FromRawFd, RawFd}; +use std::os::unix::net::UnixStream; +use std::{io, mem, ptr}; + +pub use data::*; +pub use result::*; + +const SOCKET_PATH: &str = "/var/run/devd.seqpacket.pipe"; + +pub fn parse_devd_event(event: &str) -> Result<Event> { + match parser::event(event) { + Ok((_, x)) => Ok(x), + _ => Err(Error::Parse), + } +} + +#[derive(Debug)] +pub struct Context { + sock: BufReader<UnixStream>, + sockfd: RawFd, + buffer: String, +} + +impl Context { + pub fn new() -> Result<Context> { + unsafe { + let sockfd = socket(AF_UNIX, SOCK_SEQPACKET, 0); + if sockfd < 0 { + return Err(io::Error::last_os_error().into()); + } + let mut sockaddr = sockaddr_un { sun_family: AF_UNIX as _, ..mem::zeroed() }; + ptr::copy_nonoverlapping(SOCKET_PATH.as_ptr(), sockaddr.sun_path.as_mut_ptr() as *mut u8, SOCKET_PATH.len()); + if connect( + sockfd, + &sockaddr as *const sockaddr_un as *const _, + (mem::size_of_val(&AF_UNIX) + SOCKET_PATH.len()) as _, + ) < 0 + { + return Err(io::Error::last_os_error().into()); + } + Ok(Context { + sock: BufReader::new(UnixStream::from_raw_fd(sockfd)), + sockfd, + buffer: String::new(), + }) + } + } + + pub fn wait_for_event_raw_internal(&mut self, timeout_ms: usize) -> Result<&str> { + let mut fds = [pollfd { fd: self.sockfd, events: POLLIN, revents: 0 }]; + let x = unsafe { poll((&mut fds).as_mut_ptr(), fds.len() as nfds_t, timeout_ms as c_int) }; + + match x.cmp(&0) { + Ordering::Less => Err(io::Error::last_os_error().into()), + Ordering::Equal => Err(Error::Timeout), + Ordering::Greater => { + self.buffer.clear(); + self.sock.read_line(&mut self.buffer)?; + Ok(&self.buffer) + } + } + } + + /// Waits for an event using poll(), reads it but does not parse + pub fn wait_for_event_raw(&mut self, timeout_ms: usize) -> Result<String> { + self.wait_for_event_raw_internal(timeout_ms).map(ToOwned::to_owned) + } + + /// Waits for an event using poll(), reads and parses it + pub fn wait_for_event(&mut self, timeout_ms: usize) -> Result<Event> { + self.wait_for_event_raw_internal(timeout_ms).and_then(parse_devd_event) + } + + /// Returns the devd socket file descriptor in case you want to select/poll on it together with + /// other file descriptors + pub fn fd(&self) -> RawFd { + self.sockfd + } + + /// Reads an event and parses it. Use when polling on the raw fd by yourself + pub fn read_event(&mut self) -> Result<Event> { + self.buffer.clear(); + self.sock.read_line(&mut self.buffer)?; + parse_devd_event(&self.buffer) + } +} diff --git a/third_party/rust/devd-rs/src/parser.rs b/third_party/rust/devd-rs/src/parser.rs new file mode 100644 index 0000000000..ee3c0511e9 --- /dev/null +++ b/third_party/rust/devd-rs/src/parser.rs @@ -0,0 +1,153 @@ +use crate::data::*; + +use nom::{ + branch::alt, + bytes::complete::{tag, take_while}, + character::complete::{alphanumeric1, char, multispace0, multispace1}, + combinator::success, + multi::fold_many0, + sequence::{delimited, preceded, terminated, tuple}, + IResult, Parser, +}; + +/// Parse a single value, which is either a quoted string, or a word without whitespace +fn val(input: &str) -> IResult<&str, &str, ()> { + alt((delimited(char('"'), take_while(|c| c != '"'), char('"')), take_while(|c| c != '\n' && c != ' '))).parse(input) +} + +/// Parse a key followed by a value, separated by = +fn keyval(input: &str) -> IResult<&str, (&str, &str), ()> { + terminated(alphanumeric1, char('=')).and(val).parse(input) +} + +/// Parser any number of key-value pairs, separated by 0 or more whitespace +fn keyvals(input: &str) -> IResult<&str, BTreeMap<String, String>, ()> { + fold_many0(terminated(keyval, multispace0), BTreeMap::new, |mut map, (key, value)| { + map.insert(key.to_owned(), value.to_owned()); + map + }) + .parse(input) +} + +/// Parse a key-value pair, where the key is a specific tag, separated by =, +/// terminated by whitespace +fn keyed_val<'i>(key: &'static str) -> impl Parser<&'i str, &'i str, ()> { + terminated(preceded(terminated(tag(key), char('=')), val), multispace1) +} + +fn notify(input: &str) -> IResult<&str, Event, ()> { + preceded(char('!'), tuple((keyed_val("system"), keyed_val("subsystem"), keyed_val("type"), keyvals))) + .map(|(sys, subsys, kind, data)| Event::Notify { + system: sys.to_owned(), + subsystem: subsys.to_owned(), + kind: kind.to_owned(), + data, + }) + .parse(input) +} + +/// Parse a key-value pair, where the key is a specific tag, separated by +/// whitespace +fn event_param<'i, T>(key: &'static str, value: impl Parser<&'i str, T, ()>) -> impl Parser<&'i str, T, ()> { + preceded(terminated(tag(key), multispace1), value) +} + +fn generic_event<'i, T>(prefix: char, dev: impl Parser<&'i str, T, ()>) -> impl Parser<&'i str, (T, BTreeMap<String, String>, &'i str), ()> { + tuple(( + terminated(preceded(char(prefix), dev), multispace1), + event_param("at", keyvals), + event_param("on", val), + )) +} + +fn attach(input: &str) -> IResult<&str, Event, ()> { + generic_event('+', alphanumeric1).map(|(dev, parent, loc)| Event::Attach { dev: dev.to_owned(), parent, location: loc.to_owned() }).parse(input) +} + +fn detach(input: &str) -> IResult<&str, Event, ()> { + generic_event('-', alphanumeric1).map(|(dev, parent, loc)| Event::Detach { dev: dev.to_owned(), parent, location: loc.to_owned() }).parse(input) +} + +fn nomatch(input: &str) -> IResult<&str, Event, ()> { + generic_event('?', success(())).map(|((), parent, loc)| Event::Nomatch { parent, location: loc.to_owned() }).parse(input) +} + +pub fn event(input: &str) -> IResult<&str, Event, ()> { + alt((notify, attach, detach, nomatch)).parse(input) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_notify() { + let txt = "!system=USB subsystem=INTERFACE type=ATTACH ugen=ugen0.2 vendor=0x1050 sernum=\"\" mode=host\n"; + let res = event(txt); + let mut data = BTreeMap::new(); + data.insert("ugen".to_owned(), "ugen0.2".to_owned()); + data.insert("vendor".to_owned(), "0x1050".to_owned()); + data.insert("sernum".to_owned(), "".to_owned()); + data.insert("mode".to_owned(), "host".to_owned()); + assert_eq!( + res, + Ok(( + "", + Event::Notify { + system: "USB".to_owned(), + subsystem: "INTERFACE".to_owned(), + kind: "ATTACH".to_owned(), + data, + } + )) + ) + } + + #[test] + fn test_attach() { + let txt = "+uhid1 at bus=0 sernum=\"\" on uhub1"; + let res = event(txt); + let mut data = BTreeMap::new(); + data.insert("bus".to_owned(), "0".to_owned()); + data.insert("sernum".to_owned(), "".to_owned()); + assert_eq!( + res, + Ok(( + "", + Event::Attach { + dev: "uhid1".to_owned(), + parent: data, + location: "uhub1".to_owned(), + } + )) + ) + } + + #[test] + fn test_detach() { + let txt = "-uhid1 at on uhub1"; + let res = event(txt); + let data = BTreeMap::new(); + assert_eq!( + res, + Ok(( + "", + Event::Detach { + dev: "uhid1".to_owned(), + parent: data, + location: "uhub1".to_owned(), + } + )) + ) + } + + #[test] + fn test_nomatch() { + let txt = "? at bus=0 on uhub1"; + let res = event(txt); + let mut data = BTreeMap::new(); + data.insert("bus".to_owned(), "0".to_owned()); + + assert_eq!(res, Ok(("", Event::Nomatch { parent: data, location: "uhub1".to_owned() }))) + } +} diff --git a/third_party/rust/devd-rs/src/result.rs b/third_party/rust/devd-rs/src/result.rs new file mode 100644 index 0000000000..2b47b8012c --- /dev/null +++ b/third_party/rust/devd-rs/src/result.rs @@ -0,0 +1,26 @@ +use std::{io, result}; + +#[derive(Debug)] +pub enum Error { + IoError(io::Error), + Timeout, + Parse, +} + +impl From<Error> for io::Error { + fn from(val: Error) -> Self { + match val { + Error::IoError(e) => e, + Error::Timeout => io::Error::new(io::ErrorKind::Other, "devd poll timeout"), + Error::Parse => io::Error::new(io::ErrorKind::Other, "devd parse error"), + } + } +} + +impl From<io::Error> for Error { + fn from(err: io::Error) -> Error { + Error::IoError(err) + } +} + +pub type Result<T> = result::Result<T, Error>; |