shadowvpn 0.5.0

A UDP-based, pre-shared-key (PSK), user-mode VPN using the shadowsocks AEAD UDP wire scheme.
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
//! 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 ipnetwork::{IpNetwork, Ipv6Network};
use serde::{Deserialize, Serialize};

use crate::crypto::Cipher;
use crate::mesh::{RouteApproval, MAX_ROUTES};
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";

/// File name of a GeoLite2 country database shipped alongside the client
/// binary. In chinadns mode, when the config supplies neither a `chnroute` nor
/// a `geoip` path, the client auto-discovers this file next to its own
/// executable (how the desktop `.app` and Windows packages bundle it), so the
/// China IP set works out of the box with no explicit path.
pub const DEFAULT_GEOIP_DB_NAME: &str = "GeoLite2-Country.mmdb";

/// File name of a gfwlist domain-suffix list shipped alongside the client
/// binary. When the config supplies no `gfwlist` path, the client auto-discovers
/// this file next to its own executable — as the routing list in gfwlist mode,
/// and as the force-tunnel override in chinadns mode (matching the iOS client).
pub const DEFAULT_GFWLIST_NAME: &str = "gfwlist.txt";

/// 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 default
/// keepalive interval ([`DEFAULT_KEEPALIVE_SECS`]).
pub const DEFAULT_LEASE_TTL_SECS: u64 = 120;

/// Default client keepalive interval, in seconds. Consumer routers commonly
/// expire idle UDP NAT mappings in as little as ~20 seconds; a keepalive
/// slower than that rebinds the flow to a new source port on every idle gap
/// (churning the server's per-client NAT and dropping in-flight replies), so
/// the default sits safely below it.
pub const DEFAULT_KEEPALIVE_SECS: u64 = 15;

/// 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>,

    /// Optional IPv6 address + prefix for the TUN interface (CIDR form, e.g.
    /// `"fd07:7::2/64"`). Give every node an address in one shared ULA prefix
    /// so IPv6 subnet routes have an in-tunnel source/return address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tun_ip6: Option<Ipv6Network>,

    /// 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: keepalive interval in seconds (default
    /// [`DEFAULT_KEEPALIVE_SECS`]). Must stay below the shortest UDP NAT
    /// timeout on the path or the flow rebinds to a new source port whenever
    /// it goes idle. Ignored by the server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub keepalive_secs: Option<u64>,

    // --- Mesh subnet routing (Tailscale-like) -------------------------------
    /// Client-only: subnets behind this client to advertise to the server
    /// (IPv4/IPv6 CIDRs). The server relays matching traffic here once the
    /// route is approved.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub advertise_routes: Option<Vec<IpNetwork>>,

    /// Client-only: accept subnet routes pushed by the server and install them
    /// onto the TUN interface (removed again on exit).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accept_routes: Option<bool>,

    /// Server-only: allowlist of CIDRs whose sub-networks are approved when a
    /// client advertises them. Advertised routes outside it are held as
    /// "awaiting approval" and never routed or pushed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approve_routes: Option<Vec<IpNetwork>>,

    /// Server-only: approve every advertised route (no allowlist needed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_approve_routes: Option<bool>,

    // --- 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,
    /// Optional IPv6 address + prefix on the interface (mesh IPv6 routing).
    pub ip6: Option<Ipv6Network>,
    /// 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).
    /// Also the expiry for advertised subnet routes whose owner went quiet.
    pub lease_ttl: Duration,
    /// Approval policy for client-advertised subnet routes.
    pub route_approval: RouteApproval,
}

/// 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>,
    /// Interval between keepalive datagrams.
    pub keepalive: Duration,
    /// Subnets behind this client to advertise to the server.
    pub advertise_routes: Vec<IpNetwork>,
    /// Whether to accept and install subnet routes pushed by the server.
    pub accept_routes: bool,
}

/// 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>,

    /// IPv6 address + prefix for the TUN interface (e.g. fd07:7::1/64).
    #[arg(long = "tun-ip6")]
    pub tun_ip6: Option<Ipv6Network>,

    /// 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>,

    /// Approve advertised routes covered by these CIDRs (comma-separated).
    #[arg(long = "approve-routes", value_delimiter = ',')]
    pub approve_routes: Option<Vec<IpNetwork>>,

    /// Approve every route clients advertise (Tailscale "approve all").
    #[arg(long = "auto-approve-routes")]
    pub auto_approve_routes: bool,
}

