zc2 0.0.30

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Docker backend: holds the WireGuard tunnel with the help of an alpine
//! container named `zakuro-wg`. It runs in one of two modes:
//!
//! - **hostnet** (Linux with the kernel `wireguard` module): the helper runs
//!   with `--network host --cap-add NET_ADMIN` and `wg-quick` brings
//!   `zakuro0` up *in the host's network namespace*. The host is then routable
//!   into `10.13.13.0/24` exactly as with the native backend — the CLI, a host
//!   `zc broker`, and the broker's QUIC/UDP peer transport all reach the mesh
//!   directly, and a host broker sees its own mesh IP (`discovery::get_mesh_ip`)
//!   so it can advertise a `mesh_endpoint` and be dialed by peers. No root on
//!   the host is needed: the privilege lives in the container, which is why
//!   this exists at all.
//!
//! - **proxy** (fallback: no kernel module, rootless Docker, Docker Desktop):
//!   wireguard-go in the container's own netns, a tinyproxy HTTP CONNECT proxy
//!   published on `127.0.0.1:1888x` for outbound mesh HTTP
//!   (`vpn::mesh_agent`/`mesh_proxy`), and an inbound relay: socat on the
//!   container's mesh address forwards ports 9000..=9010 to the same ports on
//!   the host (`host.docker.internal`), so a host broker on one of them is a
//!   reachable peer. TCP only: a broker on this route runs no QUIC and offers
//!   over HTTP (mesh-routes §3-4).
//!
//! Both modes stamp the container with labels (`zakuro.mode`, `zakuro.address`,
//! the proxy sidecar's `zakuro.proxy` and `zakuro.relay`, and `zakuro.node` —
//! this device's node fingerprint when the hub gave it its own mesh identity,
//! or `shared` when it answered the account's shared profile) so `status()`
//! can rebuild the `ConnectionInfo` when the state file is missing — a live
//! tunnel must never be torn down and rebuilt just because `connection.json`
//! went away — and `vpn::connect` can tell a sidecar that must be recreated.

use crate::vpn::connector::Connector;
use crate::vpn::profile::WgProfile;
use crate::vpn::{
    Backend, ConnectionInfo, NetError, PeerStatus, RELAY_FIRST_PORT, RELAY_LAST_PORT, RELAY_VERSION,
};
use std::process::Command;

pub(crate) const SIDECAR: &str = "zakuro-wg";
const IFACE: &str = "zakuro0";
const LABEL_MODE: &str = "zakuro.mode";
const LABEL_ADDRESS: &str = "zakuro.address";
const LABEL_PROXY: &str = "zakuro.proxy";
const LABEL_NODE: &str = "zakuro.node";
const LABEL_RELAY: &str = "zakuro.relay";

/// The `zakuro.node` value of a sidecar built from the account's shared
/// profile: the hub is older than per-device identities, or this device has
/// no node key yet.
pub(crate) const NODE_SHARED: &str = "shared";

/// The `zakuro.node` label for a sidecar built from a profile whose `node` is
/// this: the fingerprint the hub echoed, or [`NODE_SHARED`]. Every sidecar zc
/// creates carries one, so `vpn::connect` can tell a `shared` sidecar (kept
/// while the hub is old) from one that predates the label (recreated once).
/// Both modes build the label here and nowhere else.
fn node_label(node: Option<&str>) -> String {
    format!("{LABEL_NODE}={}", node.unwrap_or(NODE_SHARED))
}

/// What `connect` stamped on the helper container (see the module docs).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SidecarLabels {
    pub mode: Mode,
    pub address: String,
    pub proxy: Option<String>,
    /// `zakuro.node`: this device's node fingerprint when the hub gave it its
    /// own mesh identity (mesh-routes §0), else [`NODE_SHARED`]. `None` on a
    /// sidecar from before per-device mesh identities, which carried no such label.
    pub node: Option<String>,
    /// The inbound relay's version (`vpn::RELAY_VERSION`); `None` on a
    /// sidecar from before the relay.
    pub relay: Option<u32>,
}

/// A label's value, or `None` when it is unset: docker renders `index` on a
/// missing key as "" (or "<no value>").
fn label_value(s: &str) -> Option<String> {
    let s = s.trim();
    (!s.is_empty() && s != "<no value>").then(|| s.to_string())
}

