shadowvpn 0.6.0

A UDP-based, pre-shared-key (PSK), user-mode VPN using the shadowsocks AEAD UDP wire scheme.
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
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
//! Point the system resolver at the split-DNS proxy — and put it back on exit.
//!
//! For policy routing to take effect, name lookups must go through the proxy
//! (that is what installs the per-destination routes). [`apply`] configures the
//! OS resolver to do that and returns a [`DnsGuard`] that restores the previous
//! configuration when dropped:
//!
//! * **macOS** — `networksetup -setdnsservers <primary-service> <proxy-ip>`,
//!   remembering and restoring the service's previous servers.
//! * **Linux** — rewrite `/etc/resolv.conf` to `nameserver <proxy-ip>`,
//!   remembering the previous file (or symlink) and restoring it.
//! * **Windows** — `netsh interface ipv4 set dnsservers <primary-iface> static
//!   <proxy-ip>`, remembering whether the interface used DHCP or a static list
//!   and restoring it.
//!
//! The OS resolver can only point at an address, not a port, so this is only
//! applied when the proxy listens on port 53; otherwise it is skipped with a
//! warning and the operator must configure DNS themselves.
//!
//! # Crash recovery (the restore journal)
//!
//! The pre-`apply` configuration is persisted to a journal file
//! ([`JOURNAL_FILE_NAME`], next to the running binary — same convention as the
//! DNS cache) *before* the resolver is touched, and removed again after a
//! successful restore. If the process dies without restoring (SIGKILL, a
//! panic-abort, power loss), the journal survives and the original
//! configuration is recovered by whichever of these happens first:
//!
//! * the next [`apply`] (e.g. the desktop app auto-reconnecting) restores the
//!   journal *before* reading the "previous" configuration — without this, the
//!   dead run's proxy address would be recorded as the value to restore,
//!   wedging DNS permanently even across later clean exits;
//! * [`restore_from_journal`] (the client's `--restore-dns` flag), which the
//!   desktop app runs through its elevated helper when it sees a leftover
//!   journal with no client running.

use std::net::IpAddr;
use std::path::PathBuf;

use anyhow::{Context, Result};
use log::{info, warn};

/// Journal file recording the resolver configuration to restore; lives next to
/// the running binary (like the DNS cache) so it survives reboots and is found
/// again by any later invocation of the same binary.
///
/// The desktop app hard-codes the same name to detect a leftover journal
/// (`reconnect::maybe_restore_dns`); keep the two in sync.
pub const JOURNAL_FILE_NAME: &str = "dns-restore.json";

/// Restores the previous system DNS configuration when dropped.
pub struct DnsGuard {
    restore: imp::Restore,
}

impl Drop for DnsGuard {
    fn drop(&mut self) {
        if imp::restore(&self.restore) {
            remove_journal();
            info!("system resolver restored");
        } else {
            warn!(
                "failed to restore the system resolver; keeping {} so a later \
                 `shadowvpn-client --restore-dns` can retry",
                journal_path().display()
            );
        }
    }
}

/// Point the system resolver at `proxy` (the proxy's listen address).
///
/// `direct_src` is the host's physical source address (the local IP of the
/// socket connected to the server); on Windows it identifies the interface whose
/// DNS to reconfigure. Ignored on other platforms.
///
/// Returns `Ok(None)` (with a warning) if the port is not 53, since the OS
/// resolver cannot target a custom port. On success the returned guard restores
/// the prior configuration on drop.
pub fn apply(proxy: IpAddr, port: u16, direct_src: IpAddr) -> Result<Option<DnsGuard>> {
    if port != 53 {
        warn!(
            "not setting the system resolver automatically: proxy port is {port}, but the OS \
             resolver only supports port 53 — point DNS at {proxy} (port 53) yourself, or set \
             dns_listen to a :53 address"
        );
        return Ok(None);
    }

    // Self-heal: a journal here means a previous run died without restoring,
    // so the resolver may still point at that run's (now dead) proxy. Put the
    // original configuration back BEFORE snapshotting the current one below —
    // otherwise our own proxy address would be recorded as the thing to
    // "restore" on exit.
    if let Some(stale) = read_journal() {
        warn!(
            "found a DNS restore journal from a run that did not exit cleanly; restoring the \
             original resolver configuration before applying"
        );
        if !imp::restore(&stale) {
            warn!("could not restore from the stale journal; continuing");
        }
        remove_journal();
    }

    let restore = imp::snapshot(proxy, direct_src)?;
    // Persist the restore state before touching the resolver, so a crash at
    // any later point can always be recovered from disk.
    if let Err(e) = write_journal(&restore) {
        warn!(
            "could not write the DNS restore journal ({e}); if this run dies without cleaning \
             up, the resolver will stay pointed at {proxy} until the next connect"
        );
    }
    imp::engage(&restore, proxy)?;
    info!("system resolver pointed at {proxy} (restored automatically on exit)");
    Ok(Some(DnsGuard { restore }))
}