/// 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>,

    /// IPv6 address + prefix for the TUN interface (e.g. fd07:7::2/64).
    #[arg(long = "tun-ip6")]
    pub tun_ip6: Option<Ipv6Network>,

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

    /// Subnets behind this client to advertise to the server (comma-separated
    /// IPv4/IPv6 CIDRs), e.g. 192.168.200.0/24,fd42:cafe::/64.
    #[arg(long = "advertise-routes", value_delimiter = ',')]
    pub advertise_routes: Option<Vec<IpNetwork>>,

    /// Accept subnet routes pushed by the server and install them on the TUN.
    #[arg(long = "accept-routes")]
    pub accept_routes: bool,

    /// 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,

    /// Restore the system resolver from the journal left by a run that did
    /// not exit cleanly, then exit (no tunnel is brought up). Used by the
    /// desktop app to heal DNS after a crashed client.
    #[arg(long = "restore-dns")]
    pub restore_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,

    /// Keepalive interval in seconds (keep below the path's UDP NAT timeout).
    #[arg(long = "keepalive-secs")]
    pub keepalive_secs: Option<u64>,
}

/// 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)
}

/// The directory holding the running client binary, if it can be determined.
/// Bundled policy data files (a GeoLite2 database, a gfwlist) are looked up here
/// so a copy shipped alongside the executable (desktop `.app`, Windows zip) is
/// auto-discovered.
fn exe_dir() -> Option<PathBuf> {
    std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(Path::to_path_buf))
}

/// The file `name` inside `dir`, if it exists as a regular file.
fn data_file_in_dir(dir: &Path, name: &str) -> Option<PathBuf> {
    let path = dir.join(name);
    path.is_file().then_some(path)
}

/// The gfwlist to use when the config sets no explicit `gfwlist` path: a bundled
/// [`DEFAULT_GFWLIST_NAME`] in `dir`. Applied in gfwlist mode (the routing list)
/// and in chinadns mode (the force-tunnel override, matching the iOS client,
/// whose network extension always injects its bundled gfwlist in chinadns mode);
/// never in full mode.
fn bundled_gfwlist(mode: Mode, dir: &Path) -> Option<PathBuf> {
    if matches!(mode, Mode::GfwList | Mode::ChinaDns) {
        data_file_in_dir(dir, DEFAULT_GFWLIST_NAME)
    } else {
        None
    }
}

/// The GeoIP database to use when the config sets no `chnroute`/`geoip` path: a
/// bundled [`DEFAULT_GEOIP_DB_NAME`] in `dir`, in chinadns mode only (and only
/// when no `chnroute` is configured, since that supplies the China set instead).
fn bundled_geoip(mode: Mode, chnroute_set: bool, dir: &Path) -> Option<PathBuf> {
    if matches!(mode, Mode::ChinaDns) && !chnroute_set {
        data_file_in_dir(dir, DEFAULT_GEOIP_DB_NAME)
    } else {
        None
    }
}

/// 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,
    )?;

    // Data files bundled next to the client binary are the fallback when the
    // config sets no explicit path (desktop `.app`, Windows zip). Resolve the
    // exe dir once and reuse it for both lookups.
    let bundle_dir = exe_dir();

    // Explicit `gfwlist` (CLI or file) wins; otherwise fall back to a bundled
    // gfwlist.txt (routing list in gfwlist mode, force-tunnel override in
    // chinadns mode).
    let gfwlist = args
        .gfwlist
        .clone()
        .or_else(|| file.gfwlist.clone())
        .or_else(|| bundle_dir.as_deref().and_then(|d| bundled_gfwlist(mode, d)));
    let chnroute = args.chnroute.clone().or_else(|| file.chnroute.clone());
    // Explicit `geoip` (CLI or file) wins; otherwise, in chinadns mode with no
    // `chnroute` either, fall back to a bundled GeoLite2-Country.mmdb so the
    // China set works with no configured path.
    let geoip = args
        .geoip
        .clone()
        .or_else(|| file.geoip.clone())
        .or_else(|| {
            bundle_dir
                .as_deref()
                .and_then(|d| bundled_geoip(mode, chnroute.is_some(), d))
        });

    // `--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>,
    ip6: Option<Ipv6Network>,
    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"))?,
        ip6,
        mtu: mtu.unwrap_or(DEFAULT_TUN_MTU),
    })
}

