shadowvpn 0.1.1

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
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
//! Configuration for the ShadowVPN server and client.
//!
//! Configuration can come from a JSON file ([`FileConfig`], loaded with
//! [`FileConfig::load`]) and/or from command-line flags ([`ServerArgs`] /
//! [`ClientArgs`], parsed with `clap`). The binaries call
//! [`ServerArgs::resolve`] / [`ClientArgs::resolve`] to merge the two into a
//! fully validated [`ServerConfig`] / [`ClientConfig`], where CLI flags take
//! precedence over file values.
//!
//! # Example JSON
//!
//! ```json
//! {
//!   "server": "0.0.0.0:8388",
//!   "password": "correct horse battery staple",
//!   "cipher": "chacha20-poly1305",
//!   "tun_name": "utun7",
//!   "tun_ip": "10.9.0.1",
//!   "tun_netmask": "255.255.255.0",
//!   "peer_ip": "10.9.0.2",
//!   "mtu": 1400
//! }
//! ```

use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use std::time::Duration;

use clap::Parser;
use serde::{Deserialize, Serialize};

use crate::crypto::Cipher;
use crate::policy::{Mode, PolicyConfig};
use crate::protocol::DEFAULT_TUN_MTU;

/// Default cipher used when none is specified.
pub const DEFAULT_CIPHER: &str = "chacha20-poly1305";

/// Default TUN netmask (a /24).
pub const DEFAULT_NETMASK: Ipv4Addr = Ipv4Addr::new(255, 255, 255, 0);

/// Default address the split-DNS proxy listens on. Port 53 so the client can
/// point the system resolver at it automatically (the client needs root for the
/// TUN anyway, and nothing else binds `127.0.0.1:53` by default).
pub const DEFAULT_DNS_LISTEN: &str = "127.0.0.1:53";

/// Default domestic / direct DNS upstream (114DNS).
pub const DEFAULT_DNS_LOCAL: &str = "114.114.114.114:53";

/// Default clean DNS upstream, reached through the tunnel (Google DNS).
pub const DEFAULT_DNS_REMOTE: &str = "8.8.8.8:53";

/// Default GeoIP country code selected for the China set.
pub const DEFAULT_GEOIP_COUNTRY: &str = "CN";

/// Default file name for the persisted DNS cache (placed next to the binary).
pub const DEFAULT_CACHE_FILE_NAME: &str = "dns-cache.json";

/// Default per-query DNS upstream timeout, in milliseconds.
pub const DEFAULT_DNS_TIMEOUT_MS: u64 = 3000;

/// Default idle time-to-live for a client's NAT mapping, in seconds. A mapping
/// is refreshed by any traffic (data or keepalive) from the client and reclaimed
/// once idle for longer than this — comfortably above the client's 25-second
/// keepalive interval.
pub const DEFAULT_LEASE_TTL_SECS: u64 = 120;