/// Restore the system resolver from a journal left behind by a run that died
/// without cleaning up (the client's `--restore-dns` mode).
///
/// Returns `true` if a journal was found and applied, `false` if there was
/// nothing to do.
pub fn restore_from_journal() -> Result<bool> {
    let Some(restore) = read_journal() else {
        return Ok(false);
    };
    if !imp::restore(&restore) {
        anyhow::bail!(
            "failed to restore the resolver configuration recorded in {}",
            journal_path().display()
        );
    }
    remove_journal();
    info!("system resolver restored from journal");
    Ok(true)
}

fn journal_path() -> PathBuf {
    std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
        .unwrap_or_else(|| PathBuf::from("."))
        .join(JOURNAL_FILE_NAME)
}

fn read_journal() -> Option<imp::Restore> {
    let path = journal_path();
    let data = std::fs::read(&path).ok()?;
    match serde_json::from_slice(&data) {
        Ok(r) => Some(r),
        Err(e) => {
            // Unparseable (a future format, manual edits): there is nothing to
            // recover from it, and leaving it would re-warn on every start.
            warn!(
                "ignoring unreadable DNS restore journal {}: {e}",
                path.display()
            );
            let _ = std::fs::remove_file(&path);
            None
        }
    }
}

/// Write the journal atomically (tmp file + rename) so a crash mid-write can
/// never leave a truncated file behind.
fn write_journal(restore: &imp::Restore) -> Result<()> {
    let path = journal_path();
    let tmp = path.with_extension("json.tmp");
    let data = serde_json::to_vec_pretty(restore).context("serializing the restore state")?;
    std::fs::write(&tmp, data).with_context(|| format!("writing {}", tmp.display()))?;
    std::fs::rename(&tmp, &path).with_context(|| format!("renaming into {}", path.display()))?;
    Ok(())
}

fn remove_journal() {
    let _ = std::fs::remove_file(journal_path());
}

// ---------------------------------------------------------------------------
// macOS / BSD: networksetup on the primary network service.
// ---------------------------------------------------------------------------
#[cfg(any(target_os = "macos", target_os = "ios"))]
mod imp {
    use super::*;
    use anyhow::{bail, Context};
    use serde::{Deserialize, Serialize};
    use std::process::Command;

    /// What to put back: the service and its previous DNS servers (empty = none).
    #[derive(Serialize, Deserialize)]
    pub struct Restore {
        service: String,
        prev: Vec<String>,
    }

    pub fn snapshot(proxy: IpAddr, direct_src: IpAddr) -> Result<Restore> {
        let _ = direct_src; // macOS finds the primary service via the route table
        let service = primary_service()
            .context("could not determine the primary network service to configure DNS on")?;
        let prev = sanitize_prev(get_dns(&service), proxy);
        Ok(Restore { service, prev })
    }

    pub fn engage(r: &Restore, proxy: IpAddr) -> Result<()> {
        set_dns(&r.service, &[proxy.to_string()])?;
        flush();
        Ok(())
    }

    pub fn restore(r: &Restore) -> bool {
        // `empty` clears all DNS servers for the service.
        let servers: Vec<String> = if r.prev.is_empty() {
            vec!["empty".to_string()]
        } else {
            r.prev.clone()
        };
        let ok = match set_dns(&r.service, &servers) {
            Ok(()) => true,
            Err(e) => {
                warn!("restoring DNS on service '{}': {e}", r.service);
                false
            }
        };
        flush();
        ok
    }

    /// Belt-and-braces for a poisoned snapshot with no journal to explain it
    /// (e.g. a pre-journal build crashed here): the proxy's own address can
    /// never be the configuration to restore, so fall back to "no servers set"
    /// (DHCP-provided DNS).
    fn sanitize_prev(prev: Vec<String>, proxy: IpAddr) -> Vec<String> {
        if prev == [proxy.to_string()] {
            warn!(
                "current DNS ({proxy}) is this proxy itself (left by an earlier run?); will \
                 restore to automatic DNS instead"
            );
            return Vec::new();
        }
        prev
    }