/// Parse the `mode|address|proxy|node|relay` line `sidecar_labels` asks docker for.
pub(crate) fn parse_labels(out: &str) -> Option<SidecarLabels> {
    let mut parts = out.trim().splitn(5, '|');
    let mode = Mode::parse(parts.next()?)?;
    let address = label_value(parts.next()?)?;
    let proxy = parts.next().and_then(label_value);
    let node = parts.next().and_then(label_value);
    let relay = parts
        .next()
        .and_then(label_value)
        .and_then(|v| v.parse().ok());
    Some(SidecarLabels {
        mode,
        address,
        proxy,
        node,
        relay,
    })
}

/// The `ConnectionInfo` `status()` rebuilds from a live sidecar's labels when
/// the state file is gone. A proxy sidecar's relay version is recorded as its
/// `zakuro.relay` label says, so `vpn::route()` finds it in `connection.json`
/// just as `connect_proxy` left it. Pure, so it is tested without Docker.
fn info_from_labels(
    labels: SidecarLabels,
    host_routable: bool,
    peers: Vec<PeerStatus>,
) -> ConnectionInfo {
    let proxy_mode = labels.mode == Mode::Proxy;
    ConnectionInfo {
        backend: Backend::Docker,
        address: labels.address,
        link: SIDECAR.to_string(),
        peers,
        host_routable,
        proxy: if proxy_mode { labels.proxy } else { None },
        relay: if proxy_mode { labels.relay } else { None },
    }
}

/// The proxy sidecar's start script: wireguard-go, tinyproxy for outbound
/// CONNECT, then the inbound relay (mesh-routes §3). For each port in
/// 9000..=9010, a socat on this container's mesh address forwards to the same
/// port on the host (`host.docker.internal`), so peers reach a host broker.
/// TCP only: the proxy route runs no QUIC.
///
/// `docker run` stamps `zakuro.relay` before this runs, so the script makes
/// the label true or stops: without socat it exits non-zero right after
/// `apk add`, saying why in `/tmp/wg.log` and the docker logs. The tunnel then
/// never gets an address, and `connect_proxy` fails the bring-up instead of
/// recording a relay that forwards nothing.
pub(crate) fn proxy_start_script(conf_b64: &str) -> String {
    format!(
        "apk add -q wireguard-tools wireguard-go tinyproxy socat 2>/dev/null; \
         if ! command -v socat >/dev/null 2>&1; then \
         echo 'socat did not install, so the mesh relay cannot run' | tee /tmp/wg.log >&2; \
         exit 1; \
         fi; \
         mkdir -p /etc/wireguard; \
         echo '{b64}' | base64 -d > /etc/wireguard/{iface}.conf; \
         chmod 600 /etc/wireguard/{iface}.conf; \
         export WG_QUICK_USERSPACE_IMPLEMENTATION=wireguard-go; \
         wg-quick up {iface} >/tmp/wg.log 2>&1; \
         printf 'Port 8888\\nListen 0.0.0.0\\nTimeout 60\\nAllow 172.16.0.0/12\\nAllow 127.0.0.1\\n' > /etc/tinyproxy/tinyproxy.conf; \
         tinyproxy -d >/tmp/tinyproxy.log 2>&1 & \
         WG_IP=$(ip -4 addr show {iface} | awk '/inet /{{print $2}}' | cut -d/ -f1); \
         if [ -n \"$WG_IP\" ]; then \
         for p in $(seq {first} {last}); do \
         socat TCP-LISTEN:$p,bind=$WG_IP,fork,reuseaddr TCP:host.docker.internal:$p >/tmp/relay-$p.log 2>&1 & \
         done; \
         fi; \
         exec sleep infinity",
        b64 = conf_b64,
        iface = IFACE,
        first = RELAY_FIRST_PORT,
        last = RELAY_LAST_PORT,
    )
}

/// `docker run` arguments for the proxy sidecar: wireguard-go, tinyproxy on
/// `127.0.0.1:<proxy_port>` and the relay, labelled so `status()` can rebuild
/// the connection and `vpn::connect` can tell an outdated sidecar. Pure, so
/// it is tested without Docker.
pub(crate) fn proxy_run_args(
    address: &str,
    proxy_port: u16,
    node: Option<&str>,
    run_cmd: &str,
) -> Vec<String> {
    let mut args: Vec<String> = [
        "run",
        "-d",
        "--name",
        SIDECAR,
        "--cap-add",
        "NET_ADMIN",
        "--device",
        "/dev/net/tun",
        // The relay's target. Docker Desktop resolves this name already; the
        // mapping makes Linux and rootless Docker behave the same.
        "--add-host",
        "host.docker.internal:host-gateway",
    ]
    .map(String::from)
    .to_vec();
    let labels = [
        format!("{LABEL_MODE}={}", Mode::Proxy.label()),
        format!("{LABEL_ADDRESS}={address}"),
        format!("{LABEL_PROXY}=127.0.0.1:{proxy_port}"),
        format!("{LABEL_RELAY}={RELAY_VERSION}"),
        node_label(node),
    ];
    for label in labels {
        args.push("--label".to_string());
        args.push(label);
    }
    // tinyproxy only. No broker port: peers come in through the relay, and a
    // 127.0.0.1:9000 publish is what took 9000 from the agent's broker.
    args.push("-p".to_string());
    args.push(format!("127.0.0.1:{proxy_port}:8888"));
    args.extend(["alpine", "sh", "-c", run_cmd].map(String::from));
    args
}