/// Errors raised while loading or validating configuration.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    /// The JSON config file could not be read.
    #[error("failed to read config file {path}: {source}")]
    Read {
        /// Path that failed to read.
        path: PathBuf,
        /// Underlying IO error.
        #[source]
        source: std::io::Error,
    },

    /// The JSON config file could not be parsed.
    #[error("failed to parse config file {path}: {source}")]
    Parse {
        /// Path that failed to parse.
        path: PathBuf,
        /// Underlying JSON error.
        #[source]
        source: serde_json::Error,
    },

    /// A required field was missing from both the file and the CLI flags.
    #[error("missing required configuration field: {0}")]
    Missing(&'static str),

    /// The cipher name was not recognized.
    #[error(transparent)]
    Cipher(#[from] crate::crypto::CryptoError),

    /// A policy-routing value was invalid (e.g. an unknown mode).
    #[error(transparent)]
    Policy(#[from] crate::policy::PolicyError),

    /// A field had an invalid value (e.g. an unparsable socket address).
    #[error("invalid value for {field}: {message}")]
    Invalid {
        /// Field name.
        field: &'static str,
        /// Human-readable explanation.
        message: String,
    },
}

/// The JSON config file schema, shared by server and client.
///
/// All fields are optional so that any subset can live in the file and the rest
/// can be supplied on the command line. Field semantics differ slightly between
/// server and client (see [`ServerConfig`] / [`ClientConfig`]).
///
/// `None` fields are omitted on serialization (`skip_serializing_if`) so an
/// exported config — and the `shadowvpn://` URI built from it — stays compact and
/// matches the hand-written configs, which simply leave unused keys out. Missing
/// keys deserialize back to `None`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileConfig {
    /// Server `host:port`. On the server this is the bind/listen address; on
    /// the client this is the remote address to connect to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub server: Option<String>,

    /// Pre-shared password; the AEAD master key is derived from it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,

    /// AEAD cipher name (e.g. `"aes-256-gcm"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cipher: Option<String>,

    /// Optional explicit TUN interface name (e.g. `utun7` / `tun0`). If unset,
    /// the OS picks a name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tun_name: Option<String>,

    /// Local IPv4 address assigned to the TUN interface.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tun_ip: Option<Ipv4Addr>,

    /// IPv4 netmask for the TUN interface.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tun_netmask: Option<Ipv4Addr>,

    /// Peer / point-to-point destination IPv4 address inside the tunnel.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub peer_ip: Option<Ipv4Addr>,

    /// TUN interface MTU.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mtu: Option<u16>,

    /// Carrier obfuscation: `"none"` (default), `"quic"` (wrap datagrams to
    /// look like QUIC/HTTP3 short-header packets), or `"base64"` (printable
    /// ASCII payload). Must match the other end.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub obfs: Option<String>,

    /// Server-only: NAT multiple clients (each identified by its UDP endpoint)
    /// onto distinct internal IPs from the TUN subnet, so every client can share
    /// one static config. Ignored by the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nat: Option<bool>,

    /// Server-only: idle time-to-live for a client's NAT mapping, in seconds
    /// (default [`DEFAULT_LEASE_TTL_SECS`]). Ignored by the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lease_ttl_secs: Option<u64>,

    // --- Client-only policy routing (ignored by the server) ----------------
    /// Policy-routing mode: `full` (default), `gfwlist`, or `chinadns`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,

    /// Address the split-DNS proxy listens on.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_listen: Option<String>,

    /// Domestic / direct DNS upstream.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_local: Option<String>,

    /// Clean DNS upstream (reached through the tunnel).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_remote: Option<String>,

    /// Path to the gfwlist domain file (gfwlist mode).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gfwlist: Option<PathBuf>,

    /// Path to the China route (CIDR) file (chinadns mode).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chnroute: Option<PathBuf>,

    /// Path to a GeoLite2/GeoIP2 country database (chinadns mode); when set, the
    /// China set is built from it instead of `chnroute`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geoip: Option<PathBuf>,

    /// ISO 3166-1 alpha-2 country code to select from the GeoIP database.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geoip_country: Option<String>,

    /// Whether to point the system resolver at the proxy automatically
    /// (default `true` in gfwlist/chinadns mode).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub set_dns: Option<bool>,

    /// Domains to pre-resolve into the cache on startup. Absent uses a built-in
    /// list of common domains; an empty list disables pre-warming.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prewarm: Option<Vec<String>>,

    /// Where to persist the DNS cache across restarts. Absent uses the default
    /// path; set to disable via `--no-cache-persist`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_file: Option<String>,

    /// Per-query DNS upstream timeout, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_timeout_ms: Option<u64>,
}

impl FileConfig {
    /// Load and parse a JSON config file from `path`.
    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        let bytes = std::fs::read(path).map_err(|source| ConfigError::Read {
            path: path.to_path_buf(),
            source,
        })?;
        serde_json::from_slice(&bytes).map_err(|source| ConfigError::Parse {
            path: path.to_path_buf(),
            source,
        })
    }
}

/// Settings for the TUN interface, resolved and validated.
#[derive(Debug, Clone)]
pub struct TunConfig {
    /// Explicit interface name, or `None` to let the OS choose.
    pub name: Option<String>,
    /// Local IPv4 address on the interface.
    pub ip: Ipv4Addr,
    /// IPv4 netmask.
    pub netmask: Ipv4Addr,
    /// Peer / point-to-point destination address inside the tunnel.
    pub peer_ip: Ipv4Addr,
    /// Interface MTU.
    pub mtu: u16,
}

