shoes 0.3.2

A multi-protocol proxy server.
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
//! DNS configuration types.

use serde::{Deserialize, Serialize};

use crate::config::types::rules::ClientChain;
use crate::config::types::selection::ConfigSelection;
use crate::dns::IpStrategy;
use crate::option_util::NoneOrSome;

/// Default timeout for DNS resolution in seconds.
fn default_timeout_secs() -> u32 {
    5
}

/// Default connect timeout for DNS upstream connections in seconds.
fn default_connect_timeout_secs() -> u32 {
    5
}

/// Default number of retry attempts for custom DNS groups.
/// Lower than hickory's default to avoid turning transient failures into slow successes.
fn default_attempts() -> usize {
    1
}

/// A DNS server specification in config.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum DnsServerSpec {
    /// Simple URL string: "system", "udp://8.8.8.8", etc.
    /// Must be IP-based (no hostnames). Cannot have bootstrap_url.
    Simple(String),
    /// Object with URL and optional client_chain, bootstrap_url, server_name, ip_strategy.
    WithOptions {
        url: String,
        #[serde(default)]
        client_chain: NoneOrSome<ConfigSelection<ClientChain>>,
        /// Bootstrap resolver for hostname resolution.
        /// Can be a URL string (e.g., "udp://8.8.8.8") or a dns_group name.
        #[serde(default)]
        bootstrap_url: Option<String>,
        /// SNI server name override for TLS/HTTPS. Defaults to hostname from URL.
        #[serde(default)]
        server_name: Option<String>,
        /// IP lookup strategy for DNS resolution. Defaults to ipv4_then_ipv6.
        #[serde(default)]
        ip_strategy: IpStrategy,
        /// Timeout for DNS resolution in seconds. Defaults to 5. Set to 0 to disable.
        #[serde(default = "default_timeout_secs")]
        timeout_secs: u32,
        /// Timeout for establishing connections to DNS upstreams in seconds.
        /// Defaults to 5. Separate from timeout_secs which covers the full request.
        /// For plain `tcp://` upstreams, hickory also passes the request timeout
        /// into `connect_tcp`, so the runtime uses the shorter of that value and
        /// this connect timeout.
        #[serde(default = "default_connect_timeout_secs")]
        connect_timeout_secs: u32,
        /// Number of retry attempts for failed queries. Defaults to 1.
        #[serde(default = "default_attempts")]
        attempts: usize,
    },
}

impl DnsServerSpec {
    /// Check if a string looks like a DNS URL (has known scheme) vs a group reference.
    fn is_url_string(s: &str) -> bool {
        s == "system" || s.contains("://")
    }

    /// Get the group name if this is a group reference.
    pub fn as_group_ref(&self) -> Option<&str> {
        if let Self::Simple(s) = self
            && !Self::is_url_string(s)
        {
            return Some(s);
        }
        None
    }

    /// Get the URL string from this spec.
    /// Panics if called on a group reference - use as_group_ref() to check first.
    pub fn url(&self) -> &str {
        match self {
            Self::Simple(s) => {
                debug_assert!(Self::is_url_string(s), "called url() on group reference");
                s
            }
            Self::WithOptions { url, .. } => url,
        }
    }

    /// Get the client_chain.
    pub fn client_chains(&self) -> &NoneOrSome<ConfigSelection<ClientChain>> {
        static NONE: NoneOrSome<ConfigSelection<ClientChain>> = NoneOrSome::None;
        if let Self::WithOptions { client_chain, .. } = self {
            client_chain
        } else {
            &NONE
        }
    }

    /// Get the bootstrap_url if present.
    pub fn bootstrap_url(&self) -> Option<&str> {
        if let Self::WithOptions { bootstrap_url, .. } = self {
            bootstrap_url.as_deref()
        } else {
            None
        }
    }

    /// Get the server_name override if present.
    pub fn server_name(&self) -> Option<&str> {
        if let Self::WithOptions { server_name, .. } = self {
            server_name.as_deref()
        } else {
            None
        }
    }

    /// Get the ip_strategy (defaults to Ipv4ThenIpv6 for Simple variant).
    pub fn ip_strategy(&self) -> IpStrategy {
        if let Self::WithOptions { ip_strategy, .. } = self {
            *ip_strategy
        } else {
            IpStrategy::default()
        }
    }

    /// Get the timeout in seconds (defaults to 5 for Simple variant).
    /// Returns 0 if timeout is disabled.
    pub fn timeout_secs(&self) -> u32 {
        if let Self::WithOptions { timeout_secs, .. } = self {
            *timeout_secs
        } else {
            default_timeout_secs()
        }
    }

    /// Get the connect timeout in seconds (defaults to 5 for Simple variant).
    pub fn connect_timeout_secs(&self) -> u32 {
        if let Self::WithOptions {
            connect_timeout_secs,
            ..
        } = self
        {
            *connect_timeout_secs
        } else {
            default_connect_timeout_secs()
        }
    }

