//! Checks a configuration before the service takes it, as upstream's assertions do at //! evaluation. Errors refuse the configuration; warnings go with it. use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use super::{Backend, Config, GroupStrategy, Selection, ZapretEngine}; use crate::derived::{self, BUILTIN_TAGS}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Severity { Error, Warning, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Issue { pub severity: Severity, /// The option it is about, as `proxy.outbounds.2.tag`. pub path: String, pub message: String, } struct Issues(Vec); impl Issues { fn error(&mut self, path: impl Into, message: impl Into) { self.0.push(Issue { severity: Severity::Error, path: path.into(), message: message.into() }); } fn warn(&mut self, path: impl Into, message: impl Into) { self.0.push(Issue { severity: Severity::Warning, path: path.into(), message: message.into() }); } /// `used` needs `dependency`: the shape of most of upstream's assertions. fn requires(&mut self, used: bool, dependency: bool, path: &str, used_label: &str, dependency_label: &str) { if used && !dependency { self.error(path, format!("{used_label} requires {dependency_label}")); } } } fn tag_pattern_ok(tag: &str) -> bool { let mut chars = tag.chars(); matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric()) && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) } /// A name that becomes part of a file path, a Windows service name or an adapter name: /// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters. pub(crate) fn path_name_ok(name: &str) -> bool { !name.is_empty() && name.len() <= 64 && !name.starts_with('.') && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) } fn profile_name_ok(name: &str) -> bool { let mut chars = name.chars(); matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit()) && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') } fn count_some(values: &[bool]) -> usize { values.iter().filter(|v| **v).count() } /// Every problem with `cfg`, errors first. pub fn validate(cfg: &Config) -> Vec { let mut v = Issues(Vec::new()); proxy(cfg, &mut v); tunnels(cfg, &mut v); zapret(cfg, &mut v); per_app(cfg, &mut v); inbounds(cfg, &mut v); ports(cfg, &mut v); let mut issues = v.0; issues.sort_by_key(|i| i.severity != Severity::Error); issues } fn proxy(cfg: &Config, v: &mut Issues) { let p = &cfg.proxy; let sing_box = p.backend.runs_sing_box(); let mut seen = BTreeSet::new(); for (i, ob) in p.outbounds.iter().enumerate() { let path = format!("proxy.outbounds.{i}"); if ob.tag.is_empty() { v.error(format!("{path}.tag"), "an outbound needs a tag"); } else if BUILTIN_TAGS.contains(&ob.tag.as_str()) { v.error(format!("{path}.tag"), format!("'{}' is a builtin target and cannot be an outbound's tag", ob.tag)); } else if !seen.insert(ob.tag.as_str()) { v.error(format!("{path}.tag"), format!("outbound tag '{}' is used twice", ob.tag)); } let sources = [ob.url.is_some(), ob.url_file.is_some(), ob.sing_box_json.is_some(), ob.xray_json.is_some()]; if count_some(&sources) != 1 { v.error(&path, format!("outbound '{}' sets {} of url, urlFile, singBoxJson and xrayJson; it needs exactly one", ob.tag, count_some(&sources))); } if ob.sing_box_json.is_some() && p.backend == Backend::Xray { v.error(&path, format!("outbound '{}' is sing-box JSON, which the xray backend cannot run", ob.tag)); } if ob.xray_json.is_some() && p.backend == Backend::SingBox { v.error(&path, format!("outbound '{}' is XRay JSON, which the sing-box backend cannot run", ob.tag)); } if !ob.routing.rule_sets.is_empty() && !sing_box { v.error(format!("{path}.routing.ruleSets"), "rule sets need the sing-box or hybrid backend"); } for name in &ob.routing.rule_sets { if !p.routing.rule_sets.contains_key(name) { v.error(format!("{path}.routing.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets")); } } } let mut subs = BTreeSet::new(); for (i, sub) in p.subscriptions.iter().enumerate() { let path = format!("proxy.subscriptions.{i}"); if !tag_pattern_ok(&sub.tag) { v.error(format!("{path}.tag"), format!("subscription tag '{}' must start with a letter or digit and hold only letters, digits, '.', '_' and '-'", sub.tag)); } else if !subs.insert(sub.tag.as_str()) { v.error(format!("{path}.tag"), format!("subscription tag '{}' is used twice", sub.tag)); } if count_some(&[sub.url.is_some(), sub.url_file.is_some()]) != 1 { v.error(&path, format!("subscription '{}' needs exactly one of url and urlFile", sub.tag)); } } let known = |t: &str| derived::is_known_target(cfg, t); for (i, ob) in p.outbounds.iter().enumerate() { if let Some(hop) = &ob.detour { if hop == &ob.tag { v.error(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' cannot chain through itself", ob.tag)); } else if !known(hop) { // A subscription entry, perhaps: those only exist once fetched. v.warn(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' chains through '{hop}', which names no outbound declared here; it must be a subscription entry", ob.tag)); } } } for (i, rule) in p.routing.rules.iter().enumerate() { let path = format!("proxy.routing.rules.{i}"); if !known(&rule.outbound) { v.error(format!("{path}.outbound"), format!("routing rule target '{}' is not an outbound, a group, or proxy, direct or block", rule.outbound)); } if rule.matches.is_empty() && rule.process_names.is_empty() && rule.process_paths.is_empty() { v.warn(&path, "this rule matches nothing"); } if !rule.matches.rule_sets.is_empty() && !sing_box { v.error(format!("{path}.ruleSets"), "rule sets need the sing-box or hybrid backend"); } if (!rule.process_names.is_empty() || !rule.process_paths.is_empty()) && !sing_box { v.error(&path, "matching programs needs the sing-box or hybrid backend"); } for name in &rule.matches.rule_sets { if !p.routing.rule_sets.contains_key(name) { v.error(format!("{path}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets")); } } } for (bucket, m) in [("proxy", &p.routing.proxy), ("direct", &p.routing.direct), ("block", &p.routing.block)] { for name in &m.rule_sets { if !p.routing.rule_sets.contains_key(name) { v.error(format!("proxy.routing.{bucket}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets")); } } } if !p.routing.rule_sets.is_empty() && !sing_box { v.error("proxy.routing.ruleSets", "rule sets need the sing-box or hybrid backend"); } for (name, rs) in &p.routing.rule_sets { if !rs.url.starts_with("https://") || rs.url.len() <= "https://".len() { v.error(format!("proxy.routing.ruleSets.{name}.url"), "a rule set is fetched over https only"); } } if !p.groups.is_empty() && !sing_box { v.error("proxy.groups", "outbound groups need the sing-box or hybrid backend"); } for (name, group) in &p.groups { let path = format!("proxy.groups.{name}"); if !path_name_ok(name) { v.error(&path, format!("group name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot")); } if BUILTIN_TAGS.contains(&name.as_str()) || p.outbounds.iter().any(|o| &o.tag == name) { v.error(&path, format!("group '{name}' takes a tag an outbound or builtin already has")); } for member in &group.outbounds { if member == name { v.error(format!("{path}.outbounds"), format!("group '{name}' cannot contain itself")); } else if !known(member) { v.warn(format!("{path}.outbounds"), format!("member '{member}' names no outbound declared here; it is left out unless a subscription brings it")); } } for sub in &group.subscriptions { if !p.subscriptions.iter().any(|s| &s.tag == sub) { v.error(format!("{path}.subscriptions"), format!("subscription '{sub}' does not exist")); } } if group.outbounds.is_empty() && group.subscriptions.is_empty() && group.match_.is_empty() { v.warn(&path, format!("group '{name}' has no members: it blocks")); } if group.strategy != GroupStrategy::Failover && !group.failback { v.warn(format!("{path}.failback"), "failback only applies to the failover strategy"); } } if p.selection == Selection::Failover && !sing_box { v.error("proxy.selection", "\"failover\" selection needs the sing-box or hybrid backend"); } if p.auto_proxy.enable && !sing_box { v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend"); } if p.auto_proxy.slow_below_kibps > 0 && p.auto_proxy.enable && p.selection == Selection::First { v.warn("proxy.autoProxy.slowBelowKiBps", "slow destinations are only routed with a selection other than \"first\""); } if p.dns.fake_ip.enable && !sing_box { v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend"); } if p.enable && !derived::has_available_outbounds(cfg) { v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added"); } v.requires(p.autostart.is_some(), p.tun.enable, "proxy.autostart", "proxy.autostart = \"tun\"", "proxy.tun.enable = true"); v.requires(p.tun.enable, p.enable, "proxy.tun.enable", "proxy.tun.enable", "proxy.enable = true"); v.requires(p.system_proxy.enable, p.enable, "proxy.systemProxy.enable", "proxy.systemProxy.enable", "proxy.enable = true"); let auth = &p.listener.auth; if auth.username.is_some() && auth.password.is_none() && auth.password_file.is_none() { v.error("proxy.listener.auth", "a username needs password or passwordFile"); } if auth.password.is_some() && auth.password_file.is_some() { v.error("proxy.listener.auth", "set password or passwordFile, not both"); } if auth.username.is_none() && (auth.password.is_some() || auth.password_file.is_some()) { v.error("proxy.listener.auth", "a password needs a username"); } for (label, value) in [("username", &auth.username), ("password", &auth.password)] { if value.as_deref().is_some_and(|s| s.is_empty() || s.chars().any(char::is_whitespace)) { v.error(format!("proxy.listener.auth.{label}"), "it must be a single word"); } } if p.system_proxy.enable && auth.enabled() { v.warn("proxy.systemProxy.enable", "the system proxy cannot carry a login: apps that follow it will be asked for one"); } } fn tunnels(cfg: &Config, v: &mut Issues) { let proxy_on = cfg.proxy.enable; let w = &cfg.warp; if w.enable { if w.as_outbound.is_none() && !w.as_amnezia_wg { v.warn("warp.enable", "WARP is on, but neither asOutbound nor asAmneziaWg uses it"); } if w.as_outbound.is_some() && w.as_amnezia_wg { v.error("warp.asAmneziaWg", "asAmneziaWg cannot be used with asOutbound"); } v.requires(w.as_outbound.is_some(), proxy_on, "warp.asOutbound", "warp.asOutbound", "proxy.enable = true"); v.requires(w.as_amnezia_wg, cfg.amnezia_wg.enable, "warp.asAmneziaWg", "warp.asAmneziaWg", "amneziaWg.enable = true"); v.requires(w.autostart, w.as_amnezia_wg, "warp.autostart", "warp.autostart", "warp.asAmneziaWg = true"); if w.instances.is_some() && !w.devices.is_empty() { v.error("warp.instances", "instances cannot be used with devices"); } if w.devices.len() > 1 && w.devices.contains_key(derived::WARP_TAG) { v.error("warp.devices", "with several devices, \"warp\" names their group and cannot be a device"); } if w.config_file.is_some() && w.config.is_some() { v.error("warp.config", "set configFile or config, not both"); } for name in w.devices.keys() { if !path_name_ok(name) { v.error(format!("warp.devices.{name}"), "a device name takes letters, digits, '.', '_' and '-', and no leading dot"); } } } let a = &cfg.amnezia_wg; if a.enable { let mut autostarts = Vec::new(); for (name, p) in &a.profiles { let path = format!("amneziaWg.profiles.{name}"); let sources = [p.config_file.is_some(), p.config.is_some(), p.vpn_file.is_some(), p.vpn.is_some(), p.settings.is_some()]; if count_some(&sources) != 1 { v.error(&path, format!("profile '{name}' needs exactly one of configFile, config, vpnFile, vpn and settings")); } if p.autostart { autostarts.push(name.clone()); } if p.as_outbound.is_some() && p.autostart { v.warn(format!("{path}.autostart"), "an outbound always runs: autostart only applies to a global profile"); } v.requires(p.as_outbound.is_some(), proxy_on, &format!("{path}.asOutbound"), &format!("amneziaWg.profiles.{name}.asOutbound"), "proxy.enable = true"); if !path_name_ok(name) { v.error(&path, format!("profile name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot")); } if let Some(iface) = &p.interface_name && (!path_name_ok(iface) || iface.len() > 32) { v.error(format!("{path}.interfaceName"), "a tunnel name takes letters, digits, '.', '_' and '-' (at most 32, no leading dot)"); } if let Some(settings) = &p.settings { if settings.peers.is_empty() { v.error(format!("{path}.settings.peers"), "a profile needs a peer"); } if settings.private_key.is_some() == settings.private_key_file.is_some() { v.error(format!("{path}.settings"), "set exactly one of privateKey and privateKeyFile"); } } if BUILTIN_TAGS.contains(&name.as_str()) { v.error(&path, format!("'{name}' is a builtin target")); } } if w.autostart { autostarts.push(derived::WARP_TAG.into()); } if autostarts.len() > 1 { v.error("amneziaWg.profiles", format!("only one global profile can autostart, not {}", autostarts.join(", "))); } if !autostarts.is_empty() && cfg.proxy.autostart.is_some() { v.error("proxy.autostart", "only one global mode can autostart: a TUN and an AmneziaWG profile both do"); } } let t = &cfg.tor; if t.enable { v.requires(t.as_outbound, proxy_on, "tor.asOutbound", "tor.asOutbound", "proxy.enable = true"); v.requires(t.onion_service.enable, cfg.inbounds.enable, "tor.onionService.enable", "tor.onionService.enable", "inbounds.enable = true"); if !t.as_outbound && !t.onion_service.enable { v.warn("tor.enable", "Tor is on, but neither asOutbound nor onionService uses it"); } if t.socks_port == t.control_port { v.error("tor.controlPort", "Tor's SOCKS and control ports must differ"); } } let s = &cfg.ssh_proxy; if s.enable { if s.server.host.is_none() { v.error("sshProxy.server.host", "the SSH tunnel needs a server"); } if s.server.user.is_none() { v.error("sshProxy.server.user", "the SSH tunnel needs a login user"); } v.requires(s.as_outbound, proxy_on, "sshProxy.asOutbound", "sshProxy.asOutbound", "proxy.enable = true"); if s.strict_host_key_checking == crate::config::StrictHostKeyChecking::Yes && s.known_hosts_file.is_none() && s.host_key_file.is_none() && s.host_key.is_empty() { v.error("sshProxy.strictHostKeyChecking", "\"yes\" needs the server's keys: knownHostsFile, hostKeyFile or hostKey"); } } let g = &cfg.tg_ws_proxy; if g.enable { if g.secret.is_some() && g.secret_file.is_some() { v.error("tgWsProxy.secret", "set secret or secretFile, not both"); } if let Some(secret) = &g.secret && (secret.len() != 32 || !secret.chars().all(|c| c.is_ascii_hexdigit())) { v.error("tgWsProxy.secret", "an MTProto secret is 32 hex digits"); } if g.buffer_kib < 4 { v.error("tgWsProxy.bufferKiB", "the buffer is at least 4 KiB"); } } let wl = &cfg.whitelist_bypass; if wl.enable { v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true"); for name in wl.joiners.keys().chain(wl.creators.keys()) { if !path_name_ok(name) { v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot"); } } for (name, j) in &wl.joiners { if j.platform == crate::config::WlPlatform::Vk { v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here"); } } if wl.joiners.is_empty() && wl.creators.is_empty() { v.warn("whitelistBypass.enable", "whitelist-bypass is on without creators or joiners"); } } } fn zapret(cfg: &Config, v: &mut Issues) { let z = &cfg.zapret; if !z.enable { return; } if z.engine == ZapretEngine::DiscordYoutube { let mut names = BTreeSet::new(); for (i, rule) in z.discord_youtube.hostlist_rules.iter().enumerate() { let path = format!("zapret.zapret-discord-youtube.hostlistRules.{i}"); if !profile_name_ok(&rule.name) { v.error(format!("{path}.name"), "a list name takes lowercase letters, digits and '-'"); } else if !names.insert(rule.name.as_str()) { v.error(format!("{path}.name"), format!("list '{}' is defined twice", rule.name)); } if rule.config_name.is_some() && !rule.nfqws_args.is_empty() { v.error(&path, "configName cannot be used with nfqwsArgs"); } if rule.preset.is_none() && rule.config_name.is_none() && rule.nfqws_args.is_empty() && rule.default_domains.len() != 1 { v.error(&path, "without preset, configName or nfqwsArgs, use exactly one of defaultDomains, so its strategy can be inferred"); } if rule.domains.is_empty() && rule.default_domains.is_empty() && rule.ips.is_empty() && rule.default_ips.is_empty() { v.warn(&path, format!("list '{}' holds no sites", rule.name)); } } } if z.engine == ZapretEngine::Zapret2 { let ah = &z.zapret2.auto_hostlist; for (label, value) in [("failThreshold", ah.fail_threshold), ("failTime", ah.fail_time), ("retransThreshold", ah.retrans_threshold), ("udpOut", ah.udp_out)] { if value == 0 { v.error(format!("zapret.zapret2.autoHostlist.{label}"), "it must be greater than zero"); } } if z.zapret2.proxy_fallback && !derived::has_available_outbounds(cfg) { v.warn("zapret.zapret2.proxyFallback", "proxyFallback needs an outbound to fall back to"); } if z.zapret2.cutoff.enable && z.zapret2.cutoff.proxy_fallback && !derived::sing_box_enabled(cfg) { v.warn("zapret.zapret2.cutoff.proxyFallback", "the cutoff fallback needs the sing-box backend"); } } if z.cidr_exemption.enable && z.cidr_exemption.cidrs.is_empty() { v.warn("zapret.cidrExemption", "the exemption is on but lists no networks"); } } fn per_app(cfg: &Config, v: &mut Issues) { let pa = &cfg.per_app_routing; if !pa.enable { return; } v.requires(true, cfg.proxy.enable, "perAppRouting.enable", "perAppRouting", "proxy.enable = true"); if !cfg.proxy.backend.runs_sing_box() { v.error("perAppRouting.enable", "per-app routing needs the sing-box or hybrid backend"); } let mut names = BTreeSet::new(); for (i, prof) in pa.profiles.iter().enumerate() { let path = format!("perAppRouting.profiles.{i}"); if !profile_name_ok(&prof.name) { v.error(format!("{path}.name"), "a profile name takes lowercase letters, digits and '-'"); } else if !names.insert(prof.name.as_str()) { v.error(format!("{path}.name"), format!("profile '{}' is defined twice", prof.name)); } if !derived::is_known_target(cfg, &prof.outbound) { v.error(format!("{path}.outbound"), format!("'{}' is not an outbound, a group, or proxy, direct or block", prof.outbound)); } } if pa.profiles.len() > 200 { v.error("perAppRouting.profiles", "at most 200 profiles"); } } fn inbounds(cfg: &Config, v: &mut Issues) { let ib = &cfg.inbounds; if !ib.enable { return; } let via_ok = |via: &str| { matches!(via, "proxy" | "direct" | "block") || cfg.proxy.outbounds.iter().any(|o| o.tag == via) }; if !via_ok(&ib.routing.via) { v.error("inbounds.routing.via", format!("'{}' is not proxy, direct, block or a proxy.outbounds tag", ib.routing.via)); } v.requires(ib.routing.via == "proxy", cfg.proxy.enable, "inbounds.routing.via", "inbounds.routing.via = \"proxy\"", "proxy.enable = true"); v.requires(ib.subscriptions.enable, ib.share_links, "inbounds.subscriptions.enable", "inbounds.subscriptions", "inbounds.shareLinks = true"); let mut ports: BTreeMap<(u16, bool), &str> = BTreeMap::new(); for (tag, l) in &ib.listeners { let path = format!("inbounds.listeners.{tag}"); if !path_name_ok(tag) { v.error(&path, format!("listener tag '{tag}' takes letters, digits, '.', '_' and '-', and no leading dot")); } let sources = [l.kind.is_some(), l.xray_json.is_some(), l.json_file.is_some()]; if count_some(&sources) != 1 { v.error(&path, format!("listener '{tag}' needs exactly one of type, xrayJson and jsonFile")); } for user in &l.users { if !ib.users.contains_key(user) { v.error(format!("{path}.users"), format!("listener '{tag}' names user '{user}', which inbounds.users does not define")); } } if let Some(via) = &l.via && !via_ok(via) { v.error(format!("{path}.via"), format!("'{via}' is not proxy, direct, block or a proxy.outbounds tag")); } if l.tls.enable && l.reality.enable { v.error(&path, "tls cannot be used with reality"); } use crate::config::InboundType as T; let udp = matches!(l.kind, Some(T::Hysteria2) | Some(T::Amneziawg)); if let Some(other) = ports.insert((l.port, udp), tag) { v.error(format!("{path}.port"), format!("listeners '{other}' and '{tag}' share port {}", l.port)); } match l.kind { Some(T::Hysteria2) if !l.tls.enable => { v.error(format!("{path}.tls"), "hysteria2 needs tls"); } Some(T::Trojan) if !l.tls.enable && !l.reality.enable => { v.error(format!("{path}.tls"), "trojan needs tls or reality"); } _ => {} } if l.reality.enable { if l.reality.server_names.is_empty() { v.error(format!("{path}.reality.serverNames"), "REALITY needs at least one server name"); } if l.reality.private_key.is_some() == l.reality.private_key_file.is_some() { v.error(format!("{path}.reality"), "set exactly one of privateKey and privateKeyFile"); } if ib.share_links && l.reality.public_key.is_none() { v.warn(format!("{path}.reality.publicKey"), "share links need the public key"); } } if l.tls.enable && (l.tls.certificate_file.is_none() || l.tls.key_file.is_none()) { v.error(format!("{path}.tls"), "TLS needs certificateFile and keyFile"); } if l.flow.is_some() && l.transport.kind != "raw" { v.error(format!("{path}.flow"), "the vision flow only works on the raw transport"); } } let mut orders = BTreeMap::new(); for (name, user) in &ib.users { if !path_name_ok(name) { v.error(format!("inbounds.users.{name}"), format!("user name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot")); } if let Some(order) = user.order && let Some(other) = orders.insert(order, name) { v.error(format!("inbounds.users.{name}.order"), format!("users '{other}' and '{name}' share order {order}")); } if user.uuid.is_some() && user.uuid_file.is_some() { v.error(format!("inbounds.users.{name}"), "set uuid or uuidFile, not both"); } if user.password.is_some() && user.password_file.is_some() { v.error(format!("inbounds.users.{name}"), "set password or passwordFile, not both"); } } if ib.manager.enable && (ib.manager.interval < 5 || ib.manager.interval > 3600) { v.error("inbounds.manager.interval", "between 5 and 3600 seconds"); } if ib.manager.api.listen.is_some() && ib.manager.api.tokens_file.is_none() { v.error("inbounds.manager.api.listen", "a TCP API needs tokensFile"); } } /// Loopback listeners must not collide: whichever starts second would die. fn ports(cfg: &Config, v: &mut Issues) { let mut taken: BTreeMap = BTreeMap::new(); let mut claim = |port: u16, who: String, v: &mut Issues| { if let Some(other) = taken.get(&port) { v.error(who.clone(), format!("port {port} is taken by {other} too")); } else { taken.insert(port, who); } }; let p = &cfg.proxy; if p.enable { claim(p.listener.port, "proxy.listener.port".into(), v); if p.backend.runs_sing_box() { claim(p.sing_box.clash_api_port, "proxy.singBox.clashApiPort".into(), v); } if p.backend.runs_sing_box() { claim(p.sing_box.test_port, "proxy.singBox.testPort".into(), v); } } if cfg.tor.enable { claim(cfg.tor.socks_port, "tor.socksPort".into(), v); claim(cfg.tor.control_port, "tor.controlPort".into(), v); } if cfg.ssh_proxy.enable { claim(cfg.ssh_proxy.listener.port, "sshProxy.listener.port".into(), v); } if cfg.tg_ws_proxy.enable { claim(cfg.tg_ws_proxy.listener.port, "tgWsProxy.listener.port".into(), v); } if cfg.per_app_routing.enable { for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() { claim( cfg.per_app_routing.listener_base_port.saturating_add(i as u16), format!("perAppRouting.profiles.{i} ({})", prof.name), v, ); } } for ob in derived::extra_outbounds(cfg) { use derived::ExtraKind as K; match ob.kind { K::Awg { port, kind: crate::config::AwgOutboundKind::Userspace, .. } => { claim(port, format!("AmneziaWG outbound '{}'", ob.tag), v) } K::WlJoiner { port, .. } => claim(port, format!("whitelist-bypass joiner '{}'", ob.tag), v), K::Warp { device } if device.kind == crate::config::WarpOutboundKind::Userspace => { claim(device.port, format!("WARP device '{}'", device.tag), v) } _ => {} } } if p.enable && p.auto_proxy.enable { let base = p.auto_proxy.probe_base_port; for i in 0..p.auto_proxy.max_exits.min(64) as u16 { claim(base.saturating_add(i), format!("proxy.autoProxy.probeBasePort (+{i})"), v); } } } #[cfg(test)] mod tests { use super::*; use crate::config::{Group, Outbound, RoutingRule}; fn errors(cfg: &Config) -> Vec { validate(cfg) .into_iter() .filter(|i| i.severity == Severity::Error) .map(|i| format!("{}: {}", i.path, i.message)) .collect() } fn outbound(tag: &str) -> Outbound { Outbound { tag: tag.into(), url: Some("hy2://pw@example.com:443".into()), ..Default::default() } } #[test] fn the_default_config_is_valid() { assert_eq!(errors(&Config::default()), Vec::::new()); } #[test] fn outbound_tags_are_unique_and_not_builtin() { let mut cfg = Config::default(); cfg.proxy.enable = true; cfg.proxy.outbounds = vec![outbound("de"), outbound("de"), outbound("direct")]; let errs = errors(&cfg); assert!(errs.iter().any(|e| e.contains("'de' is used twice")), "{errs:?}"); assert!(errs.iter().any(|e| e.contains("'direct' is a builtin")), "{errs:?}"); } #[test] fn an_outbound_needs_exactly_one_source() { let mut cfg = Config::default(); cfg.proxy.outbounds = vec![Outbound { tag: "x".into(), ..Default::default() }]; assert!(errors(&cfg)[0].contains("needs exactly one")); } #[test] fn rule_targets_must_exist() { let mut cfg = Config::default(); cfg.proxy.outbounds = vec![outbound("de")]; cfg.proxy.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], ..Default::default() }); let rule = |target: &str| RoutingRule { outbound: target.into(), matches: crate::config::RouteMatch { domains: vec!["example.com".into()], ..Default::default() }, ..Default::default() }; cfg.proxy.routing.rules = vec![rule("de"), rule("eu"), rule("direct"), rule("nowhere")]; let errs = errors(&cfg); assert_eq!(errs.len(), 1, "{errs:?}"); assert!(errs[0].contains("'nowhere'")); } #[test] fn colliding_ports_are_refused() { let mut cfg = Config::default(); cfg.proxy.enable = true; cfg.proxy.outbounds = vec![outbound("de")]; cfg.tor.enable = true; cfg.tor.as_outbound = true; cfg.tor.socks_port = 1080; assert!(errors(&cfg).iter().any(|e| e.contains("port 1080"))); } #[test] fn names_that_become_paths_are_checked() { let mut cfg = Config::default(); cfg.amnezia_wg.enable = true; cfg.amnezia_wg.profiles.insert( "..\\evil".into(), crate::config::AwgProfile { config: Some("[Interface]".into()), ..Default::default() }, ); assert!(errors(&cfg).iter().any(|e| e.contains("profile name")), "{:?}", errors(&cfg)); } #[test] fn groups_need_sing_box() { let mut cfg = Config::default(); cfg.proxy.backend = Backend::Xray; cfg.proxy.groups.insert("g".into(), Group::default()); assert!(errors(&cfg).iter().any(|e| e.contains("groups need"))); } }