/// Fully resolved, validated server configuration.
#[derive(Debug, Clone)]
pub struct ServerConfig {
    /// Address to bind the UDP socket to (`host:port`).
    pub listen: String,
    /// Negotiated AEAD cipher.
    pub cipher: Cipher,
    /// `EVP_BytesToKey`-derived master key (length == `cipher.key_len()`).
    pub master_key: Vec<u8>,
    /// TUN interface settings.
    pub tun: TunConfig,
    /// Carrier obfuscation name (`"quic"` | `"base64"`), or `None` for plain.
    pub obfs: Option<String>,
    /// NAT multiple clients onto distinct internal IPs (keyed by UDP endpoint).
    pub nat: bool,
    /// Idle time-to-live for a client's NAT mapping (reclamation threshold).
    pub lease_ttl: Duration,
}

/// Fully resolved, validated client configuration.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Remote server address to send to (`host:port`).
    pub server: String,
    /// Negotiated AEAD cipher.
    pub cipher: Cipher,
    /// `EVP_BytesToKey`-derived master key (length == `cipher.key_len()`).
    pub master_key: Vec<u8>,
    /// TUN interface settings.
    pub tun: TunConfig,
    /// Policy-routing settings (mode `full` means no policy routing).
    pub policy: PolicyConfig,
    /// Carrier obfuscation name (`"quic"` | `"base64"`), or `None` for plain.
    /// Must match the server.
    pub obfs: Option<String>,
}

/// Command-line arguments for `shadowvpn-server`.
///
/// Every option overrides the corresponding JSON field when present.
#[derive(Debug, Clone, Parser)]
#[command(
    name = "shadowvpn-server",
    about = "ShadowVPN server: terminates the encrypted UDP tunnel onto a TUN device."
)]
pub struct ServerArgs {
    /// Path to a JSON config file. CLI flags override its values.
    #[arg(short = 'c', long = "config")]
    pub config: Option<PathBuf>,

    /// UDP address to listen on, e.g. `0.0.0.0:8388`.
    #[arg(short = 'l', long = "listen")]
    pub listen: Option<String>,

    /// Pre-shared password.
    #[arg(short = 'k', long = "password")]
    pub password: Option<String>,

    /// AEAD cipher: aes-128-gcm | aes-256-gcm | chacha20-poly1305.
    #[arg(short = 'm', long = "cipher")]
    pub cipher: Option<String>,

    /// Explicit TUN interface name.
    #[arg(long = "tun-name")]
    pub tun_name: Option<String>,

    /// Local IPv4 address for the TUN interface.
    #[arg(long = "tun-ip")]
    pub tun_ip: Option<Ipv4Addr>,

    /// IPv4 netmask for the TUN interface.
    #[arg(long = "tun-netmask")]
    pub tun_netmask: Option<Ipv4Addr>,

    /// Peer (client) IPv4 address inside the tunnel.
    #[arg(long = "peer-ip")]
    pub peer_ip: Option<Ipv4Addr>,

    /// TUN interface MTU.
    #[arg(long = "mtu")]
    pub mtu: Option<u16>,

    /// NAT multiple clients (by UDP endpoint) onto distinct internal IPs so they
    /// can share one static config.
    #[arg(long = "nat")]
    pub nat: bool,

    /// Idle time-to-live for a client's NAT mapping, in seconds.
    #[arg(long = "lease-ttl-secs")]
    pub lease_ttl_secs: Option<u64>,
}

/// Command-line arguments for `shadowvpn-client`.
///
/// Every option overrides the corresponding JSON field when present.
#[derive(Debug, Clone, Parser)]
#[command(
    name = "shadowvpn-client",
    about = "ShadowVPN client: tunnels TUN traffic to the server over encrypted UDP."
)]
pub struct ClientArgs {
    /// Path to a JSON config file. CLI flags override its values.
    #[arg(short = 'c', long = "config")]
    pub config: Option<PathBuf>,

    /// Remote server address to connect to, e.g. `vpn.example.com:8388`.
    #[arg(short = 's', long = "server")]
    pub server: Option<String>,

    /// Pre-shared password.
    #[arg(short = 'k', long = "password")]
    pub password: Option<String>,

    /// AEAD cipher: aes-128-gcm | aes-256-gcm | chacha20-poly1305.
    #[arg(short = 'm', long = "cipher")]
    pub cipher: Option<String>,

    /// Explicit TUN interface name.
    #[arg(long = "tun-name")]
    pub tun_name: Option<String>,

    /// Local IPv4 address for the TUN interface.
    #[arg(long = "tun-ip")]
    pub tun_ip: Option<Ipv4Addr>,

    /// IPv4 netmask for the TUN interface.
    #[arg(long = "tun-netmask")]
    pub tun_netmask: Option<Ipv4Addr>,