    /// Get the number of retry attempts (defaults to 1 for Simple variant).
    pub fn attempts(&self) -> usize {
        if let Self::WithOptions { attempts, .. } = self {
            *attempts
        } else {
            default_attempts()
        }
    }
}

/// DNS group configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DnsConfigGroup {
    pub dns_group: String,
    #[serde(alias = "dns_server")]
    pub dns_servers: NoneOrSome<DnsServerSpec>,
}

/// DNS configuration for servers.
/// The `servers` field can be a group name, inline specs, or None (use default).
/// After validation, `servers` is mutated to a single group name reference.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DnsConfig {
    #[serde(alias = "server")]
    pub servers: NoneOrSome<DnsServerSpec>,
}

impl DnsConfig {
    /// Get the resolved group name after validation.
    /// Returns None if servers was None/Unspecified (use default system resolver).
    /// Panics if called before validation or if servers wasn't resolved properly.
    pub fn resolved_group(&self) -> Option<&str> {
        match &self.servers {
            NoneOrSome::Unspecified | NoneOrSome::None => None,
            NoneOrSome::One(spec) => Some(
                spec.as_group_ref()
                    .expect("DnsConfig.servers should be a single group name after validation"),
            ),
            NoneOrSome::Some(_) => {
                panic!("DnsConfig.servers should be a single group name after validation")
            }
        }
    }
}

/// A DNS server spec with all group references expanded.
/// Client chains contain actual ClientConfig objects, not group names.
#[derive(Debug, Clone)]
pub struct ExpandedDnsSpec {
    pub url: String,
    pub server_name: Option<String>,
    /// Client chains with all group refs resolved to configs.
    pub client_chains: Vec<ClientChain>,
    /// Bootstrap resolver URL or group name. Groups are resolved at runtime.
    pub bootstrap_url: Option<String>,
    pub ip_strategy: IpStrategy,
    /// Timeout for DNS resolution in seconds. 0 means no timeout.
    pub timeout_secs: u32,
    /// Timeout for establishing connections to DNS upstreams in seconds.
    pub connect_timeout_secs: u32,
    /// Number of retry attempts for failed queries.
    pub attempts: usize,
}

