summaryrefslogtreecommitdiffstats
path: root/webd/src/main.rs
blob: c2cf0ff79a00983aa0a917e2650628be8a1ddc3a (plain) (blame)
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
//! Browser gateway for zagan-bet.
//!
//! nginx terminates TLS, serves the static app and proxies `/ws` here. This
//! process owns one upstream TLS connection and one `ClientCore` per browser
//! session, so the browser never speaks the game wire protocol and never sees
//! a certificate.

mod config;
mod session;

use std::net::TcpListener;
use std::sync::Arc;
use std::thread;

use config::Config;

fn main() {
    let config = match Config::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("webd: {error}");
            std::process::exit(2);
        }
    };

    let listener = match TcpListener::bind(&config.bind) {
        Ok(listener) => listener,
        Err(error) => {
            eprintln!("webd: could not bind {}: {error}", config.bind);
            std::process::exit(1);
        }
    };

    println!(
        "webd listening on ws://{} for origin {}; upstream {} pinned to {}; grace {}s",
        config.bind,
        config.origin,
        config.upstream,
        config.fingerprint,
        config.grace.as_secs()
    );

    let registry = session::new_registry();
    for stream in listener.incoming() {
        let stream = match stream {
            Ok(stream) => stream,
            Err(error) => {
                eprintln!("webd: accept failed: {error}");
                continue;
            }
        };
        let _ = stream.set_nodelay(true);
        let config = config.clone();
        let registry = Arc::clone(&registry);
        thread::spawn(move || {
            if let Err(error) = session::accept(stream, config, registry) {
                eprintln!("webd: {error}");
            }
        });
    }
}