    fn set_dns(service: &str, servers: &[String]) -> Result<()> {
        let mut cmd = Command::new("networksetup");
        cmd.arg("-setdnsservers").arg(service).args(servers);
        let out = cmd
            .output()
            .context("running networksetup -setdnsservers")?;
        if !out.status.success() {
            bail!(
                "networksetup -setdnsservers {service} failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Ok(())
    }

    /// Current DNS servers for a service, or empty if none are set.
    fn get_dns(service: &str) -> Vec<String> {
        let out = match Command::new("networksetup")
            .arg("-getdnsservers")
            .arg(service)
            .output()
        {
            Ok(o) => o,
            Err(_) => return Vec::new(),
        };
        let text = String::from_utf8_lossy(&out.stdout);
        // "There aren't any DNS Servers set on <service>." means none.
        if text.contains("aren't any") {
            return Vec::new();
        }
        text.lines()
            .map(str::trim)
            .filter(|l| l.parse::<IpAddr>().is_ok())
            .map(String::from)
            .collect()
    }

    /// Map the default-route interface to its network service name.
    fn primary_service() -> Option<String> {
        let iface = default_iface()?;
        let out = Command::new("networksetup")
            .arg("-listnetworkserviceorder")
            .output()
            .ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        // Blocks look like:
        //   (1) Ethernet
        //   (Hardware Port: Ethernet, Device: en0)
        let mut current: Option<String> = None;
        for line in text.lines() {
            let t = line.trim();
            if let Some(rest) = t.strip_prefix('(') {
                if let Some((num, name)) = rest.split_once(')') {
                    if num.chars().all(|c| c.is_ascii_digit()) {
                        current = Some(name.trim().to_string());
                        continue;
                    }
                }
            }
            if t.contains(&format!("Device: {iface})")) {
                return current.take();
            }
        }
        None
    }

    /// Interface carrying the default route, e.g. `en0`.
    fn default_iface() -> Option<String> {
        let out = Command::new("route")
            .args(["-n", "get", "default"])
            .output()
            .ok()?;
        String::from_utf8_lossy(&out.stdout).lines().find_map(|l| {
            l.trim()
                .strip_prefix("interface:")
                .map(|s| s.trim().to_string())
        })
    }

    fn flush() {
        let _ = Command::new("dscacheutil").arg("-flushcache").status();
        let _ = Command::new("killall")
            .args(["-HUP", "mDNSResponder"])
            .status();
    }

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

        #[test]
        fn sanitize_drops_own_proxy_address() {
            let proxy: IpAddr = "127.0.0.1".parse().unwrap();
            assert!(sanitize_prev(vec!["127.0.0.1".to_string()], proxy).is_empty());
            // A real upstream list is kept, even one containing the proxy
            // among others (someone's deliberate config).
            let mixed = vec!["127.0.0.1".to_string(), "1.1.1.1".to_string()];
            assert_eq!(sanitize_prev(mixed.clone(), proxy), mixed);
            let real = vec!["192.168.0.1".to_string()];
            assert_eq!(sanitize_prev(real.clone(), proxy), real);
        }

        #[test]
        fn restore_journal_round_trips() {
            let r = Restore {
                service: "Wi-Fi".to_string(),
                prev: vec!["192.168.0.1".to_string(), "8.8.8.8".to_string()],
            };
            let json = serde_json::to_string(&r).unwrap();
            let back: Restore = serde_json::from_str(&json).unwrap();
            assert_eq!(back.service, r.service);
            assert_eq!(back.prev, r.prev);
        }
    }
}

// ---------------------------------------------------------------------------
// Linux: rewrite /etc/resolv.conf, remembering the previous file/symlink.
// ---------------------------------------------------------------------------
#[cfg(target_os = "linux")]
mod imp {
    use super::*;
    use anyhow::Context;
    use serde::{Deserialize, Serialize};
    use std::fs;
    use std::os::unix::fs::symlink;
    use std::path::PathBuf;

    const PATH: &str = "/etc/resolv.conf";

    /// First line of the resolv.conf we write; identifies our own leftovers.
    const MARKER: &str = "# shadowvpn split-DNS";

    /// What `/etc/resolv.conf` was before we changed it.
    #[derive(Serialize, Deserialize)]
    pub enum Restore {
        /// It was a symlink to this target.
        Symlink(PathBuf),
        /// It was a regular file with these bytes.
        File(Vec<u8>),
        /// It did not exist.
        Absent,
    }

