1use std::io;
6use std::path::Path;
7
8use teter_common::command::{CHANNEL_PREFIX, Command, FromMachine, MAX_FRAME, Outcome, ToMachine};
9use teter_common::{Message, MessagePayload, MessageType, SessionId};
10
11pub use teter_core::command::{Challenge, check_challenge, open_reply, seal_command};
12
13use crate::account::AccountKeys;
14use crate::{Relay, recv, send};
15
16pub const ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
20
21pub struct Channel {
23 relay: Relay,
24 session: SessionId,
25 pub machine: String,
27 machine_key: Vec<u8>,
29}
30
31impl Channel {
32 pub async fn open(
40 url: &str,
41 ca_cert: Option<&Path>,
42 session: SessionId,
43 token: String,
44 machine: String,
45 machine_key: Vec<u8>,
46 ) -> io::Result<Self> {
47 if machine_key.is_empty() {
48 return Err(io::Error::new(
49 io::ErrorKind::Unsupported,
50 "the relay gives no machine key (too old for commands)",
51 ));
52 }
53 let mut random = [0_u8; 16];
54 getrandom::fill(&mut random).map_err(io::Error::other)?;
55 let channel = format!("{CHANNEL_PREFIX}{}", teter_common::account::hex(&random));
56 let mut relay = crate::connect(url, ca_cert).await?;
57 send(&mut relay, Message::auth(token)).await?;
58 send(
59 &mut relay,
60 Message::session_join(session).on_channel(Some(channel)),
61 )
62 .await?;
63 loop {
64 let msg = recv(&mut relay)
65 .await?
66 .ok_or_else(|| io::Error::other("the relay closed before the join"))?;
67 if msg.msg_type == MessageType::SessionJoined {
68 if let Some(MessagePayload::SessionCreated { protocol, .. }) = &msg.payload {
69 teter_common::check_relay_protocol(*protocol).map_err(io::Error::other)?;
70 }
71 break;
72 }
73 if msg.msg_type == MessageType::SessionError {
74 return Err(io::Error::other(format!(
75 "the relay refused the join: {}",
76 reason(&msg.payload)
77 )));
78 }
79 }
80 Ok(Self {
81 relay,
82 session,
83 machine,
84 machine_key,
85 })
86 }
87
88 async fn put(&mut self, frame: &ToMachine) -> io::Result<()> {
90 let data = serde_json::to_vec(frame).map_err(io::Error::other)?;
91 send(&mut self.relay, Message::input(self.session, data)).await
92 }
93
94 async fn take(&mut self) -> io::Result<FromMachine> {
96 tokio::time::timeout(ANSWER_TIMEOUT, self.next_frame())
97 .await
98 .map_err(|_elapsed| {
99 io::Error::new(io::ErrorKind::TimedOut, "the machine did not answer")
100 })?
101 }
102
103 async fn next_frame(&mut self) -> io::Result<FromMachine> {
105 loop {
106 let msg = recv(&mut self.relay)
107 .await?
108 .ok_or_else(|| io::Error::other("the relay closed the command channel"))?;
109 if let (MessageType::Output, Some(MessagePayload::OutputData { data })) =
110 (&msg.msg_type, &msg.payload)
111 {
112 if data.len() > MAX_FRAME {
113 return Err(io::Error::other("a command frame too large"));
114 }
115 return serde_json::from_slice(data).map_err(io::Error::other);
116 }
117 if msg.msg_type == MessageType::SessionError {
118 return Err(io::Error::other(format!(
119 "the relay ended the command channel: {}",
120 reason(&msg.payload)
121 )));
122 }
123 }
124 }
125
126 pub async fn challenge(&mut self) -> io::Result<Challenge> {
132 self.put(&ToMachine::Hello).await?;
133 match self.take().await? {
134 FromMachine::Challenge {
135 nonce,
136 key,
137 signature,
138 } => check_challenge(&self.machine, &self.machine_key, nonce, key, &signature)
139 .ok_or_else(|| io::Error::other("the challenge is not signed by the machine")),
140 FromMachine::Refused { reason } => Err(io::Error::other(reason)),
141 FromMachine::Reply { .. } => Err(io::Error::other("a reply where a challenge was due")),
142 }
143 }
144
145 pub async fn send_sealed(
152 &mut self,
153 account: &AccountKeys,
154 nonce: &[u8],
155 sealed: Vec<u8>,
156 ) -> io::Result<Outcome> {
157 self.put(&ToMachine::Command { sealed }).await?;
158 match self.take().await? {
159 FromMachine::Reply { sealed, signature } => open_reply(
160 account,
161 &self.machine,
162 &self.machine_key,
163 nonce,
164 &sealed,
165 &signature,
166 ),
167 FromMachine::Refused { reason } => Err(io::Error::new(
168 io::ErrorKind::PermissionDenied,
169 format!("the machine refused the command: {reason}"),
170 )),
171 FromMachine::Challenge { .. } => {
172 Err(io::Error::other("a challenge where a reply was due"))
173 }
174 }
175 }
176
177 pub async fn run(&mut self, account: &AccountKeys, command: Command) -> io::Result<Outcome> {
183 let challenge = self.challenge().await?;
184 let sealed = seal_command(account, &self.machine, &challenge, command)?;
185 self.send_sealed(account, &challenge.nonce, sealed).await
186 }
187}
188
189fn reason(payload: &Option<MessagePayload>) -> &str {
191 match payload {
192 Some(MessagePayload::ErrorReason { reason }) => reason,
193 _ => "no reason given",
194 }
195}