#[derive(Default)]
pub struct DockerConnector;

/// How the helper container carries the tunnel. See the module docs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mode {
    HostNet,
    Proxy,
}

impl Mode {
    fn label(self) -> &'static str {
        match self {
            Mode::HostNet => "hostnet",
            Mode::Proxy => "proxy",
        }
    }
    fn parse(s: &str) -> Option<Mode> {
        match s.trim() {
            "hostnet" => Some(Mode::HostNet),
            "proxy" => Some(Mode::Proxy),
            _ => None,
        }
    }
}

/// Pure mode decision. `hostnet` is only possible where the kernel module is
/// present (Linux); `ZAKURO_WG_DOCKER_MODE=proxy|hostnet` forces either way so
/// an operator can pin the old behaviour if a host's Docker cannot share the
/// host netns (rootless daemons).
pub(crate) fn choose_mode(env_override: Option<&str>, kernel_wg: bool, linux: bool) -> Mode {
    match env_override.map(str::trim) {
        Some("proxy") => Mode::Proxy,
        Some("hostnet") => Mode::HostNet,
        _ => {
            if linux && kernel_wg {
                Mode::HostNet
            } else {
                Mode::Proxy
            }
        }
    }
}

fn kernel_wireguard_present() -> bool {
    std::path::Path::new("/sys/module/wireguard").exists()
}

fn preferred_mode() -> Mode {
    choose_mode(
        std::env::var("ZAKURO_WG_DOCKER_MODE").ok().as_deref(),
        kernel_wireguard_present(),
        cfg!(target_os = "linux"),
    )
}

/// First bindable port in 18888..18899 (loopback only).
pub(crate) fn pick_proxy_port() -> Option<u16> {
    (18888..18899).find(|p| std::net::TcpListener::bind(("127.0.0.1", *p)).is_ok())
}

/// Parse `wg show <iface> latest-handshakes` output into unix-secs values.
/// Each line is "<pubkey>\t<unix_secs>"; 0 means "no handshake yet".
fn parse_handshakes(out: &str) -> Vec<u64> {
    out.lines()
        .filter_map(|l| l.split_whitespace().nth(1))
        .filter_map(|s| s.parse::<u64>().ok())
        .collect()
}

fn docker(args: &[&str]) -> Result<String, NetError> {
    crate::vpn::host_ops_allowed(&format!("docker {}", args.first().copied().unwrap_or("")))?;
    crate::vpn::vlog(&format!("docker {}", args.join(" ")));
    let out = Command::new("docker")
        .args(args)
        .output()
        .map_err(|e| NetError::Backend(format!("docker: {}", e)))?;
    if out.status.success() {
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    } else {
        Err(NetError::Backend(
            String::from_utf8_lossy(&out.stderr).trim().to_string(),
        ))
    }
}

/// The `zakuro0` address as seen from THIS process's netns (host), CIDR-less.
/// `Some` only in hostnet mode (or native); `None` in proxy mode.
fn host_iface_ip() -> Option<String> {
    let all = ifaces::Interface::get_all().ok()?;
    all.into_iter()
        .filter(|i| i.name == IFACE)
        .filter_map(|i| i.addr)
        .map(|a| a.ip().to_string())
        .find(|ip| crate::vpn::is_mesh_ip(ip))
}

/// The error for a failed bring-up: the last line of the container's
/// `wg-quick` log says why. A start script that exited (the proxy script's
/// socat guard) leaves no running container to read that log from, so the
/// last line of its docker logs says why instead.
fn bringup_error(mode: Mode, wglog: &str, dlog: &str) -> NetError {
    fn last(log: &str) -> Option<&str> {
        log.lines().map(str::trim).rfind(|l| !l.is_empty())
    }
    let msg = match (last(wglog), last(dlog)) {
        (Some(detail), _) => format!(
            "tunnel did not come up — wg-quick ({}): {}",
            mode.label(),
            detail
        ),
        (None, Some(detail)) => format!(
            "tunnel did not come up — {SIDECAR} ({}): {}",
            mode.label(),
            detail
        ),
        (None, None) => format!(
            "tunnel did not come up ({} mode; run `zc vpn connect --docker --verbose` for container logs)",
            mode.label()
        ),
    };
    NetError::Backend(msg)
}

