Files
proxy-suite-flake/windows/crates/ps-core/src/derived.rs
T
faumarayandClaude Opus 5.5 c837db1c18 windows: workspace, dev shell and the config model
Start of the native Windows port. windows/ holds a Rust workspace; this
first piece is ps-core's model of the services.proxy-suite option tree,
with upstream's names and defaults, Windows-only additions documented,
validation ported from the module's assertions, and the derived tags and
loopback ports the tunnels add.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:28:10 +03:00

263 lines
9.3 KiB
Rust

//! What the configuration implies beyond its options: the outbounds that tunnels add, the
//! loopback ports everything listens on, which backends run. Upstream's `derived.nix`.
use crate::config::{
AwgOutboundKind, Backend, Config, WarpOutboundKind, WlPlatform,
};
/// Tags no outbound may take: the routing targets every config has.
pub const BUILTIN_TAGS: [&str; 3] = ["proxy", "direct", "block"];
pub const SSH_OUTBOUND_TAG: &str = "ssh-proxy";
pub const TOR_OUTBOUND_TAG: &str = "tor";
pub const WARP_TAG: &str = "warp";
/// Fixed loopback ports, as upstream numbers them where it has them.
pub mod ports {
/// The listener `proxy-ctl proxy outbounds test` dials each outbound through.
pub const OUTBOUND_TEST: u16 = 18537;
/// The global TUN's own Clash API (it is a separate sing-box instance).
pub const TUN_CLASH_API: u16 = 19181;
/// wireproxy-awg listeners of "userspace" AmneziaWG outbounds, one each.
pub const AWG_TUNNEL_BASE: u16 = 18600;
/// whitelist-bypass joiners' SOCKS listeners, one each.
pub const WL_JOINER_BASE: u16 = 18750;
/// wireproxy-awg listeners of "userspace" WARP devices, one each.
pub const WARP_USERSPACE_BASE: u16 = 18900;
/// The hybrid backend's XRay sidecar, which sing-box hands XRay-only outbounds to.
pub const XRAY_SIDECAR_SOCKS: u16 = 33080;
pub const XRAY_SIDECAR_TUN: u16 = 33180;
}
/// An outbound that a tunnel, not `proxy.outbounds`, adds.
#[derive(Debug, Clone, PartialEq)]
pub struct ExtraOutbound {
pub tag: String,
pub kind: ExtraKind,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExtraKind {
/// OpenSSH's `-D` listener (or sing-box's own SSH outbound, which needs a host key).
Ssh,
/// Tor's SOCKS port.
Tor { port: u16 },
/// A WARP device: a WireGuard endpoint in sing-box, or wireproxy-awg on `port`.
Warp { device: WarpDeviceSpec },
/// An AmneziaWG profile used as an outbound.
Awg { profile: String, kind: AwgOutboundKind, port: u16 },
/// A whitelist-bypass joiner's SOCKS listener.
WlJoiner { platform: WlPlatform, port: u16 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct WarpDeviceSpec {
pub tag: String,
/// The first device keeps a single device's state directory, so a registration carries
/// over when more are added.
pub first: bool,
pub kind: WarpOutboundKind,
pub config_file: Option<String>,
pub config: Option<String>,
pub endpoint: Option<String>,
/// The wireproxy-awg listener, for the "userspace" kind.
pub port: u16,
/// Below the state directory: `warp` for the first device, `warp/<tag>` for the rest.
pub state_subdir: String,
}
impl WarpDeviceSpec {
/// Registered on first start: no profile was given.
pub fn auto_register(&self) -> bool {
self.config_file.is_none() && self.config.is_none()
}
}
/// The WARP device tags: "warp", or what `devices` or `instances` name.
pub fn warp_device_names(cfg: &Config) -> Vec<String> {
if let Some(n) = cfg.warp.instances {
(1..=n).map(|i| format!("warp-{i}")).collect()
} else if !cfg.warp.devices.is_empty() {
cfg.warp.devices.keys().cloned().collect()
} else {
vec![WARP_TAG.to_owned()]
}
}
pub fn warp_devices(cfg: &Config) -> Vec<WarpDeviceSpec> {
let Some(kind) = cfg.warp.as_outbound.filter(|_| cfg.warp.enable) else {
return Vec::new();
};
warp_device_names(cfg)
.into_iter()
.enumerate()
.map(|(index, tag)| {
let device = cfg.warp.devices.get(&tag).cloned().unwrap_or_default();
let first = index == 0;
let (config_file, config) = if device.config_file.is_some() || device.config.is_some() {
(device.config_file, device.config)
} else if first {
(cfg.warp.config_file.clone(), cfg.warp.config.clone())
} else {
(None, None)
};
WarpDeviceSpec {
state_subdir: if first { "warp".into() } else { format!("warp/{tag}") },
tag,
first,
kind,
config_file,
config,
endpoint: device.endpoint.or_else(|| cfg.warp.endpoint.clone()),
port: ports::WARP_USERSPACE_BASE + index as u16,
}
})
.collect()
}
/// Whether "warp" names a group of devices rather than a device.
pub fn warp_grouped(cfg: &Config) -> bool {
warp_devices(cfg).len() > 1
}
/// The AmneziaWG profiles that are outbounds, in name order.
pub fn awg_outbounds(cfg: &Config) -> Vec<(String, AwgOutboundKind, u16)> {
if !cfg.amnezia_wg.enable {
return Vec::new();
}
cfg.amnezia_wg
.profiles
.iter()
.filter_map(|(name, p)| p.as_outbound.map(|kind| (name.clone(), kind)))
.enumerate()
.map(|(i, (name, kind))| (name, kind, ports::AWG_TUNNEL_BASE + i as u16))
.collect()
}
/// The AmneziaWG profiles that are global VPNs (`proxy-ctl awg on`), in name order.
pub fn awg_global_profiles(cfg: &Config) -> Vec<String> {
if !cfg.amnezia_wg.enable {
return Vec::new();
}
let mut names: Vec<String> = cfg
.amnezia_wg
.profiles
.iter()
.filter(|(_, p)| p.as_outbound.is_none())
.map(|(name, _)| name.clone())
.collect();
if cfg.warp.enable && cfg.warp.as_amnezia_wg && !names.iter().any(|n| n == WARP_TAG) {
names.push(WARP_TAG.into());
}
names
}
/// Every outbound the tunnels add, in the order upstream lists them.
pub fn extra_outbounds(cfg: &Config) -> Vec<ExtraOutbound> {
let mut out = Vec::new();
if cfg.ssh_proxy.enable && cfg.ssh_proxy.as_outbound {
out.push(ExtraOutbound { tag: SSH_OUTBOUND_TAG.into(), kind: ExtraKind::Ssh });
}
for device in warp_devices(cfg) {
out.push(ExtraOutbound { tag: device.tag.clone(), kind: ExtraKind::Warp { device } });
}
if cfg.tor.enable && cfg.tor.as_outbound {
out.push(ExtraOutbound {
tag: TOR_OUTBOUND_TAG.into(),
kind: ExtraKind::Tor { port: cfg.tor.socks_port },
});
}
if cfg.whitelist_bypass.enable {
for (i, (tag, joiner)) in cfg.whitelist_bypass.joiners.iter().enumerate() {
out.push(ExtraOutbound {
tag: tag.clone(),
kind: ExtraKind::WlJoiner {
platform: joiner.platform,
port: ports::WL_JOINER_BASE + i as u16,
},
});
}
}
for (profile, kind, port) in awg_outbounds(cfg) {
out.push(ExtraOutbound {
tag: profile.clone(),
kind: ExtraKind::Awg { profile, kind, port },
});
}
out
}
/// The tags known before anything runs: declared outbounds and the tunnels'. Subscription
/// entries only exist once fetched.
pub fn effective_outbound_tags(cfg: &Config) -> Vec<String> {
let mut tags: Vec<String> = cfg.proxy.outbounds.iter().map(|o| o.tag.clone()).collect();
tags.extend(extra_outbounds(cfg).into_iter().map(|o| o.tag));
if warp_grouped(cfg) {
tags.push(WARP_TAG.into());
}
tags
}
pub fn group_tags(cfg: &Config) -> Vec<String> {
cfg.proxy.groups.keys().cloned().collect()
}
/// Whether a routing target names something: a builtin, an outbound or a group.
pub fn is_known_target(cfg: &Config, target: &str) -> bool {
BUILTIN_TAGS.contains(&target)
|| effective_outbound_tags(cfg).iter().any(|t| t == target)
|| cfg.proxy.groups.contains_key(target)
}
/// Whether the proxy has anything to send traffic through, before subscriptions are fetched.
pub fn has_available_outbounds(cfg: &Config) -> bool {
!cfg.proxy.outbounds.is_empty()
|| !cfg.proxy.subscriptions.is_empty()
|| !extra_outbounds(cfg).is_empty()
}
pub fn sing_box_enabled(cfg: &Config) -> bool {
cfg.proxy.enable && cfg.proxy.backend.runs_sing_box()
}
pub fn xray_enabled(cfg: &Config) -> bool {
cfg.proxy.enable && cfg.proxy.backend != Backend::SingBox
}
pub fn tor_route_onion(cfg: &Config) -> bool {
cfg.tor.enable && cfg.tor.as_outbound && cfg.tor.route_onion && cfg.proxy.enable
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::WarpDevice;
#[test]
fn warp_names_follow_instances_then_devices() {
let mut cfg = Config::default();
assert_eq!(warp_device_names(&cfg), ["warp"]);
cfg.warp.devices.insert("warp-b".into(), WarpDevice::default());
cfg.warp.devices.insert("warp-a".into(), WarpDevice::default());
assert_eq!(warp_device_names(&cfg), ["warp-a", "warp-b"]);
cfg.warp.instances = Some(3);
assert_eq!(warp_device_names(&cfg), ["warp-1", "warp-2", "warp-3"]);
}
#[test]
fn first_warp_device_inherits_the_top_level_profile() {
let mut cfg = Config::default();
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
cfg.warp.config_file = Some(r"C:\secrets\wgcf.conf".into());
cfg.warp.instances = Some(2);
let devices = warp_devices(&cfg);
assert_eq!(devices[0].config_file.as_deref(), Some(r"C:\secrets\wgcf.conf"));
assert!(!devices[0].auto_register());
assert!(devices[1].auto_register());
assert_eq!(devices[1].state_subdir, "warp/warp-2");
assert!(warp_grouped(&cfg));
assert!(effective_outbound_tags(&cfg).contains(&"warp".to_owned()));
}
}