/// A DNS group with all specs expanded.
#[derive(Debug, Clone)]
pub struct ExpandedDnsGroup {
    pub name: String,
    pub specs: Vec<ExpandedDnsSpec>,
}

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

    #[test]
    fn test_dns_server_spec_simple() {
        let yaml = r#"system"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert!(matches!(spec, DnsServerSpec::Simple(ref s) if s == "system"));
        assert_eq!(spec.url(), "system");
        assert!(spec.client_chains().is_empty());
    }

    #[test]
    fn test_dns_server_spec_url() {
        let yaml = r#"udp://8.8.8.8"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.url(), "udp://8.8.8.8");
    }

    #[test]
    fn test_dns_server_spec_with_chain() {
        let yaml = r#"
url: https://1.1.1.1/dns-query
client_chain: my-proxy
"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.url(), "https://1.1.1.1/dns-query");
        assert!(!spec.client_chains().is_empty());
        assert!(spec.bootstrap_url().is_none());
        assert!(spec.server_name().is_none());
    }

    #[test]
    fn test_dns_server_spec_with_bootstrap() {
        let yaml = r#"
url: tls://dns.google
bootstrap_url: udp://8.8.8.8
server_name: dns.google
"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.url(), "tls://dns.google");
        assert!(spec.client_chains().is_empty());
        assert_eq!(spec.bootstrap_url(), Some("udp://8.8.8.8"));
        assert_eq!(spec.server_name(), Some("dns.google"));
    }

    #[test]
    fn test_dns_server_spec_with_bootstrap_group_ref() {
        let yaml = r#"
url: https://cloudflare-dns.com/dns-query
client_chain: privacy-proxy
bootstrap_url: fast-dns
"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.url(), "https://cloudflare-dns.com/dns-query");
        assert!(!spec.client_chains().is_empty());
        assert_eq!(spec.bootstrap_url(), Some("fast-dns"));
    }

    #[test]
    fn test_dns_config_group() {
        let yaml = r#"
dns_group: my-dns
dns_servers:
  - system
  - udp://8.8.8.8
  - url: https://1.1.1.1/dns-query
    client_chain: proxy-group
"#;
        let group: DnsConfigGroup = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(group.dns_group, "my-dns");
        let servers = group.dns_servers.into_vec();
        assert_eq!(servers.len(), 3);
    }

    #[test]
    fn test_dns_config_bare_group_name_rejected() {
        // Bare group names are not allowed - must use servers field
        let yaml = r#"my-dns-group"#;
        let result: Result<DnsConfig, _> = serde_yaml::from_str(yaml);
        assert!(result.is_err(), "bare group name should be rejected");
    }

    #[test]
    fn test_dns_config_with_servers() {
        let yaml = r#"
servers:
  - system
  - udp://8.8.8.8
"#;
        let config: DnsConfig = serde_yaml::from_str(yaml).unwrap();
        let servers = config.servers.into_vec();
        assert_eq!(servers.len(), 2);
    }

    #[test]
    fn test_dns_config_with_servers_group_ref() {
        // Group reference inside servers field is allowed
        let yaml = r#"
servers: my-dns-group
"#;
        let config: DnsConfig = serde_yaml::from_str(yaml).unwrap();
        let servers = config.servers.into_vec();
        assert_eq!(servers.len(), 1);
        assert!(servers[0].as_group_ref().is_some());
        assert_eq!(servers[0].as_group_ref(), Some("my-dns-group"));
    }

    #[test]
    fn test_dns_config_resolved_group() {
        // After validation, servers should be a single group name
        let config = DnsConfig {
            servers: NoneOrSome::One(DnsServerSpec::Simple("my-resolved-group".to_string())),
        };
        assert_eq!(config.resolved_group(), Some("my-resolved-group"));
    }

    #[test]
    fn test_dns_server_spec_group_ref() {
        // Group reference (no URL scheme)
        let yaml = r#"base-dns"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert!(spec.as_group_ref().is_some());
        assert_eq!(spec.as_group_ref(), Some("base-dns"));
    }

    #[test]
    fn test_dns_server_spec_url_not_group_ref() {
        // URLs should not be detected as group refs
        for url in [
            "system",
            "udp://8.8.8.8",
            "tcp://1.1.1.1",
            "tls://dns.google",
            "https://cloudflare.com/dns-query",
            "h3://cloudflare.com/dns-query",
        ] {
            let spec = DnsServerSpec::Simple(url.to_string());
            assert!(
                !spec.as_group_ref().is_some(),
                "{} should not be a group ref",
                url
            );
            assert!(spec.as_group_ref().is_none());
        }
    }

    #[test]
    fn test_dns_server_spec_with_options_not_group_ref() {
        // WithOptions is never a group ref
        let spec = DnsServerSpec::WithOptions {
            url: "tls://dns.google".to_string(),
            client_chain: NoneOrSome::None,
            bootstrap_url: None,
            server_name: None,
            ip_strategy: IpStrategy::default(),
            timeout_secs: default_timeout_secs(),
            connect_timeout_secs: default_connect_timeout_secs(),
            attempts: default_attempts(),
        };
        assert!(!spec.as_group_ref().is_some());
        assert!(spec.as_group_ref().is_none());
    }

    #[test]
    fn test_dns_group_with_composition() {
        let yaml = r#"
dns_group: full-dns
dns_servers:
  - base-dns
  - fast-dns
  - tls://1.1.1.1
"#;
        let group: DnsConfigGroup = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(group.dns_group, "full-dns");
        let servers = group.dns_servers.into_vec();
        assert_eq!(servers.len(), 3);
        assert!(servers[0].as_group_ref().is_some());
        assert_eq!(servers[0].as_group_ref(), Some("base-dns"));
        assert!(servers[1].as_group_ref().is_some());
        assert_eq!(servers[1].as_group_ref(), Some("fast-dns"));
        assert!(!servers[2].as_group_ref().is_some());
    }

    #[test]
    fn test_dns_server_spec_attempts_default() {
        let yaml = r#"udp://8.8.8.8"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.attempts(), 1);
    }

    #[test]
    fn test_dns_server_spec_attempts_custom() {
        let yaml = r#"
url: tls://8.8.8.8
server_name: dns.google
attempts: 3
"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.attempts(), 3);
    }

    #[test]
    fn test_dns_server_spec_connect_timeout_default() {
        let yaml = r#"udp://8.8.8.8"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.connect_timeout_secs(), 5);
    }

    #[test]
    fn test_dns_server_spec_connect_timeout_custom() {
        let yaml = r#"
url: tls://8.8.8.8
connect_timeout_secs: 2
"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.connect_timeout_secs(), 2);
    }

    #[test]
    fn test_dns_server_spec_timeout_secs_default() {
        let yaml = r#"udp://8.8.8.8"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.timeout_secs(), 5);
    }

    #[test]
    fn test_dns_server_spec_full_options() {
        let yaml = r#"
url: https://1.1.1.1/dns-query
server_name: cloudflare-dns.com
timeout_secs: 3
connect_timeout_secs: 1
attempts: 1
ip_strategy: ipv4_only
"#;
        let spec: DnsServerSpec = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(spec.timeout_secs(), 3);
        assert_eq!(spec.connect_timeout_secs(), 1);
        assert_eq!(spec.attempts(), 1);
        assert_eq!(spec.ip_strategy(), IpStrategy::Ipv4Only);
        assert_eq!(spec.server_name(), Some("cloudflare-dns.com"));
    }
}