summaryrefslogtreecommitdiffstats
path: root/gui/src/net.rs
blob: 7cba60422c27e866343cb578ae4a860a3d65b6da (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
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
//! Background network worker for the desktop frontend.
//!
//! The core is I/O-free, so the adapter owns the TLS stream. One blocking
//! thread keeps the connection, forwards every server line, and wakes the UI
//! through `egui::Context::request_repaint`. There is no async runtime: the
//! protocol has one request in flight plus server pushes.

use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::thread;
use std::time::Duration;

use eframe::egui;
use rusqlite::Connection;
use zagan_bet::client::transport::{self, TlsStream, TransportError, TrustPrompt};
use zagan_bet::client::{database, paths};

/// How often the worker checks the socket for pushes when idle.
const POLL: Duration = Duration::from_millis(8);
/// How long a first-contact prompt may stay unanswered.
const TRUST_TIMEOUT: Duration = Duration::from_secs(120);

/// What the UI asks the worker to do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    Connect { addr: String },
    Send(String),
    Disconnect,
    Stop,
}

/// Why a connection attempt failed. The UI picks a screen from this.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Failure {
    TrustDeclined,
    KeyChanged { expected: String, observed: String },
    VersionMismatch,
    Timeout,
    Other,
}

/// A connection that survived trust, version and auto-login.
#[derive(Debug, Clone, PartialEq)]
pub struct Connected {
    pub addr: String,
    pub user: Option<String>,
    pub auth_error: Option<String>,
    pub fingerprint: Option<String>,
    pub latest: String,
    pub url: String,
    pub elapsed_ms: f32,
}

/// What the worker tells the UI.
pub enum Event {
    /// First contact: the UI must answer through the sender.
    Trust {
        addr: String,
        fingerprint: String,
        reply: Sender<bool>,
    },
    Connected(Connected),
    Failed {
        addr: String,
        failure: Failure,
        message: String,
    },
    Line(String),
    Closed,
}

fn classify(error: &TransportError) -> Failure {
    match error {
        TransportError::TrustDeclined => Failure::TrustDeclined,
        TransportError::KeyChanged { expected, observed } => Failure::KeyChanged {
            expected: expected.clone(),
            observed: observed.clone(),
        },
        TransportError::VersionMismatch(_) => Failure::VersionMismatch,
        TransportError::Timeout => Failure::Timeout,
        _ => Failure::Other,
    }
}

/// Handle held by the app. Dropping it stops the worker.
pub struct Network {
    commands: Sender<Command>,
    events: Receiver<Event>,
}

impl Network {
    pub fn spawn(ctx: egui::Context, data_dir: PathBuf, unsafe_mode: bool) -> Self {
        let (commands, command_rx) = mpsc::channel();
        let (event_tx, events) = mpsc::channel();
        thread::spawn(move || worker(ctx, data_dir, unsafe_mode, command_rx, event_tx));
        Self { commands, events }
    }

    pub fn send(&self, command: Command) {
        let _ = self.commands.send(command);
    }

    pub fn try_recv(&self) -> Option<Event> {
        self.events.try_recv().ok()
    }
}

impl Drop for Network {
    fn drop(&mut self) {
        let _ = self.commands.send(Command::Stop);
    }
}

fn worker(
    ctx: egui::Context,
    data_dir: PathBuf,
    unsafe_mode: bool,
    commands: Receiver<Command>,
    events: Sender<Event>,
) {
    let db_path = paths::database_path(&data_dir);
    let conn = match Connection::open(&db_path) {
        Ok(conn) => {
            let _ = conn.busy_timeout(Duration::from_secs(2));
            database::init_db(&conn);
            Some(conn)
        }
        Err(_) => None,
    };

    let mut stream: Option<TlsStream> = None;

    loop {
        match commands.recv_timeout(POLL) {
            Ok(Command::Connect { addr }) => {
                stream = None;
                let Some(conn) = &conn else {
                    let _ = events.send(Event::Failed {
                        addr,
                        failure: Failure::Other,
                        message: format!("cannot open {}", db_path.display()),
                    });
                    ctx.request_repaint();
                    continue;
                };
                let mut trust = |prompt: &TrustPrompt| {
                    let (reply, decision) = mpsc::channel();
                    let _ = events.send(Event::Trust {
                        addr: prompt.addr.clone(),
                        fingerprint: prompt.fingerprint.clone(),
                        reply,
                    });
                    ctx.request_repaint();
                    decision.recv_timeout(TRUST_TIMEOUT).unwrap_or(false)
                };
                match transport::connect(&addr, conn, unsafe_mode, &mut trust) {
                    Ok(connected) => {
                        let fingerprint = database::get_fingerprint(conn, &addr);
                        let _ = events.send(Event::Connected(Connected {
                            addr: addr.clone(),
                            user: connected.user,
                            auth_error: connected.auth_error,
                            fingerprint,
                            latest: connected.latest,
                            url: connected.url,
                            elapsed_ms: connected.elapsed.as_secs_f64() as f32 * 1000.0,
                        }));
                        stream = Some(connected.stream);
                    }
                    Err(error) => {
                        let _ = events.send(Event::Failed {
                            addr,
                            failure: classify(&error),
                            message: error.to_string(),
                        });
                    }
                }
                ctx.request_repaint();
            }
            Ok(Command::Send(line)) => {
                if let Some(open) = &mut stream {
                    if open.write_line(&line).is_err() {
                        stream = None;
                        let _ = events.send(Event::Closed);
                    }
                }
                ctx.request_repaint();
            }
            Ok(Command::Disconnect) => {
                stream = None;
                ctx.request_repaint();
            }
            Ok(Command::Stop) => break,
            Err(RecvTimeoutError::Timeout) => {}
            Err(RecvTimeoutError::Disconnected) => break,
        }

        // Drain pushes and replies without blocking the command channel.
        if let Some(open) = &mut stream {
            loop {
                match open.read_available_line() {
                    Ok(Some(line)) => {
                        if events.send(Event::Line(line)).is_err() {
                            return;
                        }
                    }
                    Ok(None) => break,
                    Err(_) => {
                        stream = None;
                        let _ = events.send(Event::Closed);
                        break;
                    }
                }
            }
            ctx.request_repaint();
        }
    }
}