use super::encode::Held;
use super::input::ClientMsg;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::State;
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::extract::Path;
use axum::routing::{get, post};
use futures_util::{SinkExt, StreamExt};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub const PROTOCOL: u32 = 1;
pub const MAX_INFLIGHT: u32 = 2;
pub const SLOW_LINK: std::time::Duration = std::time::Duration::from_millis(120);
pub const SLOW_JPEG: u8 = 40;
pub const MAX_UPLOAD: u64 = 256 << 20;
const MAX_ANNOUNCED: usize = 8;
const MAX_OFFERED: usize = 64;
const INDEX_HTML: &str = include_str!("client/index.html");
const STREAM_JS: &str = include_str!("client/stream.js");
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
Control,
View,
}
impl Role {
fn name(self) -> &'static str {
match self {
Role::Control => "control",
Role::View => "view",
}
}
}
pub struct Client {
pub role: Role,
wants_control: bool,
ctrl: tokio::sync::mpsc::UnboundedSender<String>,
slot: Arc<Mutex<Option<Vec<u8>>>>,
notify: Arc<tokio::sync::Notify>,
pub held: Held,
pub sent_seq: u32,
pub acked_seq: u32,
pub jpeg_quality: u8,
sent_at: std::collections::VecDeque<(u32, std::time::Instant)>,
pub frame_time: Option<std::time::Duration>,
}
impl Client {
pub fn slow(&self) -> bool {
self.frame_time.is_some_and(|t| t > SLOW_LINK)
}
pub fn can_take_frame(&self) -> bool {
let limit = if self.slow() { 1 } else { MAX_INFLIGHT };
self.sent_seq.wrapping_sub(self.acked_seq) < limit && self.slot.lock().unwrap().is_none()
}
pub fn quality(&self) -> u8 {
if self.slow() { self.jpeg_quality.min(SLOW_JPEG) } else { self.jpeg_quality }
}
fn acked(&mut self, seq: u32) {
self.acked_seq = seq;
let now = std::time::Instant::now();
while let Some(&(sent, at)) = self.sent_at.front() {
if (seq.wrapping_sub(sent) as i32) < 0 {
break;
}
self.sent_at.pop_front();
if sent == seq {
let took = now - at;
self.frame_time = Some(match self.frame_time {
Some(t) => (t * 7 + took * 3) / 10,
None => took,
});
}
}
}
pub fn send_frame(&mut self, message: Vec<u8>) {
self.sent_at.push_back((self.sent_seq, std::time::Instant::now()));
if self.sent_at.len() > 64 {
self.sent_at.pop_front();
}
*self.slot.lock().unwrap() = Some(message);
self.notify.notify_one();
}
pub fn send_json(&self, value: serde_json::Value) {
let _ = self.ctrl.send(value.to_string());
}
}
#[derive(Default)]
pub struct Inbox {
pub input: Vec<ClientMsg>,
pub resize: Option<(f32, f32, f32)>,
pub joined: bool,
pub acked: bool,
pub uploaded: Vec<std::path::PathBuf>,
}
struct Announced {
client: u64,
name: String,
size: u64,
}
struct Offered {
path: std::path::PathBuf,
name: String,
}
#[derive(Default)]
pub struct HubInner {
pub clients: HashMap<u64, Client>,
pub controller: Option<u64>,
next_id: u64,
pub inbox: Inbox,
pub stopping: bool,
announced: HashMap<String, Announced>,
offered: HashMap<String, Offered>,
offer_order: std::collections::VecDeque<String>,
uploads: u64,
}
pub struct Hub {
pub inner: Mutex<HubInner>,
token: String,
origins: Vec<String>,
wake: crate::desktop_loop::Waker,
pub session: String,
pub surface: Mutex<(u32, u32, f32)>,
upload_dir: Mutex<std::path::PathBuf>,
}
impl Hub {
pub fn new(token: String, origins: Vec<String>, wake: crate::desktop_loop::Waker) -> Arc<Hub> {
Arc::new(Hub {
inner: Mutex::default(),
token,
origins,
wake,
session: uuid::Uuid::new_v4().simple().to_string()[..12].to_string(),
surface: Mutex::new((0, 0, 1.0)),
upload_dir: Mutex::new(crate::help_local::data_dir().join("stream-uploads")),
})
}
pub fn set_upload_dir(&self, dir: std::path::PathBuf) {
*self.upload_dir.lock().unwrap() = dir;
}
pub fn to_all(&self, value: serde_json::Value) {
let text = value.to_string();
for c in self.lock().clients.values() {
let _ = c.ctrl.send(text.clone());
}
}
pub fn offer(&self, path: std::path::PathBuf) {
let Ok(meta) = std::fs::metadata(&path) else { return };
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "download".into());
let id = uuid::Uuid::new_v4().simple().to_string();
let mut inner = self.lock();
inner.offer_order.push_back(id.clone());
if inner.offer_order.len() > MAX_OFFERED {
if let Some(old) = inner.offer_order.pop_front() {
inner.offered.remove(&old);
}
}
inner.offered.insert(id.clone(), Offered { path, name: name.clone() });
let text = serde_json::json!({"t": "download", "id": id, "name": name, "size": meta.len()}).to_string();
for c in inner.clients.values() {
let _ = c.ctrl.send(text.clone());
}
}
fn announce(&self, inner: &mut HubInner, id: u64, name: &str, size: u64) {
let refuse = |inner: &HubInner, msg: String| {
if let Some(c) = inner.clients.get(&id) {
c.send_json(serde_json::json!({"t": "error", "code": "upload", "name": name, "msg": msg}));
}
};
if inner.controller != Some(id) {
return refuse(inner, "only the controlling page uploads".into());
}
let Some(clean) = sanitise_name(name) else {
return refuse(inner, format!("{name:?} is not a file name"));
};
if size > MAX_UPLOAD {
return refuse(inner, format!("{clean} is {size} bytes; the limit is {MAX_UPLOAD}"));
}
if inner.announced.values().filter(|a| a.client == id).count() >= MAX_ANNOUNCED {
return refuse(inner, "too many uploads waiting".into());
}
let upload = uuid::Uuid::new_v4().simple().to_string();
inner.announced.insert(upload.clone(), Announced { client: id, name: clean.clone(), size });
if let Some(c) = inner.clients.get(&id) {
c.send_json(serde_json::json!({"t": "upload", "id": upload, "name": clean, "size": size}));
}
}
pub fn stop(&self) {
self.lock().stopping = true;
(self.wake)();
}
pub fn lock(&self) -> std::sync::MutexGuard<'_, HubInner> {
self.inner.lock().unwrap_or_else(|p| p.into_inner())
}
pub fn to_controller(&self, value: serde_json::Value) {
let inner = self.lock();
if let Some(c) = inner.controller.and_then(|id| inner.clients.get(&id)) {
c.send_json(value);
}
}
fn token_ok(&self, given: &str) -> bool {
let (a, b) = (self.token.as_bytes(), given.as_bytes());
let mut diff = a.len() ^ b.len();
for (i, x) in a.iter().enumerate() {
diff |= usize::from(x ^ b.get(i).copied().unwrap_or(0));
}
diff == 0
}
fn origin_ok(&self, headers: &HeaderMap) -> bool {
let Some(origin) = headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) else {
return true;
};
if self.origins.iter().any(|o| o == "*" || o == origin) {
return true;
}
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("");
origin.strip_prefix("http://").or_else(|| origin.strip_prefix("https://")) == Some(host)
}
fn join(&self, role: Role, w: Option<f32>, h: Option<f32>, dpr: Option<f32>) -> (u64, Role, ClientIo) {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let slot = Arc::new(Mutex::new(None));
let notify = Arc::new(tokio::sync::Notify::new());
let mut inner = self.lock();
inner.next_id += 1;
let id = inner.next_id;
let wants_control = role == Role::Control;
let role = if wants_control && inner.controller.is_none() { Role::Control } else { Role::View };
if role == Role::Control {
inner.controller = Some(id);
if let (Some(w), Some(h)) = (w, h) {
inner.inbox.resize = Some((w, h, dpr.unwrap_or(1.0)));
}
}
inner.clients.insert(
id,
Client {
role,
wants_control,
ctrl: tx,
slot: slot.clone(),
notify: notify.clone(),
held: Held::default(),
sent_seq: 0,
acked_seq: 0,
jpeg_quality: 70,
sent_at: Default::default(),
frame_time: None,
},
);
inner.inbox.joined = true;
drop(inner);
(self.wake)();
(id, role, ClientIo { rx, slot, notify })
}
fn leave(&self, id: u64) {
let mut inner = self.lock();
inner.clients.remove(&id);
inner.announced.retain(|_, a| a.client != id);
if inner.controller == Some(id) {
inner.controller = None;
let next = inner.clients.iter().filter(|(_, c)| c.wants_control).map(|(id, _)| *id).min();
if let Some(next) = next {
inner.controller = Some(next);
if let Some(c) = inner.clients.get_mut(&next) {
c.role = Role::Control;
c.send_json(serde_json::json!({"t": "role", "role": "control"}));
}
}
}
}
fn receive(&self, id: u64, msg: ClientMsg) {
let mut inner = self.lock();
let controller = inner.controller == Some(id);
match msg {
ClientMsg::Hello { .. } => {}
ClientMsg::Ack { seq } => {
if let Some(c) = inner.clients.get_mut(&id) {
c.acked(seq);
}
inner.inbox.acked = true;
}
ClientMsg::Quality { jpeg } => {
if let (Some(c), Some(q)) = (inner.clients.get_mut(&id), jpeg) {
c.jpeg_quality = q.clamp(10, 95);
}
}
ClientMsg::TakeControl => {
if let Some(old) = inner.controller.filter(|old| *old != id) {
if let Some(c) = inner.clients.get_mut(&old) {
c.role = Role::View;
c.send_json(serde_json::json!({"t": "role", "role": "view"}));
}
}
inner.controller = Some(id);
if let Some(c) = inner.clients.get_mut(&id) {
c.role = Role::Control;
c.send_json(serde_json::json!({"t": "role", "role": "control"}));
}
}
ClientMsg::Drop { name, size } => {
self.announce(&mut inner, id, &name, size);
return;
}
ClientMsg::Resize { w, h, dpr } if controller => inner.inbox.resize = Some((w, h, dpr)),
other if controller => inner.inbox.input.push(other),
_ => return,
}
drop(inner);
(self.wake)();
}
}
struct ClientIo {
rx: tokio::sync::mpsc::UnboundedReceiver<String>,
slot: Arc<Mutex<Option<Vec<u8>>>>,
notify: Arc<tokio::sync::Notify>,
}
pub fn start(listener: std::net::TcpListener, hub: Arc<Hub>) -> Result<std::thread::JoinHandle<()>, String> {
listener.set_nonblocking(true).map_err(|e| format!("listener: {e}"))?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("brep-stream")
.enable_all()
.build()
.map_err(|e| format!("runtime: {e}"))?;
let app = axum::Router::new()
.route("/", get(|| async { axum::response::Redirect::temporary("/stream/") }))
.route("/stream", get(|| async { axum::response::Redirect::temporary("/stream/") }))
.route("/stream/", get(index))
.route("/stream/stream.js", get(script))
.route("/stream/ws", get(upgrade))
.route("/stream/uploads/:id", post(upload))
.route("/stream/downloads/:id", get(download))
.with_state(hub);
std::thread::Builder::new()
.name("brep-stream-server".into())
.spawn(move || {
runtime.block_on(async move {
let listener = match tokio::net::TcpListener::from_std(listener) {
Ok(l) => l,
Err(e) => return eprintln!("brep-app --stream: {e}"),
};
if let Err(e) = axum::serve(listener, app).await {
eprintln!("brep-app --stream: server stopped: {e}");
}
})
})
.map_err(|e| format!("server thread: {e}"))
}
fn no_store(content_type: &'static str, body: &'static str) -> Response {
([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, "no-store")], body).into_response()
}
async fn index() -> Response {
no_store("text/html; charset=utf-8", INDEX_HTML)
}
async fn script() -> Response {
no_store("text/javascript; charset=utf-8", STREAM_JS)
}
async fn upgrade(State(hub): State<Arc<Hub>>, headers: HeaderMap, ws: WebSocketUpgrade) -> Response {
if !hub.origin_ok(&headers) {
return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
}
ws.max_message_size(64 << 20).on_upgrade(move |socket| serve(hub, socket))
}
pub fn sanitise_name(name: &str) -> Option<String> {
let base = name.rsplit(['/', '\\']).next().unwrap_or("");
let clean: String = base
.chars()
.map(|c| if c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c })
.collect();
let clean = clean.trim().trim_start_matches('.').trim().to_string();
if clean.is_empty() || clean.chars().all(|c| c == '_' || c == '.') {
return None;
}
if clean.len() <= 120 {
return Some(clean);
}
let (stem, ext) = match clean.rsplit_once('.') {
Some((stem, ext)) if ext.len() <= 16 => (stem, format!(".{ext}")),
_ => (clean.as_str(), String::new()),
};
let mut cut = 120 - ext.len();
while !stem.is_char_boundary(cut) {
cut -= 1;
}
Some(format!("{}{ext}", &stem[..cut]))
}
async fn bearer_ok(hub: &Hub, headers: &HeaderMap) -> bool {
let given = headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or("");
if hub.token_ok(given) {
return true;
}
tokio::time::sleep(Duration::from_millis(500)).await;
false
}
async fn upload(State(hub): State<Arc<Hub>>, Path(id): Path<String>, headers: HeaderMap, body: axum::body::Body) -> Response {
if !hub.origin_ok(&headers) {
return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
}
if !bearer_ok(&hub, &headers).await {
return (StatusCode::UNAUTHORIZED, "wrong token").into_response();
}
let announced = {
let mut inner = hub.lock();
let Some(announced) = inner.announced.remove(&id) else {
return (StatusCode::NOT_FOUND, "no such upload").into_response();
};
if inner.controller != Some(announced.client) {
return (StatusCode::CONFLICT, "the page that announced this upload no longer controls the session").into_response();
}
announced
};
let declared = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
if declared != Some(announced.size) {
return (StatusCode::BAD_REQUEST, format!("announced {} bytes; the request declares {declared:?}", announced.size)).into_response();
}
let body = match axum::body::to_bytes(body, announced.size as usize).await {
Ok(body) if body.len() as u64 == announced.size => body,
Ok(body) => return (StatusCode::BAD_REQUEST, format!("announced {} bytes, sent {}", announced.size, body.len())).into_response(),
Err(e) => return (StatusCode::BAD_REQUEST, format!("the upload did not arrive whole: {e}")).into_response(),
};
let n = {
let mut inner = hub.lock();
inner.uploads += 1;
inner.uploads
};
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let dir = hub.upload_dir.lock().unwrap().join(format!("{stamp}-{n}"));
let path = dir.join(&announced.name);
let part = dir.join(".upload.part");
let target = path.clone();
let written = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
std::fs::create_dir_all(&dir)?;
std::fs::write(&part, &body)?;
std::fs::rename(&part, &target).inspect_err(|_| {
let _ = std::fs::remove_file(&part);
})
})
.await;
match written {
Ok(Ok(())) => {}
Ok(Err(e)) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("could not write the upload: {e}")).into_response(),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("upload task: {e}")).into_response(),
}
let shown = path.display().to_string();
{
let mut inner = hub.lock();
inner.inbox.uploaded.push(path);
if let Some(c) = inner.clients.get(&announced.client) {
c.send_json(serde_json::json!({"t": "uploaded", "id": id, "name": announced.name, "path": shown}));
}
}
(hub.wake)();
([(header::CONTENT_TYPE, "application/json")], serde_json::json!({"path": shown}).to_string()).into_response()
}
async fn download(State(hub): State<Arc<Hub>>, Path(id): Path<String>, headers: HeaderMap) -> Response {
if !hub.origin_ok(&headers) {
return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
}
if !bearer_ok(&hub, &headers).await {
return (StatusCode::UNAUTHORIZED, "wrong token").into_response();
}
let Some((path, name)) = hub.lock().offered.get(&id).map(|o| (o.path.clone(), o.name.clone())) else {
return (StatusCode::NOT_FOUND, "no such download").into_response();
};
let bytes = match tokio::task::spawn_blocking(move || std::fs::read(path)).await {
Ok(Ok(bytes)) => bytes,
Ok(Err(e)) => return (StatusCode::GONE, format!("the export is gone: {e}")).into_response(),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("download task: {e}")).into_response(),
};
let ascii: String = name.chars().map(|c| if c == ' ' || (c.is_ascii_graphic() && c != '"' && c != '\\') { c } else { '_' }).collect();
(
[
(header::CONTENT_TYPE, "application/octet-stream".to_string()),
(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{ascii}\"")),
(header::CACHE_CONTROL, "no-store".to_string()),
],
bytes,
)
.into_response()
}
fn json(value: serde_json::Value) -> Message {
Message::Text(value.to_string())
}
async fn serve(hub: Arc<Hub>, mut socket: WebSocket) {
let hello = tokio::time::timeout(Duration::from_secs(10), socket.recv()).await;
let Ok(Some(Ok(Message::Text(text)))) = hello else { return };
let Ok(ClientMsg::Hello { v, token, role, w, h, dpr }) = serde_json::from_str::<ClientMsg>(&text) else {
let _ = socket.send(json(serde_json::json!({"t": "error", "code": "protocol", "msg": "the first message must be hello"}))).await;
return;
};
if !hub.token_ok(&token) {
tokio::time::sleep(Duration::from_millis(500)).await;
let _ = socket.send(json(serde_json::json!({"t": "error", "code": "auth", "msg": "wrong token"}))).await;
return;
}
if v != PROTOCOL {
let _ = socket.send(json(serde_json::json!({"t": "error", "code": "version", "msg": format!("this server speaks version {PROTOCOL}")}))).await;
return;
}
let asked = if role.as_deref() == Some("view") { Role::View } else { Role::Control };
let (id, role, mut io) = hub.join(asked, w, h, dpr);
let (sw, sh, ppp) = *hub.surface.lock().unwrap();
let welcome = serde_json::json!({
"t": "welcome", "v": PROTOCOL, "session": hub.session, "role": role.name(),
"caps": ["png", "jpeg"], "w": sw, "h": sh, "ppp": ppp,
});
let (mut tx, mut rx) = socket.split();
if tx.send(json(welcome)).await.is_err() {
return hub.leave(id);
}
let reader_hub = hub.clone();
let mut reader = tokio::spawn(async move {
while let Some(Ok(message)) = rx.next().await {
match message {
Message::Text(text) => match serde_json::from_str::<ClientMsg>(&text) {
Ok(msg) => reader_hub.receive(id, msg),
Err(e) => log::debug!("stream: bad message: {e}"),
},
Message::Close(_) => break,
_ => {}
}
}
});
loop {
tokio::select! {
biased;
text = io.rx.recv() => match text {
Some(text) => if tx.send(Message::Text(text)).await.is_err() { break },
None => break,
},
_ = io.notify.notified() => {
let frame = io.slot.lock().unwrap().take();
if let Some(frame) = frame {
if tx.send(Message::Binary(frame)).await.is_err() { break }
}
}
_ = &mut reader => break,
}
}
reader.abort();
hub.leave(id);
}