use super::Seat;
use super::keeper::LockState;
use super::socket::{self, Address, PATIENCE};
use super::wire::{self, Answer, Request};
use crate::crypto::{DerivedKey, SALT_LEN};
use crate::error::{Error, Result};
use crate::keys::{FreshKey, KeySource};
use std::sync::mpsc;
use std::time::Duration;
use zeroize::Zeroizing;
#[derive(Debug, Clone)]
pub struct Client {
seat: Seat,
address: Address,
patience: Duration,
looking: bool,
}
impl Client {
pub fn of(seat: Seat) -> Option<Self> {
Some(Self {
seat,
address: Address::of(seat)?,
patience: PATIENCE,
looking: false,
})
}
pub fn only_looking(mut self) -> Self {
self.looking = true;
self
}
pub fn with_patience(mut self, patience: Duration) -> Self {
self.patience = patience;
self
}
pub fn seat(&self) -> Seat {
self.seat
}
pub fn state(&self) -> Option<LockState> {
match self.ask(&Request::State)? {
Answer::Locked => Some(LockState::Locked),
Answer::Unlocked { left, idle } => Some(LockState::Unlocked { left, idle }),
_ => None,
}
}
pub fn lock(&self) -> Option<bool> {
match self.ask(&Request::Lock)? {
Answer::LockedNow(had) => Some(had),
_ => None,
}
}
fn ask(&self, request: &Request) -> Option<Answer> {
ask(&self.address, request, self.patience)
}
}
impl KeySource for Client {
fn key_for(&self, salt: &[u8; SALT_LEN]) -> Result<DerivedKey> {
let request = if self.looking {
Request::Peek(*salt)
} else {
Request::Key(*salt)
};
match self.ask(&request) {
Some(Answer::Key(key)) => Ok(key),
_ => Err(Error::KeysGone),
}
}
fn fresh(&self, opened_with: &[u8; SALT_LEN]) -> Result<FreshKey> {
match self.ask(&Request::Fresh(*opened_with)) {
Some(Answer::Fresh(fresh)) => Ok(fresh),
_ => Err(Error::KeysGone),
}
}
}
pub(super) fn answers_at(address: &Address) -> bool {
ask(address, &Request::State, PATIENCE).is_some()
}
fn ask(address: &Address, request: &Request, patience: Duration) -> Option<Answer> {
let (answer, answered) = mpsc::channel();
let address = address.clone();
let request = request.encode();
std::thread::Builder::new()
.name("agent question".to_owned())
.spawn(move || {
let _ = answer.send(exchange(&address, &request));
})
.ok()?;
answered.recv_timeout(patience).ok().flatten()
}
fn exchange(address: &Address, request: &Zeroizing<Vec<u8>>) -> Option<Answer> {
let stream = socket::connect(address).ok()?;
wire::send(&stream, request).ok()?;
let answer = wire::receive(&stream).ok()?;
Answer::decode(&answer)
}