-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathclient.rs
More file actions
790 lines (726 loc) · 26.4 KB
/
Copy pathclient.rs
File metadata and controls
790 lines (726 loc) · 26.4 KB
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
//! Client configuration types.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::address::NetLocation;
use crate::h2mux::{H2MuxOptions, MuxProtocol};
use crate::option_util::{NoneOrOne, NoneOrSome};
use super::common::{
default_reality_client_short_id, default_true, is_false, is_true, unspecified_address,
};
use super::server::WebsocketPingType;
use super::shadowsocks::ShadowsocksConfig;
use super::transport::{ClientQuicConfig, TcpConfig, Transport};
const REDACTED: &str = "<redacted>";
/// Configuration for h2mux (HTTP/2 multiplexing) on protocols that support it.
///
/// H2MUX multiplexes multiple proxy streams over a single HTTP/2 connection,
/// reducing connection overhead and improving performance for many concurrent streams.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct H2MuxConfig {
/// Maximum number of connections to maintain
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_connections: Option<u32>,
/// Minimum number of streams before opening a new connection
#[serde(default, skip_serializing_if = "Option::is_none")]
pub min_streams: Option<u32>,
/// Maximum number of streams per connection (0 = unlimited)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_streams: Option<u32>,
/// Enable padding for traffic obfuscation
#[serde(default, skip_serializing_if = "is_false")]
pub padding: bool,
}
impl H2MuxConfig {
/// Converts this config to H2MuxOptions for the client handler.
pub fn to_options(&self) -> H2MuxOptions {
H2MuxOptions {
protocol: MuxProtocol::H2Mux,
max_connections: self.max_connections.unwrap_or(4),
min_streams: self.min_streams.unwrap_or(4),
max_streams: self.max_streams.unwrap_or(0),
padding: self.padding,
}
}
}
/// Custom deserializer for ClientProxyConfig::Shadowsocks
fn deserialize_shadowsocks_client<'de, D>(
deserializer: D,
) -> Result<(ShadowsocksConfig, bool), D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ShadowsocksClientTemp {
cipher: String,
password: String,
#[serde(default = "default_true")]
udp_enabled: bool,
}
let temp = ShadowsocksClientTemp::deserialize(deserializer)?;
let config =
ShadowsocksConfig::from_fields(&temp.cipher, &temp.password).map_err(Error::custom)?;
Ok((config, temp.udp_enabled))
}
/// Custom serializer for ClientProxyConfig::Shadowsocks - flattens config fields
fn serialize_shadowsocks_client<S>(
config: &ShadowsocksConfig,
udp_enabled: &bool,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
// Only serialize udp_enabled if it's not the default (true)
let field_count = if *udp_enabled { 2 } else { 3 };
let mut state = serializer.serialize_struct("Shadowsocks", field_count)?;
config.serialize_fields(&mut state)?;
if !*udp_enabled {
state.serialize_field("udp_enabled", udp_enabled)?;
}
state.end()
}
/// Custom deserializer for ClientProxyConfig::Snell - flattens config fields
fn deserialize_snell_client<'de, D>(deserializer: D) -> Result<(ShadowsocksConfig, bool), D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SnellClientTemp {
cipher: String,
password: String,
#[serde(default = "default_true")]
udp_enabled: bool,
}
let temp = SnellClientTemp::deserialize(deserializer)?;
let config =
ShadowsocksConfig::from_fields(&temp.cipher, &temp.password).map_err(Error::custom)?;
Ok((config, temp.udp_enabled))
}
/// Custom serializer for ClientProxyConfig::Snell - flattens config fields
fn serialize_snell_client<S>(
config: &ShadowsocksConfig,
udp_enabled: &bool,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
// Only serialize udp_enabled if it's not the default (true)
let field_count = if *udp_enabled { 2 } else { 3 };
let mut state = serializer.serialize_struct("Snell", field_count)?;
config.serialize_fields(&mut state)?;
if !*udp_enabled {
state.serialize_field("udp_enabled", udp_enabled)?;
}
state.end()
}
/// Custom deserializer for ClientProxyConfig::Vmess that validates legacy aead field
fn deserialize_vmess_client<'de, D>(
deserializer: D,
) -> Result<(String, String, bool, Option<H2MuxConfig>), D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct VmessClientTemp {
cipher: String,
user_id: String,
#[serde(default, alias = "force_aead")]
aead: Option<bool>,
#[serde(default = "default_true")]
udp_enabled: bool,
#[serde(default)]
h2mux: Option<H2MuxConfig>,
}
let temp = VmessClientTemp::deserialize(deserializer)?;
// Check if aead/force_aead was explicitly set
if let Some(aead_value) = temp.aead {
if !aead_value {
return Err(Error::custom(
"Non-AEAD VMess mode (aead=false or force_aead=false) is no longer supported. \
Please remove the aead/force_aead field from your configuration, or set it to true.",
));
}
// Warn about deprecated field
log::warn!(
"The 'aead'/'force_aead' field in VMess client configuration is deprecated and will be removed in a future version. \
AEAD mode is now always enabled. Please remove this field from your configuration."
);
}
Ok((temp.cipher, temp.user_id, temp.udp_enabled, temp.h2mux))
}
/// Custom deserializer for TlsClientConfig that handles deprecated shadowtls_password field
fn deserialize_tls_client_config<'de, D>(deserializer: D) -> Result<TlsClientConfig, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TlsClientConfigTemp {
#[serde(default = "default_true")]
verify: bool,
#[serde(alias = "server_fingerprint", default)]
server_fingerprints: NoneOrSome<String>,
#[serde(default)]
sni_hostname: NoneOrOne<String>,
#[serde(alias = "alpn_protocol", default)]
alpn_protocols: NoneOrSome<String>,
#[serde(default)]
tls_buffer_size: Option<usize>,
#[serde(default)]
key: Option<String>,
#[serde(default)]
cert: Option<String>,
#[serde(default)]
shadowtls_password: Option<String>,
#[serde(default)]
vision: bool,
protocol: Box<ClientProxyConfig>,
}
let temp = TlsClientConfigTemp::deserialize(deserializer)?;
// Check for mutually exclusive fields
if temp.vision && temp.shadowtls_password.is_some() {
return Err(Error::custom(
"TLS client config cannot have both vision=true and shadowtls_password set. \
Vision and ShadowTLS are incompatible. \
Use either 'vision: true' with regular TLS, or 'type: shadowtls' for ShadowTLS.",
));
}
// Check if deprecated shadowtls_password was used
if let Some(password) = temp.shadowtls_password {
log::warn!(
"The 'shadowtls_password' field in TLS client configuration is deprecated. \
Please use 'type: shadowtls' with 'password' field instead. \
This field will be removed in a future version."
);
// Transform to ShadowTLS variant internally by wrapping protocol
return Ok(TlsClientConfig {
verify: temp.verify,
server_fingerprints: temp.server_fingerprints,
sni_hostname: temp.sni_hostname.clone(),
alpn_protocols: temp.alpn_protocols,
tls_buffer_size: temp.tls_buffer_size,
key: temp.key,
cert: temp.cert,
vision: false,
protocol: Box::new(ClientProxyConfig::ShadowTls {
password,
sni_hostname: temp.sni_hostname.into_option(),
protocol: temp.protocol,
}),
});
}
// Normal case - no shadowtls_password
Ok(TlsClientConfig {
verify: temp.verify,
server_fingerprints: temp.server_fingerprints,
sni_hostname: temp.sni_hostname,
alpn_protocols: temp.alpn_protocols,
tls_buffer_size: temp.tls_buffer_size,
key: temp.key,
cert: temp.cert,
vision: temp.vision,
protocol: temp.protocol,
})
}
/// Variant deserializer for Tls in ClientProxyConfig enum
fn deserialize_tls_variant<'de, D>(deserializer: D) -> Result<TlsClientConfig, D::Error>
where
D: serde::Deserializer<'de>,
{
deserialize_tls_client_config(deserializer)
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ClientConfig {
#[serde(default, skip_serializing_if = "NoneOrOne::is_unspecified")]
pub bind_interface: NoneOrOne<String>,
#[serde(
default = "unspecified_address",
skip_serializing_if = "NetLocation::is_unspecified"
)]
pub address: NetLocation,
pub protocol: ClientProxyConfig,
#[serde(default, skip_serializing_if = "Transport::is_default")]
pub transport: Transport,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tcp_settings: Option<TcpConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quic_settings: Option<ClientQuicConfig>,
}
impl Default for ClientConfig {
fn default() -> Self {
Self {
bind_interface: NoneOrOne::None,
address: unspecified_address(),
protocol: ClientProxyConfig::Direct,
transport: Transport::default(),
tcp_settings: None,
quic_settings: None,
}
}
}
#[derive(Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ClientProxyConfig {
Direct,
Http {
#[serde(default, skip_serializing_if = "Option::is_none")]
username: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
password: Option<String>,
/// When true, resolve hostnames to IP addresses before passing to HTTP CONNECT.
/// Used when the upstream proxy blocks by hostname.
#[serde(default, skip_serializing_if = "is_false")]
resolve_hostname: bool,
},
#[serde(alias = "socks5")]
Socks {
#[serde(default, skip_serializing_if = "Option::is_none")]
username: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
password: Option<String>,
},
#[serde(
alias = "ss",
deserialize_with = "deserialize_shadowsocks_client",
serialize_with = "serialize_shadowsocks_client"
)]
Shadowsocks {
config: ShadowsocksConfig,
udp_enabled: bool,
},
#[serde(
deserialize_with = "deserialize_snell_client",
serialize_with = "serialize_snell_client"
)]
Snell {
config: ShadowsocksConfig,
udp_enabled: bool,
},
Vless {
user_id: String,
#[serde(default = "default_true", skip_serializing_if = "is_true")]
udp_enabled: bool,
/// H2MUX multiplexing configuration
#[serde(default, skip_serializing_if = "Option::is_none")]
h2mux: Option<H2MuxConfig>,
},
Trojan {
password: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
shadowsocks: Option<ShadowsocksConfig>,
/// H2MUX multiplexing configuration
#[serde(default, skip_serializing_if = "Option::is_none")]
h2mux: Option<H2MuxConfig>,
},
Reality {
public_key: String,
#[serde(default = "default_reality_client_short_id")]
short_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
sni_hostname: Option<String>,
/// TLS 1.3 cipher suites to use (optional)
/// Valid values: "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256"
/// If empty or not specified, all three cipher suites are offered.
#[serde(
alias = "cipher_suite",
default,
skip_serializing_if = "NoneOrSome::is_unspecified"
)]
cipher_suites: NoneOrSome<crate::reality::CipherSuite>,
/// Enable XTLS-Vision protocol for TLS-in-TLS optimization.
/// When enabled, the inner protocol MUST be VLESS.
#[serde(default, skip_serializing_if = "is_false")]
vision: bool,
protocol: Box<ClientProxyConfig>,
},
#[serde(alias = "shadowtls")]
ShadowTls {
/// ShadowTLS password for authentication
password: String,
/// Optional SNI hostname override
#[serde(default, skip_serializing_if = "Option::is_none")]
sni_hostname: Option<String>,
/// Inner protocol (typically VLESS, Trojan, etc.)
protocol: Box<ClientProxyConfig>,
},
#[serde(deserialize_with = "deserialize_tls_variant")]
Tls(TlsClientConfig),
#[serde(deserialize_with = "deserialize_vmess_client")]
Vmess {
cipher: String,
user_id: String,
#[serde(default = "default_true", skip_serializing_if = "is_true")]
udp_enabled: bool,
/// H2MUX multiplexing configuration
#[serde(default, skip_serializing_if = "Option::is_none")]
h2mux: Option<H2MuxConfig>,
},
#[serde(alias = "ws")]
Websocket(WebsocketClientConfig),
#[serde(alias = "noop")]
PortForward,
/// AnyTLS outbound protocol
Anytls {
/// Authentication password
password: String,
/// UDP over TCP support (default: true)
#[serde(default = "default_true", skip_serializing_if = "is_true")]
udp_enabled: bool,
/// Custom padding scheme (optional, uses default if not specified)
/// Each line is a key=value pair like "stop=8" or "0=30-30"
#[serde(default, skip_serializing_if = "Option::is_none")]
padding_scheme: Option<Vec<String>>,
},
/// NaiveProxy client protocol (HTTP/2 CONNECT with padding)
#[serde(alias = "naive")]
Naiveproxy {
/// Username for Basic Auth
username: String,
/// Password for Basic Auth
password: String,
/// Enable padding protocol (default: true)
#[serde(default = "default_true", skip_serializing_if = "is_true")]
padding: bool,
},
}
impl std::fmt::Debug for ClientProxyConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClientProxyConfig::Direct => f.write_str("Direct"),
ClientProxyConfig::Http {
username,
password,
resolve_hostname,
} => f
.debug_struct("Http")
.field("username", username)
.field("password", &password.as_ref().map(|_| REDACTED))
.field("resolve_hostname", resolve_hostname)
.finish(),
ClientProxyConfig::Socks { username, password } => f
.debug_struct("Socks")
.field("username", username)
.field("password", &password.as_ref().map(|_| REDACTED))
.finish(),
ClientProxyConfig::Shadowsocks {
config,
udp_enabled,
} => f
.debug_struct("Shadowsocks")
.field("config", config)
.field("udp_enabled", udp_enabled)
.finish(),
ClientProxyConfig::Snell {
config,
udp_enabled,
} => f
.debug_struct("Snell")
.field("config", config)
.field("udp_enabled", udp_enabled)
.finish(),
ClientProxyConfig::Vless {
udp_enabled, h2mux, ..
} => f
.debug_struct("Vless")
.field("user_id", &REDACTED)
.field("udp_enabled", udp_enabled)
.field("h2mux", h2mux)
.finish(),
ClientProxyConfig::Trojan {
shadowsocks, h2mux, ..
} => f
.debug_struct("Trojan")
.field("password", &REDACTED)
.field("shadowsocks", shadowsocks)
.field("h2mux", h2mux)
.finish(),
ClientProxyConfig::Reality {
public_key,
sni_hostname,
cipher_suites,
vision,
protocol,
..
} => f
.debug_struct("Reality")
.field("public_key", public_key)
.field("short_id", &REDACTED)
.field("sni_hostname", sni_hostname)
.field("cipher_suites", cipher_suites)
.field("vision", vision)
.field("protocol", protocol)
.finish(),
ClientProxyConfig::ShadowTls {
sni_hostname,
protocol,
..
} => f
.debug_struct("ShadowTls")
.field("password", &REDACTED)
.field("sni_hostname", sni_hostname)
.field("protocol", protocol)
.finish(),
ClientProxyConfig::Tls(tls_config) => f.debug_tuple("Tls").field(tls_config).finish(),
ClientProxyConfig::Vmess {
cipher,
udp_enabled,
h2mux,
..
} => f
.debug_struct("Vmess")
.field("cipher", cipher)
.field("user_id", &REDACTED)
.field("udp_enabled", udp_enabled)
.field("h2mux", h2mux)
.finish(),
ClientProxyConfig::Websocket(ws_config) => {
f.debug_tuple("Websocket").field(ws_config).finish()
}
ClientProxyConfig::PortForward => f.write_str("PortForward"),
ClientProxyConfig::Anytls {
udp_enabled,
padding_scheme,
..
} => f
.debug_struct("Anytls")
.field("password", &REDACTED)
.field("udp_enabled", udp_enabled)
.field("padding_scheme", padding_scheme)
.finish(),
ClientProxyConfig::Naiveproxy {
username, padding, ..
} => f
.debug_struct("Naiveproxy")
.field("username", username)
.field("password", &REDACTED)
.field("padding", padding)
.finish(),
}
}
}
impl ClientProxyConfig {
pub fn is_direct(&self) -> bool {
matches!(self, ClientProxyConfig::Direct)
}
/// Returns the protocol name for display/error messages
pub fn protocol_name(&self) -> &str {
match self {
ClientProxyConfig::Direct => "Direct",
ClientProxyConfig::Http { .. } => "HTTP",
ClientProxyConfig::Socks { .. } => "SOCKS5",
ClientProxyConfig::Shadowsocks { .. } => "Shadowsocks",
ClientProxyConfig::Snell { .. } => "Snell",
ClientProxyConfig::Vless { .. } => "VLESS",
ClientProxyConfig::Trojan { .. } => "Trojan",
ClientProxyConfig::Reality { .. } => "Reality",
ClientProxyConfig::Tls(..) => "TLS",
ClientProxyConfig::ShadowTls { .. } => "ShadowTLS",
ClientProxyConfig::Vmess { .. } => "VMess",
ClientProxyConfig::Websocket(..) => "WebSocket",
ClientProxyConfig::PortForward => "PortForward",
ClientProxyConfig::Anytls { .. } => "AnyTLS",
ClientProxyConfig::Naiveproxy { .. } => "NaiveProxy",
}
}
}
#[derive(Clone, Serialize)]
pub struct TlsClientConfig {
#[serde(default = "default_true", skip_serializing_if = "is_true")]
pub verify: bool,
#[serde(
alias = "server_fingerprint",
default,
skip_serializing_if = "NoneOrSome::is_unspecified"
)]
pub server_fingerprints: NoneOrSome<String>,
#[serde(default, skip_serializing_if = "NoneOrOne::is_unspecified")]
pub sni_hostname: NoneOrOne<String>,
#[serde(
alias = "alpn_protocol",
default,
skip_serializing_if = "NoneOrSome::is_unspecified"
)]
pub alpn_protocols: NoneOrSome<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tls_buffer_size: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cert: Option<String>,
/// Enable XTLS-Vision protocol for TLS-in-TLS optimization.
/// When enabled, the inner protocol MUST be VLESS.
/// Requires TLS 1.3.
#[serde(default, skip_serializing_if = "is_false")]
pub vision: bool,
pub protocol: Box<ClientProxyConfig>,
}
impl std::fmt::Debug for TlsClientConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TlsClientConfig")
.field("verify", &self.verify)
.field("server_fingerprints", &self.server_fingerprints)
.field("sni_hostname", &self.sni_hostname)
.field("alpn_protocols", &self.alpn_protocols)
.field("tls_buffer_size", &self.tls_buffer_size)
.field("key", &self.key.as_ref().map(|_| REDACTED))
.field("cert", &self.cert.as_ref().map(|_| "<present>"))
.field("vision", &self.vision)
.field("protocol", &self.protocol)
.finish()
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WebsocketClientConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matching_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matching_headers: Option<HashMap<String, String>>,
#[serde(default, skip_serializing_if = "WebsocketPingType::is_default")]
pub ping_type: WebsocketPingType,
pub protocol: Box<ClientProxyConfig>,
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::{IpAddr, Ipv4Addr};
fn create_test_client_config() -> ClientConfig {
ClientConfig {
bind_interface: NoneOrOne::One("eth0".to_string()),
address: NetLocation::from_ip_addr(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 1080),
protocol: ClientProxyConfig::Socks {
username: Some("client_user".to_string()),
password: Some("client_pass".to_string()),
},
transport: Transport::Tcp,
tcp_settings: None,
quic_settings: None,
}
}
#[test]
fn test_client_config_serialization() {
let original = create_test_client_config();
let yaml_str = serde_yaml::to_string(&original).expect("Failed to serialize");
println!("Client config YAML:\n{yaml_str}");
let deserialized: ClientConfig =
serde_yaml::from_str(&yaml_str).expect("Failed to deserialize");
assert!(matches!(
deserialized.protocol,
ClientProxyConfig::Socks { .. }
));
}
#[test]
fn test_client_config_debug_redacts_secrets() {
let config = ClientProxyConfig::Socks {
username: Some("client_user".to_string()),
password: Some("client_pass".to_string()),
};
let debug = format!("{config:?}");
assert!(debug.contains(REDACTED));
assert!(!debug.contains("client_pass"));
}
#[test]
fn test_rejects_unknown_field_in_vmess_client() {
// Test ClientProxyConfig::Vmess directly
let yaml = r#"
type: vmess
cipher: aes-128-gcm
user_id: "b0e80a62-8a51-47f0-91f1-f0f7faf8d9d4"
unknown_option: true
"#;
let result: Result<ClientProxyConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("unknown field `unknown_option`"),
"Error should mention unknown field: {err}"
);
}
#[test]
fn test_rejects_unknown_field_in_tls_client_config() {
// Test ClientProxyConfig::Tls directly
let yaml = r#"
type: tls
verify: true
wrong_field: "oops"
protocol:
type: socks
"#;
let result: Result<ClientProxyConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("unknown field `wrong_field`"),
"Error should mention unknown field: {err}"
);
}
#[test]
fn test_rejects_unknown_field_in_client_config() {
// Test ClientConfig directly
let yaml = r#"
address: "127.0.0.1:9090"
protocol:
type: socks
invalid_client_field: "bad"
"#;
let result: Result<ClientConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("unknown field `invalid_client_field`"),
"Error should mention unknown field: {err}"
);
}
#[test]
fn test_client_proxy_config_direct() {
let yaml = r#"
type: direct
"#;
let result: Result<ClientProxyConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_ok());
assert!(result.unwrap().is_direct());
}
#[test]
fn test_client_proxy_config_socks() {
let yaml = r#"
type: socks
username: "user"
password: "pass"
"#;
let result: Result<ClientProxyConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_ok());
assert!(matches!(result.unwrap(), ClientProxyConfig::Socks { .. }));
}
#[test]
fn test_client_proxy_config_http() {
let yaml = r#"
type: http
"#;
let result: Result<ClientProxyConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_ok());
assert!(matches!(result.unwrap(), ClientProxyConfig::Http { .. }));
}
#[test]
fn test_websocket_client_config() {
let yaml = r#"
type: websocket
matching_path: "/ws"
protocol:
type: direct
"#;
let result: Result<ClientProxyConfig, _> = serde_yaml::from_str(yaml);
assert!(result.is_ok());
assert!(matches!(result.unwrap(), ClientProxyConfig::Websocket(_)));
}
}