use std::collections::HashMap;
#[cfg(feature = "pcsc")]
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, TryLockError, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::core::Transport;
use crate::device::DeviceError;
use crate::management::{DeviceInfo, UsbInterface};
use crate::platform::device::LocalYubiKeyDevice;
#[cfg(feature = "pcsc")]
use super::device::pid_from_reader_name;
#[cfg(feature = "hid")]
use super::hidapi::{
FidoDeviceInfo, HidFidoConnection, HidOtpConnection, list_fido_devices, list_otp_devices,
};
#[cfg(feature = "pcsc")]
use super::pcsc::{PcscSmartCardConnection, ReaderStatus, is_reader_usb, list_reader_statuses};
#[cfg(feature = "pcsc")]
use crate::device::read_info_ccid;
#[cfg(feature = "hid")]
use crate::device::{read_info_fido, read_info_otp};
#[derive(Debug, Clone, PartialEq)]
pub enum DeviceNode {
UsbReaderNode {
reader_name: String,
pid: u16,
},
CardNode {
reader_name: String,
device_info: DeviceInfo,
},
HidOtpNode {
hid_path: String,
pid: u16,
device_info: DeviceInfo,
},
HidFidoNode {
hid_path: String,
pid: u16,
device_info: DeviceInfo,
},
}
#[derive(Debug, Clone, PartialEq)]
pub enum NodeEvent {
Added(DeviceNode),
Removed(DeviceNode),
}
enum Change {
#[cfg(feature = "pcsc")]
Pcsc,
#[cfg(all(feature = "pcsc", windows))]
PcscReaderRemoved(Option<String>),
#[cfg(feature = "hid")]
Hid,
VerifiedReinsert(u64),
Stop,
}
struct Shutdown {
stopped: AtomicBool,
stop_tx: mpsc::Sender<Change>,
#[cfg(all(feature = "pcsc", not(windows)))]
pcsc_ctx: std::sync::Mutex<Option<::pcsc::Context>>,
#[cfg(all(feature = "hid", target_os = "windows"))]
win_thread_id: std::sync::atomic::AtomicU32,
#[cfg(all(feature = "hid", target_os = "macos"))]
macos_runloop: std::sync::Mutex<Option<usize>>,
}
impl Shutdown {
fn new(stop_tx: mpsc::Sender<Change>) -> Self {
Self {
stopped: AtomicBool::new(false),
stop_tx,
#[cfg(all(feature = "pcsc", not(windows)))]
pcsc_ctx: std::sync::Mutex::new(None),
#[cfg(all(feature = "hid", target_os = "windows"))]
win_thread_id: std::sync::atomic::AtomicU32::new(0),
#[cfg(all(feature = "hid", target_os = "macos"))]
macos_runloop: std::sync::Mutex::new(None),
}
}
fn is_stopped(&self) -> bool {
self.stopped.load(Ordering::SeqCst)
}
fn signal_stop(&self) {
if self.stopped.swap(true, Ordering::SeqCst) {
return;
}
let _ = self.stop_tx.send(Change::Stop);
#[cfg(all(feature = "pcsc", not(windows)))]
if let Some(ctx) = self.pcsc_ctx.lock().unwrap().as_ref() {
let _ = ctx.cancel();
}
#[cfg(all(feature = "hid", target_os = "windows"))]
{
let tid = self.win_thread_id.load(Ordering::SeqCst);
if tid != 0 {
use windows_sys::Win32::UI::WindowsAndMessaging::{PostThreadMessageW, WM_QUIT};
unsafe { PostThreadMessageW(tid, WM_QUIT, 0, 0) };
}
}
#[cfg(all(feature = "hid", target_os = "macos"))]
if let Some(rl) = *self.macos_runloop.lock().unwrap() {
use core_foundation_sys::runloop::{CFRunLoopRef, CFRunLoopStop};
unsafe { CFRunLoopStop(rl as CFRunLoopRef) };
}
}
}
#[derive(Clone)]
struct ReadySignal {
inner: Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
}
impl ReadySignal {
fn new() -> Self {
Self {
inner: Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())),
}
}
fn signal(&self) {
let (lock, cvar) = &*self.inner;
let mut ready = lock.lock().unwrap_or_else(|p| p.into_inner());
*ready = true;
cvar.notify_all();
}
fn wait_timeout(&self, timeout: Duration) -> bool {
let (lock, cvar) = &*self.inner;
let deadline = Instant::now() + timeout;
let mut ready = lock.lock().unwrap_or_else(|p| p.into_inner());
while !*ready {
let now = Instant::now();
if now >= deadline {
return false;
}
let (guard, _) = cvar
.wait_timeout(ready, deadline - now)
.unwrap_or_else(|p| p.into_inner());
ready = guard;
}
true
}
}
#[must_use = "the monitor stops when the handle is dropped"]
pub struct MonitorHandle {
shutdown: Arc<Shutdown>,
threads: Vec<JoinHandle<()>>,
coordinator: Arc<ProbeCoordinator>,
ready: ReadySignal,
}
struct ProbeCoordinator {
probe_gate: Mutex<()>,
verified: Mutex<Vec<(u64, LocalYubiKeyDevice)>>,
next_verification: AtomicU64,
change_tx: mpsc::Sender<Change>,
}
static MONITORS: OnceLock<Mutex<Vec<Weak<ProbeCoordinator>>>> = OnceLock::new();
pub(crate) fn with_paused_monitors(
reinsert: impl FnOnce() -> Result<LocalYubiKeyDevice, DeviceError>,
) -> Result<(), DeviceError> {
let mut registry = MONITORS
.get_or_init(|| Mutex::new(Vec::new()))
.lock()
.unwrap_or_else(|e| e.into_inner());
registry.retain(|monitor| monitor.strong_count() > 0);
let monitors: Vec<_> = registry.iter().filter_map(Weak::upgrade).collect();
let mut guards = Vec::new();
for monitor in &monitors {
guards.push(
MonitorHandle::lock_probe_gate(&monitor.probe_gate, Duration::from_secs(10))
.ok_or_else(|| {
DeviceError::Transport(Box::new(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"Timed out waiting for device monitor probes",
)))
})?,
);
}
let verified = reinsert()?;
if verified.info().serial.is_some() {
for monitor in &monitors {
let id = monitor.next_verification.fetch_add(1, Ordering::Relaxed);
monitor
.verified
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((id, verified.clone()));
monitor
.change_tx
.send(Change::VerifiedReinsert(id))
.map_err(|_| {
DeviceError::Transport(Box::new(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"Device monitor stopped during reinsert",
)))
})?;
}
}
drop(guards);
drop(registry);
Ok(())
}
#[derive(Clone, Copy)]
enum VerifiedInterface {
Ccid,
Otp,
Fido,
}
fn verified_info(
devices: &[LocalYubiKeyDevice],
interface: VerifiedInterface,
path: &str,
pid: Option<u16>,
) -> Option<DeviceInfo> {
devices
.iter()
.rev()
.find(|dev| {
dev.pid() == pid
&& match interface {
VerifiedInterface::Ccid => dev.reader_name.as_deref() == Some(path),
VerifiedInterface::Otp => dev.hid_path.as_deref() == Some(path),
VerifiedInterface::Fido => dev.fido_path.as_deref() == Some(path),
}
})
.map(|dev| dev.info().clone())
}
pub struct MonitorPauseGuard<'a> {
_guard: MutexGuard<'a, ()>,
}
impl MonitorHandle {
pub fn stop(mut self) {
self.shutdown_and_join();
}
pub fn wait_ready(&self, timeout: Duration) -> bool {
self.ready.wait_timeout(timeout)
}
pub fn pause(&self, timeout: Duration) -> Option<MonitorPauseGuard<'_>> {
Self::lock_probe_gate(&self.coordinator.probe_gate, timeout)
.map(|guard| MonitorPauseGuard { _guard: guard })
}
fn shutdown_and_join(&mut self) {
self.shutdown.signal_stop();
self.ready.signal();
for handle in self.threads.drain(..) {
let _ = handle.join();
}
}
fn lock_probe_gate(gate: &Mutex<()>, timeout: Duration) -> Option<MutexGuard<'_, ()>> {
let deadline = Instant::now() + timeout;
loop {
match gate.try_lock() {
Ok(guard) => return Some(guard),
Err(TryLockError::Poisoned(error)) => return Some(error.into_inner()),
Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
thread::sleep(Duration::from_millis(10));
}
Err(TryLockError::WouldBlock) => return None,
}
}
}
fn attach_thread(&mut self, handle: JoinHandle<()>) {
self.threads.push(handle);
}
}
impl Drop for MonitorHandle {
fn drop(&mut self) {
self.shutdown_and_join();
}
}
pub fn monitor_device_events(
usb_interfaces: UsbInterface,
mut on_event: impl FnMut(NodeEvent) + Send + 'static,
) -> MonitorHandle {
let (tx, rx) = mpsc::channel::<Change>();
let shutdown = Arc::new(Shutdown::new(tx.clone()));
let ready = ReadySignal::new();
let coordinator = Arc::new(ProbeCoordinator {
probe_gate: Mutex::new(()),
verified: Mutex::new(Vec::new()),
next_verification: AtomicU64::new(0),
change_tx: tx.clone(),
});
MONITORS
.get_or_init(|| Mutex::new(Vec::new()))
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Arc::downgrade(&coordinator));
let mut threads: Vec<JoinHandle<()>> = Vec::new();
#[cfg(feature = "pcsc")]
if usb_interfaces.contains(UsbInterface::CCID) {
threads.push(spawn_pcsc_watcher(tx.clone(), Arc::clone(&shutdown)));
}
#[cfg(feature = "hid")]
if usb_interfaces.contains(UsbInterface::OTP) || usb_interfaces.contains(UsbInterface::FIDO) {
threads.push(spawn_hid_watcher(tx.clone(), Arc::clone(&shutdown)));
}
drop(tx);
let coordinator_ready = ready.clone();
let probe_coordinator = Arc::clone(&coordinator);
let coordinator_thread = thread::spawn(move || {
let mut state = MonitorState::default();
let gate = probe_coordinator
.probe_gate
.lock()
.unwrap_or_else(|e| e.into_inner());
#[cfg(feature = "pcsc")]
if usb_interfaces.contains(UsbInterface::CCID) {
state.refresh_pcsc(&mut on_event, &[]);
}
#[cfg(feature = "hid")]
if usb_interfaces.contains(UsbInterface::OTP) || usb_interfaces.contains(UsbInterface::FIDO)
{
state.refresh_hid(usb_interfaces, &mut on_event, &[]);
}
coordinator_ready.signal();
drop(gate);
while let Ok(change) = rx.recv() {
let _gate = probe_coordinator
.probe_gate
.lock()
.unwrap_or_else(|e| e.into_inner());
let verified: Vec<_> = probe_coordinator
.verified
.lock()
.unwrap_or_else(|e| e.into_inner())
.iter()
.map(|(_, device)| device.clone())
.collect();
match change {
Change::Stop => break,
#[cfg(feature = "pcsc")]
Change::Pcsc => state.refresh_pcsc(&mut on_event, &verified),
#[cfg(all(feature = "pcsc", windows))]
Change::PcscReaderRemoved(instance) => {
state.invalidate_usb_cards(instance.as_deref(), &mut on_event);
state.refresh_pcsc(&mut on_event, &verified);
}
#[cfg(feature = "hid")]
Change::Hid => state.refresh_hid(usb_interfaces, &mut on_event, &verified),
Change::VerifiedReinsert(id) => {
#[cfg(feature = "pcsc")]
if usb_interfaces.contains(UsbInterface::CCID) {
state.refresh_pcsc(&mut on_event, &verified);
}
#[cfg(feature = "hid")]
if usb_interfaces.contains(UsbInterface::OTP)
|| usb_interfaces.contains(UsbInterface::FIDO)
{
state.refresh_hid(usb_interfaces, &mut on_event, &verified);
}
probe_coordinator
.verified
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|(token, _)| *token != id);
}
}
}
});
threads.push(coordinator_thread);
MonitorHandle {
shutdown,
threads,
coordinator,
ready,
}
}
#[derive(Default)]
struct MonitorState {
#[cfg(feature = "pcsc")]
usb_readers: HashMap<String, DeviceNode>,
#[cfg(feature = "pcsc")]
cards: HashMap<String, DeviceNode>,
#[cfg(feature = "pcsc")]
card_events: HashMap<String, u32>,
#[cfg(feature = "pcsc")]
stale_cards: HashSet<String>,
#[cfg(all(feature = "pcsc", any(windows, test)))]
reader_instances: HashMap<String, ReaderInstance>,
#[cfg(feature = "hid")]
hid_otp: HashMap<String, DeviceNode>,
#[cfg(feature = "hid")]
hid_fido: HashMap<String, DeviceNode>,
}
#[cfg(all(feature = "pcsc", any(windows, test)))]
#[derive(Debug, Clone, PartialEq)]
enum ReaderInstance {
Known(String),
Unknown {
retry_at: Instant,
},
}
#[cfg(all(feature = "pcsc", windows))]
const READER_INSTANCE_RETRY: Duration = Duration::from_secs(5);
#[cfg(feature = "pcsc")]
impl MonitorState {
#[cfg(any(windows, test))]
fn invalidate_usb_cards(
&mut self,
instance: Option<&str>,
on_event: &mut impl FnMut(NodeEvent),
) {
let names: Vec<(String, bool)> = self
.usb_readers
.keys()
.filter_map(|name| match (instance, self.reader_instances.get(name)) {
(Some(removed), Some(ReaderInstance::Known(known))) => known
.eq_ignore_ascii_case(removed)
.then(|| (name.clone(), true)),
_ => Some((name.clone(), false)),
})
.collect();
for (name, removed) in names {
if !removed {
if self.cards.contains_key(&name) {
self.stale_cards.insert(name.clone());
}
if matches!(
self.reader_instances.get(&name),
Some(ReaderInstance::Known(_))
) {
self.reader_instances.remove(&name);
}
continue;
}
self.reader_instances.remove(&name);
self.card_events.remove(&name);
self.stale_cards.remove(&name);
if let Some(node) = self.cards.remove(&name) {
on_event(NodeEvent::Removed(node));
}
}
}
#[cfg(windows)]
fn lookup_reader_instances(&mut self, readers: &[ReaderStatus]) {
let now = Instant::now();
let names: Vec<&str> = readers
.iter()
.map(|status| status.name.as_str())
.filter(|name| is_reader_usb(name))
.filter(|name| match self.reader_instances.get(*name) {
None => true,
Some(ReaderInstance::Known(_)) => false,
Some(ReaderInstance::Unknown { retry_at }) => now >= *retry_at,
})
.collect();
if names.is_empty() {
return;
}
let results = match windows_pcsc::reader_device_instances(&names) {
Ok(results) => results,
Err(e) => {
log::debug!("Reading reader device instances failed: {e}");
names
.iter()
.map(|_| Err(std::io::Error::other("no smart card context")))
.collect()
}
};
for (name, result) in names.into_iter().zip(results) {
let instance = match result {
Ok(instance) => ReaderInstance::Known(instance),
Err(e) => {
log::debug!("Reading device instance for '{name}' failed: {e}");
ReaderInstance::Unknown {
retry_at: now + READER_INSTANCE_RETRY,
}
}
};
self.reader_instances.insert(name.to_string(), instance);
}
}
fn refresh_pcsc(
&mut self,
on_event: &mut impl FnMut(NodeEvent),
verified: &[LocalYubiKeyDevice],
) {
let readers = match list_reader_statuses() {
Ok(readers) => readers,
Err(e) => {
log::debug!("PC/SC enumeration failed: {e}");
return;
}
};
let present: HashMap<&str, bool> = readers
.iter()
.map(|r| (r.name.as_str(), r.card_present))
.collect();
let gone: Vec<String> = self
.usb_readers
.keys()
.filter(|name| !present.contains_key(name.as_str()))
.cloned()
.collect();
for name in gone {
#[cfg(windows)]
self.reader_instances.remove(&name);
self.card_events.remove(&name);
self.stale_cards.remove(&name);
if let Some(node) = self.cards.remove(&name) {
on_event(NodeEvent::Removed(node));
}
if let Some(node) = self.usb_readers.remove(&name) {
on_event(NodeEvent::Removed(node));
}
}
let gone_cards: Vec<String> = self
.cards
.keys()
.filter(|name| !present.contains_key(name.as_str()))
.cloned()
.collect();
for name in gone_cards {
if let Some(node) = self.cards.remove(&name) {
on_event(NodeEvent::Removed(node));
}
}
#[cfg(windows)]
self.lookup_reader_instances(&readers);
self.refresh_pcsc_cards(&readers, on_event, verified, read_card_info);
}
fn refresh_pcsc_cards(
&mut self,
readers: &[ReaderStatus],
on_event: &mut impl FnMut(NodeEvent),
verified: &[LocalYubiKeyDevice],
mut read_info: impl FnMut(&str, bool, bool) -> Result<DeviceInfo, DeviceError>,
) {
for status in readers {
let name = &status.name;
let card_present = &status.card_present;
let usb = is_reader_usb(name);
if *card_present
&& self.cards.contains_key(name)
&& self.card_events.get(name) != Some(&status.event_count)
&& let Some(node) = self.cards.remove(name)
{
self.stale_cards.remove(name);
on_event(NodeEvent::Removed(node));
}
if usb
&& let Some(pid) = pid_from_reader_name(name)
&& !self.usb_readers.contains_key(name)
{
let node = DeviceNode::UsbReaderNode {
reader_name: name.clone(),
pid,
};
self.usb_readers.insert(name.clone(), node.clone());
on_event(NodeEvent::Added(node));
}
if *card_present {
let refresh = self.stale_cards.contains(name);
if refresh || !self.cards.contains_key(name) {
let pid = if usb {
pid_from_reader_name(name)
} else {
None
};
let info = verified_info(verified, VerifiedInterface::Ccid, name, pid)
.map(Ok)
.unwrap_or_else(|| read_info(name, usb, refresh));
match info {
Ok(info) => {
let node = DeviceNode::CardNode {
reader_name: name.clone(),
device_info: info,
};
let previous = self.cards.insert(name.clone(), node.clone());
self.card_events.insert(name.clone(), status.event_count);
self.stale_cards.remove(name);
if previous.as_ref() != Some(&node) {
if let Some(previous) = previous {
on_event(NodeEvent::Removed(previous));
}
on_event(NodeEvent::Added(node));
}
}
Err(e) => {
log::debug!("Reading card info from '{name}' failed: {e}");
}
}
}
} else {
self.stale_cards.remove(name);
if let Some(node) = self.cards.remove(name) {
on_event(NodeEvent::Removed(node));
}
}
}
}
}
#[cfg(feature = "hid")]
impl MonitorState {
fn refresh_hid(
&mut self,
interfaces: UsbInterface,
on_event: &mut impl FnMut(NodeEvent),
verified: &[LocalYubiKeyDevice],
) {
if interfaces.contains(UsbInterface::OTP) {
match list_otp_devices() {
Ok(devices) => {
let current: HashMap<&str, u16> =
devices.iter().map(|d| (d.path.as_str(), d.pid)).collect();
let gone: Vec<String> = self
.hid_otp
.keys()
.filter(|path| !current.contains_key(path.as_str()))
.cloned()
.collect();
for path in gone {
if let Some(node) = self.hid_otp.remove(&path) {
on_event(NodeEvent::Removed(node));
}
}
for device in &devices {
if self.hid_otp.contains_key(&device.path) {
continue;
}
let info = verified_info(
verified,
VerifiedInterface::Otp,
&device.path,
Some(device.pid),
)
.map(Ok)
.unwrap_or_else(|| read_otp_info(&device.path, device.pid));
match info {
Ok(info) => {
let node = DeviceNode::HidOtpNode {
hid_path: device.path.clone(),
pid: device.pid,
device_info: info,
};
self.hid_otp.insert(device.path.clone(), node.clone());
on_event(NodeEvent::Added(node));
}
Err(e) => {
log::debug!("Reading OTP info from '{}' failed: {e}", device.path);
}
}
}
}
Err(e) => log::debug!("OTP HID enumeration failed: {e}"),
}
}
if interfaces.contains(UsbInterface::FIDO) {
match list_fido_devices() {
Ok(devices) => {
let current: HashMap<&str, u16> =
devices.iter().map(|d| (d.path.as_str(), d.pid)).collect();
let gone: Vec<String> = self
.hid_fido
.keys()
.filter(|path| !current.contains_key(path.as_str()))
.cloned()
.collect();
for path in gone {
if let Some(node) = self.hid_fido.remove(&path) {
on_event(NodeEvent::Removed(node));
}
}
for device in &devices {
if self.hid_fido.contains_key(&device.path) {
continue;
}
let info = verified_info(
verified,
VerifiedInterface::Fido,
&device.path,
Some(device.pid),
)
.map(Ok)
.unwrap_or_else(|| read_fido_info(device));
match info {
Ok(info) => {
let node = DeviceNode::HidFidoNode {
hid_path: device.path.clone(),
pid: device.pid,
device_info: info,
};
self.hid_fido.insert(device.path.clone(), node.clone());
on_event(NodeEvent::Added(node));
}
Err(e) => {
log::debug!("Reading FIDO info from '{}' failed: {e}", device.path);
}
}
}
}
Err(e) => log::debug!("FIDO HID enumeration failed: {e}"),
}
}
}
}
#[cfg(feature = "pcsc")]
fn read_card_info(
reader_name: &str,
usb: bool,
exclusive_only: bool,
) -> Result<DeviceInfo, DeviceError> {
let conn = if exclusive_only {
PcscSmartCardConnection::new(reader_name, true)
} else {
PcscSmartCardConnection::open(reader_name)
}?;
let pid = if usb {
pid_from_reader_name(reader_name)
} else {
None
};
let (info, _conn) = read_info_ccid(conn, pid)?;
Ok(info)
}
#[cfg(feature = "hid")]
fn read_otp_info(path: &str, pid: u16) -> Result<DeviceInfo, DeviceError> {
let conn = HidOtpConnection::new(path)?;
read_info_otp(conn, pid)
.map(|(info, _)| info)
.map_err(|(e, _)| e)
}
#[cfg(feature = "hid")]
fn read_fido_info(device: &FidoDeviceInfo) -> Result<DeviceInfo, DeviceError> {
let conn = HidFidoConnection::open(device)?;
read_info_fido(conn, device.pid)
.map(|(info, _)| info)
.map_err(|(e, _)| e)
}
#[cfg(feature = "pcsc")]
fn spawn_pcsc_watcher(tx: mpsc::Sender<Change>, shutdown: Arc<Shutdown>) -> JoinHandle<()> {
thread::spawn(move || pcsc_watch_loop(&tx, &shutdown))
}
#[cfg(all(feature = "pcsc", not(windows)))]
fn pcsc_watch_loop(tx: &mpsc::Sender<Change>, shutdown: &Shutdown) {
use ::pcsc::{Context, PNP_NOTIFICATION, ReaderState, Scope, State};
use std::ffi::CString;
let ctx = match Context::establish(Scope::User) {
Ok(ctx) => ctx,
Err(e) => {
log::debug!("PC/SC watcher couldn't establish context: {e}");
return;
}
};
*shutdown.pcsc_ctx.lock().unwrap() = Some(ctx.clone());
if shutdown.is_stopped() {
return;
}
let mut states: Vec<ReaderState> = vec![ReaderState::new(PNP_NOTIFICATION(), State::UNAWARE)];
loop {
if shutdown.is_stopped() {
return;
}
let names = current_reader_names(&ctx);
states.retain(|rs| {
rs.name() == PNP_NOTIFICATION()
|| names
.iter()
.any(|n| n.as_str() == rs.name().to_string_lossy().as_ref())
});
for name in &names {
let known = states
.iter()
.any(|rs| rs.name().to_string_lossy().as_ref() == name.as_str());
if !known && let Ok(cname) = CString::new(name.as_str()) {
states.push(ReaderState::new(cname, State::UNAWARE));
}
}
match ctx.get_status_change(Some(Duration::from_secs(1)), &mut states) {
Ok(()) => {
for rs in &mut states {
rs.sync_current_state();
}
if shutdown.is_stopped() || tx.send(Change::Pcsc).is_err() {
return;
}
}
Err(::pcsc::Error::Timeout) => {
for rs in &mut states {
rs.sync_current_state();
}
}
Err(e) => {
if !shutdown.is_stopped() {
log::debug!("PC/SC watcher stopped: {e}");
}
return;
}
}
}
}
#[cfg(all(feature = "pcsc", windows))]
fn pcsc_watch_loop(tx: &mpsc::Sender<Change>, shutdown: &Shutdown) {
windows_pcsc::run(tx, shutdown);
}
#[cfg(all(feature = "pcsc", any(windows, test)))]
fn reader_instance_from_path(path: &str) -> Option<String> {
let mut parts = path.strip_prefix(r"\\?\")?.split('#');
let bus = parts.next().filter(|part| !part.is_empty())?;
let device = parts.next().filter(|part| !part.is_empty())?;
let instance = parts.next().filter(|part| !part.is_empty())?;
let class = parts.next()?;
if !class.starts_with('{') || !class.ends_with('}') || parts.next().is_some() {
return None;
}
Some(format!(r"{bus}\{device}\{instance}"))
}
#[cfg(all(feature = "pcsc", windows))]
mod windows_pcsc {
use super::{Change, Shutdown, reader_instance_from_path};
use std::cell::RefCell;
use std::sync::mpsc;
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::Security::Credentials::{
SCARD_SCOPE_USER, SCardEstablishContext, SCardGetReaderDeviceInstanceIdW,
SCardReleaseContext,
};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DBT_DEVICEREMOVECOMPLETE, DBT_DEVTYP_DEVICEINTERFACE,
DEV_BROADCAST_DEVICEINTERFACE_W, DEV_BROADCAST_HDR, DEVICE_NOTIFY_WINDOW_HANDLE,
DefWindowProcW, DestroyWindow, DispatchMessageW, HWND_MESSAGE, MSG,
MsgWaitForMultipleObjects, PM_REMOVE, PeekMessageW, QS_ALLINPUT, RegisterClassW,
RegisterDeviceNotificationW, TranslateMessage, UnregisterDeviceNotification,
WM_DEVICECHANGE, WNDCLASSW,
};
use windows_sys::core::GUID;
const POLL_INTERVAL: Duration = Duration::from_millis(750);
const GUID_DEVINTERFACE_SMARTCARD_READER: GUID =
GUID::from_u128(0x50dd5230_ba8a_11d1_bf5d_0000f805f530);
thread_local! {
static SENDER: RefCell<Option<mpsc::Sender<Change>>> = const { RefCell::new(None) };
}
fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(std::iter::once(0)).collect()
}
pub(super) fn reader_device_instances(
names: &[&str],
) -> std::io::Result<Vec<std::io::Result<String>>> {
struct Context(usize);
impl Drop for Context {
fn drop(&mut self) {
let status = unsafe { SCardReleaseContext(self.0) };
if status != 0 {
log::debug!("Releasing smart card context failed: {status:#x}");
}
}
}
fn check(status: i32) -> std::io::Result<()> {
if status == 0 {
Ok(())
} else {
Err(std::io::Error::from_raw_os_error(status))
}
}
fn instance_id(context: usize, name: &str) -> std::io::Result<String> {
let name = wide(name);
let mut len = 0;
check(unsafe {
SCardGetReaderDeviceInstanceIdW(
context,
name.as_ptr(),
std::ptr::null_mut(),
&mut len,
)
})?;
let mut instance = vec![0; len as usize];
check(unsafe {
SCardGetReaderDeviceInstanceIdW(
context,
name.as_ptr(),
instance.as_mut_ptr(),
&mut len,
)
})?;
let end = instance.iter().position(|&c| c == 0).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Unterminated device instance ID",
)
})?;
String::from_utf16(&instance[..end])
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
let mut context = 0;
check(unsafe {
SCardEstablishContext(
SCARD_SCOPE_USER,
std::ptr::null(),
std::ptr::null(),
&mut context,
)
})?;
let context = Context(context);
Ok(names
.iter()
.map(|name| instance_id(context.0, name))
.collect())
}
unsafe extern "system" fn wndproc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
if msg == WM_DEVICECHANGE && wparam == DBT_DEVICEREMOVECOMPLETE as WPARAM {
let header = lparam as *const DEV_BROADCAST_HDR;
if !header.is_null()
&& unsafe { (*header).dbch_devicetype } == DBT_DEVTYP_DEVICEINTERFACE
{
let broadcast = lparam as *const DEV_BROADCAST_DEVICEINTERFACE_W;
let offset = std::mem::offset_of!(DEV_BROADCAST_DEVICEINTERFACE_W, dbcc_name);
let size = unsafe { (*header).dbch_size } as usize;
if size < offset + std::mem::size_of::<u16>() {
log::debug!("Smart card removal notification has no interface path");
return 1;
}
let name = unsafe {
let start = std::ptr::addr_of!((*broadcast).dbcc_name).cast::<u16>();
std::slice::from_raw_parts(start, (size - offset) / 2)
};
let Some(end) = name.iter().position(|&c| c == 0) else {
log::debug!("Smart card removal notification has an unterminated path");
return 1;
};
let name = String::from_utf16_lossy(&name[..end]);
log::debug!("Smart card reader removed: {name}");
let instance = reader_instance_from_path(&name);
if instance.is_none() {
log::debug!("Unrecognised reader path; re-reading all USB readers");
}
SENDER.with(|sender| {
if let Some(tx) = sender.borrow().as_ref() {
let _ = tx.send(Change::PcscReaderRemoved(instance));
}
});
}
return 1;
}
unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
}
fn register_notifications() -> Option<(HWND, *mut core::ffi::c_void)> {
unsafe {
let hinstance = GetModuleHandleW(std::ptr::null());
let class_name = wide("YubiKitPcscMonitor");
let mut wc: WNDCLASSW = std::mem::zeroed();
wc.lpfnWndProc = Some(wndproc);
wc.hInstance = hinstance;
wc.lpszClassName = class_name.as_ptr();
RegisterClassW(&wc);
let hwnd = CreateWindowExW(
0,
class_name.as_ptr(),
std::ptr::null(),
0,
0,
0,
0,
0,
HWND_MESSAGE,
std::ptr::null_mut(),
hinstance,
std::ptr::null(),
);
if hwnd.is_null() {
return None;
}
let mut filter: DEV_BROADCAST_DEVICEINTERFACE_W = std::mem::zeroed();
filter.dbcc_size = std::mem::size_of::<DEV_BROADCAST_DEVICEINTERFACE_W>() as u32;
filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
filter.dbcc_classguid = GUID_DEVINTERFACE_SMARTCARD_READER;
let notify = RegisterDeviceNotificationW(
hwnd as _,
&mut filter as *mut _ as *mut _,
DEVICE_NOTIFY_WINDOW_HANDLE,
);
if notify.is_null() {
DestroyWindow(hwnd);
return None;
}
Some((hwnd, notify))
}
}
pub(super) fn run(tx: &mpsc::Sender<Change>, shutdown: &Shutdown) {
SENDER.with(|sender| *sender.borrow_mut() = Some(tx.clone()));
let registration = register_notifications();
if registration.is_none() {
log::debug!("Failed to register for smart card reader notifications");
}
let mut next_poll = Instant::now() + POLL_INTERVAL;
while !shutdown.is_stopped() {
let timeout = next_poll.saturating_duration_since(Instant::now());
unsafe {
MsgWaitForMultipleObjects(
0,
std::ptr::null(),
0,
timeout.as_millis() as u32,
QS_ALLINPUT,
);
let mut msg: MSG = std::mem::zeroed();
while PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) != 0 {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
if Instant::now() >= next_poll {
if shutdown.is_stopped() || tx.send(Change::Pcsc).is_err() {
break;
}
next_poll = Instant::now() + POLL_INTERVAL;
}
}
if let Some((hwnd, notify)) = registration {
unsafe {
UnregisterDeviceNotification(notify);
DestroyWindow(hwnd);
}
}
SENDER.with(|sender| *sender.borrow_mut() = None);
}
}
#[cfg(all(feature = "pcsc", not(windows)))]
fn current_reader_names(ctx: &::pcsc::Context) -> Vec<String> {
let len = match ctx.list_readers_len() {
Ok(len) => len,
Err(_) => return Vec::new(),
};
let mut buf = vec![0u8; len];
match ctx.list_readers(&mut buf) {
Ok(readers) => readers.map(|r| r.to_string_lossy().into_owned()).collect(),
Err(_) => Vec::new(),
}
}
#[cfg(all(feature = "hid", target_os = "linux"))]
fn spawn_hid_watcher(tx: mpsc::Sender<Change>, shutdown: Arc<Shutdown>) -> JoinHandle<()> {
use std::os::fd::AsRawFd;
thread::spawn(move || {
let socket = match udev::MonitorBuilder::new()
.and_then(|builder| builder.match_subsystem("hidraw"))
.and_then(|builder| builder.listen())
{
Ok(socket) => socket,
Err(e) => {
log::debug!("Failed to start udev HID monitor: {e}");
return;
}
};
loop {
if shutdown.is_stopped() {
return;
}
let mut pollfd = libc::pollfd {
fd: socket.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let result = unsafe { libc::poll(&mut pollfd, 1, 1000) };
if result < 0 {
log::debug!(
"udev HID monitor poll failed: {}",
std::io::Error::last_os_error()
);
thread::sleep(Duration::from_secs(1));
continue;
}
if result == 0 {
continue;
}
let mut relevant = false;
for event in socket.iter() {
if matches!(
event.event_type(),
udev::EventType::Add
| udev::EventType::Remove
| udev::EventType::Change
| udev::EventType::Bind
| udev::EventType::Unbind
) {
relevant = true;
}
}
if relevant && (shutdown.is_stopped() || tx.send(Change::Hid).is_err()) {
return;
}
}
})
}
#[cfg(all(feature = "hid", target_os = "windows"))]
fn spawn_hid_watcher(tx: mpsc::Sender<Change>, shutdown: Arc<Shutdown>) -> JoinHandle<()> {
thread::spawn(move || windows_hid::run(tx, &shutdown))
}
#[cfg(all(feature = "hid", target_os = "macos"))]
fn spawn_hid_watcher(tx: mpsc::Sender<Change>, shutdown: Arc<Shutdown>) -> JoinHandle<()> {
thread::spawn(move || macos_hid::run(tx, &shutdown))
}
#[cfg(all(
feature = "hid",
not(any(target_os = "linux", target_os = "windows", target_os = "macos"))
))]
fn spawn_hid_watcher(tx: mpsc::Sender<Change>, shutdown: Arc<Shutdown>) -> JoinHandle<()> {
let _ = (tx, shutdown);
log::warn!("HID device-event monitoring is not supported on this platform");
thread::spawn(|| {})
}
#[cfg(all(feature = "hid", target_os = "windows"))]
mod windows_hid {
use super::{Change, Shutdown};
use std::cell::RefCell;
use std::sync::atomic::Ordering;
use std::sync::mpsc;
use windows_sys::Win32::Devices::HumanInterfaceDevice::GUID_DEVINTERFACE_HID;
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::System::Threading::GetCurrentThreadId;
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DBT_DEVICEARRIVAL, DBT_DEVICEREMOVECOMPLETE, DBT_DEVTYP_DEVICEINTERFACE,
DEV_BROADCAST_DEVICEINTERFACE_W, DEVICE_NOTIFY_WINDOW_HANDLE, DefWindowProcW,
DispatchMessageW, GetMessageW, HWND_MESSAGE, MSG, PM_NOREMOVE, PeekMessageW,
RegisterClassW, RegisterDeviceNotificationW, TranslateMessage, WM_DEVICECHANGE, WM_USER,
WNDCLASSW,
};
thread_local! {
static SENDER: RefCell<Option<mpsc::Sender<Change>>> = const { RefCell::new(None) };
}
fn wide(value: &str) -> Vec<u16> {
value.encode_utf16().chain(std::iter::once(0)).collect()
}
unsafe extern "system" fn wndproc(
hwnd: HWND,
msg: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
if msg == WM_DEVICECHANGE
&& (wparam == DBT_DEVICEARRIVAL as WPARAM
|| wparam == DBT_DEVICEREMOVECOMPLETE as WPARAM)
{
SENDER.with(|sender| {
if let Some(tx) = sender.borrow().as_ref() {
let _ = tx.send(Change::Hid);
}
});
return 0;
}
unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
}
pub(super) fn run(tx: mpsc::Sender<Change>, shutdown: &Shutdown) {
SENDER.with(|sender| *sender.borrow_mut() = Some(tx));
unsafe {
let hinstance = GetModuleHandleW(std::ptr::null());
let class_name = wide("YubiKitHidMonitor");
let mut wc: WNDCLASSW = std::mem::zeroed();
wc.lpfnWndProc = Some(wndproc);
wc.hInstance = hinstance;
wc.lpszClassName = class_name.as_ptr();
RegisterClassW(&wc);
let hwnd = CreateWindowExW(
0,
class_name.as_ptr(),
std::ptr::null(),
0,
0,
0,
0,
0,
HWND_MESSAGE,
std::ptr::null_mut(),
hinstance,
std::ptr::null(),
);
if hwnd.is_null() {
log::debug!("Failed to create HID monitor window");
return;
}
let mut filter: DEV_BROADCAST_DEVICEINTERFACE_W = std::mem::zeroed();
filter.dbcc_size = std::mem::size_of::<DEV_BROADCAST_DEVICEINTERFACE_W>() as u32;
filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
filter.dbcc_classguid = GUID_DEVINTERFACE_HID;
let notify = RegisterDeviceNotificationW(
hwnd as _,
&mut filter as *mut _ as *mut _,
DEVICE_NOTIFY_WINDOW_HANDLE,
);
if notify.is_null() {
log::debug!("Failed to register for HID device notifications");
return;
}
let mut msg: MSG = std::mem::zeroed();
PeekMessageW(
&mut msg,
std::ptr::null_mut(),
WM_USER,
WM_USER,
PM_NOREMOVE,
);
shutdown
.win_thread_id
.store(GetCurrentThreadId(), Ordering::SeqCst);
if shutdown.is_stopped() {
return;
}
while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}
}
#[cfg(all(feature = "hid", target_os = "macos"))]
mod macos_hid {
use super::{Change, Shutdown};
use core_foundation_sys::base::{CFAllocatorRef, kCFAllocatorDefault};
use core_foundation_sys::dictionary::CFDictionaryRef;
use core_foundation_sys::runloop::{
CFRunLoopGetCurrent, CFRunLoopRef, CFRunLoopRun, kCFRunLoopDefaultMode,
};
use core_foundation_sys::string::CFStringRef;
use std::os::raw::c_void;
use std::sync::mpsc;
#[repr(C)]
struct IOHIDManager(c_void);
type IOHIDManagerRef = *mut IOHIDManager;
type IOHIDDeviceRef = *mut c_void;
type IOReturn = i32;
type IOOptionBits = u32;
type IOHIDDeviceCallback = extern "C" fn(
context: *mut c_void,
result: IOReturn,
sender: *mut c_void,
device: IOHIDDeviceRef,
);
#[link(name = "IOKit", kind = "framework")]
unsafe extern "C" {
fn IOHIDManagerCreate(allocator: CFAllocatorRef, options: IOOptionBits) -> IOHIDManagerRef;
fn IOHIDManagerSetDeviceMatching(manager: IOHIDManagerRef, matching: CFDictionaryRef);
fn IOHIDManagerRegisterDeviceMatchingCallback(
manager: IOHIDManagerRef,
callback: IOHIDDeviceCallback,
context: *mut c_void,
);
fn IOHIDManagerRegisterDeviceRemovalCallback(
manager: IOHIDManagerRef,
callback: IOHIDDeviceCallback,
context: *mut c_void,
);
fn IOHIDManagerScheduleWithRunLoop(
manager: IOHIDManagerRef,
run_loop: CFRunLoopRef,
run_loop_mode: CFStringRef,
);
fn IOHIDManagerUnscheduleFromRunLoop(
manager: IOHIDManagerRef,
run_loop: CFRunLoopRef,
run_loop_mode: CFStringRef,
);
fn IOHIDManagerOpen(manager: IOHIDManagerRef, options: IOOptionBits) -> IOReturn;
fn IOHIDManagerClose(manager: IOHIDManagerRef, options: IOOptionBits) -> IOReturn;
}
extern "C" fn device_callback(
context: *mut c_void,
_result: IOReturn,
_sender: *mut c_void,
_device: IOHIDDeviceRef,
) {
let tx = unsafe { &*(context as *const mpsc::Sender<Change>) };
let _ = tx.send(Change::Hid);
}
pub(super) fn run(tx: mpsc::Sender<Change>, shutdown: &Shutdown) {
let tx = Box::new(tx);
let context = (&*tx as *const mpsc::Sender<Change>) as *mut c_void;
unsafe {
let manager = IOHIDManagerCreate(kCFAllocatorDefault, 0);
if manager.is_null() {
log::debug!("Failed to create IOHIDManager");
return;
}
IOHIDManagerSetDeviceMatching(manager, std::ptr::null());
IOHIDManagerRegisterDeviceMatchingCallback(manager, device_callback, context);
IOHIDManagerRegisterDeviceRemovalCallback(manager, device_callback, context);
let run_loop = CFRunLoopGetCurrent();
IOHIDManagerScheduleWithRunLoop(manager, run_loop, kCFRunLoopDefaultMode);
IOHIDManagerOpen(manager, 0);
*shutdown.macos_runloop.lock().unwrap() = Some(run_loop as usize);
if !shutdown.is_stopped() {
CFRunLoopRun();
}
IOHIDManagerUnscheduleFromRunLoop(manager, run_loop, kCFRunLoopDefaultMode);
IOHIDManagerClose(manager, 0);
}
drop(tx);
}
}
pub type YubiKeyId = u64;
#[derive(Debug, Clone)]
pub struct YubiKey {
id: YubiKeyId,
device: LocalYubiKeyDevice,
nodes: Vec<DeviceNode>,
}
impl YubiKey {
pub fn id(&self) -> YubiKeyId {
self.id
}
pub fn device(&self) -> &LocalYubiKeyDevice {
&self.device
}
pub fn into_device(self) -> LocalYubiKeyDevice {
self.device
}
pub fn nodes(&self) -> &[DeviceNode] {
&self.nodes
}
pub fn info(&self) -> &DeviceInfo {
self.device.info()
}
pub fn serial(&self) -> Option<u32> {
self.device.info().serial
}
}
#[derive(Debug, Clone)]
pub enum YubiKeyEvent {
Added(YubiKey),
Changed(YubiKey),
Removed(YubiKey),
}
pub fn monitor_yubikeys(
usb_interfaces: UsbInterface,
mut on_event: impl FnMut(YubiKeyEvent) + Send + 'static,
) -> MonitorHandle {
enum AggMsg {
Node(Box<NodeEvent>),
Ready,
}
let (node_tx, node_rx) = mpsc::channel::<AggMsg>();
let ready_tx = node_tx.clone();
let ready = ReadySignal::new();
let agg_ready = ready.clone();
let aggregator = thread::spawn(move || {
let mut state = Aggregator::default();
loop {
let first = match node_rx.recv() {
Ok(msg) => msg,
Err(_) => return,
};
let mut batch = vec![first];
while let Ok(msg) = node_rx.try_recv() {
batch.push(msg);
}
let mut became_ready = false;
for msg in batch {
match msg {
AggMsg::Node(event) => state.apply(*event),
AggMsg::Ready => became_ready = true,
}
}
state.reconcile(&mut on_event);
if became_ready {
agg_ready.signal();
}
}
});
let low_handle = monitor_device_events(usb_interfaces, move |event| {
let _ = node_tx.send(AggMsg::Node(Box::new(event)));
});
let low_ready = low_handle.ready.clone();
let low_shutdown = Arc::clone(&low_handle.shutdown);
let forwarder = thread::spawn(move || {
loop {
if low_shutdown.is_stopped() {
return;
}
if low_ready.wait_timeout(Duration::from_millis(100)) {
let _ = ready_tx.send(AggMsg::Ready);
return;
}
}
});
let mut handle = low_handle;
handle.attach_thread(aggregator);
handle.attach_thread(forwarder);
handle.ready = ready;
handle
}
#[derive(Default)]
struct Aggregator {
usb_readers: HashMap<String, DeviceNode>,
cards: HashMap<String, DeviceNode>,
otp: HashMap<String, DeviceNode>,
fido: HashMap<String, DeviceNode>,
devices: Vec<YubiKey>,
next_id: YubiKeyId,
}
impl Aggregator {
fn apply(&mut self, event: NodeEvent) {
let (added, node) = match event {
NodeEvent::Added(node) => (true, node),
NodeEvent::Removed(node) => (false, node),
};
let (map, key) = match &node {
DeviceNode::UsbReaderNode { reader_name, .. } => {
(&mut self.usb_readers, reader_name.clone())
}
DeviceNode::CardNode { reader_name, .. } => (&mut self.cards, reader_name.clone()),
DeviceNode::HidOtpNode { hid_path, .. } => (&mut self.otp, hid_path.clone()),
DeviceNode::HidFidoNode { hid_path, .. } => (&mut self.fido, hid_path.clone()),
};
if added {
map.insert(key, node);
} else {
map.remove(&key);
}
}
fn reconcile(&mut self, on_event: &mut impl FnMut(YubiKeyEvent)) {
let built = self.build_devices();
let prev = std::mem::take(&mut self.devices);
let mut used = vec![false; prev.len()];
let mut new_devices: Vec<YubiKey> = Vec::new();
let mut added = Vec::new();
let mut changed = Vec::new();
for b in built {
let b_serial = b.device.info().serial;
let idx = (0..prev.len()).find(|&i| {
if used[i] {
return false;
}
let p_serial = prev[i].device.info().serial;
match (b_serial, p_serial) {
(Some(a), Some(c)) => a == c,
(Some(_), None) | (None, None) => shares_path(&b.device, &prev[i].device),
(None, Some(_)) => false,
}
});
match idx {
Some(i) => {
used[i] = true;
let yk = YubiKey {
id: prev[i].id,
device: b.device,
nodes: b.nodes,
};
if yk.nodes != prev[i].nodes {
changed.push(yk.clone());
}
new_devices.push(yk);
}
None => {
let id = self.next_id;
self.next_id += 1;
let yk = YubiKey {
id,
device: b.device,
nodes: b.nodes,
};
added.push(yk.clone());
new_devices.push(yk);
}
}
}
let mut removed = Vec::new();
for (i, p) in prev.into_iter().enumerate() {
if !used[i] {
removed.push(p);
}
}
self.devices = new_devices;
for p in removed {
on_event(YubiKeyEvent::Removed(p));
}
for yk in added {
on_event(YubiKeyEvent::Added(yk));
}
for yk in changed {
on_event(YubiKeyEvent::Changed(yk));
}
}
fn build_devices(&self) -> Vec<BuiltDevice> {
let mut built = Vec::new();
for (reader_name, node) in &self.cards {
if self.usb_readers.contains_key(reader_name) {
continue;
}
if let DeviceNode::CardNode { device_info, .. } = node {
built.push(BuiltDevice {
device: LocalYubiKeyDevice::from_parts(
Some(reader_name.clone()),
None,
None,
None,
Transport::Nfc,
device_info.clone(),
),
nodes: vec![node.clone()],
});
}
}
let mut counts: HashMap<u16, usize> = HashMap::new();
{
let mut per_iface: [HashMap<u16, usize>; 3] = Default::default();
for node in self.usb_readers.values() {
if let DeviceNode::UsbReaderNode { pid, .. } = node {
*per_iface[0].entry(*pid).or_insert(0) += 1;
}
}
for node in self.otp.values() {
if let DeviceNode::HidOtpNode { pid, .. } = node {
*per_iface[1].entry(*pid).or_insert(0) += 1;
}
}
for node in self.fido.values() {
if let DeviceNode::HidFidoNode { pid, .. } = node {
*per_iface[2].entry(*pid).or_insert(0) += 1;
}
}
for map in &per_iface {
for (&pid, &c) in map {
let e = counts.entry(pid).or_insert(0);
*e = (*e).max(c);
}
}
}
let mut readers: Vec<Partial> = Vec::new();
for (reader_name, node) in &self.usb_readers {
if let DeviceNode::UsbReaderNode { pid, .. } = node {
let mut nodes = vec![node.clone()];
let info = match self.cards.get(reader_name) {
Some(card @ DeviceNode::CardNode { device_info, .. }) => {
nodes.push(card.clone());
Some(device_info.clone())
}
_ => None,
};
readers.push(Partial {
reader_name: Some(reader_name.clone()),
hid_path: None,
fido_path: None,
pid: Some(*pid),
info,
nodes,
});
}
}
let otp: Vec<Partial> = self
.otp
.iter()
.filter_map(|(path, node)| {
if let DeviceNode::HidOtpNode {
pid, device_info, ..
} = node
{
Some(Partial {
reader_name: None,
hid_path: Some(path.clone()),
fido_path: None,
pid: Some(*pid),
info: Some(device_info.clone()),
nodes: vec![node.clone()],
})
} else {
None
}
})
.collect();
let fido: Vec<Partial> = self
.fido
.iter()
.filter_map(|(path, node)| {
if let DeviceNode::HidFidoNode {
pid, device_info, ..
} = node
{
Some(Partial {
reader_name: None,
hid_path: None,
fido_path: Some(path.clone()),
pid: Some(*pid),
info: Some(device_info.clone()),
nodes: vec![node.clone()],
})
} else {
None
}
})
.collect();
let mut base = readers;
merge_partials(&mut base, otp, &counts);
merge_partials(&mut base, fido, &counts);
for mut p in base {
if let Some(info) = p.info.take() {
p.nodes.sort_by(node_sort_key);
built.push(BuiltDevice {
device: LocalYubiKeyDevice::from_parts(
p.reader_name,
p.hid_path,
p.fido_path,
p.pid,
Transport::Usb,
info,
),
nodes: p.nodes,
});
}
}
built
}
}
struct BuiltDevice {
device: LocalYubiKeyDevice,
nodes: Vec<DeviceNode>,
}
struct Partial {
reader_name: Option<String>,
hid_path: Option<String>,
fido_path: Option<String>,
pid: Option<u16>,
info: Option<DeviceInfo>,
nodes: Vec<DeviceNode>,
}
impl Partial {
fn serial(&self) -> Option<u32> {
self.info.as_ref().and_then(|i| i.serial)
}
fn merge(&mut self, other: Partial) {
if self.reader_name.is_none() {
self.reader_name = other.reader_name;
}
if self.hid_path.is_none() {
self.hid_path = other.hid_path;
}
if self.fido_path.is_none() {
self.fido_path = other.fido_path;
}
if self.pid.is_none() {
self.pid = other.pid;
}
let take = match (&self.info, &other.info) {
(None, Some(_)) => true,
(Some(a), Some(b)) => {
(a.serial.is_none() && b.serial.is_some())
|| (a.serial == b.serial && b.version > a.version)
}
_ => false,
};
if take {
self.info = other.info;
}
self.nodes.extend(other.nodes);
}
}
fn merge_partials(base: &mut Vec<Partial>, incoming: Vec<Partial>, counts: &HashMap<u16, usize>) {
for inc in incoming {
let serial = inc.serial();
let pid = inc.pid;
let unique_pid = pid.map(|p| counts.get(&p) == Some(&1)).unwrap_or(false);
let idx = serial
.and_then(|s| base.iter().position(|b| b.serial() == Some(s)))
.or_else(|| {
if unique_pid {
base.iter().position(|b| b.pid == pid)
} else {
None
}
});
match idx {
Some(i) => base[i].merge(inc),
None => base.push(inc),
}
}
}
fn shares_path(a: &LocalYubiKeyDevice, b: &LocalYubiKeyDevice) -> bool {
fn eq(x: &Option<String>, y: &Option<String>) -> bool {
matches!((x, y), (Some(x), Some(y)) if x == y)
}
eq(&a.reader_name, &b.reader_name)
|| eq(&a.hid_path, &b.hid_path)
|| eq(&a.fido_path, &b.fido_path)
}
fn node_sort_key(a: &DeviceNode, b: &DeviceNode) -> std::cmp::Ordering {
fn key(n: &DeviceNode) -> (u8, &str) {
match n {
DeviceNode::UsbReaderNode { reader_name, .. } => (0, reader_name),
DeviceNode::CardNode { reader_name, .. } => (1, reader_name),
DeviceNode::HidOtpNode { hid_path, .. } => (2, hid_path),
DeviceNode::HidFidoNode { hid_path, .. } => (3, hid_path),
}
}
key(a).cmp(&key(b))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Version;
#[test]
fn monitor_pause_is_exclusive_and_resumes_on_drop() {
let handle = monitor_device_events(UsbInterface(0), |_| {});
assert!(handle.wait_ready(Duration::from_secs(1)));
let pause = handle.pause(Duration::from_secs(1)).unwrap();
assert!(handle.pause(Duration::ZERO).is_none());
drop(pause);
assert!(handle.pause(Duration::from_secs(1)).is_some());
}
#[test]
fn verified_reinsert_info_requires_matching_path_and_pid() {
let mut info = DeviceInfo::parse_tlvs(&HashMap::new(), Version(5, 8, 0)).unwrap();
info.serial = Some(1234);
let device = LocalYubiKeyDevice::from_parts(
Some("reader".into()),
Some("otp".into()),
Some("fido".into()),
Some(0x407),
Transport::Usb,
info.clone(),
);
let verified = [device];
for (interface, path) in [
(VerifiedInterface::Ccid, "reader"),
(VerifiedInterface::Otp, "otp"),
(VerifiedInterface::Fido, "fido"),
] {
assert_eq!(
verified_info(&verified, interface, path, Some(0x407)),
Some(info.clone())
);
assert_eq!(
verified_info(&verified, interface, "another device", Some(0x407)),
None
);
assert_eq!(verified_info(&verified, interface, path, Some(0x408)), None);
}
}
#[cfg(feature = "pcsc")]
fn state_with_usb_cards(readers: &[(&str, Option<ReaderInstance>)]) -> MonitorState {
let info = DeviceInfo::parse_tlvs(&HashMap::new(), Version(5, 8, 0)).unwrap();
let mut state = MonitorState::default();
for (name, instance) in readers {
let name = *name;
state.usb_readers.insert(
name.into(),
DeviceNode::UsbReaderNode {
reader_name: name.into(),
pid: 0x407,
},
);
state.cards.insert(
name.into(),
DeviceNode::CardNode {
reader_name: name.into(),
device_info: info.clone(),
},
);
state.card_events.insert(name.into(), 1);
if let Some(instance) = instance {
state.reader_instances.insert(name.into(), instance.clone());
}
}
state
}
#[cfg(feature = "pcsc")]
#[test]
fn uncertain_reader_removal_preserves_cards_and_retry_deadlines() {
let known = |id: &str| Some(ReaderInstance::Known(id.into()));
let failed = ReaderInstance::Unknown {
retry_at: Instant::now() + Duration::from_secs(5),
};
let mut state = state_with_usb_cards(&[
("known", known(r"USB\VID_1050&PID_0407\1")),
("failed", Some(failed.clone())),
("uncached", None),
]);
let cards = state.cards.clone();
let counters = state.card_events.clone();
let mut removed = Vec::new();
state.invalidate_usb_cards(Some(r"USB\VID_1050&PID_0407\0"), &mut |e| removed.push(e));
assert!(removed.is_empty());
assert_eq!(state.cards, cards);
assert_eq!(state.card_events, counters);
assert_eq!(state.reader_instances.get("failed"), Some(&failed));
assert_eq!(state.stale_cards.len(), 2);
assert!(!state.stale_cards.contains("known"));
state.invalidate_usb_cards(None, &mut |e| removed.push(e));
assert!(removed.is_empty());
assert_eq!(state.cards, cards);
assert_eq!(state.card_events, counters);
assert_eq!(state.stale_cards.len(), 3);
assert_eq!(state.reader_instances.get("failed"), Some(&failed));
assert!(!state.reader_instances.contains_key("known"));
}
#[cfg(feature = "pcsc")]
#[test]
fn uncertain_refresh_keeps_busy_card_and_retries_without_invalidating_it() {
let reader = "Yubico YubiKey OTP+FIDO+CCID 0";
let failed = ReaderInstance::Unknown {
retry_at: Instant::now() + Duration::from_secs(5),
};
for (instance, removed) in [
(Some(failed.clone()), Some(r"USB\VID_1050&PID_0407\other")),
(Some(failed), None),
(
Some(ReaderInstance::Known(r"USB\VID_1050&PID_0407\0".into())),
None,
),
(None, Some(r"USB\VID_1050&PID_0407\other")),
] {
let mut state = state_with_usb_cards(&[(reader, instance)]);
let cards = state.cards.clone();
let counters = state.card_events.clone();
let info = match &cards[reader] {
DeviceNode::CardNode { device_info, .. } => device_info.clone(),
_ => unreachable!(),
};
let statuses = [ReaderStatus {
name: reader.into(),
card_present: true,
event_count: 1,
}];
let mut events = Vec::new();
state.invalidate_usb_cards(removed, &mut |e| events.push(e));
let instances = state.reader_instances.clone();
let mut probes = 0;
state.refresh_pcsc_cards(
&statuses,
&mut |e| events.push(e),
&[],
|name, usb, exclusive_only| {
assert_eq!(name, reader);
assert!(usb && exclusive_only);
probes += 1;
Err(
crate::platform::pcsc::PcscError::Pcsc(::pcsc::Error::SharingViolation)
.into(),
)
},
);
assert_eq!(probes, 1);
assert!(events.is_empty());
assert_eq!(state.cards, cards);
assert_eq!(state.card_events, counters);
assert_eq!(state.reader_instances, instances);
assert!(state.stale_cards.contains(reader));
state.refresh_pcsc_cards(
&statuses,
&mut |e| events.push(e),
&[],
|_, _, exclusive_only| {
assert!(exclusive_only);
Ok(info.clone())
},
);
assert!(events.is_empty());
assert_eq!(state.cards, cards);
assert_eq!(state.card_events, counters);
assert_eq!(state.reader_instances, instances);
assert!(state.stale_cards.is_empty());
state.refresh_pcsc_cards(&statuses, &mut |e| events.push(e), &[], |_, _, _| {
panic!("An unchanged card should not be probed again")
});
}
}
#[cfg(feature = "pcsc")]
#[test]
fn uncertain_refresh_publishes_changed_metadata_after_successful_probe() {
let reader = "Yubico YubiKey OTP+FIDO+CCID 0";
let mut state = state_with_usb_cards(&[(reader, None)]);
let previous = state.cards[reader].clone();
let mut events = Vec::new();
state.invalidate_usb_cards(None, &mut |e| events.push(e));
assert!(events.is_empty());
let info = DeviceInfo::parse_tlvs(&HashMap::new(), Version(5, 8, 1)).unwrap();
let node = DeviceNode::CardNode {
reader_name: reader.into(),
device_info: info.clone(),
};
state.refresh_pcsc_cards(
&[ReaderStatus {
name: reader.into(),
card_present: true,
event_count: 1,
}],
&mut |e| events.push(e),
&[],
|_, _, exclusive_only| {
assert!(exclusive_only);
Ok(info.clone())
},
);
assert_eq!(
events,
vec![NodeEvent::Removed(previous), NodeEvent::Added(node.clone())]
);
assert_eq!(state.cards[reader], node);
assert!(state.stale_cards.is_empty());
}
#[cfg(feature = "pcsc")]
#[test]
fn uncertain_refresh_uses_regular_read_for_uncached_card() {
let reader = "Yubico YubiKey OTP+FIDO+CCID 0";
let mut state = state_with_usb_cards(&[(reader, None)]);
let node = state.cards.remove(reader).unwrap();
state.card_events.remove(reader);
let info = match &node {
DeviceNode::CardNode { device_info, .. } => device_info.clone(),
_ => unreachable!(),
};
let mut events = Vec::new();
state.invalidate_usb_cards(None, &mut |e| events.push(e));
assert!(state.stale_cards.is_empty());
state.refresh_pcsc_cards(
&[ReaderStatus {
name: reader.into(),
card_present: true,
event_count: 1,
}],
&mut |e| events.push(e),
&[],
|_, _, exclusive_only| {
assert!(!exclusive_only);
Ok(info.clone())
},
);
assert_eq!(events, vec![NodeEvent::Added(node)]);
}
#[cfg(feature = "pcsc")]
#[test]
fn uncertain_refresh_does_not_hide_confirmed_card_removal() {
let reader = "Yubico YubiKey OTP+FIDO+CCID 0";
let mut state = state_with_usb_cards(&[(reader, None)]);
let previous = state.cards[reader].clone();
let mut events = Vec::new();
state.invalidate_usb_cards(None, &mut |e| events.push(e));
state.refresh_pcsc_cards(
&[ReaderStatus {
name: reader.into(),
card_present: false,
event_count: 2,
}],
&mut |e| events.push(e),
&[],
|_, _, _| panic!("An absent card should not be probed"),
);
assert_eq!(events, vec![NodeEvent::Removed(previous)]);
assert!(!state.cards.contains_key(reader));
assert!(state.stale_cards.is_empty());
}
#[cfg(feature = "pcsc")]
#[test]
fn uncertain_refresh_does_not_hide_confirmed_card_replacement() {
let reader = "Yubico YubiKey OTP+FIDO+CCID 0";
let mut state = state_with_usb_cards(&[(reader, None)]);
let previous = state.cards[reader].clone();
let info = match &previous {
DeviceNode::CardNode { device_info, .. } => device_info.clone(),
_ => unreachable!(),
};
let mut events = Vec::new();
state.invalidate_usb_cards(None, &mut |e| events.push(e));
state.refresh_pcsc_cards(
&[ReaderStatus {
name: reader.into(),
card_present: true,
event_count: 2,
}],
&mut |e| events.push(e),
&[],
|_, _, exclusive_only| {
assert!(!exclusive_only);
Ok(info.clone())
},
);
assert_eq!(
events,
vec![
NodeEvent::Removed(previous.clone()),
NodeEvent::Added(previous)
]
);
assert_eq!(state.card_events.get(reader), Some(&2));
assert!(state.stale_cards.is_empty());
}
#[cfg(feature = "pcsc")]
#[test]
fn removed_reader_preserves_other_cards_with_the_same_pid() {
let info = DeviceInfo::parse_tlvs(&HashMap::new(), Version(5, 8, 0)).unwrap();
let mut state = MonitorState::default();
for (name, instance) in [
("yk 0", r"USB\VID_1050&PID_0407\0"),
("yk 1", r"USB\VID_1050&PID_0407\1"),
] {
state.usb_readers.insert(
name.into(),
DeviceNode::UsbReaderNode {
reader_name: name.into(),
pid: 0x407,
},
);
state.cards.insert(
name.into(),
DeviceNode::CardNode {
reader_name: name.into(),
device_info: info.clone(),
},
);
state.card_events.insert(name.into(), 1);
state
.reader_instances
.insert(name.into(), ReaderInstance::Known(instance.into()));
}
let mut removed = Vec::new();
state.invalidate_usb_cards(Some(r"usb\vid_1050&pid_0407\0"), &mut |event| {
removed.push(event)
});
assert_eq!(removed.len(), 1);
assert!(!state.cards.contains_key("yk 0") && !state.card_events.contains_key("yk 0"));
assert!(state.cards.contains_key("yk 1") && state.usb_readers.contains_key("yk 0"));
assert_eq!(state.card_events.get("yk 1"), Some(&1));
assert!(!state.reader_instances.contains_key("yk 0"));
assert!(state.reader_instances.contains_key("yk 1"));
for instance in [r"SWD\ScReader\unknown", r"USB\VID_1050&PID_0407\unknown"] {
state.invalidate_usb_cards(Some(instance), &mut |event| removed.push(event));
}
assert_eq!(removed.len(), 1);
assert!(state.cards.contains_key("yk 1"));
}
#[cfg(feature = "pcsc")]
#[test]
fn reader_instance_is_parsed_from_interface_path() {
assert_eq!(
reader_instance_from_path(
r"\\?\USB#VID_1050&PID_0407&MI_02#7&1a2b&0&0002#{50dd5230-ba8a-11d1-bf5d-0000f805f530}"
),
Some(r"USB\VID_1050&PID_0407&MI_02\7&1a2b&0&0002".into())
);
assert_eq!(
reader_instance_from_path(r"\\?\SWD#ScReader#x#{50dd5230-ba8a-11d1-bf5d-0000f805f530}"),
Some(r"SWD\ScReader\x".into())
);
for path in [
"",
r"\\?\USB#VID_1050&PID_0407#x",
r"\\?\SWD#ScReader#x",
r"\\?\USB##x#{guid}",
r"USB\VID_1050&PID_0407\x",
] {
assert_eq!(reader_instance_from_path(path), None, "{path}");
}
}
}