tvpipe 0.3.0

Stream a program's frames and sound, files, web pages or the screen to Apple TVs, Chromecasts and browser tabs with low latency, in process
Documentation
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! The two listeners (docs/playshare-design.md ยง4): the local one (the
//! window: launcher, host page, API; the TV page) and the public one
//! (phones through the tunnel, or the LAN). Each checks `Host` (421:
//! DNS rebinding) and WebSocket `Origin` (403: cross-site hijacking).

use std::sync::Arc;

use crate::browser::fonts;
use crate::crypto::ring::ct_eq;
use crate::net::http::{Request, Response, Version};
use crate::net::httpd::{self, Handler, Reply};
use crate::net::websocket;

use super::bundle::{self, clean_path, percent_decode, Lookup};
use super::hub::{Hub, Via};
use super::web;

/// Which listener a handler serves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Listener {
    Local,
    Public,
    Lan,
}

/// The standard launcher.
pub const LAUNCHER: &str = "/_tvpipe/launcher/";

fn loopback_names(port: u16) -> [String; 3] {
    [
        format!("127.0.0.1:{port}"),
        format!("localhost:{port}"),
        format!("[::1]:{port}"),
    ]
}

fn redirect(status: u16, location: &str) -> Response {
    let mut r = httpd::response(
        status,
        if status == 301 {
            "Moved Permanently"
        } else {
            "Found"
        },
        "text/plain; charset=utf-8",
        Vec::new(),
    );
    r.headers.add("Location", location);
    r
}

/// The session cookie's name: per local port, since cookies are shared
/// by every port of a host.
pub fn cookie_name(port: u16) -> String {
    format!("tvpipe-{port}")
}

fn cookie<'a>(req: &'a Request, name: &str) -> Option<&'a str> {
    req.headers.get_all("cookie").find_map(|h| {
        h.split(';').find_map(|kv| {
            let (k, v) = kv.trim().split_once('=')?;
            (k == name).then_some(v)
        })
    })
}

fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
    query
        .split('&')
        .find_map(|kv| kv.strip_prefix(key)?.strip_prefix('='))
}

impl Hub {
    fn host_ok(&self, req: &Request, l: Listener) -> bool {
        let Some(host) = req
            .headers
            .get("host")
            .map(|h| h.trim().to_ascii_lowercase())
        else {
            return false;
        };
        let p = self.ports.get().copied();
        let Some(p) = p else { return false };
        match l {
            Listener::Local => loopback_names(p.local).contains(&host),
            Listener::Lan => p.lan.is_some_and(|a| a.to_string() == host),
            Listener::Public => {
                if loopback_names(p.public).contains(&host) {
                    return true;
                }
                let bare = host.strip_suffix(":443").unwrap_or(&host);
                self.tunnel
                    .read()
                    .unwrap_or_else(|e| e.into_inner())
                    .host
                    .as_deref()
                    .is_some_and(|h| h.eq_ignore_ascii_case(bare))
            }
        }
    }

    fn origin_ok(&self, req: &Request, l: Listener) -> bool {
        // Not a browser: tokens and keys still apply.
        let Some(o) = req
            .headers
            .get("origin")
            .map(|o| o.trim().to_ascii_lowercase())
        else {
            return true;
        };
        let Some(p) = self.ports.get().copied() else {
            return false;
        };
        let loopback = |port: u16| {
            o.strip_prefix("http://")
                .is_some_and(|a| loopback_names(port).iter().any(|n| n == a))
        };
        match l {
            Listener::Local => loopback(p.local),
            Listener::Lan => p.lan.is_some_and(|a| o == format!("http://{a}")),
            Listener::Public => {
                loopback(p.public)
                    || o.strip_prefix("https://").is_some_and(|h| {
                        self.tunnel
                            .read()
                            .unwrap_or_else(|e| e.into_inner())
                            .host
                            .as_deref()
                            .is_some_and(|t| t.eq_ignore_ascii_case(h))
                    })
            }
        }
    }

    /// Whether the request carries the API token (cookie or `?t=`).
    pub fn token_ok(&self, req: &Request, query: &str) -> bool {
        let port = self.ports.get().map(|p| p.local).unwrap_or(0);
        let want = self.token.as_bytes();
        query_param(query, "t").is_some_and(|t| ct_eq(t.as_bytes(), want))
            || cookie(req, &cookie_name(port)).is_some_and(|t| ct_eq(t.as_bytes(), want))
    }

    /// The visitor's address for limits and the host.
    fn address(&self, req: &Request, l: Listener) -> String {
        let peer = httpd::current_peer();
        if l == Listener::Public {
            let host = req.headers.get("host").unwrap_or("").to_ascii_lowercase();
            let tunnel = !host.starts_with("127.0.0.1:")
                && !host.starts_with("localhost:")
                && !host.starts_with("[::1]:");
            if tunnel {
                if let Some(cf) = req
                    .headers
                    .get("cf-connecting-ip")
                    .map(str::trim)
                    .filter(|c| !c.is_empty() && c.len() < 64)
                {
                    return cf.to_owned();
                }
                let peers = self.peers.read().unwrap_or_else(|e| e.into_inner());
                if let Some(v) = peers.as_ref().and_then(|f| peer.and_then(|a| f(a))) {
                    return v;
                }
            }
        }
        peer.map(|a| a.ip().to_string())
            .unwrap_or_else(|| "?".into())
    }

