apeirogond 0.8.0

Daemon for Apeirogon, a cross-platform software KVM
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// SPDX-License-Identifier: GPL-3.0-or-later

use std::net::{Ipv4Addr, SocketAddr};

use a7n_core::layout::Placement;
use a7n_proto::v1::{InputEvent, KeyEvent, RefuseReason, input_event};
use a7n_proto::{FrameKind, limits};
use tempfile::TempDir;
use tokio::sync::{mpsc, oneshot};
use tokio::time::timeout;

use super::*;
use crate::daemon::test_peer::{Peer, TEST_TIMEOUT};
use crate::pin_store::Entry;

mod config;
mod hotkeys;
mod pause;

struct FakeInput {
    capture: mpsc::Sender<Captured>,
    control: mpsc::Receiver<CaptureControl>,
    inject: mpsc::Receiver<Inject>,
    feedback: mpsc::Sender<Captured>,
}

fn daemon(input: bool) -> (Daemon, TempDir, Option<FakeInput>) {
    let dir = tempfile::tempdir().unwrap();
    let daemon = Daemon::load(dir.path(), SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).unwrap();
    if !input {
        return (daemon, dir, None);
    }
    let (handles, fake) = fake_input();
    (daemon.with_input(Some(handles)), dir, Some(fake))
}

fn fake_input() -> (Handles, FakeInput) {
    let (capture_tx, capture_rx) = mpsc::channel(super::super::MAILBOX_CAPACITY);
    let (control_tx, control_rx) = mpsc::channel(super::super::MAILBOX_CAPACITY);
    let (inject_tx, inject_rx) = mpsc::channel(super::super::MAILBOX_CAPACITY);
    let (feedback_tx, feedback_rx) = mpsc::channel(super::super::MAILBOX_CAPACITY);
    let bounds = Bounds {
        x: 0,
        y: 0,
        width: 100,
        height: 100,
    };
    (
        (
            Capture {
                bounds,
                events: capture_rx,
                control: control_tx,
            },
            Injector {
                bounds,
                commands: inject_tx,
                pointer: feedback_rx,
            },
        ),
        FakeInput {
            capture: capture_tx,
            control: control_rx,
            inject: inject_rx,
            feedback: feedback_tx,
        },
    )
}

async fn pair() -> (Peer, Peer, FakeInput, FakeInput) {
    configured_pair(|_, _| {}).await
}

async fn configured_pair(
    configure: impl FnOnce(&mut Daemon, &mut Daemon),
) -> (Peer, Peer, FakeInput, FakeInput) {
    let (mut a, a_dir, a_input) = daemon(true);
    let (mut b, b_dir, b_input) = daemon(true);
    configure(&mut a, &mut b);
    let placements = [a.identity.machine_id, b.identity.machine_id]
        .into_iter()
        .zip([0, 100])
        .map(|(id, x)| Placement {
            id,
            x,
            y: 0,
            width: 100,
            height: 100,
        })
        .collect();
    a.layout.state = a
        .layout
        .state
        .edit(placements, a.identity.machine_id)
        .unwrap();
    b.layout.state = a.layout.state.clone();
    let (a, b) = (Peer::run(a, a_dir), Peer::run(b, b_dir));
    a.pair(&b).await;
    (a, b, a_input.unwrap(), b_input.unwrap())
}

impl FakeInput {
    async fn grab(&mut self, expected: bool) {
        timeout(TEST_TIMEOUT, async {
            loop {
                if matches!(self.control.recv().await.unwrap(), CaptureControl::Grab(value) if value == expected) { return; }
            }
        }).await.unwrap();
    }

    async fn injected(&mut self) -> Inject {
        timeout(TEST_TIMEOUT, self.inject.recv())
            .await
            .unwrap()
            .unwrap()
    }

    async fn cross(&self, right: bool) {
        self.capture.send(pointer(right)).await.unwrap();
    }
}

fn pointer(right: bool) -> Captured {
    let resistance = i32::try_from(limits::DEFAULT_RESISTANCE_PX).unwrap();
    Captured::Pointer {
        x: if right { 99 } else { 0 },
        y: 50,
        dx: if right { resistance } else { -resistance },
        dy: 0,
    }
}

fn key(down: bool) -> InputEvent {
    InputEvent {
        event: Some(input_event::Event::Key(KeyEvent {
            usage: 0x0007_0004,
            down,
            character: String::new(),
        })),
    }
}

async fn drive(a: &mut FakeInput, b: &mut FakeInput) {
    a.cross(true).await;
    a.grab(true).await;
    assert!(matches!(
        b.injected().await,
        Inject::Warp { x: 0, y: 0..=99 }
    ));
}