impl DockerConnector {
    fn exec_capture(&self, args: &[&str]) -> Result<String, NetError> {
        let mut full = vec!["exec", SIDECAR];
        full.extend_from_slice(args);
        docker(&full)
    }

    fn is_up(&self) -> bool {
        docker(&[
            "ps",
            "--filter",
            &format!("name=^{}$", SIDECAR),
            "--format",
            "{{.Names}}",
        ])
        .map(|s| s.lines().any(|l| l == SIDECAR))
        .unwrap_or(false)
    }

    /// Read the labels stamped at `connect` time. One `docker inspect`.
    pub(crate) fn sidecar_labels(&self) -> Option<SidecarLabels> {
        let format = [
            LABEL_MODE,
            LABEL_ADDRESS,
            LABEL_PROXY,
            LABEL_NODE,
            LABEL_RELAY,
        ]
        .map(|l| format!("{{{{index .Config.Labels \"{l}\"}}}}"))
        .join("|");
        parse_labels(&docker(&["inspect", "-f", &format, SIDECAR]).ok()?)
    }

    /// Read peers from `wg show <iface>` inside the sidecar. Best-effort. Works
    /// in both modes: in hostnet mode the container shares the host netns.
    fn read_peers(&self) -> Vec<PeerStatus> {
        let allowed = self
            .exec_capture(&["wg", "show", IFACE, "allowed-ips"])
            .unwrap_or_default();
        let hs = self
            .exec_capture(&["wg", "show", IFACE, "latest-handshakes"])
            .map(|o| parse_handshakes(&o))
            .unwrap_or_default();
        allowed
            .lines()
            .enumerate()
            .filter_map(|(i, line)| {
                let cidr = line.split_whitespace().nth(1)?;
                let ip = cidr.split('/').next()?.to_string();
                let secs = hs.get(i).copied();
                Some(PeerStatus {
                    ip,
                    last_handshake_secs: secs.filter(|s| *s > 0),
                    reachable: secs.map(|s| s > 0).unwrap_or(false),
                })
            })
            .collect()
    }

    /// Surface WHY a bring-up failed: the container's wg-quick log plus recent
    /// docker logs, then remove the dead container.
    fn fail_bringup(&self, mode: Mode) -> NetError {
        let wglog = self
            .exec_capture(&["cat", "/tmp/wg.log"])
            .unwrap_or_default();
        let dlog = docker(&["logs", "--tail", "30", SIDECAR]).unwrap_or_default();
        if crate::vpn::verbose() {
            for l in wglog.lines() {
                crate::vpn::vlog(&format!("wg.log: {}", l));
            }
            for l in dlog.lines() {
                crate::vpn::vlog(&format!("docker logs: {}", l));
            }
        }
        let _ = docker(&["rm", "-f", SIDECAR]);
        bringup_error(mode, &wglog, &dlog)
    }

    /// hostnet mode: `zakuro0` lands in the HOST netns.
    fn connect_hostnet(
        &self,
        profile: &WgProfile,
        conf_b64: &str,
    ) -> Result<ConnectionInfo, NetError> {
        let address = profile.interface.address.clone();
        // `wg-quick down` + `ip link delete` first: a helper that was removed
        // without disconnecting leaves the host interface behind, and wg-quick
        // refuses to bring up an interface that already exists.
        let run_cmd = format!(
            "apk add -q wireguard-tools iproute2 2>/dev/null; \
             mkdir -p /etc/wireguard; \
             echo '{b64}' | base64 -d > /etc/wireguard/{iface}.conf; \
             chmod 600 /etc/wireguard/{iface}.conf; \
             wg-quick down {iface} >/dev/null 2>&1; \
             ip link delete {iface} >/dev/null 2>&1; \
             wg-quick up {iface} >/tmp/wg.log 2>&1; \
             exec sleep infinity",
            b64 = conf_b64,
            iface = IFACE
        );
        let mode_label = format!("{LABEL_MODE}={}", Mode::HostNet.label());
        let addr_label = format!("{LABEL_ADDRESS}={address}");
        let node = node_label(profile.node.as_deref());
        let args: Vec<&str> = vec![
            "run",
            "-d",
            "--name",
            SIDECAR,
            "--network",
            "host",
            "--cap-add",
            "NET_ADMIN",
            "--label",
            &mode_label,
            "--label",
            &addr_label,
            "--label",
            &node,
            "alpine",
            "sh",
            "-c",
            &run_cmd,
        ];
        docker(&args)?;
        crate::vpn::vlog(&format!(
            "helper {} started (hostnet); waiting for {} in the host netns…",
            SIDECAR, IFACE
        ));
        // apk + wg-quick take a few seconds; the interface appears in OUR netns.
        let mut seen = None;
        for _ in 0..12 {
            if let Some(ip) = host_iface_ip() {
                seen = Some(ip);
                break;
            }
            std::thread::sleep(std::time::Duration::from_secs(2));
        }
        if seen.is_none() {
            return Err(self.fail_bringup(Mode::HostNet));
        }
        let info = ConnectionInfo {
            backend: Backend::Docker,
            address,
            link: SIDECAR.to_string(),
            peers: self.read_peers(),
            host_routable: true,
            proxy: None,
            relay: None,
        };
        crate::vpn::state::save_or_warn(&info);
        Ok(info)
    }

