1use super::encode::Held;
5use super::input::ClientMsg;
6use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
7use axum::extract::State;
8use axum::http::{header, HeaderMap, StatusCode};
9use axum::response::{IntoResponse, Response};
10use axum::extract::Path;
11use axum::routing::{get, post};
12use futures_util::{SinkExt, StreamExt};
13use std::collections::HashMap;
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16
17pub const PROTOCOL: u32 = 1;
18pub const MAX_INFLIGHT: u32 = 2;
20pub const SLOW_LINK: std::time::Duration = std::time::Duration::from_millis(120);
24pub const SLOW_JPEG: u8 = 40;
25pub const MAX_UPLOAD: u64 = 256 << 20;
27const MAX_ANNOUNCED: usize = 8;
29const MAX_OFFERED: usize = 64;
31const INDEX_HTML: &str = include_str!("client/index.html");
32const STREAM_JS: &str = include_str!("client/stream.js");
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Role {
36 Control,
37 View,
38}
39
40impl Role {
41 fn name(self) -> &'static str {
42 match self {
43 Role::Control => "control",
44 Role::View => "view",
45 }
46 }
47}
48
49pub struct Client {
51 pub role: Role,
52 wants_control: bool,
56 ctrl: tokio::sync::mpsc::UnboundedSender<String>,
57 slot: Arc<Mutex<Option<Vec<u8>>>>,
59 notify: Arc<tokio::sync::Notify>,
60 pub held: Held,
61 pub sent_seq: u32,
62 pub acked_seq: u32,
63 pub jpeg_quality: u8,
64 sent_at: std::collections::VecDeque<(u32, std::time::Instant)>,
66 pub frame_time: Option<std::time::Duration>,
68}
69
70impl Client {
71 pub fn slow(&self) -> bool {
73 self.frame_time.is_some_and(|t| t > SLOW_LINK)
74 }
75
76 pub fn can_take_frame(&self) -> bool {
77 let limit = if self.slow() { 1 } else { MAX_INFLIGHT };
78 self.sent_seq.wrapping_sub(self.acked_seq) < limit && self.slot.lock().unwrap().is_none()
79 }
80
81 pub fn quality(&self) -> u8 {
83 if self.slow() { self.jpeg_quality.min(SLOW_JPEG) } else { self.jpeg_quality }
84 }
85
86 fn acked(&mut self, seq: u32) {
87 self.acked_seq = seq;
88 let now = std::time::Instant::now();
89 while let Some(&(sent, at)) = self.sent_at.front() {
90 if (seq.wrapping_sub(sent) as i32) < 0 {
92 break;
93 }
94 self.sent_at.pop_front();
95 if sent == seq {
96 let took = now - at;
97 self.frame_time = Some(match self.frame_time {
98 Some(t) => (t * 7 + took * 3) / 10,
99 None => took,
100 });
101 }
102 }
103 }
104
105 pub fn send_frame(&mut self, message: Vec<u8>) {
106 self.sent_at.push_back((self.sent_seq, std::time::Instant::now()));
107 if self.sent_at.len() > 64 {
108 self.sent_at.pop_front();
109 }
110 *self.slot.lock().unwrap() = Some(message);
111 self.notify.notify_one();
112 }
113
114 pub fn send_json(&self, value: serde_json::Value) {
115 let _ = self.ctrl.send(value.to_string());
116 }
117}
118
119#[derive(Default)]
121pub struct Inbox {
122 pub input: Vec<ClientMsg>,
124 pub resize: Option<(f32, f32, f32)>,
126 pub joined: bool,
128 pub acked: bool,
130 pub uploaded: Vec<std::path::PathBuf>,
132}
133
134struct Announced {
136 client: u64,
137 name: String,
138 size: u64,
139}
140
141struct Offered {
143 path: std::path::PathBuf,
144 name: String,
145}
146
147#[derive(Default)]
148pub struct HubInner {
149 pub clients: HashMap<u64, Client>,
150 pub controller: Option<u64>,
151 next_id: u64,
152 pub inbox: Inbox,
153 pub stopping: bool,
154 announced: HashMap<String, Announced>,
155 offered: HashMap<String, Offered>,
156 offer_order: std::collections::VecDeque<String>,
158 uploads: u64,
159}
160
161pub struct Hub {
163 pub inner: Mutex<HubInner>,
164 token: String,
165 origins: Vec<String>,
166 wake: crate::desktop_loop::Waker,
167 pub session: String,
168 pub surface: Mutex<(u32, u32, f32)>,
170 upload_dir: Mutex<std::path::PathBuf>,
172}
173
174impl Hub {
175 pub fn new(token: String, origins: Vec<String>, wake: crate::desktop_loop::Waker) -> Arc<Hub> {
176 Arc::new(Hub {
177 inner: Mutex::default(),
178 token,
179 origins,
180 wake,
181 session: uuid::Uuid::new_v4().simple().to_string()[..12].to_string(),
182 surface: Mutex::new((0, 0, 1.0)),
183 upload_dir: Mutex::new(crate::help_local::data_dir().join("stream-uploads")),
184 })
185 }
186
187 pub fn set_upload_dir(&self, dir: std::path::PathBuf) {
189 *self.upload_dir.lock().unwrap() = dir;
190 }
191
192 pub fn to_all(&self, value: serde_json::Value) {
194 let text = value.to_string();
195 for c in self.lock().clients.values() {
196 let _ = c.ctrl.send(text.clone());
197 }
198 }
199
200 pub fn offer(&self, path: std::path::PathBuf) {
202 let Ok(meta) = std::fs::metadata(&path) else { return };
203 let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "download".into());
204 let id = uuid::Uuid::new_v4().simple().to_string();
205 let mut inner = self.lock();
206 inner.offer_order.push_back(id.clone());
207 if inner.offer_order.len() > MAX_OFFERED {
208 if let Some(old) = inner.offer_order.pop_front() {
209 inner.offered.remove(&old);
210 }
211 }
212 inner.offered.insert(id.clone(), Offered { path, name: name.clone() });
213 let text = serde_json::json!({"t": "download", "id": id, "name": name, "size": meta.len()}).to_string();
214 for c in inner.clients.values() {
215 let _ = c.ctrl.send(text.clone());
216 }
217 }
218
219 fn announce(&self, inner: &mut HubInner, id: u64, name: &str, size: u64) {
223 let refuse = |inner: &HubInner, msg: String| {
224 if let Some(c) = inner.clients.get(&id) {
225 c.send_json(serde_json::json!({"t": "error", "code": "upload", "name": name, "msg": msg}));
226 }
227 };
228 if inner.controller != Some(id) {
229 return refuse(inner, "only the controlling page uploads".into());
230 }
231 let Some(clean) = sanitise_name(name) else {
232 return refuse(inner, format!("{name:?} is not a file name"));
233 };
234 if size > MAX_UPLOAD {
235 return refuse(inner, format!("{clean} is {size} bytes; the limit is {MAX_UPLOAD}"));
236 }
237 if inner.announced.values().filter(|a| a.client == id).count() >= MAX_ANNOUNCED {
238 return refuse(inner, "too many uploads waiting".into());
239 }
240 let upload = uuid::Uuid::new_v4().simple().to_string();
241 inner.announced.insert(upload.clone(), Announced { client: id, name: clean.clone(), size });
242 if let Some(c) = inner.clients.get(&id) {
243 c.send_json(serde_json::json!({"t": "upload", "id": upload, "name": clean, "size": size}));
244 }
245 }
246
247 pub fn stop(&self) {
249 self.lock().stopping = true;
250 (self.wake)();
251 }
252
253 pub fn lock(&self) -> std::sync::MutexGuard<'_, HubInner> {
254 self.inner.lock().unwrap_or_else(|p| p.into_inner())
255 }
256
257 pub fn to_controller(&self, value: serde_json::Value) {
259 let inner = self.lock();
260 if let Some(c) = inner.controller.and_then(|id| inner.clients.get(&id)) {
261 c.send_json(value);
262 }
263 }
264
265 fn token_ok(&self, given: &str) -> bool {
266 let (a, b) = (self.token.as_bytes(), given.as_bytes());
268 let mut diff = a.len() ^ b.len();
269 for (i, x) in a.iter().enumerate() {
270 diff |= usize::from(x ^ b.get(i).copied().unwrap_or(0));
271 }
272 diff == 0
273 }
274
275 fn origin_ok(&self, headers: &HeaderMap) -> bool {
276 let Some(origin) = headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) else {
277 return true;
279 };
280 if self.origins.iter().any(|o| o == "*" || o == origin) {
281 return true;
282 }
283 let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("");
285 origin.strip_prefix("http://").or_else(|| origin.strip_prefix("https://")) == Some(host)
286 }
287
288 fn join(&self, role: Role, w: Option<f32>, h: Option<f32>, dpr: Option<f32>) -> (u64, Role, ClientIo) {
289 let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
290 let slot = Arc::new(Mutex::new(None));
291 let notify = Arc::new(tokio::sync::Notify::new());
292 let mut inner = self.lock();
293 inner.next_id += 1;
294 let id = inner.next_id;
295 let wants_control = role == Role::Control;
296 let role = if wants_control && inner.controller.is_none() { Role::Control } else { Role::View };
297 if role == Role::Control {
298 inner.controller = Some(id);
299 if let (Some(w), Some(h)) = (w, h) {
300 inner.inbox.resize = Some((w, h, dpr.unwrap_or(1.0)));
301 }
302 }
303 inner.clients.insert(
304 id,
305 Client {
306 role,
307 wants_control,
308 ctrl: tx,
309 slot: slot.clone(),
310 notify: notify.clone(),
311 held: Held::default(),
312 sent_seq: 0,
313 acked_seq: 0,
314 jpeg_quality: 70,
315 sent_at: Default::default(),
316 frame_time: None,
317 },
318 );
319 inner.inbox.joined = true;
320 drop(inner);
321 (self.wake)();
322 (id, role, ClientIo { rx, slot, notify })
323 }
324
325 fn leave(&self, id: u64) {
326 let mut inner = self.lock();
327 inner.clients.remove(&id);
328 inner.announced.retain(|_, a| a.client != id);
329 if inner.controller == Some(id) {
330 inner.controller = None;
331 let next = inner.clients.iter().filter(|(_, c)| c.wants_control).map(|(id, _)| *id).min();
333 if let Some(next) = next {
334 inner.controller = Some(next);
335 if let Some(c) = inner.clients.get_mut(&next) {
336 c.role = Role::Control;
337 c.send_json(serde_json::json!({"t": "role", "role": "control"}));
338 }
339 }
341 }
342 }
343
344 fn receive(&self, id: u64, msg: ClientMsg) {
346 let mut inner = self.lock();
347 let controller = inner.controller == Some(id);
348 match msg {
349 ClientMsg::Hello { .. } => {}
350 ClientMsg::Ack { seq } => {
351 if let Some(c) = inner.clients.get_mut(&id) {
352 c.acked(seq);
353 }
354 inner.inbox.acked = true;
355 }
356 ClientMsg::Quality { jpeg } => {
357 if let (Some(c), Some(q)) = (inner.clients.get_mut(&id), jpeg) {
358 c.jpeg_quality = q.clamp(10, 95);
359 }
360 }
361 ClientMsg::TakeControl => {
362 if let Some(old) = inner.controller.filter(|old| *old != id) {
363 if let Some(c) = inner.clients.get_mut(&old) {
364 c.role = Role::View;
365 c.send_json(serde_json::json!({"t": "role", "role": "view"}));
366 }
367 }
368 inner.controller = Some(id);
369 if let Some(c) = inner.clients.get_mut(&id) {
370 c.role = Role::Control;
371 c.send_json(serde_json::json!({"t": "role", "role": "control"}));
372 }
373 }
374 ClientMsg::Drop { name, size } => {
375 self.announce(&mut inner, id, &name, size);
376 return;
377 }
378 ClientMsg::Resize { w, h, dpr } if controller => inner.inbox.resize = Some((w, h, dpr)),
379 other if controller => inner.inbox.input.push(other),
380 _ => return,
381 }
382 drop(inner);
383 (self.wake)();
384 }
385}
386
387struct ClientIo {
388 rx: tokio::sync::mpsc::UnboundedReceiver<String>,
389 slot: Arc<Mutex<Option<Vec<u8>>>>,
390 notify: Arc<tokio::sync::Notify>,
391}
392
393pub fn start(listener: std::net::TcpListener, hub: Arc<Hub>) -> Result<std::thread::JoinHandle<()>, String> {
395 listener.set_nonblocking(true).map_err(|e| format!("listener: {e}"))?;
396 let runtime = tokio::runtime::Builder::new_multi_thread()
397 .worker_threads(2)
398 .thread_name("brep-stream")
399 .enable_all()
400 .build()
401 .map_err(|e| format!("runtime: {e}"))?;
402 let app = axum::Router::new()
403 .route("/", get(|| async { axum::response::Redirect::temporary("/stream/") }))
404 .route("/stream", get(|| async { axum::response::Redirect::temporary("/stream/") }))
405 .route("/stream/", get(index))
406 .route("/stream/stream.js", get(script))
407 .route("/stream/ws", get(upgrade))
408 .route("/stream/uploads/:id", post(upload))
409 .route("/stream/downloads/:id", get(download))
410 .with_state(hub);
411 std::thread::Builder::new()
412 .name("brep-stream-server".into())
413 .spawn(move || {
414 runtime.block_on(async move {
415 let listener = match tokio::net::TcpListener::from_std(listener) {
416 Ok(l) => l,
417 Err(e) => return eprintln!("brep-app --stream: {e}"),
418 };
419 if let Err(e) = axum::serve(listener, app).await {
420 eprintln!("brep-app --stream: server stopped: {e}");
421 }
422 })
423 })
424 .map_err(|e| format!("server thread: {e}"))
425}
426
427fn no_store(content_type: &'static str, body: &'static str) -> Response {
428 ([(header::CONTENT_TYPE, content_type), (header::CACHE_CONTROL, "no-store")], body).into_response()
429}
430
431async fn index() -> Response {
432 no_store("text/html; charset=utf-8", INDEX_HTML)
433}
434
435async fn script() -> Response {
436 no_store("text/javascript; charset=utf-8", STREAM_JS)
437}
438
439async fn upgrade(State(hub): State<Arc<Hub>>, headers: HeaderMap, ws: WebSocketUpgrade) -> Response {
440 if !hub.origin_ok(&headers) {
441 return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
442 }
443 ws.max_message_size(64 << 20).on_upgrade(move |socket| serve(hub, socket))
444}
445
446pub fn sanitise_name(name: &str) -> Option<String> {
450 let base = name.rsplit(['/', '\\']).next().unwrap_or("");
451 let clean: String = base
452 .chars()
453 .map(|c| if c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c })
454 .collect();
455 let clean = clean.trim().trim_start_matches('.').trim().to_string();
456 if clean.is_empty() || clean.chars().all(|c| c == '_' || c == '.') {
457 return None;
458 }
459 if clean.len() <= 120 {
460 return Some(clean);
461 }
462 let (stem, ext) = match clean.rsplit_once('.') {
463 Some((stem, ext)) if ext.len() <= 16 => (stem, format!(".{ext}")),
464 _ => (clean.as_str(), String::new()),
465 };
466 let mut cut = 120 - ext.len();
467 while !stem.is_char_boundary(cut) {
468 cut -= 1;
469 }
470 Some(format!("{}{ext}", &stem[..cut]))
471}
472
473async fn bearer_ok(hub: &Hub, headers: &HeaderMap) -> bool {
476 let given = headers.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok()).and_then(|v| v.strip_prefix("Bearer ")).unwrap_or("");
477 if hub.token_ok(given) {
478 return true;
479 }
480 tokio::time::sleep(Duration::from_millis(500)).await;
481 false
482}
483
484async fn upload(State(hub): State<Arc<Hub>>, Path(id): Path<String>, headers: HeaderMap, body: axum::body::Body) -> Response {
491 if !hub.origin_ok(&headers) {
492 return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
493 }
494 if !bearer_ok(&hub, &headers).await {
495 return (StatusCode::UNAUTHORIZED, "wrong token").into_response();
496 }
497 let announced = {
498 let mut inner = hub.lock();
499 let Some(announced) = inner.announced.remove(&id) else {
500 return (StatusCode::NOT_FOUND, "no such upload").into_response();
501 };
502 if inner.controller != Some(announced.client) {
503 return (StatusCode::CONFLICT, "the page that announced this upload no longer controls the session").into_response();
504 }
505 announced
506 };
507 let declared = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
508 if declared != Some(announced.size) {
509 return (StatusCode::BAD_REQUEST, format!("announced {} bytes; the request declares {declared:?}", announced.size)).into_response();
510 }
511 let body = match axum::body::to_bytes(body, announced.size as usize).await {
512 Ok(body) if body.len() as u64 == announced.size => body,
513 Ok(body) => return (StatusCode::BAD_REQUEST, format!("announced {} bytes, sent {}", announced.size, body.len())).into_response(),
514 Err(e) => return (StatusCode::BAD_REQUEST, format!("the upload did not arrive whole: {e}")).into_response(),
515 };
516 let n = {
517 let mut inner = hub.lock();
518 inner.uploads += 1;
519 inner.uploads
520 };
521 let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
522 let dir = hub.upload_dir.lock().unwrap().join(format!("{stamp}-{n}"));
525 let path = dir.join(&announced.name);
526 let part = dir.join(".upload.part");
527 let target = path.clone();
528 let written = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
529 std::fs::create_dir_all(&dir)?;
530 std::fs::write(&part, &body)?;
531 std::fs::rename(&part, &target).inspect_err(|_| {
532 let _ = std::fs::remove_file(&part);
533 })
534 })
535 .await;
536 match written {
537 Ok(Ok(())) => {}
538 Ok(Err(e)) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("could not write the upload: {e}")).into_response(),
539 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("upload task: {e}")).into_response(),
540 }
541 let shown = path.display().to_string();
542 {
543 let mut inner = hub.lock();
544 inner.inbox.uploaded.push(path);
545 if let Some(c) = inner.clients.get(&announced.client) {
546 c.send_json(serde_json::json!({"t": "uploaded", "id": id, "name": announced.name, "path": shown}));
547 }
548 }
549 (hub.wake)();
550 ([(header::CONTENT_TYPE, "application/json")], serde_json::json!({"path": shown}).to_string()).into_response()
551}
552
553async fn download(State(hub): State<Arc<Hub>>, Path(id): Path<String>, headers: HeaderMap) -> Response {
556 if !hub.origin_ok(&headers) {
557 return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
558 }
559 if !bearer_ok(&hub, &headers).await {
560 return (StatusCode::UNAUTHORIZED, "wrong token").into_response();
561 }
562 let Some((path, name)) = hub.lock().offered.get(&id).map(|o| (o.path.clone(), o.name.clone())) else {
563 return (StatusCode::NOT_FOUND, "no such download").into_response();
564 };
565 let bytes = match tokio::task::spawn_blocking(move || std::fs::read(path)).await {
566 Ok(Ok(bytes)) => bytes,
567 Ok(Err(e)) => return (StatusCode::GONE, format!("the export is gone: {e}")).into_response(),
568 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, format!("download task: {e}")).into_response(),
569 };
570 let ascii: String = name.chars().map(|c| if c == ' ' || (c.is_ascii_graphic() && c != '"' && c != '\\') { c } else { '_' }).collect();
571 (
572 [
573 (header::CONTENT_TYPE, "application/octet-stream".to_string()),
574 (header::CONTENT_DISPOSITION, format!("attachment; filename=\"{ascii}\"")),
575 (header::CACHE_CONTROL, "no-store".to_string()),
576 ],
577 bytes,
578 )
579 .into_response()
580}
581
582fn json(value: serde_json::Value) -> Message {
583 Message::Text(value.to_string())
584}
585
586async fn serve(hub: Arc<Hub>, mut socket: WebSocket) {
587 let hello = tokio::time::timeout(Duration::from_secs(10), socket.recv()).await;
589 let Ok(Some(Ok(Message::Text(text)))) = hello else { return };
590 let Ok(ClientMsg::Hello { v, token, role, w, h, dpr }) = serde_json::from_str::<ClientMsg>(&text) else {
591 let _ = socket.send(json(serde_json::json!({"t": "error", "code": "protocol", "msg": "the first message must be hello"}))).await;
592 return;
593 };
594 if !hub.token_ok(&token) {
595 tokio::time::sleep(Duration::from_millis(500)).await;
596 let _ = socket.send(json(serde_json::json!({"t": "error", "code": "auth", "msg": "wrong token"}))).await;
597 return;
598 }
599 if v != PROTOCOL {
600 let _ = socket.send(json(serde_json::json!({"t": "error", "code": "version", "msg": format!("this server speaks version {PROTOCOL}")}))).await;
601 return;
602 }
603 let asked = if role.as_deref() == Some("view") { Role::View } else { Role::Control };
604 let (id, role, mut io) = hub.join(asked, w, h, dpr);
605 let (sw, sh, ppp) = *hub.surface.lock().unwrap();
606 let welcome = serde_json::json!({
607 "t": "welcome", "v": PROTOCOL, "session": hub.session, "role": role.name(),
608 "caps": ["png", "jpeg"], "w": sw, "h": sh, "ppp": ppp,
609 });
610 let (mut tx, mut rx) = socket.split();
611 if tx.send(json(welcome)).await.is_err() {
612 return hub.leave(id);
613 }
614 let reader_hub = hub.clone();
616 let mut reader = tokio::spawn(async move {
617 while let Some(Ok(message)) = rx.next().await {
618 match message {
619 Message::Text(text) => match serde_json::from_str::<ClientMsg>(&text) {
620 Ok(msg) => reader_hub.receive(id, msg),
621 Err(e) => log::debug!("stream: bad message: {e}"),
622 },
623 Message::Close(_) => break,
624 _ => {}
625 }
626 }
627 });
628 loop {
629 tokio::select! {
630 biased;
631 text = io.rx.recv() => match text {
632 Some(text) => if tx.send(Message::Text(text)).await.is_err() { break },
633 None => break,
634 },
635 _ = io.notify.notified() => {
636 let frame = io.slot.lock().unwrap().take();
637 if let Some(frame) = frame {
638 if tx.send(Message::Binary(frame)).await.is_err() { break }
639 }
640 }
641 _ = &mut reader => break,
644 }
645 }
646 reader.abort();
647 hub.leave(id);
648}
649