#[tokio::test]
async fn captured_right_edge_takes_peer_grabs_and_warps() {
    // Arrange
    let (a, b, mut a_input, mut b_input) = pair().await;

    // Act
    a_input.cross(true).await;

    // Assert
    a_input.grab(true).await;
    b_input.grab(true).await;
    assert!(matches!(
        b_input.injected().await,
        Inject::Warp { x: 0, y: 0..=99 }
    ));
    a.stop().await;
    b.stop().await;
}

#[tokio::test]
async fn receive_input_link_lost_releases_held_key() {
    // Arrange
    let (a, b, mut a_input, mut b_input) = pair().await;
    drive(&mut a_input, &mut b_input).await;

    // Act
    a_input
        .capture
        .send(Captured::Input(key(true)))
        .await
        .unwrap();
    let pressed = b_input.injected().await;
    a.stop().await;
    let released = b_input.injected().await;

    // Assert
    assert!(matches!(pressed, Inject::Event(event) if event == key(true)));
    assert!(matches!(released, Inject::Event(event) if event == key(false)));
    b_input.grab(false).await;
    b.stop().await;
}

#[tokio::test]
async fn pointer_feedback_left_edge_returns_owner_home_and_ungrabs() {
    // Arrange
    let (a, b, mut a_input, mut b_input) = pair().await;
    drive(&mut a_input, &mut b_input).await;

    // Act
    b_input.feedback.send(pointer(false)).await.unwrap();

    // Assert
    a_input.grab(false).await;
    b_input.grab(false).await;
    a.stop().await;
    b.stop().await;
}

#[tokio::test]
async fn receive_focus_unavailable_or_denied_refuses_not_allowed() {
    for backend in [false, true] {
        // Arrange
        let (a, _a_dir, _) = daemon(false);
        let (mut b, b_dir, _input) = daemon(backend);
        if backend {
            b.config
                .set(
                    &format!("peers.{}.allow_drive", a.identity.machine_id),
                    "false",
                )
                .unwrap();
        }
        b.pins.add(Entry {
            machine_id: a.identity.machine_id,
            pin: a.identity.pin,
            name: "owner".into(),
            spki_der: None,
        });
        b.sync_trust().unwrap();
        // Trust the responder for A's outgoing TLS handshake.
        a.trust.write().unwrap().pins.insert(b.identity.pin);
        let b = Peer::run(b, b_dir);
        let connection = timeout(
            limits::HANDSHAKE_TIMEOUT,
            a.endpoint
                .connect(b.addr, crate::tls::TLS_SERVER_NAME)
                .unwrap(),
        )
        .await
        .unwrap()
        .unwrap();
        let (mut send, mut recv) = connection.open_bi().await.unwrap();
        let mut buffer = Vec::new();
        let mut incoming = Vec::new();

        // Act
        crate::handshake::send_envelope(
            &mut send,
            &mut buffer,
            Body::Hello(a7n_proto::v1::Hello {
                protocol_version: a7n_proto::PROTOCOL_VERSION,
                info: Some(a.info.clone()),
            }),
        )
        .await
        .unwrap();
        let welcome = timeout(
            TEST_TIMEOUT,
            crate::handshake::read_frame(&mut recv, &mut incoming, FrameKind::Control),
        )
        .await
        .unwrap()
        .unwrap();
        crate::handshake::send_envelope(
            &mut send,
            &mut buffer,
            Body::Focus(a7n_proto::v1::Focus {
                route: 1,
                target: b.machine.as_bytes().to_vec(),
                ..Default::default()
            }),
        )
        .await
        .unwrap();
        let refusal = timeout(TEST_TIMEOUT, async {
            loop {
                let envelope =
                    crate::handshake::read_frame(&mut recv, &mut incoming, FrameKind::Control)
                        .await
                        .unwrap();
                if let Some(Body::Refuse(refuse)) = envelope.body {
                    break refuse;
                }
            }
        })
        .await
        .unwrap();

        // Assert
        assert!(matches!(welcome.body, Some(Body::Welcome(welcome)) if !welcome.accepts_drive));
        assert_eq!(refusal.route, 1);
        assert_eq!(refusal.reason, i32::from(RefuseReason::NotAllowed));
        b.stop().await;
    }
}

