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