/// Validate a set of advertised routes: bounded and free of degenerate
/// (default-route) entries, which must go through the normal full-tunnel
/// routing setup rather than a subnet advertisement.
fn validate_advertised(routes: &[IpNetwork]) -> Result<(), ConfigError> {
    if routes.len() > MAX_ROUTES {
        return Err(ConfigError::Invalid {
            field: "advertise_routes",
            message: format!("at most {MAX_ROUTES} routes may be advertised"),
        });
    }
    if let Some(net) = routes.iter().find(|net| net.prefix() == 0) {
        return Err(ConfigError::Invalid {
            field: "advertise_routes",
            message: format!("`{net}` is a default route; advertise specific subnets instead"),
        });
    }
    Ok(())
}

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.tun_ip6.or(file.tun_ip6),
            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),
        );

        let route_approval = RouteApproval {
            auto: self.auto_approve_routes || file.auto_approve_routes.unwrap_or(false),
            allowlist: self
                .approve_routes
                .or(file.approve_routes)
                .unwrap_or_default(),
        };

        // Mesh routing identifies clients by their distinct tunnel IPs; NAT
        // mode deliberately erases that distinction (one shared config), so
        // the two cannot be combined.
        if nat && (route_approval.auto || !route_approval.allowlist.is_empty() || tun.ip6.is_some())
        {
            return Err(ConfigError::Invalid {
                field: "nat",
                message: "mesh subnet routing (approve_routes / auto_approve_routes / tun_ip6) \
                          requires learning mode; remove --nat"
                    .to_string(),
            });
        }

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

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.tun_ip6.or(file.tun_ip6),
            self.mtu.or(file.mtu),
        )?;

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

        let keepalive_secs = self
            .keepalive_secs
            .or(file.keepalive_secs)
            .unwrap_or(DEFAULT_KEEPALIVE_SECS);
        if keepalive_secs == 0 {
            return Err(ConfigError::Invalid {
                field: "keepalive_secs",
                message: "must be at least 1 second".to_string(),
            });
        }

        let advertise_routes = self
            .advertise_routes
            .or(file.advertise_routes)
            .unwrap_or_default();
        validate_advertised(&advertise_routes)?;
        let accept_routes = self.accept_routes || file.accept_routes.unwrap_or(false);

        Ok(ClientConfig {
            server,
            cipher,
            master_key,
            tun,
            policy,
            obfs,
            keepalive: Duration::from_secs(keepalive_secs),
            advertise_routes,
            accept_routes,
        })
    }
}