    fn launcher_path(&self) -> String {
        match &self.bundle.manifest.pages.launcher {
            Some(l) => format!("/{l}"),
            None => LAUNCHER.to_owned(),
        }
    }

    fn handle(self: &Arc<Hub>, req: &Request, l: Listener) -> Reply {
        if !self.host_ok(req, l) {
            return Reply::Response(httpd::error_response(421, "Misdirected Request"));
        }
        let (path, query) = req.target.split_once('?').unwrap_or((&req.target, ""));
        if websocket::is_upgrade(req) {
            return self.upgrade(req, l, path, query);
        }
        if req.method != "GET" && req.method != "HEAD" {
            let mut r = httpd::error_response(405, "Method Not Allowed");
            r.headers.add("Allow", "GET, HEAD");
            return Reply::Response(r);
        }
        // A service worker on the phones' origin would outlive the game:
        // the next game on the same name (a reused Cloudflare hostname,
        // `--lan`'s port) would run under it (ยง18).
        if l != Listener::Local
            && req
                .headers
                .get("service-worker")
                .is_some_and(|v| v.trim().eq_ignore_ascii_case("script"))
        {
            return Reply::Response(httpd::error_response(
                403,
                "Forbidden: no service workers on the phones' link",
            ));
        }
        let r = self.get(req, l, path, query);
        Reply::Response(self.for_browser(req, l, r))
    }

    /// An error a browser navigated to becomes a page in tvpipe's look
    /// (scripts, `fetch` and tools keep the plain text).
    fn for_browser(&self, req: &Request, l: Listener, mut r: Response) -> Response {
        let navigation = req
            .headers
            .get("accept")
            .is_some_and(|a| a.contains("text/html"));
        if r.status < 400 || !navigation {
            return r;
        }
        let (heading, text) = match (r.status, l) {
            (403, Listener::Local) => (
                "Open the link tvpipe printed",
                "This browser has no key to the game yet: open the link tvpipe printed in the terminal, or use the window it opened.",
            ),
            (404, Listener::Local) => (
                "Nothing here",
                "The game has no page at this address. The link tvpipe printed opens the game.",
            ),
            (404, _) => (
                "Nothing here",
                "The game has no page at this address. To join, scan the QR code on the TV again.",
            ),
            _ => ("tvpipe refused this", "Open the game with the link tvpipe printed or the QR code on the TV."),
        };
        let reason = r.reason.split(':').next().unwrap_or("").to_owned();
        r.headers.set("Content-Type", "text/html; charset=utf-8");
        r.body = web::error_page(
            r.status,
            &reason,
            &self.bundle.manifest.title,
            heading,
            text,
        );
        r
    }

    fn get(&self, req: &Request, l: Listener, path: &str, query: &str) -> Response {
        if path == "/" {
            return match l {
                Listener::Local => {
                    if self.token_ok(req, "") {
                        redirect(302, &self.launcher_path())
                    } else {
                        httpd::error_response(403, "Forbidden: open the link tvpipe printed")
                    }
                }
                _ => {
                    let phone = format!("/{}", self.bundle.manifest.pages.phone);
                    if query.is_empty() {
                        redirect(302, &phone)
                    } else {
                        redirect(302, &format!("{phone}?{query}"))
                    }
                }
            };
        }
        if let Some(rest) = path.strip_prefix("/_tvpipe/") {
            if l == Listener::Local && rest == "start" {
                if !self.token_ok(req, query) {
                    return httpd::error_response(403, "Forbidden");
                }
                let port = self.ports.get().map(|p| p.local).unwrap_or(0);
                // `next`: a page of this origin instead of the launcher
                // (tests, a browser opened by hand).
                let next = query_param(query, "next")
                    .and_then(percent_decode)
                    .filter(|n| n.starts_with('/') && !n.starts_with("//") && !n.contains('\\'))
                    .unwrap_or_else(|| self.launcher_path());
                let mut r = redirect(302, &next);
                r.headers.add(
                    "Set-Cookie",
                    format!(
                        "{}={}; Path=/; HttpOnly; SameSite=Strict",
                        cookie_name(port),
                        self.token
                    ),
                );
                return r;
            }
            if rest == "launcher" && l == Listener::Local {
                return redirect(301, LAUNCHER);
            }
            // tvpipe's look, for any page (the browser player's files).
            if rest == "ui.css" {
                let css = fonts::UI_CSS.as_bytes().to_vec();
                return file_response(req, "ui.css", css, None);
            }
            if let Some(name) = rest.strip_prefix("fonts/") {
                return fonts::font_response(fonts::font(name));
            }
            let Some(rel) = percent_decode(rest).and_then(|r| {
                let r = if r.is_empty() || r.ends_with('/') {
                    format!("{r}index.html")
                } else {
                    r
                };
                clean_path(&r)
            }) else {
                return httpd::error_response(404, "Not Found");
            };
            let allowed =
                rel.starts_with("lib/") || (l == Listener::Local && rel.starts_with("launcher/"));
            if !allowed {
                return httpd::error_response(404, "Not Found");
            }
            return match web::get(&rel) {
                Some(bytes) => file_response(req, &rel, bytes.into_owned(), None),
                None => httpd::error_response(404, "Not Found"),
            };
        }
        self.bundle_file(req, path, query)
    }