    pub fn snapshot(proxy: IpAddr, direct_src: IpAddr) -> Result<Restore> {
        let _ = proxy;
        let _ = direct_src; // Linux rewrites the global /etc/resolv.conf
        Ok(match fs::symlink_metadata(PATH) {
            Ok(m) if m.file_type().is_symlink() => {
                let target = fs::read_link(PATH).context("reading resolv.conf symlink")?;
                Restore::Symlink(target)
            }
            Ok(_) => {
                let content = fs::read(PATH).unwrap_or_default();
                if content.starts_with(MARKER.as_bytes()) {
                    // Our own file, left by a pre-journal build's crash: never
                    // the thing to restore. Removing it on restore lets the
                    // network manager / resolver daemon regenerate the real one.
                    warn!(
                        "current /etc/resolv.conf was written by a previous shadowvpn run; it \
                         will be removed on restore so the resolver daemon can regenerate it"
                    );
                    Restore::Absent
                } else {
                    Restore::File(content)
                }
            }
            Err(_) => Restore::Absent,
        })
    }

    pub fn engage(r: &Restore, proxy: IpAddr) -> Result<()> {
        let _ = r;
        // Remove first: writing through a symlink would clobber its target
        // (e.g. systemd-resolved's stub file), and replacing the symlink with
        // a regular file also stops a resolver daemon from overwriting us.
        let _ = fs::remove_file(PATH);
        fs::write(PATH, format!("{MARKER}\nnameserver {proxy}\n"))
            .context("writing /etc/resolv.conf")?;
        Ok(())
    }