    /// Peer (server) IPv4 address inside the tunnel.
    #[arg(long = "peer-ip")]
    pub peer_ip: Option<Ipv4Addr>,

    /// TUN interface MTU.
    #[arg(long = "mtu")]
    pub mtu: Option<u16>,

    /// Policy-routing mode: full | gfwlist | chinadns.
    #[arg(long = "mode")]
    pub mode: Option<String>,

    /// Address for the split-DNS proxy to listen on.
    #[arg(long = "dns-listen")]
    pub dns_listen: Option<String>,

    /// Domestic / direct DNS upstream.
    #[arg(long = "dns-local")]
    pub dns_local: Option<String>,

    /// Clean DNS upstream (reached through the tunnel).
    #[arg(long = "dns-remote")]
    pub dns_remote: Option<String>,

    /// Path to the gfwlist domain file (gfwlist mode).
    #[arg(long = "gfwlist")]
    pub gfwlist: Option<PathBuf>,

    /// Path to the China route (CIDR) file (chinadns mode).
    #[arg(long = "chnroute")]
    pub chnroute: Option<PathBuf>,

    /// Path to a GeoLite2/GeoIP2 country database (chinadns mode).
    #[arg(long = "geoip")]
    pub geoip: Option<PathBuf>,

    /// ISO country code to select from the GeoIP database (default CN).
    #[arg(long = "geoip-country")]
    pub geoip_country: Option<String>,

    /// Point the system resolver at the split-DNS proxy (the default in
    /// gfwlist/chinadns mode).
    #[arg(long = "set-dns")]
    pub set_dns: bool,

    /// Do NOT modify the system resolver; configure DNS yourself.
    #[arg(long = "no-set-dns")]
    pub no_set_dns: bool,

    /// Do NOT pre-resolve common domains into the cache on startup.
    #[arg(long = "no-prewarm")]
    pub no_prewarm: bool,

    /// Path to persist the DNS cache across restarts.
    #[arg(long = "cache-file")]
    pub cache_file: Option<String>,

    /// Do NOT persist the DNS cache to disk.
    #[arg(long = "no-cache-persist")]
    pub no_cache_persist: bool,
}

/// Load the optional file config referenced by a `--config` path.
fn load_file(config: &Option<PathBuf>) -> Result<FileConfig, ConfigError> {
    match config {
        Some(path) => FileConfig::load(path),
        None => Ok(FileConfig::default()),
    }
}

/// Derive cipher + master key from a (possibly file-supplied) cipher name and
/// password, applying defaults and validating presence.
fn resolve_crypto(
    cipher_name: Option<String>,
    password: Option<String>,
) -> Result<(Cipher, Vec<u8>), ConfigError> {
    let cipher_name = cipher_name.unwrap_or_else(|| DEFAULT_CIPHER.to_string());
    let cipher = Cipher::from_name(&cipher_name)?;
    let password = password.ok_or(ConfigError::Missing("password"))?;
    let master_key = crate::crypto::evp_bytes_to_key(password.as_bytes(), cipher.key_len());
    Ok((cipher, master_key))
}

/// Default DNS-cache path: `dns-cache.json` in the same directory as the running
/// binary (falling back to the current directory if the exe path is unknown).
fn default_cache_file() -> PathBuf {
    std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(Path::to_path_buf))
        .unwrap_or_else(|| PathBuf::from("."))
        .join(DEFAULT_CACHE_FILE_NAME)
}

/// Parse a DNS endpoint that may be `ip:port` or a bare `ip` (defaulting the
/// port to `default_port`).
fn parse_dns_addr(
    field: &'static str,
    value: &str,
    default_port: u16,
) -> Result<SocketAddr, ConfigError> {
    if let Ok(addr) = value.parse::<SocketAddr>() {
        return Ok(addr);
    }
    if let Ok(ip) = value.parse::<IpAddr>() {
        return Ok(SocketAddr::new(ip, default_port));
    }
    Err(ConfigError::Invalid {
        field,
        message: format!("`{value}` is not an `ip` or `ip:port` address"),
    })
}

