Skip to main content

brep_app/stream/
server.rs

1//! The stream's network side: axum serves the client page and the
2//! WebSocket on a tokio runtime of its own; the [`Hub`] is what the host
3//! loop and the sockets share (clients, roles, input, frame slots).
4use 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;
18/// Frames a client may have un-acknowledged before it is skipped.
19pub const MAX_INFLIGHT: u32 = 2;
20/// A client whose frames take longer than this from send to ack is on a slow
21/// link: it gets one frame in flight (so the next input's frame never queues
22/// behind two) and the 3D view's lossy tiles at [`SLOW_JPEG`] at most.
23pub const SLOW_LINK: std::time::Duration = std::time::Duration::from_millis(120);
24pub const SLOW_JPEG: u8 = 40;
25/// The largest file a page may upload.
26pub const MAX_UPLOAD: u64 = 256 << 20;
27/// Uploads announced and not yet sent, per client.
28const MAX_ANNOUNCED: usize = 8;
29/// Downloads kept on offer (the oldest goes first).
30const 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
49/// One connected, authenticated client.
50pub struct Client {
51    pub role: Role,
52    /// It asked for control in its hello: it takes control when the
53    /// controller leaves (a reloaded page whose new connection arrived before
54    /// the old one closed).
55    wants_control: bool,
56    ctrl: tokio::sync::mpsc::UnboundedSender<String>,
57    /// The newest frame for the writer; filled only when empty.
58    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    /// `(seq, when sent)` of the frames not yet acknowledged.
65    sent_at: std::collections::VecDeque<(u32, std::time::Instant)>,
66    /// Smoothed send-to-ack time of this client's frames.
67    pub frame_time: Option<std::time::Duration>,
68}
69
70impl Client {
71    /// Whether this client's link is slow (see [`SLOW_LINK`]).
72    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    /// The JPEG quality this client's moving 3D view is sent at.
82    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            // Sequence numbers wrap; anything not after `seq` is answered.
91            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/// What the page asked for since the host last looked.
120#[derive(Default)]
121pub struct Inbox {
122    /// Controller input, in order.
123    pub input: Vec<ClientMsg>,
124    /// The controller's latest surface `(w, h, dpr)` in CSS pixels.
125    pub resize: Option<(f32, f32, f32)>,
126    /// A client joined (it needs a frame even if nothing changed).
127    pub joined: bool,
128    /// An ack freed a client that had been skipped.
129    pub acked: bool,
130    /// Files the page uploaded, on disk, for the app to open.
131    pub uploaded: Vec<std::path::PathBuf>,
132}
133
134/// An upload the controller announced: its bytes come by POST.
135struct Announced {
136    client: u64,
137    name: String,
138    size: u64,
139}
140
141/// An export the app wrote and the page may fetch.
142struct 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 ids, oldest first.
157    offer_order: std::collections::VecDeque<String>,
158    uploads: u64,
159}
160
161/// Shared by the host loop and the sockets.
162pub 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    /// The surface a client is told about at once in its welcome.
169    pub surface: Mutex<(u32, u32, f32)>,
170    /// Where uploads land: durable, since an opened document keeps its path.
171    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    /// Put uploads in `dir` instead of `<data dir>/brep-app/stream-uploads`.
188    pub fn set_upload_dir(&self, dir: std::path::PathBuf) {
189        *self.upload_dir.lock().unwrap() = dir;
190    }
191
192    /// Send `value` to every client.
193    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    /// Offer the export at `path` to every page as a download.
201    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    /// Client `id` announces an upload: refused unless it controls the
220    /// session, the name keeps something after sanitising, and the size is
221    /// allowed; else answered with the id the bytes go to.
222    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    /// End the session: the host loop returns (the app's `on_exit` runs).
248    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    /// Send `value` to the controller.
258    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        // Constant time in the token's length.
267        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            // Not a browser (a native client sends no Origin): the token decides.
278            return true;
279        };
280        if self.origins.iter().any(|o| o == "*" || o == origin) {
281            return true;
282        }
283        // The server's own origin: the page it served.
284        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            // The oldest client that asked for control takes it.
332            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                // Its page size applies from now: it sends it on the role change.
340            }
341        }
342    }
343
344    /// One message from client `id`.
345    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
393/// Start the server on its own thread and runtime; returns once listening.
394pub 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
446/// A client's file name with no path in it: the last component, control and
447/// path characters replaced, no leading dots, at most 120 bytes (the
448/// extension kept). `None` when nothing is left.
449pub 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
473/// The `Authorization: Bearer` token, checked; a wrong one waits half a
474/// second like a wrong hello.
475async 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
484/// `POST /stream/uploads/<id>`: the bytes of an announced upload. Nothing
485/// is read before the origin, the token, the id, the announcer still holding
486/// control and the declared length are checked, so a stranger cannot make the
487/// server buffer a body. Written under a temporary name and renamed when
488/// whole, so the app never opens a partial file; a body that does not arrive
489/// whole leaves nothing.
490async 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    // A folder per upload keeps the page's file name (an imported tab is
523    // named after it) and never collides.
524    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
553/// `GET /stream/downloads/<id>`: an export the app offered, never any
554/// other path.
555async 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    // The first message is the hello, within ten seconds.
588    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    // Input is read on its own task: a slow frame send never holds it.
615    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            // The page closed (or its socket broke): leave at once, so a page
642            // that reloads finds the controller's place free.
643            _ = &mut reader => break,
644        }
645    }
646    reader.abort();
647    hub.leave(id);
648}
649