| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use crate::transport::device_selector::DeviceSelectorEvent; |
| 6 |
use libc::{c_int, c_short, c_ulong}; |
| 7 |
use libudev::EventType; |
| 8 |
use runloop::RunLoop; |
| 9 |
use std::collections::HashMap; |
| 10 |
use std::error::Error; |
| 11 |
use std::io; |
| 12 |
use std::os::unix::io::AsRawFd; |
| 13 |
use std::path::PathBuf; |
| 14 |
use std::sync::{mpsc::Sender, Arc}; |
| 15 |
|
| 16 |
const UDEV_SUBSYSTEM: &str = "hidraw"; |
| 17 |
const POLLIN: c_short = 0x0001; |
| 18 |
const POLL_TIMEOUT: c_int = 100; |
| 19 |
|
| 20 |
fn poll(fds: &mut Vec<::libc::pollfd>) -> io::Result<()> { |
| 21 |
let nfds = fds.len() as c_ulong; |
| 22 |
|
| 23 |
let rv = unsafe { ::libc::poll((fds[..]).as_mut_ptr(), nfds, POLL_TIMEOUT) }; |
| 24 |
|
| 25 |
if rv < 0 { |
| 26 |
Err(io::Error::from_raw_os_error(rv)) |
| 27 |
} else { |
| 28 |
Ok(()) |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
pub struct Monitor<F> |
| 33 |
where |
| 34 |
F: Fn(PathBuf, Sender<DeviceSelectorEvent>, Sender<crate::StatusUpdate>, &dyn Fn() -> bool) |
| 35 |
+ Sync, |
| 36 |
{ |
| 37 |
runloops: HashMap<PathBuf, RunLoop>, |
| 38 |
new_device_cb: Arc<F>, |
| 39 |
selector_sender: Sender<DeviceSelectorEvent>, |
| 40 |
status_sender: Sender<crate::StatusUpdate>, |
| 41 |
} |
| 42 |
|
| 43 |
impl<F> Monitor<F> |
| 44 |
where |
| 45 |
F: Fn(PathBuf, Sender<DeviceSelectorEvent>, Sender<crate::StatusUpdate>, &dyn Fn() -> bool) |
| 46 |
+ Send |
| 47 |
+ Sync |
| 48 |
+ 'static, |
| 49 |
{ |
| 50 |
pub fn new( |
| 51 |
new_device_cb: F, |
| 52 |
selector_sender: Sender<DeviceSelectorEvent>, |
| 53 |
status_sender: Sender<crate::StatusUpdate>, |
| 54 |
) -> Self { |
| 55 |
Self { |
| 56 |
runloops: HashMap::new(), |
| 57 |
new_device_cb: Arc::new(new_device_cb), |
| 58 |
selector_sender, |
| 59 |
status_sender, |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
pub fn run(&mut self, alive: &dyn Fn() -> bool) -> Result<(), Box<dyn Error>> { |
| 64 |
let ctx = libudev::Context::new()?; |
| 65 |
|
| 66 |
let mut enumerator = libudev::Enumerator::new(&ctx)?; |
| 67 |
enumerator.match_subsystem(UDEV_SUBSYSTEM)?; |
| 68 |
|
| 69 |
// Iterate all existing devices. |
| 70 |
let paths: Vec<PathBuf> = enumerator |
| 71 |
.scan_devices()? |
| 72 |
.filter_map(|dev| dev.devnode().map(|p| p.to_owned())) |
| 73 |
.collect(); |
| 74 |
|
| 75 |
// Add them all in one go to avoid race conditions in DeviceSelector |
| 76 |
// (8 devices should be added, but the first returns already before all |
| 77 |
// others are known to DeviceSelector) |
| 78 |
self.selector_sender |
| 79 |
.send(DeviceSelectorEvent::DevicesAdded(paths.clone()))?; |
| 80 |
for path in paths { |
| 81 |
self.add_device(path); |
| 82 |
} |
| 83 |
|
| 84 |
let mut monitor = libudev::Monitor::new(&ctx)?; |
| 85 |
monitor.match_subsystem(UDEV_SUBSYSTEM)?; |
| 86 |
|
| 87 |
// Start listening for new devices. |
| 88 |
let mut socket = monitor.listen()?; |
| 89 |
let mut fds = vec![::libc::pollfd { |
| 90 |
fd: socket.as_raw_fd(), |
| 91 |
events: POLLIN, |
| 92 |
revents: 0, |
| 93 |
}]; |
| 94 |
|
| 95 |
while alive() { |
| 96 |
// Wait for new events, break on failure. |
| 97 |
poll(&mut fds)?; |
| 98 |
|
| 99 |
if let Some(event) = socket.receive_event() { |
| 100 |
self.process_event(&event); |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
// Remove all tracked devices. |
| 105 |
self.remove_all_devices(); |
| 106 |
|
| 107 |
Ok(()) |
| 108 |
} |
| 109 |
|
| 110 |
fn process_event(&mut self, event: &libudev::Event) { |
| 111 |
let path = event.device().devnode().map(|dn| dn.to_owned()); |
| 112 |
|
| 113 |
match (event.event_type(), path) { |
| 114 |
(EventType::Add, Some(path)) => { |
| 115 |
let _ = self |
| 116 |
.selector_sender |
| 117 |
.send(DeviceSelectorEvent::DevicesAdded(vec![path.clone()])); |
| 118 |
self.add_device(path); |
| 119 |
} |
| 120 |
(EventType::Remove, Some(path)) => { |
| 121 |
self.remove_device(&path); |
| 122 |
} |
| 123 |
_ => { /* ignore other types and failures */ } |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
fn add_device(&mut self, path: PathBuf) { |
| 128 |
let f = self.new_device_cb.clone(); |
| 129 |
let key = path.clone(); |
| 130 |
let selector_sender = self.selector_sender.clone(); |
| 131 |
let status_sender = self.status_sender.clone(); |
| 132 |
debug!("Adding device {}", path.to_string_lossy()); |
| 133 |
|
| 134 |
let runloop = RunLoop::new(move |alive| { |
| 135 |
if alive() { |
| 136 |
f(path, selector_sender, status_sender, alive); |
| 137 |
} |
| 138 |
}); |
| 139 |
|
| 140 |
if let Ok(runloop) = runloop { |
| 141 |
self.runloops.insert(key, runloop); |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
fn remove_device(&mut self, path: &PathBuf) { |
| 146 |
let _ = self |
| 147 |
.selector_sender |
| 148 |
.send(DeviceSelectorEvent::DeviceRemoved(path.clone())); |
| 149 |
|
| 150 |
debug!("Removing device {}", path.to_string_lossy()); |
| 151 |
if let Some(runloop) = self.runloops.remove(path) { |
| 152 |
runloop.cancel(); |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
fn remove_all_devices(&mut self) { |
| 157 |
while !self.runloops.is_empty() { |
| 158 |
let path = self.runloops.keys().next().unwrap().clone(); |
| 159 |
self.remove_device(&path); |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
pub fn get_property_linux(path: &PathBuf, prop_name: &str) -> io::Result<String> { |
| 165 |
let ctx = libudev::Context::new()?; |
| 166 |
|
| 167 |
let mut enumerator = libudev::Enumerator::new(&ctx)?; |
| 168 |
enumerator.match_subsystem(UDEV_SUBSYSTEM)?; |
| 169 |
|
| 170 |
// Iterate all existing devices, since we don't have a syspath |
| 171 |
// and libudev-rs doesn't implement opening by devnode. |
| 172 |
for dev in enumerator.scan_devices()? { |
| 173 |
if dev.devnode().is_some() && dev.devnode().unwrap() == path { |
| 174 |
debug!( |
| 175 |
"get_property_linux Querying property {} from {}", |
| 176 |
prop_name, |
| 177 |
dev.syspath().display() |
| 178 |
); |
| 179 |
|
| 180 |
let value = dev |
| 181 |
.attribute_value(prop_name) |
| 182 |
.ok_or(io::ErrorKind::Other)? |
| 183 |
.to_string_lossy(); |
| 184 |
|
| 185 |
debug!("get_property_linux Fetched Result, {}={}", prop_name, value); |
| 186 |
return Ok(value.to_string()); |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
Err(io::Error::new( |
| 191 |
io::ErrorKind::Other, |
| 192 |
"Unable to find device", |
| 193 |
)) |
| 194 |
} |