    /// proxy mode: wireguard-go, tinyproxy for outbound CONNECT, and the
    /// inbound relay (see `proxy_start_script`).
    fn connect_proxy(
        &self,
        profile: &WgProfile,
        conf_b64: &str,
    ) -> Result<ConnectionInfo, NetError> {
        let proxy_port = pick_proxy_port()
            .ok_or_else(|| NetError::Backend("no free local port in 18888..18899".into()))?;
        let proxy_addr = format!("127.0.0.1:{}", proxy_port);
        let args = proxy_run_args(
            &profile.interface.address,
            proxy_port,
            profile.node.as_deref(),
            &proxy_start_script(conf_b64),
        );
        docker(&args.iter().map(String::as_str).collect::<Vec<_>>())?;

        crate::vpn::vlog(&format!(
            "sidecar {} started (proxy); waiting for {} to get a mesh address…",
            SIDECAR, IFACE
        ));
        let mut address = String::new();
        for _ in 0..8 {
            if let Ok(a) = self.exec_capture(&["ip", "-4", "addr", "show", IFACE]) {
                if let Some(ip) = a.split_whitespace().skip_while(|t| *t != "inet").nth(1) {
                    address = ip.to_string();
                    break;
                }
            }
            std::thread::sleep(std::time::Duration::from_secs(2));
        }
        if address.is_empty() {
            return Err(self.fail_bringup(Mode::Proxy));
        }
        // The script's socat guard runs before wg-quick, so a mesh address
        // means socat is there and the relay starts right behind it.
        let info = ConnectionInfo {
            backend: Backend::Docker,
            address,
            link: SIDECAR.to_string(),
            peers: self.read_peers(),
            host_routable: false,
            proxy: Some(proxy_addr),
            relay: Some(RELAY_VERSION),
        };
        crate::vpn::state::save_or_warn(&info);
        Ok(info)
    }

    /// Remove a host-netns `zakuro0` left behind by a helper that vanished
    /// without `wg-quick down` (best-effort, one-shot privileged container).
    fn delete_host_iface(&self) {
        if crate::vpn::host_ops_allowed("delete the host zakuro0").is_err() {
            return;
        }
        if host_iface_ip().is_none() {
            return;
        }
        let _ = docker(&[
            "run",
            "--rm",
            "--network",
            "host",
            "--cap-add",
            "NET_ADMIN",
            "alpine",
            "ip",
            "link",
            "delete",
            IFACE,
        ]);
    }
}