#[tokio::test]
async fn receive_input_full_injector_waits_and_delivers_both_events() {
    // Arrange
    let (mut daemon, _dir, input) = daemon(true);
    let mut input = input.unwrap();
    let (commands, receiver) = mpsc::channel(1);
    daemon.input.injector.as_mut().unwrap().commands = commands;
    input.inject = receiver;
    let peer = MachineId::try_from(&[42; MachineId::LEN][..]).unwrap();
    daemon.pins.add(Entry {
        machine_id: peer,
        pin: daemon.identity.pin,
        name: "owner".into(),
        spki_der: None,
    });
    daemon
        .receive_from(
            peer,
            Envelope {
                body: Some(Body::Focus(a7n_proto::v1::Focus {
                    route: 1,
                    target: daemon.identity.machine_id.as_bytes().to_vec(),
                    ..Default::default()
                })),
            },
        )
        .await
        .unwrap();

    // Act
    let task = tokio::spawn(async move {
        daemon
            .receive_from(
                peer,
                Envelope {
                    body: Some(Body::Input(InputBatch {
                        route: 1,
                        events: vec![key(true), key(false)],
                        ..Default::default()
                    })),
                },
            )
            .await
            .unwrap();
        daemon
    });
    timeout(TEST_TIMEOUT, async {
        while input.inject.is_empty() {
            tokio::task::yield_now().await;
        }
    })
    .await
    .unwrap();
    let blocked = !task.is_finished();
    let queued = input.inject.len();
    let first = input.injected().await;
    let second = input.injected().await;
    let daemon = timeout(TEST_TIMEOUT, task).await.unwrap().unwrap();

    // Assert
    assert!(blocked, "dispatch must wait for backend capacity");
    assert_eq!(queued, 1);
    assert!(matches!(first, Inject::Event(event) if event == key(true)));
    assert!(matches!(second, Inject::Event(event) if event == key(false)));
    assert!(!daemon.input.failed);
}

#[tokio::test]
async fn keepalive_full_control_is_ignored_and_closed_control_is_fatal() {
    // Arrange
    let (mut daemon, _dir, input) = daemon(true);
    let mut input = input.unwrap();
    let (control, receiver) = mpsc::channel(1);
    control.send(CaptureControl::Grab(true)).await.unwrap();
    daemon.input.capture.as_mut().unwrap().control = control;
    input.control = receiver;

    // Act
    daemon.input.keepalive();
    let full_failed = daemon.input.failed;
    drop(input.control);
    daemon.input.keepalive();

    // Assert
    assert!(!full_failed);
    assert!(daemon.input.failed);
}

#[tokio::test]
async fn shutdown_driven_machine_releases_key_and_ungrabs_before_done() {
    // Arrange
    let (a, b, mut a_input, mut b_input) = pair().await;
    drive(&mut a_input, &mut b_input).await;
    b_input.grab(true).await;
    a_input
        .capture
        .send(Captured::Input(key(true)))
        .await
        .unwrap();
    b_input.injected().await;

    // Act
    b.command(crate::command::Command::Shutdown).await.unwrap();

    // Assert
    assert!(matches!(b_input.injected().await, Inject::Event(event) if event == key(false)));
    b_input.grab(false).await;
    b.stop().await;
    a.stop().await;
}

#[tokio::test]
async fn attach_input_after_unavailable_start_clears_status_and_forwards_input() {
    // Arrange
    let (retry, retried) = oneshot::channel();
    let (a, b, a_input, mut b_input) = configured_pair(|a, _| {
        a.input.capture = None;
        a.input.injector = None;
        a.input.unavailable = Some("Accessibility permission missing".to_owned());
        a.input.retried = Some(retried);
    })
    .await;
    assert!(a.status().await.input.is_some());
    let (handles, mut late_input) = fake_input();

    // Act
    retry.send(Ok(handles)).unwrap();
    let status = a.wait(|status| status.input.is_none()).await;
    late_input.cross(true).await;

    // Assert
    assert_eq!(status.input, None);
    late_input.grab(true).await;
    b_input.grab(true).await;
    assert!(matches!(
        b_input.injected().await,
        Inject::Warp { x: 0, y: 0..=99 }
    ));
    drop(a_input);
    a.stop().await;
    b.stop().await;
}

#[tokio::test]
async fn finish_input_retry_after_backend_closes_restores_input() {
    // Arrange
    let (mut daemon, _dir, _old_input) = daemon(true);
    daemon.input.closed();
    let (handles, mut restarted) = fake_input();

    // Act
    daemon.finish_input_retry(Some(Ok(handles)));
    daemon.input.grab(true).await;

    // Assert
    assert!(!daemon.input.failed);
    assert!(daemon.status().input.is_none());
    restarted.grab(true).await;
}