/// Build the validated [`PolicyConfig`] from merged file + CLI values, applying
/// defaults and validating that the active mode has the data file it needs.
fn resolve_policy(args: &ClientArgs, file: &FileConfig) -> Result<PolicyConfig, ConfigError> {
    let mode = match args.mode.clone().or_else(|| file.mode.clone()) {
        Some(name) => Mode::from_name(&name)?,
        None => Mode::Full,
    };

    let pick = |a: &Option<String>, f: &Option<String>, default: &str| -> String {
        a.clone()
            .or_else(|| f.clone())
            .unwrap_or_else(|| default.to_string())
    };

    let dns_listen = parse_dns_addr(
        "dns_listen",
        &pick(&args.dns_listen, &file.dns_listen, DEFAULT_DNS_LISTEN),
        53,
    )?;
    let dns_local = parse_dns_addr(
        "dns_local",
        &pick(&args.dns_local, &file.dns_local, DEFAULT_DNS_LOCAL),
        53,
    )?;
    let dns_remote = parse_dns_addr(
        "dns_remote",
        &pick(&args.dns_remote, &file.dns_remote, DEFAULT_DNS_REMOTE),
        53,
    )?;

    let gfwlist = args.gfwlist.clone().or_else(|| file.gfwlist.clone());
    let chnroute = args.chnroute.clone().or_else(|| file.chnroute.clone());
    let geoip = args.geoip.clone().or_else(|| file.geoip.clone());

    // `--no-set-dns` wins over `--set-dns`; otherwise file value; default on.
    let set_dns = if args.no_set_dns {
        false
    } else if args.set_dns {
        true
    } else {
        file.set_dns.unwrap_or(true)
    };

    // Pre-warm: `--no-prewarm` disables; else the file list, else the built-in.
    let prewarm = if args.no_prewarm {
        Vec::new()
    } else {
        file.prewarm.clone().unwrap_or_else(|| {
            crate::policy::DEFAULT_PREWARM
                .iter()
                .map(|s| s.to_string())
                .collect()
        })
    };

    // Cache persistence: `--no-cache-persist` disables; else CLI/file path, else
    // a file next to the binary.
    let cache_file = if args.no_cache_persist {
        None
    } else {
        Some(
            args.cache_file
                .clone()
                .or_else(|| file.cache_file.clone())
                .map(PathBuf::from)
                .unwrap_or_else(default_cache_file),
        )
    };

    // Fail fast if the chosen mode is missing its data file.
    if matches!(mode, Mode::GfwList) && gfwlist.is_none() {
        return Err(ConfigError::Missing("gfwlist (required by gfwlist mode)"));
    }
    if matches!(mode, Mode::ChinaDns) && chnroute.is_none() && geoip.is_none() {
        return Err(ConfigError::Missing(
            "chnroute or geoip (required by chinadns mode)",
        ));
    }

    Ok(PolicyConfig {
        mode,
        dns_listen,
        dns_local,
        dns_remote,
        gfwlist,
        chnroute,
        geoip,
        geoip_country: args
            .geoip_country
            .clone()
            .or_else(|| file.geoip_country.clone())
            .unwrap_or_else(|| DEFAULT_GEOIP_COUNTRY.to_string()),
        set_dns,
        prewarm,
        cache_file,
        dns_timeout: Duration::from_millis(file.dns_timeout_ms.unwrap_or(DEFAULT_DNS_TIMEOUT_MS)),
    })
}

/// Build the validated [`TunConfig`] from merged file + CLI values.
#[allow(clippy::too_many_arguments)]
fn resolve_tun(
    name: Option<String>,
    ip: Option<Ipv4Addr>,
    netmask: Option<Ipv4Addr>,
    peer_ip: Option<Ipv4Addr>,
    mtu: Option<u16>,
) -> Result<TunConfig, ConfigError> {
    Ok(TunConfig {
        name,
        ip: ip.ok_or(ConfigError::Missing("tun_ip"))?,
        netmask: netmask.unwrap_or(DEFAULT_NETMASK),
        peer_ip: peer_ip.ok_or(ConfigError::Missing("peer_ip"))?,
        mtu: mtu.unwrap_or(DEFAULT_TUN_MTU),
    })
}