impl Connector for DockerConnector {
    fn available(&self) -> bool {
        if crate::vpn::host_ops_allowed("docker info").is_err() {
            return false;
        }
        Command::new("docker")
            .arg("info")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    fn connect(&self, profile: &WgProfile) -> Result<ConnectionInfo, NetError> {
        use base64::Engine;
        let conf_text = profile
            .to_conf()
            .map_err(|e| NetError::Backend(format!("invalid profile: {}", e)))?;
        // Embed the WireGuard conf as base64 in the container's start script rather
        // than bind-mounting it. On Docker Desktop for macOS the host temp dir
        // (/var/folders/…) is NOT a shared path, so `-v <tmp>.conf:/etc/wireguard/…`
        // silently materializes an empty DIRECTORY inside the container — wg-quick
        // then reads a directory ("read error: Is a directory") and never sets the
        // Address. Writing the conf from base64 inside the container avoids the
        // whole file-sharing dependency and works on macOS + Linux.
        let conf_b64 = base64::engine::general_purpose::STANDARD.encode(conf_text.as_bytes());

        let _ = docker(&["rm", "-f", SIDECAR]);
        match preferred_mode() {
            Mode::HostNet => match self.connect_hostnet(profile, &conf_b64) {
                Ok(info) => Ok(info),
                Err(e) => {
                    // Docker that cannot share the host netns (rootless, Desktop
                    // without the module) — fall back to the proxy sidecar so the
                    // user still gets a tunnel, just not a routable host.
                    crate::vpn::vlog(&format!(
                        "hostnet mode failed ({e}); falling back to proxy mode"
                    ));
                    eprintln!(
                        "  ⚠ host-routable tunnel unavailable ({e}); using the proxy sidecar instead"
                    );
                    self.delete_host_iface();
                    self.connect_proxy(profile, &conf_b64)
                }
            },
            Mode::Proxy => self.connect_proxy(profile, &conf_b64),
        }
    }

    fn status(&self) -> Result<Option<ConnectionInfo>, NetError> {
        if !self.is_up() {
            return Ok(None);
        }
        if let Some(saved) = crate::vpn::state::load() {
            // hostnet: the interface must still exist in our netns, otherwise the
            // helper is a zombie and the caller should reconnect.
            if saved.host_routable && host_iface_ip().is_none() {
                return Ok(None);
            }
            return Ok(Some(saved));
        }
        // No state file but a live helper: rebuild from the container labels and
        // re-persist. Tearing a working tunnel down here (the old behaviour via
        // `connect`'s `rm -f`) is exactly what left users "disconnected".
        let Some(labels) = self.sidecar_labels() else {
            return Ok(None);
        };
        let host_routable = match labels.mode {
            Mode::HostNet => host_iface_ip().is_some(),
            Mode::Proxy => false,
        };
        if labels.mode == Mode::HostNet && !host_routable {
            return Ok(None);
        }
        let info = info_from_labels(labels, host_routable, self.read_peers());
        crate::vpn::state::save_or_warn(&info);
        Ok(Some(info))
    }

    fn disconnect(&self) -> Result<(), NetError> {
        // hostnet: take the host interface down through the helper (same netns)
        // BEFORE removing it; otherwise `zakuro0` outlives the container.
        if self.is_up() {
            let _ = self.exec_capture(&["wg-quick", "down", IFACE]);
        }
        let _ = docker(&["rm", "-f", SIDECAR]);
        self.delete_host_iface();
        let _ = crate::vpn::state::clear();
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn picks_a_free_proxy_port_in_range() {
        let p = pick_proxy_port().expect("some port free in 18888..18899");
        assert!((18888..18899).contains(&p));
        // it really is bindable
        std::net::TcpListener::bind(("127.0.0.1", p)).unwrap();
    }

    #[test]
    fn parses_latest_handshakes() {
        let out = "ABCKEY=\t1780820000\nDEFKEY=\t0\n";
        let hs = parse_handshakes(out);
        assert_eq!(hs, vec![1780820000, 0]);
    }

    /// hostnet only where it can work: Linux with the kernel module. Everything
    /// else keeps the proxy sidecar, and the env override wins either way.
    #[test]
    fn mode_selection() {
        assert_eq!(choose_mode(None, true, true), Mode::HostNet);
        assert_eq!(choose_mode(None, false, true), Mode::Proxy);
        assert_eq!(choose_mode(None, true, false), Mode::Proxy);
        assert_eq!(choose_mode(Some("proxy"), true, true), Mode::Proxy);
        assert_eq!(choose_mode(Some("hostnet"), false, false), Mode::HostNet);
        assert_eq!(choose_mode(Some("garbage"), true, true), Mode::HostNet);
    }

    #[test]
    fn mode_labels_roundtrip() {
        for m in [Mode::HostNet, Mode::Proxy] {
            assert_eq!(Mode::parse(m.label()), Some(m));
        }
        assert_eq!(Mode::parse("nope"), None);
    }

    /// zc#211: every `docker` call this backend makes (`ps`, `exec`,
    /// `rm -f zakuro-wg`, the privileged `ip link delete zakuro0`) goes
    /// through `docker()`, which refuses inside the unit-test binary.
    #[test]
    fn docker_is_refused_in_unit_tests() {
        assert!(matches!(docker(&["ps"]), Err(NetError::Refused(_))));
    }

    #[test]
    fn docker_backend_is_unavailable_in_unit_tests() {
        assert!(!DockerConnector.available());
    }

    const FP: &str = "0123456789abcdef";

    /// The values that follow each `flag` in a `docker run` argv.
    fn values_after<'a>(args: &'a [String], flag: &str) -> Vec<&'a str> {
        args.windows(2)
            .filter(|w| w[0] == flag)
            .map(|w| w[1].as_str())
            .collect()
    }

