1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use async_std::{io, task};
use async_std::prelude::*;
use async_trait::async_trait;
use async_std::net::{TcpListener, TcpStream};
use log::{debug, error, info, trace};
use crate::protocol::{FtlCommand, FtlError, FtlHandshake, FtlHandshakeFinalised, FtlResponse};
use crate::util;
pub struct IngestClient {
channel_id: Option<String>,
hmac_payload: String,
handshake: FtlHandshake,
should_stop: Arc<AtomicBool>
}
#[async_trait]
pub trait IngestServer {
async fn launch(&'static self, addr: String) -> Result<(), io::Error> {
let listener = TcpListener::bind(addr).await?;
while let Ok((stream, address)) = listener.accept().await {
info!("Remote client connected: {}", address);
task::spawn(async move {
let (reader, writer) = &mut (&stream, &stream);
let mut client = IngestClient {
channel_id: None,
hmac_payload: util::generate_hmac(),
handshake: FtlHandshake::default(),
should_stop: Arc::new(AtomicBool::new(false)),
};
let mut reader = reader.bytes();
let mut buffer = Vec::with_capacity(128);
while let Some(byte) = reader.next().await {
if let Ok(byte) = byte {
match byte {
b'\n' => {
if buffer.len() > 0 {
if let Ok(payload) = std::str::from_utf8(&buffer) {
if let Ok(command) = FtlCommand::from_str(payload) {
if let Err(error) = self.handler(&mut client, writer, command).await {
if error.is_err() {
error!("Failed to execute FTL command. {:?}", error);
}
writer.write(
error
.to_string()
.as_bytes()
)
.await
.ok();
break;
}
} else {
error!("Failed to deserialise FTL command. {}", payload);
}
} else {
error!("Failed to convert buffer to UTF8 string.");
}
buffer.clear();
}
}
b'\r' => continue,
byte => buffer.push(byte)
}
} else {
error!("Failed to read anymore bytes from client.");
break;
}
}
info!("Remote FTL client disconnected.");
client.should_stop.store(true, Ordering::Relaxed);
stream.shutdown(std::net::Shutdown::Both).ok();
});
}
Ok(())
}
async fn handler(&self, client: &mut IngestClient, mut writer: &TcpStream, command: FtlCommand) -> Result<(), FtlError> {
match command {
FtlCommand::HMAC => {
debug!("Client requested HMAC payload, sending response.");
writer.write(
FtlResponse::HMAC {
hmac_payload: client.hmac_payload.clone()
}
.to_string()
.as_bytes()
)
.await
.map_err(|_| FtlError::IoError)?;
Ok(())
}
FtlCommand::Connect { channel_id, hashed_hmac_payload } => {
debug!("Client is connecting, attempting to stream to {}.", &channel_id);
let known_key = self.get_stream_key(&channel_id)
.await.map_err(|_| FtlError::InvalidStreamKey)?;
let client_hash = hex::decode(hashed_hmac_payload[1..].to_string())
.map_err(|_| FtlError::DecodeError)?;
let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA512, &known_key.as_bytes());
ring::hmac::verify(
&key,
&hex::decode(client.hmac_payload.clone().into_bytes())
.map_err(|_| FtlError::DecodeError)?,
&client_hash.as_slice()
).map_err(|_| FtlError::RingError)?;
debug!("Client was verified, ready to stream to {}.", &channel_id);
client.channel_id = Some(channel_id);
writer.write(
FtlResponse::Success
.to_string()
.as_bytes()
)
.await
.map_err(|_| FtlError::IoError)?;
Ok(())
}
FtlCommand::Attribute { key, value } => client.handshake.insert(key, value),
FtlCommand::Dot => {
if let Some(channel_id) = &client.channel_id {
let handshake = client.handshake.clone().finalise()?;
let udp_port = self.allocate_ingest(channel_id, handshake, client.should_stop.clone())
.await.map_err(|_| FtlError::AllocateError)?;
debug!("Client is about to begin stream. Allocated port {}.", udp_port);
writer.write(
FtlResponse::Connect { udp_port }
.to_string()
.as_bytes()
)
.await
.map_err(|_| FtlError::IoError)?;
Ok(())
} else {
Err(FtlError::InvalidStreamKey)
}
}
FtlCommand::Ping { channel_id } => {
trace!("Client sent ping. {}", &channel_id);
writer.write(
FtlResponse::Pong
.to_string()
.as_bytes()
)
.await
.map_err(|_| FtlError::IoError)?;
Ok(())
}
FtlCommand::Disconnect => Err(FtlError::Disconnect)
}
}
async fn get_stream_key(&self, channel_id: &str) -> Result<String, ()>;
async fn allocate_ingest(&self, channel_id: &str, handshake: FtlHandshakeFinalised, should_stop: Arc<AtomicBool>) -> Result<u16, ()>;
}