use std::io;
use std::path::Path;
use teter_common::command::{CHANNEL_PREFIX, Command, FromMachine, MAX_FRAME, Outcome, ToMachine};
use teter_common::{Message, MessagePayload, MessageType, SessionId};
pub use teter_core::command::{Challenge, check_challenge, open_reply, seal_command};
use crate::account::AccountKeys;
use crate::{Relay, recv, send};
pub const ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
pub struct Channel {
relay: Relay,
session: SessionId,
pub machine: String,
machine_key: Vec<u8>,
}
impl Channel {
pub async fn open(
url: &str,
ca_cert: Option<&Path>,
session: SessionId,
token: String,
machine: String,
machine_key: Vec<u8>,
) -> io::Result<Self> {
if machine_key.is_empty() {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"the relay gives no machine key (too old for commands)",
));
}
let mut random = [0_u8; 16];
getrandom::fill(&mut random).map_err(io::Error::other)?;
let channel = format!("{CHANNEL_PREFIX}{}", teter_common::account::hex(&random));
let mut relay = crate::connect(url, ca_cert).await?;
send(&mut relay, Message::auth(token)).await?;
send(
&mut relay,
Message::session_join(session).on_channel(Some(channel)),
)
.await?;
loop {
let msg = recv(&mut relay)
.await?
.ok_or_else(|| io::Error::other("the relay closed before the join"))?;
if msg.msg_type == MessageType::SessionJoined {
if let Some(MessagePayload::SessionCreated { protocol, .. }) = &msg.payload {
teter_common::check_relay_protocol(*protocol).map_err(io::Error::other)?;
}
break;
}
if msg.msg_type == MessageType::SessionError {
return Err(io::Error::other(format!(
"the relay refused the join: {}",
reason(&msg.payload)
)));
}
}
Ok(Self {
relay,
session,
machine,
machine_key,
})
}
async fn put(&mut self, frame: &ToMachine) -> io::Result<()> {
let data = serde_json::to_vec(frame).map_err(io::Error::other)?;
send(&mut self.relay, Message::input(self.session, data)).await
}
async fn take(&mut self) -> io::Result<FromMachine> {
tokio::time::timeout(ANSWER_TIMEOUT, self.next_frame())
.await
.map_err(|_elapsed| {
io::Error::new(io::ErrorKind::TimedOut, "the machine did not answer")
})?
}
async fn next_frame(&mut self) -> io::Result<FromMachine> {
loop {
let msg = recv(&mut self.relay)
.await?
.ok_or_else(|| io::Error::other("the relay closed the command channel"))?;
if let (MessageType::Output, Some(MessagePayload::OutputData { data })) =
(&msg.msg_type, &msg.payload)
{
if data.len() > MAX_FRAME {
return Err(io::Error::other("a command frame too large"));
}
return serde_json::from_slice(data).map_err(io::Error::other);
}
if msg.msg_type == MessageType::SessionError {
return Err(io::Error::other(format!(
"the relay ended the command channel: {}",
reason(&msg.payload)
)));
}
}
}
pub async fn challenge(&mut self) -> io::Result<Challenge> {
self.put(&ToMachine::Hello).await?;
match self.take().await? {
FromMachine::Challenge {
nonce,
key,
signature,
} => check_challenge(&self.machine, &self.machine_key, nonce, key, &signature)
.ok_or_else(|| io::Error::other("the challenge is not signed by the machine")),
FromMachine::Refused { reason } => Err(io::Error::other(reason)),
FromMachine::Reply { .. } => Err(io::Error::other("a reply where a challenge was due")),
}
}
pub async fn send_sealed(
&mut self,
account: &AccountKeys,
nonce: &[u8],
sealed: Vec<u8>,
) -> io::Result<Outcome> {
self.put(&ToMachine::Command { sealed }).await?;
match self.take().await? {
FromMachine::Reply { sealed, signature } => open_reply(
account,
&self.machine,
&self.machine_key,
nonce,
&sealed,
&signature,
),
FromMachine::Refused { reason } => Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("the machine refused the command: {reason}"),
)),
FromMachine::Challenge { .. } => {
Err(io::Error::other("a challenge where a reply was due"))
}
}
}
pub async fn run(&mut self, account: &AccountKeys, command: Command) -> io::Result<Outcome> {
let challenge = self.challenge().await?;
let sealed = seal_command(account, &self.machine, &challenge, command)?;
self.send_sealed(account, &challenge.nonce, sealed).await
}
}
fn reason(payload: &Option<MessagePayload>) -> &str {
match payload {
Some(MessagePayload::ErrorReason { reason }) => reason,
_ => "no reason given",
}
}