    #[test]
    fn proxy_run_args_publish_only_the_connect_proxy() {
        let args = proxy_run_args("10.13.13.7/24", 18888, Some(FP), "true");
        assert_eq!(
            values_after(&args, "-p"),
            vec!["127.0.0.1:18888:8888"],
            "no broker port: peers come in through the relay"
        );
        assert!(
            !args.iter().any(|a| a.contains("9000")),
            "no 127.0.0.1:9000 publish to take the agent's broker port: {args:?}"
        );
    }

    #[test]
    fn proxy_run_args_reach_the_host_through_host_gateway() {
        let args = proxy_run_args("10.13.13.7/24", 18888, Some(FP), "true");
        assert_eq!(
            values_after(&args, "--add-host"),
            vec!["host.docker.internal:host-gateway"]
        );
    }

    #[test]
    fn proxy_run_args_stamp_the_labels_status_and_connect_read() {
        let args = proxy_run_args("10.13.13.7/24", 18888, Some(FP), "true");
        assert_eq!(
            values_after(&args, "--label"),
            vec![
                "zakuro.mode=proxy",
                "zakuro.address=10.13.13.7/24",
                "zakuro.proxy=127.0.0.1:18888",
                "zakuro.relay=1",
                "zakuro.node=0123456789abcdef",
            ]
        );
        let shared = proxy_run_args("10.13.13.7/24", 18888, None, "true");
        let nodes: Vec<&str> = values_after(&shared, "--label")
            .into_iter()
            .filter(|l| l.starts_with("zakuro.node="))
            .collect();
        assert_eq!(
            nodes,
            vec!["zakuro.node=shared"],
            "a profile the hub didn't make per device is labeled shared, so an older hub \
             doesn't get the sidecar recreated on every connect: {shared:?}"
        );
    }

    #[test]
    fn proxy_run_args_name_the_sidecar_and_end_with_the_script() {
        let args = proxy_run_args("10.13.13.7/24", 18888, Some(FP), "the script");
        assert_eq!(&args[..4], ["run", "-d", "--name", "zakuro-wg"]);
        assert_eq!(
            &args[args.len() - 4..],
            ["alpine", "sh", "-c", "the script"]
        );
    }

    /// Both modes build the label here, so every sidecar zc creates carries one.
    #[test]
    fn node_label_names_the_fingerprint_or_shared() {
        assert_eq!(node_label(Some(FP)), "zakuro.node=0123456789abcdef");
        assert_eq!(node_label(None), "zakuro.node=shared");
        assert_eq!(
            parse_labels("hostnet|10.13.13.7/24||shared")
                .unwrap()
                .node
                .as_deref(),
            Some(NODE_SHARED)
        );
    }

    #[test]
    fn labels_parse_the_node_and_the_relay_version() {
        assert_eq!(
            parse_labels("proxy|10.13.13.7/24|127.0.0.1:18888|0123456789abcdef|1"),
            Some(SidecarLabels {
                mode: Mode::Proxy,
                address: "10.13.13.7/24".into(),
                proxy: Some("127.0.0.1:18888".into()),
                node: Some(FP.into()),
                relay: Some(1),
            })
        );
        assert_eq!(
            parse_labels("proxy|10.13.13.7/24|127.0.0.1:18888|0123456789abcdef|")
                .unwrap()
                .relay,
            None,
            "a sidecar from before the relay"
        );
        assert_eq!(
            parse_labels("proxy|10.13.13.7/24|127.0.0.1:18888||<no value>")
                .unwrap()
                .relay,
            None
        );
    }

    #[test]
    fn labels_from_an_older_sidecar_have_no_node() {
        // `index` on a missing label renders as "" (or "<no value>").
        assert_eq!(
            parse_labels("proxy|10.13.13.7/24|127.0.0.1:18888|")
                .unwrap()
                .node,
            None
        );
        assert_eq!(
            parse_labels("proxy|10.13.13.7/24|127.0.0.1:18888|<no value>")
                .unwrap()
                .node,
            None
        );
        assert_eq!(parse_labels("hostnet|10.13.13.7/24||").unwrap().proxy, None);
        assert_eq!(
            parse_labels("proxy||127.0.0.1:18888|x"),
            None,
            "no address: not a sidecar zc made"
        );
    }