impl ServerArgs {
    /// Merge these CLI args over the (optional) JSON file and produce a
    /// validated [`ServerConfig`]. CLI flags take precedence over file values.
    pub fn resolve(self) -> Result<ServerConfig, ConfigError> {
        let file = load_file(&self.config)?;

        let listen = self
            .listen
            .or(file.server)
            .ok_or(ConfigError::Missing("listen"))?;

        let (cipher, master_key) =
            resolve_crypto(self.cipher.or(file.cipher), self.password.or(file.password))?;

        let tun = resolve_tun(
            self.tun_name.or(file.tun_name),
            self.tun_ip.or(file.tun_ip),
            self.tun_netmask.or(file.tun_netmask),
            self.peer_ip.or(file.peer_ip),
            self.mtu.or(file.mtu),
        )?;

        let obfs = file.obfs.filter(|s| !s.is_empty() && s != "none");

        let nat = self.nat || file.nat.unwrap_or(false);
        let lease_ttl = Duration::from_secs(
            self.lease_ttl_secs
                .or(file.lease_ttl_secs)
                .unwrap_or(DEFAULT_LEASE_TTL_SECS),
        );

        Ok(ServerConfig {
            listen,
            cipher,
            master_key,
            tun,
            obfs,
            nat,
            lease_ttl,
        })
    }
}