    fn bundle_file(&self, req: &Request, path: &str, query: &str) -> Response {
        let Some(decoded) = percent_decode(path) else {
            return httpd::error_response(400, "Bad Request");
        };
        let rel = decoded.trim_start_matches('/');
        let rel = if rel.is_empty() || rel.ends_with('/') {
            format!("{rel}index.html")
        } else {
            rel.to_owned()
        };
        let Some(rel) = clean_path(&rel) else {
            return httpd::error_response(404, "Not Found");
        };
        if rel == "_tvpipe" || rel.starts_with("_tvpipe/") {
            return httpd::error_response(404, "Not Found");
        }
        match self.bundle.get(&rel) {
            Lookup::File(f) => file_response(req, &rel, f.bytes, Some(f.etag)),
            Lookup::Dir => {
                let q = if query.is_empty() {
                    String::new()
                } else {
                    format!("?{query}")
                };
                redirect(301, &format!("{path}/{q}"))
            }
            Lookup::NotFound => httpd::error_response(404, "Not Found"),
        }
    }

    fn upgrade(self: &Arc<Hub>, req: &Request, l: Listener, path: &str, query: &str) -> Reply {
        let refuse =
            |status: u16, reason: &str| Reply::Response(httpd::error_response(status, reason));
        let api = path == "/_tvpipe/api";
        let surface = path == "/_tvpipe/surface" && l == Listener::Local;
        if !(path == "/_tvpipe/ws" || surface || (api && l == Listener::Local)) {
            return refuse(404, "Not Found");
        }
        if !self.origin_ok(req, l) {
            warn!(
                "playshare: a WebSocket from origin {:?} refused",
                req.headers.get("origin").unwrap_or("")
            );
            return refuse(403, "Forbidden");
        }
        if (api || surface) && !self.token_ok(req, query) {
            return refuse(403, "Forbidden");
        }
        let surface_id = if surface {
            match query_param(query, "id").and_then(|i| i.parse::<u32>().ok()) {
                Some(id) if self.surface_exists(id) => Some(id),
                _ => return refuse(404, "Not Found"),
            }
        } else {
            None
        };
        let resp = match websocket::server_response(req) {
            Ok(r) => r,
            Err(e) => return refuse(400, &format!("Bad Request: {}", e.message())),
        };
        let hub = self.clone();
        if let Some(id) = surface_id {
            return Reply::Upgrade(
                resp,
                Box::new(move |tcp, rest| hub.run_surface(tcp, rest, id)),
            );
        }
        if api {
            return Reply::Upgrade(resp, Box::new(move |tcp, rest| hub.run_api(tcp, rest)));
        }
        let addr = self.address(req, l);
        if let Err((status, reason)) = self.admit(&addr) {
            return refuse(status, reason);
        }
        let via = match l {
            Listener::Local => Via::Local,
            Listener::Public => Via::Public,
            Listener::Lan => Via::Lan,
        };
        let query: String = query.chars().take(512).collect();
        let agent: String = req
            .headers
            .get("user-agent")
            .unwrap_or("")
            .chars()
            .take(256)
            .collect();
        Reply::Upgrade(
            resp,
            Box::new(move |tcp, rest| hub.run_client(tcp, rest, via, addr, query, agent)),
        )
    }
}

fn file_response(req: &Request, rel: &str, bytes: Vec<u8>, etag: Option<String>) -> Response {
    let etag = etag.unwrap_or_else(|| bundle::etag_of(&bytes));
    if req
        .headers
        .get("if-none-match")
        .is_some_and(|v| v.trim() == etag)
    {
        let mut r = Response::new(Version::Http11, 304, "Not Modified");
        r.headers.add("ETag", etag).add("Cache-Control", "no-cache");
        return r;
    }
    let mut r = httpd::response(200, "OK", bundle::mime(rel), bytes);
    r.headers
        .set("Cache-Control", "no-cache")
        .add("ETag", etag)
        .add("Referrer-Policy", "no-referrer");
    r
}

/// The handler of one listener.
pub fn handler(hub: Arc<Hub>, l: Listener) -> Handler {
    Arc::new(move |req: &Request| hub.handle(req, l))
}