    pub fn restore(r: &Restore) -> bool {
        match r {
            Restore::Symlink(target) => {
                let _ = fs::remove_file(PATH);
                symlink(target, PATH).is_ok()
            }
            Restore::File(content) => fs::write(PATH, content).is_ok(),
            Restore::Absent => {
                let _ = fs::remove_file(PATH);
                true
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Windows: point the primary interface's resolver at the proxy via `netsh`.
// ---------------------------------------------------------------------------
#[cfg(windows)]
mod imp {
    use super::*;
    use anyhow::{bail, Context};
    use serde::{Deserialize, Serialize};
    use std::io;
    use std::process::Command;

    /// What to put back when we exit: either the interface used DHCP-assigned
    /// DNS, or it had this explicit list of static servers.
    #[derive(Serialize, Deserialize)]
    pub enum Restore {
        Dhcp { alias: String },
        Static { alias: String, servers: Vec<String> },
    }

    pub fn snapshot(proxy: IpAddr, direct_src: IpAddr) -> Result<Restore> {
        let alias = primary_alias(direct_src)
            .context("could not determine the primary network interface to configure DNS on")?;
        Ok(sanitize(read_current(&alias), proxy))
    }

    pub fn engage(r: &Restore, proxy: IpAddr) -> Result<()> {
        let alias = match r {
            Restore::Dhcp { alias } | Restore::Static { alias, .. } => alias,
        };
        set_static(alias, &[proxy.to_string()])?;
        flush();
        Ok(())
    }

    pub fn restore(r: &Restore) -> bool {
        let ok = match r {
            Restore::Dhcp { alias } => netsh(&[
                "interface",
                "ipv4",
                "set",
                "dnsservers",
                &name_arg(alias),
                "dhcp",
            ])
            .map(|o| o.status.success())
            .unwrap_or(false),
            Restore::Static { alias, servers } => set_static(alias, servers).is_ok(),
        };
        flush();
        ok
    }

    /// Belt-and-braces for a poisoned snapshot with no journal to explain it
    /// (e.g. a pre-journal build crashed here): the proxy's own address can
    /// never be the configuration to restore, so fall back to DHCP DNS.
    fn sanitize(r: Restore, proxy: IpAddr) -> Restore {
        match r {
            Restore::Static { alias, servers } if servers == [proxy.to_string()] => {
                warn!(
                    "current DNS ({proxy}) is this proxy itself (left by an earlier run?); \
                     will restore to DHCP DNS instead"
                );
                Restore::Dhcp { alias }
            }
            other => other,
        }
    }

    /// The alias of the interface to reconfigure DNS on.
    ///
    /// Preferred: the interface that owns `direct_src` (the physical source
    /// address used to reach the server) — deterministic and unaffected by the
    /// route-table churn that accompanies the tun coming up. Falls back to the
    /// interface carrying the default route if `direct_src` can't be matched.
    fn primary_alias(direct_src: IpAddr) -> Option<String> {
        if !direct_src.is_unspecified() {
            if let Some(alias) = interface_for_ip(direct_src) {
                return Some(alias);
            }
        }
        default_route_alias()
    }

    /// Find the interface whose configured address is `ip` by scanning
    /// `netsh interface ipv4 show addresses` (no PowerShell dependency). Output:
    ///   Configuration for interface "Ethernet"
    ///       IP Address:                           192.168.0.109
    fn interface_for_ip(ip: IpAddr) -> Option<String> {
        let out = netsh(&["interface", "ipv4", "show", "addresses"]).ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        let want = ip.to_string();
        let mut current: Option<String> = None;
        for line in text.lines() {
            let t = line.trim();
            if let Some(rest) = t.strip_prefix("Configuration for interface ") {
                current = Some(rest.trim().trim_matches('"').to_string());
            } else if t.split_whitespace().any(|tok| tok == want) {
                if let Some(name) = current.as_ref() {
                    return Some(name.clone());
                }
            }
        }
        None
    }

    /// The alias of the interface carrying the (lowest-metric) default route.
    fn default_route_alias() -> Option<String> {
        let out = Command::new("powershell")
            .args([
                "-NoProfile",
                "-NonInteractive",
                "-Command",
                "Get-NetRoute -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue | \
                 Sort-Object RouteMetric | Select-Object -First 1 -ExpandProperty InterfaceAlias",
            ])
            .output()
            .ok()?;
        let alias = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if alias.is_empty() {
            None
        } else {
            Some(alias)
        }
    }

    /// Inspect an interface's current IPv4 DNS configuration so it can be
    /// restored later: DHCP, or a static list of servers.
    fn read_current(alias: &str) -> Restore {
        let out = netsh(&["interface", "ipv4", "show", "dnsservers", &name_arg(alias)]);
        let text = out
            .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
            .unwrap_or_default();

        // netsh prints "DNS servers configured through DHCP" for DHCP, or
        // "Statically Configured DNS Servers". The first server shares the label
        // line and the rest are indented one per line, so scan every whitespace
        // token for IPs rather than parsing whole lines.
        if text.contains("through DHCP") {
            return Restore::Dhcp {
                alias: alias.to_string(),
            };
        }
        let servers: Vec<String> = text
            .split_whitespace()
            .filter_map(|tok| tok.parse::<IpAddr>().ok().map(|ip| ip.to_string()))
            .collect();
        if servers.is_empty() {
            // No static servers and not flagged DHCP: safest is to clear to DHCP.
            Restore::Dhcp {
                alias: alias.to_string(),
            }
        } else {
            Restore::Static {
                alias: alias.to_string(),
                servers,
            }
        }
    }

    /// Replace an interface's IPv4 DNS servers with `servers` (first = primary).
    fn set_static(alias: &str, servers: &[String]) -> Result<()> {
        let (first, rest) = servers
            .split_first()
            .context("refusing to set an empty DNS server list")?;
        run_checked(&[
            "interface",
            "ipv4",
            "set",
            "dnsservers",
            &name_arg(alias),
            "static",
            first,
            "primary",
            "validate=no",
        ])?;
        for (i, srv) in rest.iter().enumerate() {
            run_checked(&[
                "interface",
                "ipv4",
                "add",
                "dnsservers",
                &name_arg(alias),
                srv,
                &format!("index={}", i + 2),
                "validate=no",
            ])?;
        }
        Ok(())
    }

    /// `name="<alias>"` argument for netsh (quoting handled by the OS, not a shell).
    fn name_arg(alias: &str) -> String {
        format!("name={alias}")
    }

    fn netsh(args: &[&str]) -> io::Result<std::process::Output> {
        Command::new("netsh").args(args).output()
    }

    fn run_checked(args: &[&str]) -> Result<()> {
        let out = netsh(args).context("running netsh")?;
        if !out.status.success() {
            bail!(
                "netsh {} failed: {}",
                args.join(" "),
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        Ok(())
    }

    fn flush() {
        let _ = Command::new("ipconfig").arg("/flushdns").status();
    }
}

// ---------------------------------------------------------------------------
// Other platforms: unsupported.
// ---------------------------------------------------------------------------
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "ios", windows)))]
mod imp {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    pub struct Restore;

    pub fn snapshot(_proxy: IpAddr, _direct_src: IpAddr) -> Result<Restore> {
        anyhow::bail!("automatic DNS configuration is not supported on this platform")
    }

    pub fn engage(_r: &Restore, _proxy: IpAddr) -> Result<()> {
        Ok(())
    }

    pub fn restore(_r: &Restore) -> bool {
        true
    }
}