| 1 |
use crate::transport::hid::HIDDevice; |
| 2 |
|
| 3 |
pub use crate::transport::platform::device::Device; |
| 4 |
|
| 5 |
use runloop::RunLoop; |
| 6 |
use std::collections::{HashMap, HashSet}; |
| 7 |
use std::sync::mpsc::{channel, RecvTimeoutError, Sender}; |
| 8 |
use std::time::Duration; |
| 9 |
|
| 10 |
pub type DeviceID = <Device as HIDDevice>::Id; |
| 11 |
pub type DeviceBuildParameters = <Device as HIDDevice>::BuildParameters; |
| 12 |
|
| 13 |
trait DeviceSelectorEventMarker {} |
| 14 |
|
| 15 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 16 |
pub enum BlinkResult { |
| 17 |
DeviceSelected, |
| 18 |
Cancelled, |
| 19 |
} |
| 20 |
|
| 21 |
#[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 22 |
pub enum DeviceCommand { |
| 23 |
Blink, |
| 24 |
Cancel, |
| 25 |
Continue, |
| 26 |
Removed, |
| 27 |
} |
| 28 |
|
| 29 |
#[derive(Debug)] |
| 30 |
pub enum DeviceSelectorEvent { |
| 31 |
Cancel, |
| 32 |
Timeout, |
| 33 |
DevicesAdded(Vec<DeviceID>), |
| 34 |
DeviceRemoved(DeviceID), |
| 35 |
NotAToken(DeviceID), |
| 36 |
ImAToken((DeviceID, Sender<DeviceCommand>)), |
| 37 |
SelectedToken(DeviceID), |
| 38 |
} |
| 39 |
|
| 40 |
pub struct DeviceSelector { |
| 41 |
/// How to send a message to the event loop |
| 42 |
sender: Sender<DeviceSelectorEvent>, |
| 43 |
/// Thread of the event loop |
| 44 |
runloop: RunLoop, |
| 45 |
} |
| 46 |
|
| 47 |
impl DeviceSelector { |
| 48 |
pub fn run() -> Self { |
| 49 |
let (selector_send, selector_rec) = channel(); |
| 50 |
// let new_device_callback = Arc::new(new_device_cb); |
| 51 |
let runloop = RunLoop::new(move |alive| { |
| 52 |
let mut blinking = false; |
| 53 |
// Device was added, but we wait for its response, if it is a token or not |
| 54 |
// We save both a write-only copy of the device (for cancellation) and it's thread |
| 55 |
let mut waiting_for_response = HashSet::new(); |
| 56 |
// Device IDs of devices that responded with "ImAToken" mapping to channels that are |
| 57 |
// waiting to receive a DeviceCommand |
| 58 |
let mut tokens = HashMap::new(); |
| 59 |
while alive() { |
| 60 |
let d = Duration::from_secs(100); |
| 61 |
let res = match selector_rec.recv_timeout(d) { |
| 62 |
Err(RecvTimeoutError::Disconnected) => { |
| 63 |
break; |
| 64 |
} |
| 65 |
Err(RecvTimeoutError::Timeout) => DeviceSelectorEvent::Timeout, |
| 66 |
Ok(res) => res, |
| 67 |
}; |
| 68 |
|
| 69 |
match res { |
| 70 |
DeviceSelectorEvent::Timeout | DeviceSelectorEvent::Cancel => { |
| 71 |
/* TODO */ |
| 72 |
Self::cancel_all(tokens, None); |
| 73 |
break; |
| 74 |
} |
| 75 |
DeviceSelectorEvent::SelectedToken(ref id) => { |
| 76 |
Self::cancel_all(tokens, Some(id)); |
| 77 |
break; // We are done here. The selected device continues without us. |
| 78 |
} |
| 79 |
DeviceSelectorEvent::DevicesAdded(ids) => { |
| 80 |
for id in ids { |
| 81 |
debug!("Device added event: {:?}", id); |
| 82 |
waiting_for_response.insert(id); |
| 83 |
} |
| 84 |
continue; |
| 85 |
} |
| 86 |
DeviceSelectorEvent::DeviceRemoved(ref id) => { |
| 87 |
debug!("Device removed event: {:?}", id); |
| 88 |
if !waiting_for_response.remove(id) { |
| 89 |
// Note: We _could_ check here if we had multiple tokens and are already blinking |
| 90 |
// and the removal of this one leads to only one token left. So we could in theory |
| 91 |
// stop blinking and select it right away. At the moment, I think this is a |
| 92 |
// too surprising behavior and therefore, we let the remaining device keep on blinking |
| 93 |
// since the user could add yet another device, instead of using the remaining one. |
| 94 |
tokens.iter().for_each(|(dev_id, tx)| { |
| 95 |
if dev_id == id { |
| 96 |
let _ = tx.send(DeviceCommand::Removed); |
| 97 |
} |
| 98 |
}); |
| 99 |
tokens.retain(|dev_id, _| dev_id != id); |
| 100 |
if tokens.is_empty() { |
| 101 |
blinking = false; |
| 102 |
continue; |
| 103 |
} |
| 104 |
} |
| 105 |
// We are already blinking, so no need to run the code below this match |
| 106 |
// that figures out if we should blink or not. In fact, currently, we do |
| 107 |
// NOT want to run this code again, because if you have 2 blinking tokens |
| 108 |
// and one got removed, we WANT the remaining one to continue blinking. |
| 109 |
// This is a design choice, because I currently think it is the "less surprising" |
| 110 |
// option to the user. |
| 111 |
if blinking { |
| 112 |
continue; |
| 113 |
} |
| 114 |
} |
| 115 |
DeviceSelectorEvent::NotAToken(ref id) => { |
| 116 |
debug!("Device not a token event: {:?}", id); |
| 117 |
waiting_for_response.remove(id); |
| 118 |
} |
| 119 |
DeviceSelectorEvent::ImAToken((id, tx)) => { |
| 120 |
let _ = waiting_for_response.remove(&id); |
| 121 |
if blinking { |
| 122 |
// We are already blinking, so this new device should blink too. |
| 123 |
if tx.send(DeviceCommand::Blink).is_ok() { |
| 124 |
tokens.insert(id, tx.clone()); |
| 125 |
} |
| 126 |
continue; |
| 127 |
} else { |
| 128 |
tokens.insert(id, tx.clone()); |
| 129 |
} |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
// All known devices told us, whether they are tokens or not and we have at least one token |
| 134 |
if waiting_for_response.is_empty() && !tokens.is_empty() { |
| 135 |
if tokens.len() == 1 { |
| 136 |
let (dev_id, tx) = tokens.drain().next().unwrap(); // We just checked that it can't be empty |
| 137 |
if tx.send(DeviceCommand::Continue).is_err() { |
| 138 |
// Device thread died in the meantime (which shouldn't happen). |
| 139 |
// Tokens is empty, so we just start over again |
| 140 |
continue; |
| 141 |
} |
| 142 |
Self::cancel_all(tokens, Some(&dev_id)); |
| 143 |
break; // We are done here |
| 144 |
} else { |
| 145 |
blinking = true; |
| 146 |
|
| 147 |
tokens.iter().for_each(|(_dev, tx)| { |
| 148 |
// A send operation can only fail if the receiving end of a channel is disconnected, implying that the data could never be received. |
| 149 |
// We ignore errors here for now, but should probably remove the device in such a case (even though it theoretically can't happen) |
| 150 |
let _ = tx.send(DeviceCommand::Blink); |
| 151 |
}); |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
}); |
| 156 |
Self { |
| 157 |
runloop: runloop.unwrap(), // TODO |
| 158 |
sender: selector_send, |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
pub fn clone_sender(&self) -> Sender<DeviceSelectorEvent> { |
| 163 |
self.sender.clone() |
| 164 |
} |
| 165 |
|
| 166 |
fn cancel_all(tokens: HashMap<DeviceID, Sender<DeviceCommand>>, exclude: Option<&DeviceID>) { |
| 167 |
for (dev_id, tx) in tokens.iter() { |
| 168 |
if Some(dev_id) != exclude { |
| 169 |
let _ = tx.send(DeviceCommand::Cancel); |
| 170 |
} |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
pub fn stop(&mut self) { |
| 175 |
// We ignore a possible error here, since we don't really care |
| 176 |
let _ = self.sender.send(DeviceSelectorEvent::Cancel); |
| 177 |
self.runloop.cancel(); |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
#[cfg(test)] |
| 182 |
pub mod tests { |
| 183 |
use super::*; |
| 184 |
use crate::{ |
| 185 |
consts::Capability, |
| 186 |
ctap2::commands::get_info::{AuthenticatorInfo, AuthenticatorOptions}, |
| 187 |
transport::FidoDevice, |
| 188 |
u2ftypes::U2FDeviceInfo, |
| 189 |
}; |
| 190 |
|
| 191 |
pub(crate) fn gen_info(id: String) -> U2FDeviceInfo { |
| 192 |
U2FDeviceInfo { |
| 193 |
vendor_name: String::from("ExampleVendor").into_bytes(), |
| 194 |
device_name: id.into_bytes(), |
| 195 |
version_interface: 1, |
| 196 |
version_major: 3, |
| 197 |
version_minor: 2, |
| 198 |
version_build: 1, |
| 199 |
cap_flags: Capability::WINK | Capability::CBOR | Capability::NMSG, |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
pub(crate) fn make_device_simple_u2f(dev: &mut Device) { |
| 204 |
dev.set_device_info(gen_info(dev.id())); |
| 205 |
dev.set_cid([1, 2, 3, 4]); // Need to set something other than broadcast |
| 206 |
dev.downgrade_to_ctap1(); |
| 207 |
dev.create_channel(); |
| 208 |
} |
| 209 |
|
| 210 |
pub(crate) fn make_device_with_pin(dev: &mut Device) { |
| 211 |
dev.set_device_info(gen_info(dev.id())); |
| 212 |
dev.set_cid([1, 2, 3, 4]); // Need to set something other than broadcast |
| 213 |
dev.create_channel(); |
| 214 |
let info = AuthenticatorInfo { |
| 215 |
options: AuthenticatorOptions { |
| 216 |
client_pin: Some(true), |
| 217 |
..Default::default() |
| 218 |
}, |
| 219 |
..Default::default() |
| 220 |
}; |
| 221 |
dev.set_authenticator_info(info); |
| 222 |
} |
| 223 |
|
| 224 |
fn send_i_am_token(dev: &Device, selector: &DeviceSelector) { |
| 225 |
selector |
| 226 |
.sender |
| 227 |
.send(DeviceSelectorEvent::ImAToken(( |
| 228 |
dev.id(), |
| 229 |
dev.sender.clone().unwrap(), |
| 230 |
))) |
| 231 |
.unwrap(); |
| 232 |
} |
| 233 |
|
| 234 |
fn send_no_token(dev: &Device, selector: &DeviceSelector) { |
| 235 |
selector |
| 236 |
.sender |
| 237 |
.send(DeviceSelectorEvent::NotAToken(dev.id())) |
| 238 |
.unwrap() |
| 239 |
} |
| 240 |
|
| 241 |
fn remove_device(dev: &Device, selector: &DeviceSelector) { |
| 242 |
selector |
| 243 |
.sender |
| 244 |
.send(DeviceSelectorEvent::DeviceRemoved(dev.id())) |
| 245 |
.unwrap(); |
| 246 |
assert_eq!( |
| 247 |
dev.receiver.as_ref().unwrap().recv().unwrap(), |
| 248 |
DeviceCommand::Removed |
| 249 |
); |
| 250 |
} |
| 251 |
|
| 252 |
fn add_devices<'a, T>(iter: T, selector: &DeviceSelector) |
| 253 |
where |
| 254 |
T: Iterator<Item = &'a Device>, |
| 255 |
{ |
| 256 |
selector |
| 257 |
.sender |
| 258 |
.send(DeviceSelectorEvent::DevicesAdded( |
| 259 |
iter.map(|f| f.id()).collect(), |
| 260 |
)) |
| 261 |
.unwrap(); |
| 262 |
} |
| 263 |
|
| 264 |
#[test] |
| 265 |
fn test_device_selector_one_token_no_late_adds() { |
| 266 |
let mut devices = vec![ |
| 267 |
Device::new("device selector 1").unwrap(), |
| 268 |
Device::new("device selector 2").unwrap(), |
| 269 |
Device::new("device selector 3").unwrap(), |
| 270 |
Device::new("device selector 4").unwrap(), |
| 271 |
]; |
| 272 |
|
| 273 |
// Make those actual tokens. The rest is interpreted as non-u2f-devices |
| 274 |
make_device_with_pin(&mut devices[2]); |
| 275 |
let selector = DeviceSelector::run(); |
| 276 |
|
| 277 |
// Adding all |
| 278 |
add_devices(devices.iter(), &selector); |
| 279 |
devices.iter_mut().for_each(|d| { |
| 280 |
if !d.is_u2f() { |
| 281 |
send_no_token(d, &selector); |
| 282 |
} |
| 283 |
}); |
| 284 |
|
| 285 |
send_i_am_token(&devices[2], &selector); |
| 286 |
|
| 287 |
assert_eq!( |
| 288 |
devices[2].receiver.as_ref().unwrap().recv().unwrap(), |
| 289 |
DeviceCommand::Continue |
| 290 |
); |
| 291 |
} |
| 292 |
|
| 293 |
// This test is mostly for testing stop() and clone_sender() |
| 294 |
#[test] |
| 295 |
fn test_device_selector_stop() { |
| 296 |
let device = Device::new("device selector 1").unwrap(); |
| 297 |
|
| 298 |
let mut selector = DeviceSelector::run(); |
| 299 |
|
| 300 |
// Adding all |
| 301 |
selector |
| 302 |
.clone_sender() |
| 303 |
.send(DeviceSelectorEvent::DevicesAdded(vec![device.id()])) |
| 304 |
.unwrap(); |
| 305 |
|
| 306 |
selector |
| 307 |
.clone_sender() |
| 308 |
.send(DeviceSelectorEvent::NotAToken(device.id())) |
| 309 |
.unwrap(); |
| 310 |
selector.stop(); |
| 311 |
} |
| 312 |
|
| 313 |
#[test] |
| 314 |
fn test_device_selector_all_pins_with_late_add() { |
| 315 |
let mut devices = vec![ |
| 316 |
Device::new("device selector 1").unwrap(), |
| 317 |
Device::new("device selector 2").unwrap(), |
| 318 |
Device::new("device selector 3").unwrap(), |
| 319 |
Device::new("device selector 4").unwrap(), |
| 320 |
Device::new("device selector 5").unwrap(), |
| 321 |
Device::new("device selector 6").unwrap(), |
| 322 |
]; |
| 323 |
|
| 324 |
// Make those actual tokens. The rest is interpreted as non-u2f-devices |
| 325 |
make_device_with_pin(&mut devices[2]); |
| 326 |
make_device_with_pin(&mut devices[4]); |
| 327 |
make_device_with_pin(&mut devices[5]); |
| 328 |
|
| 329 |
let selector = DeviceSelector::run(); |
| 330 |
|
| 331 |
// Adding all, except the last one (we simulate that this one is not yet plugged in) |
| 332 |
add_devices(devices.iter().take(5), &selector); |
| 333 |
|
| 334 |
// Interleave tokens and non-tokens |
| 335 |
send_i_am_token(&devices[2], &selector); |
| 336 |
|
| 337 |
devices.iter_mut().for_each(|d| { |
| 338 |
if !d.is_u2f() { |
| 339 |
send_no_token(d, &selector); |
| 340 |
} |
| 341 |
}); |
| 342 |
|
| 343 |
send_i_am_token(&devices[4], &selector); |
| 344 |
|
| 345 |
// We added 2 devices that are tokens. They should get the blink-command now |
| 346 |
assert_eq!( |
| 347 |
devices[2].receiver.as_ref().unwrap().recv().unwrap(), |
| 348 |
DeviceCommand::Blink |
| 349 |
); |
| 350 |
assert_eq!( |
| 351 |
devices[4].receiver.as_ref().unwrap().recv().unwrap(), |
| 352 |
DeviceCommand::Blink |
| 353 |
); |
| 354 |
|
| 355 |
// Plug in late device |
| 356 |
send_i_am_token(&devices[5], &selector); |
| 357 |
assert_eq!( |
| 358 |
devices[5].receiver.as_ref().unwrap().recv().unwrap(), |
| 359 |
DeviceCommand::Blink |
| 360 |
); |
| 361 |
} |
| 362 |
|
| 363 |
#[test] |
| 364 |
fn test_device_selector_no_pins_late_mixed_adds() { |
| 365 |
// Multiple tokes, none of them support a PIN |
| 366 |
let mut devices = vec![ |
| 367 |
Device::new("device selector 1").unwrap(), |
| 368 |
Device::new("device selector 2").unwrap(), |
| 369 |
Device::new("device selector 3").unwrap(), |
| 370 |
Device::new("device selector 4").unwrap(), |
| 371 |
Device::new("device selector 5").unwrap(), |
| 372 |
Device::new("device selector 6").unwrap(), |
| 373 |
Device::new("device selector 7").unwrap(), |
| 374 |
]; |
| 375 |
|
| 376 |
// Make those actual tokens. The rest is interpreted as non-u2f-devices |
| 377 |
make_device_simple_u2f(&mut devices[2]); |
| 378 |
make_device_simple_u2f(&mut devices[4]); |
| 379 |
make_device_simple_u2f(&mut devices[5]); |
| 380 |
|
| 381 |
let selector = DeviceSelector::run(); |
| 382 |
|
| 383 |
// Adding all, except the last one (we simulate that this one is not yet plugged in) |
| 384 |
add_devices(devices.iter().take(5), &selector); |
| 385 |
|
| 386 |
// Interleave tokens and non-tokens |
| 387 |
send_i_am_token(&devices[2], &selector); |
| 388 |
|
| 389 |
devices.iter_mut().for_each(|d| { |
| 390 |
if !d.is_u2f() { |
| 391 |
send_no_token(d, &selector); |
| 392 |
} |
| 393 |
}); |
| 394 |
|
| 395 |
send_i_am_token(&devices[4], &selector); |
| 396 |
|
| 397 |
// We added 2 devices that are tokens. They should get the blink-command now |
| 398 |
assert_eq!( |
| 399 |
devices[2].receiver.as_ref().unwrap().recv().unwrap(), |
| 400 |
DeviceCommand::Blink |
| 401 |
); |
| 402 |
assert_eq!( |
| 403 |
devices[4].receiver.as_ref().unwrap().recv().unwrap(), |
| 404 |
DeviceCommand::Blink |
| 405 |
); |
| 406 |
|
| 407 |
// Plug in late device |
| 408 |
send_i_am_token(&devices[5], &selector); |
| 409 |
assert_eq!( |
| 410 |
devices[5].receiver.as_ref().unwrap().recv().unwrap(), |
| 411 |
DeviceCommand::Blink |
| 412 |
); |
| 413 |
// Remove device again |
| 414 |
remove_device(&devices[5], &selector); |
| 415 |
|
| 416 |
// Now we add a token that has a PIN, it should not get "Continue" but "Blink" |
| 417 |
make_device_with_pin(&mut devices[6]); |
| 418 |
send_i_am_token(&devices[6], &selector); |
| 419 |
assert_eq!( |
| 420 |
devices[6].receiver.as_ref().unwrap().recv().unwrap(), |
| 421 |
DeviceCommand::Blink |
| 422 |
); |
| 423 |
} |
| 424 |
|
| 425 |
#[test] |
| 426 |
fn test_device_selector_mixed_pins_remove_all() { |
| 427 |
// Multiple tokes, none of them support a PIN, so we should get Continue-commands |
| 428 |
// for all of them |
| 429 |
let mut devices = vec![ |
| 430 |
Device::new("device selector 1").unwrap(), |
| 431 |
Device::new("device selector 2").unwrap(), |
| 432 |
Device::new("device selector 3").unwrap(), |
| 433 |
Device::new("device selector 4").unwrap(), |
| 434 |
Device::new("device selector 5").unwrap(), |
| 435 |
Device::new("device selector 6").unwrap(), |
| 436 |
]; |
| 437 |
|
| 438 |
// Make those actual tokens. The rest is interpreted as non-u2f-devices |
| 439 |
make_device_with_pin(&mut devices[2]); |
| 440 |
make_device_with_pin(&mut devices[4]); |
| 441 |
make_device_with_pin(&mut devices[5]); |
| 442 |
|
| 443 |
let selector = DeviceSelector::run(); |
| 444 |
|
| 445 |
// Adding all, except the last one (we simulate that this one is not yet plugged in) |
| 446 |
add_devices(devices.iter(), &selector); |
| 447 |
|
| 448 |
devices.iter_mut().for_each(|d| { |
| 449 |
if d.is_u2f() { |
| 450 |
send_i_am_token(d, &selector); |
| 451 |
} else { |
| 452 |
send_no_token(d, &selector); |
| 453 |
} |
| 454 |
}); |
| 455 |
|
| 456 |
for idx in [2, 4, 5] { |
| 457 |
assert_eq!( |
| 458 |
devices[idx].receiver.as_ref().unwrap().recv().unwrap(), |
| 459 |
DeviceCommand::Blink |
| 460 |
); |
| 461 |
} |
| 462 |
|
| 463 |
// Remove all tokens |
| 464 |
for idx in [2, 4, 5] { |
| 465 |
remove_device(&devices[idx], &selector); |
| 466 |
} |
| 467 |
|
| 468 |
// Adding one again |
| 469 |
send_i_am_token(&devices[4], &selector); |
| 470 |
|
| 471 |
// This should now get a "Continue" instead of "Blinking", because it's the only device |
| 472 |
assert_eq!( |
| 473 |
devices[4].receiver.as_ref().unwrap().recv().unwrap(), |
| 474 |
DeviceCommand::Continue |
| 475 |
); |
| 476 |
} |
| 477 |
} |