#[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,
                tun_ip6: None,
                mtu: None,
                advertise_routes: None,
                accept_routes: false,
                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,
                restore_dns: false,
                no_prewarm: false,
                cache_file: None,
                no_cache_persist: false,
                keepalive_secs: None,
            }
        }
    }

    #[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)),
            tun_ip6: None,
            mtu: None,
            nat: false,
            lease_ttl_secs: None,
            approve_routes: None,
            auto_approve_routes: false,
        };
        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 keepalive_defaults_overrides_and_validates() {
        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 default");
        assert_eq!(cfg.keepalive, Duration::from_secs(DEFAULT_KEEPALIVE_SECS));

        let mut k = base.clone();
        k.keepalive_secs = Some(10);
        assert_eq!(
            k.resolve().unwrap().keepalive,
            Duration::from_secs(10),
            "CLI override wins"
        );

        let mut z = base;
        z.keepalive_secs = Some(0);
        assert!(matches!(
            z.resolve(),
            Err(ConfigError::Invalid {
                field: "keepalive_secs",
                ..
            })
        ));
    }

    #[test]
    fn bundled_data_fallbacks_match_mode() {
        // A unique scratch dir with both bundled data files present.
        let dir = std::env::temp_dir().join(format!(
            "svpn-bundle-test-{}-{:p}",
            std::process::id(),
            &0u8 as *const u8
        ));
        std::fs::create_dir_all(&dir).expect("create scratch dir");
        let gfw = dir.join(DEFAULT_GFWLIST_NAME);
        let db = dir.join(DEFAULT_GEOIP_DB_NAME);
        std::fs::write(&gfw, b"example.com\n").expect("write dummy gfwlist");
        std::fs::write(&db, b"not a real mmdb").expect("write dummy db");

        // gfwlist fallback: applied in gfwlist and chinadns modes, not full.
        assert_eq!(
            bundled_gfwlist(Mode::GfwList, &dir).as_deref(),
            Some(gfw.as_path())
        );
        assert_eq!(
            bundled_gfwlist(Mode::ChinaDns, &dir).as_deref(),
            Some(gfw.as_path()),
            "chinadns must auto-apply a bundled gfwlist (iOS-aligned force-tunnel override)"
        );
        assert!(bundled_gfwlist(Mode::Full, &dir).is_none());

        // geoip fallback: chinadns only, and only when no chnroute is set.
        assert_eq!(
            bundled_geoip(Mode::ChinaDns, false, &dir).as_deref(),
            Some(db.as_path())
        );
        assert!(bundled_geoip(Mode::ChinaDns, true, &dir).is_none());
        assert!(bundled_geoip(Mode::GfwList, false, &dir).is_none());
        assert!(bundled_geoip(Mode::Full, false, &dir).is_none());

        // An empty dir yields nothing for any mode.
        let empty = dir.join("empty");
        std::fs::create_dir_all(&empty).expect("create empty subdir");
        assert!(bundled_gfwlist(Mode::ChinaDns, &empty).is_none());
        assert!(bundled_geoip(Mode::ChinaDns, false, &empty).is_none());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[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)),
            tun_ip6: None,
            mtu: None,
            nat: true,
            lease_ttl_secs: None,
            approve_routes: None,
            auto_approve_routes: false,
        };
        let cfg = args.resolve().expect("resolve");
        assert!(cfg.nat);
        assert_eq!(cfg.lease_ttl, Duration::from_secs(DEFAULT_LEASE_TTL_SECS));
    }

    #[test]
    fn mesh_config_resolves_and_validates() {
        let base = ClientArgs {
            config: None,
            server: Some("host:1".to_string()),
            password: Some("pw".to_string()),
            tun_ip: Some(Ipv4Addr::new(10, 77, 0, 2)),
            peer_ip: Some(Ipv4Addr::new(10, 77, 0, 1)),
            ..ClientArgs::empty()
        };

        // Defaults: no mesh.
        let cfg = base.clone().resolve().expect("resolve");
        assert!(cfg.advertise_routes.is_empty());
        assert!(!cfg.accept_routes);
        assert!(cfg.tun.ip6.is_none());

        // Advertise + accept + tun_ip6 resolve through.
        let mut m = base.clone();
        m.advertise_routes = Some(vec![
            "192.168.200.0/24".parse().unwrap(),
            "fd42:cafe::/64".parse().unwrap(),
        ]);
        m.accept_routes = true;
        m.tun_ip6 = Some("fd07:7::2/64".parse().unwrap());
        let cfg = m.resolve().expect("resolve mesh");
        assert_eq!(cfg.advertise_routes.len(), 2);
        assert!(cfg.accept_routes);
        assert_eq!(cfg.tun.ip6.unwrap().to_string(), "fd07:7::2/64");

        // A default route may not be advertised.
        let mut d = base.clone();
        d.advertise_routes = Some(vec!["0.0.0.0/0".parse().unwrap()]);
        assert!(matches!(
            d.resolve(),
            Err(ConfigError::Invalid {
                field: "advertise_routes",
                ..
            })
        ));

        // More than MAX_ROUTES is rejected.
        let mut o = base;
        o.advertise_routes = Some(
            (0..=MAX_ROUTES)
                .map(|i| format!("10.{}.{}.0/24", i / 256, i % 256).parse().unwrap())
                .collect(),
        );
        assert!(matches!(
            o.resolve(),
            Err(ConfigError::Invalid {
                field: "advertise_routes",
                ..
            })
        ));
    }

    #[test]
    fn server_mesh_approval_resolves_and_rejects_nat_combo() {
        let base = 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, 77, 0, 1)),
            tun_netmask: None,
            peer_ip: Some(Ipv4Addr::new(10, 77, 0, 2)),
            tun_ip6: None,
            mtu: None,
            nat: false,
            lease_ttl_secs: None,
            approve_routes: None,
            auto_approve_routes: false,
        };

        let cfg = base.clone().resolve().expect("resolve");
        assert!(!cfg.route_approval.auto);
        assert!(cfg.route_approval.allowlist.is_empty());

        let mut a = base.clone();
        a.approve_routes = Some(vec!["192.168.0.0/16".parse().unwrap()]);
        a.tun_ip6 = Some("fd07:7::1/64".parse().unwrap());
        let cfg = a.resolve().expect("resolve approval");
        assert_eq!(cfg.route_approval.allowlist.len(), 1);
        assert_eq!(cfg.tun.ip6.unwrap().prefix(), 64);

        // Mesh settings + NAT mode are mutually exclusive.
        let mut n = base;
        n.nat = true;
        n.auto_approve_routes = true;
        assert!(matches!(
            n.resolve(),
            Err(ConfigError::Invalid { field: "nat", .. })
        ));
    }
}