impl ClientArgs {
    /// Merge these CLI args over the (optional) JSON file and produce a
    /// validated [`ClientConfig`]. CLI flags take precedence over file values.
    pub fn resolve(self) -> Result<ClientConfig, ConfigError> {
        let file = load_file(&self.config)?;

        // Resolve policy first: it borrows `self`/`file`, which the moves below
        // would otherwise partially consume.
        let policy = resolve_policy(&self, &file)?;

        let server = self
            .server
            .or(file.server)
            .ok_or(ConfigError::Missing("server"))?;

        let (cipher, master_key) =
            resolve_crypto(self.cipher.or(file.cipher), self.password.or(file.password))?;

        let tun = resolve_tun(
            self.tun_name.or(file.tun_name),
            self.tun_ip.or(file.tun_ip),
            self.tun_netmask.or(file.tun_netmask),
            self.peer_ip.or(file.peer_ip),
            self.mtu.or(file.mtu),
        )?;

        let obfs = file.obfs.filter(|s| !s.is_empty() && s != "none");

        Ok(ClientConfig {
            server,
            cipher,
            master_key,
            tun,
            policy,
            obfs,
        })
    }
}

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

    impl ClientArgs {
        /// All-`None` client args, for building test cases with struct update
        /// syntax (`..ClientArgs::empty()`).
        fn empty() -> Self {
            ClientArgs {
                config: None,
                server: None,
                password: None,
                cipher: None,
                tun_name: None,
                tun_ip: None,
                tun_netmask: None,
                peer_ip: None,
                mtu: None,
                mode: None,
                dns_listen: None,
                dns_local: None,
                dns_remote: None,
                gfwlist: None,
                chnroute: None,
                geoip: None,
                geoip_country: None,
                set_dns: false,
                no_set_dns: false,
                no_prewarm: false,
                cache_file: None,
                no_cache_persist: false,
            }
        }
    }

    #[test]
    fn cli_overrides_file_and_resolves() {
        let args = ServerArgs {
            config: None,
            listen: Some("0.0.0.0:9000".to_string()),
            password: Some("test".to_string()),
            cipher: Some("aes-128-gcm".to_string()),
            tun_name: Some("utun9".to_string()),
            tun_ip: Some(Ipv4Addr::new(10, 9, 0, 1)),
            tun_netmask: None,
            peer_ip: Some(Ipv4Addr::new(10, 9, 0, 2)),
            mtu: None,
            nat: false,
            lease_ttl_secs: None,
        };
        let cfg = args.resolve().expect("resolve");
        assert_eq!(cfg.listen, "0.0.0.0:9000");
        assert_eq!(cfg.cipher, Cipher::Aes128Gcm);
        // password "test" + aes-128-gcm => MD5("test").
        assert_eq!(cfg.master_key.len(), 16);
        assert_eq!(cfg.tun.netmask, DEFAULT_NETMASK);
        assert_eq!(cfg.tun.mtu, DEFAULT_TUN_MTU);
        assert_eq!(cfg.tun.name.as_deref(), Some("utun9"));
    }

    #[test]
    fn missing_password_is_an_error() {
        let args = ClientArgs {
            config: None,
            server: Some("host:1".to_string()),
            password: None,
            cipher: None,
            tun_name: None,
            tun_ip: Some(Ipv4Addr::new(10, 0, 0, 2)),
            tun_netmask: None,
            peer_ip: Some(Ipv4Addr::new(10, 0, 0, 1)),
            mtu: None,
            ..ClientArgs::empty()
        };
        assert!(matches!(
            args.resolve(),
            Err(ConfigError::Missing("password"))
        ));
    }

    #[test]
    fn policy_defaults_to_full_and_validates() {
        // Default mode is full; no DNS/gfwlist needed.
        let base = ClientArgs {
            config: None,
            server: Some("host:1".to_string()),
            password: Some("pw".to_string()),
            tun_ip: Some(Ipv4Addr::new(10, 0, 0, 2)),
            peer_ip: Some(Ipv4Addr::new(10, 0, 0, 1)),
            ..ClientArgs::empty()
        };
        let cfg = base.clone().resolve().expect("resolve full");
        assert_eq!(cfg.policy.mode, Mode::Full);
        assert_eq!(cfg.policy.dns_listen.to_string(), "127.0.0.1:53");
        assert!(cfg.policy.set_dns, "set_dns defaults to on");

        // --no-set-dns wins; --set-dns forces on.
        let mut nd = base.clone();
        nd.no_set_dns = true;
        assert!(!nd.resolve().unwrap().policy.set_dns);
        let mut sd = base.clone();
        sd.set_dns = true;
        assert!(sd.resolve().unwrap().policy.set_dns);

        // prewarm defaults to the built-in list; --no-prewarm empties it.
        assert!(!cfg.policy.prewarm.is_empty());
        let mut np = base.clone();
        np.no_prewarm = true;
        assert!(np.resolve().unwrap().policy.prewarm.is_empty());

        // cache persistence on by default; --no-cache-persist disables it.
        assert!(cfg.policy.cache_file.is_some());
        let mut nc = base.clone();
        nc.no_cache_persist = true;
        assert!(nc.resolve().unwrap().policy.cache_file.is_none());

        // gfwlist mode without a gfwlist file is rejected.
        let mut g = base.clone();
        g.mode = Some("gfwlist".to_string());
        assert!(matches!(g.resolve(), Err(ConfigError::Missing(_))));

        // chinadns mode without a chnroute file or geoip database is rejected.
        let mut c = base.clone();
        c.mode = Some("chinadns".to_string());
        assert!(matches!(c.resolve(), Err(ConfigError::Missing(_))));

        // chinadns mode is satisfied by a geoip database alone (default CN).
        let mut cg = base.clone();
        cg.mode = Some("chinadns".to_string());
        cg.geoip = Some(PathBuf::from("/tmp/GeoLite2-Country.mmdb"));
        let cfg = cg.resolve().expect("resolve chinadns+geoip");
        assert_eq!(cfg.policy.mode, Mode::ChinaDns);
        assert_eq!(cfg.policy.geoip_country, "CN");

        // A bare DNS IP gets the default port; bad mode is an error.
        let mut d = base.clone();
        d.dns_local = Some("1.2.3.4".to_string());
        assert_eq!(
            d.resolve().unwrap().policy.dns_local.to_string(),
            "1.2.3.4:53"
        );
        let mut m = base;
        m.mode = Some("bogus".to_string());
        assert!(matches!(m.resolve(), Err(ConfigError::Policy(_))));
    }

    #[test]
    fn file_config_parses() {
        let json = r#"{
            "server": "1.2.3.4:8388",
            "password": "pw",
            "cipher": "aes-256-gcm",
            "tun_ip": "10.1.0.2",
            "peer_ip": "10.1.0.1"
        }"#;
        let fc: FileConfig = serde_json::from_str(json).expect("parse");
        assert_eq!(fc.server.as_deref(), Some("1.2.3.4:8388"));
        assert_eq!(fc.cipher.as_deref(), Some("aes-256-gcm"));
        assert_eq!(fc.tun_ip, Some(Ipv4Addr::new(10, 1, 0, 2)));
    }

    #[test]
    fn server_nat_flag_and_default_ttl() {
        let args = ServerArgs {
            config: None,
            listen: Some("0.0.0.0:1".to_string()),
            password: Some("pw".to_string()),
            cipher: None,
            tun_name: None,
            tun_ip: Some(Ipv4Addr::new(10, 9, 0, 1)),
            tun_netmask: None,
            peer_ip: Some(Ipv4Addr::new(10, 9, 0, 2)),
            mtu: None,
            nat: true,
            lease_ttl_secs: None,
        };
        let cfg = args.resolve().expect("resolve");
        assert!(cfg.nat);
        assert_eq!(cfg.lease_ttl, Duration::from_secs(DEFAULT_LEASE_TTL_SECS));
    }
}