    #[test]
    fn proxy_start_script_relays_9000_through_9010_after_the_tunnel_is_up() {
        let s = proxy_start_script("Q09ORg==");
        assert!(
            s.starts_with("apk add -q wireguard-tools wireguard-go tinyproxy socat "),
            "{s}"
        );
        let up = s.find("wg-quick up zakuro0").expect("the tunnel comes up");
        let relay = s
            .find("socat TCP-LISTEN:$p,bind=$WG_IP,fork,reuseaddr TCP:host.docker.internal:$p")
            .expect("the relay");
        assert!(
            up < relay,
            "the relay binds the mesh address, which exists only once wg-quick is up"
        );
        assert!(
            s.contains("WG_IP=$(ip -4 addr show zakuro0 | awk '/inet /{print $2}' | cut -d/ -f1)"),
            "{s}"
        );
        assert!(
            s.contains("if [ -n \"$WG_IP\" ]; then for p in $(seq 9000 9010); do "),
            "{s}"
        );
        assert!(
            s.contains(">/tmp/relay-$p.log 2>&1 & done; fi; "),
            "each socat runs in the background: {s}"
        );
        assert!(s.ends_with("exec sleep infinity"), "{s}");
    }

    /// `docker run` stamps `zakuro.relay` before the script runs, so without
    /// socat the script stops right after `apk add`: before the tunnel, before
    /// the relay, and never reaching `sleep infinity`.
    #[test]
    fn proxy_start_script_stops_before_the_tunnel_without_socat() {
        let s = proxy_start_script("Q09ORg==");
        let guard = s
            .find(
                "apk add -q wireguard-tools wireguard-go tinyproxy socat 2>/dev/null; \
                   if ! command -v socat >/dev/null 2>&1; then ",
            )
            .expect("the socat guard, right after apk add");
        let bail = s
            .find(" | tee /tmp/wg.log >&2; exit 1; fi; ")
            .expect("the guard says why, in wg.log and the docker logs, then exits non-zero");
        assert!(
            s[guard..bail].contains("echo 'socat did not install"),
            "{s}"
        );
        let up = s.find("wg-quick up zakuro0").unwrap();
        let relay = s.find("for p in $(seq 9000 9010)").unwrap();
        let sleep = s.find("exec sleep infinity").unwrap();
        assert!(guard < bail && bail < up, "no tunnel without socat: {s}");
        assert!(up < relay && relay < sleep, "{s}");
    }

    /// `status()` rewrites `connection.json` from the labels, relay included,
    /// so `vpn::route()` reads the same relay bit `connect_proxy` recorded.
    #[test]
    fn a_connection_rebuilt_from_the_labels_records_the_relay() {
        let current =
            parse_labels("proxy|10.13.13.7/24|127.0.0.1:18888|0123456789abcdef|1").unwrap();
        let info = info_from_labels(current.clone(), false, vec![]);
        assert_eq!(info.relay, Some(RELAY_VERSION));
        assert_eq!(info.proxy.as_deref(), Some("127.0.0.1:18888"));
        assert_eq!(
            (info.address.as_str(), info.link.as_str()),
            ("10.13.13.7/24", "zakuro-wg")
        );
        let old = SidecarLabels {
            relay: None,
            ..current.clone()
        };
        assert_eq!(
            info_from_labels(old, false, vec![]).relay,
            None,
            "a sidecar from before the relay"
        );
        let hostnet = SidecarLabels {
            mode: Mode::HostNet,
            ..current
        };
        let info = info_from_labels(hostnet, true, vec![]);
        assert_eq!(
            (info.proxy, info.relay),
            (None, None),
            "hostnet has no proxy and no relay"
        );
    }

    #[test]
    fn a_failed_bringup_says_why() {
        let socat = bringup_error(
            Mode::Proxy,
            "",
            "socat did not install, so the mesh relay cannot run\n",
        )
        .to_string();
        assert!(
            socat.contains("zakuro-wg (proxy): socat did not install"),
            "an exited container's docker logs say why: {socat}"
        );
        let wg = bringup_error(
            Mode::Proxy,
            "[#] ip link add zakuro0 type wireguard\nRTNETLINK answers: Operation not permitted\n\n",
            "ip: can't find device 'zakuro0'\n",
        )
        .to_string();
        assert!(
            wg.contains("wg-quick (proxy): RTNETLINK answers: Operation not permitted"),
            "wg-quick's own log wins: {wg}"
        );
        let silent = bringup_error(Mode::HostNet, "", "").to_string();
        assert!(silent.contains("hostnet mode; run"), "{silent}");
    }
}