//! Every outbound a start has, chained, grouped, and behind the "proxy" selector: upstream's //! `service/script-blocks/outbounds.nix`. //! //! Upstream fails the start over a declared outbound it cannot build and skips a runtime one //! with a warning. Here everything is edited at runtime, so an outbound that cannot be built //! is left out with a warning, and what names it (a chain, a rule) is left out after it. Only //! having no outbound at all, or nothing selection may pick, stops the start. use std::collections::{BTreeMap, HashMap, HashSet}; use serde::Serialize; use serde_json::{Value, json}; use super::groups::{self, GroupInfo}; use super::{Input, RenderError, Sources}; use crate::config::{Backend, OutboundBackend, Selection}; use crate::derived::{self, ExtraKind}; use crate::links::{self, LinkBackend, subscription}; /// What proxy-ctl and the app read about the outbounds: upstream's `outbounds.json`. #[derive(Debug, Clone, Default, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Inventory { /// Every outbound tag, in build order. pub tags: Vec, /// tag -> where it came from: "static", "sub:", "ssh", "warp", "tor", "awg", /// "whitelist-bypass". pub sources: BTreeMap, pub pinned: String, pub selection: String, /// tag -> the outbound it chains through. pub detours: BTreeMap, /// Top-level tags selection leaves alone (`selectionExclude`, Tor). pub excluded: Vec, pub disabled: Vec, pub groups: BTreeMap, pub top: Vec, pub priority: BTreeMap, pub url: String, /// The outbounds that are real exits (no selector or urltest), for autoProxy and tests. pub exits: Vec, /// tag -> the link it came from, to share it back. pub links: BTreeMap, /// tag -> the backend that runs it, on hybrid. pub runs_on: BTreeMap, } /// The outbounds, before the backend template takes them. pub(super) struct Assembly { /// sing-box outbounds (on hybrid, the sidecar's appear here as hops to it), "proxy" first. pub outbounds: Vec, /// sing-box endpoints (WireGuard). pub endpoints: Vec, /// The hybrid sidecar's XRay outbounds. pub xray: Vec, pub inventory: Inventory, } struct Builder<'a> { input: &'a Input<'a>, backend: Backend, outbounds: Vec, endpoints: Vec, xray: Vec, sources: Sources, order: Vec, links: BTreeMap, runs_on: BTreeMap, } impl Builder<'_> { fn taken(&self, tag: &str) -> bool { self.sources.contains_key(tag) || derived::BUILTIN_TAGS.contains(&tag) || tag.starts_with("proxy-suite-") } fn record(&mut self, tag: &str, source: &str) { self.sources.insert(tag.to_owned(), source.to_owned()); self.order.push(tag.to_owned()); } fn push(&mut self, ob: Value, source: &str) { let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); self.outbounds.push(ob); self.record(&tag, source); } fn push_endpoint(&mut self, ep: Value, source: &str) { let tag = ep["tag"].as_str().unwrap_or_default().to_owned(); self.endpoints.push(ep); self.record(&tag, source); } /// An XRay outbound on the hybrid backend's sidecar; sing-box reaches it as a hop. fn push_sidecar(&mut self, ob: Value, source: &str) { let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); self.xray.push(ob); self.runs_on.insert(tag.clone(), "xray".into()); self.record(&tag, source); } /// A link as this backend's outbound. On hybrid, sing-box first unless the outbound /// asks for XRay, XRay when sing-box cannot take it. fn add_url(&mut self, tag: &str, url: &str, pref: OutboundBackend, source: &str) -> Result<(), String> { match self.backend { Backend::SingBox => { let ob = links::build_outbound(url, tag, LinkBackend::SingBox).map_err(|e| e.to_string())?; self.push(ob, source); } Backend::Xray => { let ob = links::build_outbound(url, tag, LinkBackend::Xray).map_err(|e| e.to_string())?; self.push(ob, source); } Backend::Hybrid => { let sing = || links::build_outbound(url, tag, LinkBackend::SingBox); let xray = || links::build_outbound(url, tag, LinkBackend::Xray); match pref { OutboundBackend::SingBox => self.push(sing().map_err(|e| e.to_string())?, source), OutboundBackend::Xray => self.push_sidecar(xray().map_err(|e| e.to_string())?, source), OutboundBackend::Auto => match sing() { Ok(ob) => self.push(ob, source), Err(sing_err) => match xray() { Ok(ob) => self.push_sidecar(ob, source), Err(xray_err) => { return Err(format!( "cannot be parsed by sing-box ({sing_err}) or XRay ({xray_err})" )); } }, }, } } } self.links.insert(tag.to_owned(), url.to_owned()); Ok(()) } /// A loopback SOCKS hop to a helper the service runs. fn hop(&self, tag: &str, port: u16, login: bool) -> Value { let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port }); if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) { ob["username"] = user.clone().into(); ob["password"] = pass.clone().into(); } ob } } pub(super) fn assemble(input: &Input, warnings: &mut Vec) -> Result { let cfg = input.cfg; let p = &cfg.proxy; let mut b = Builder { input, backend: p.backend, outbounds: Vec::new(), endpoints: Vec::new(), xray: Vec::new(), sources: HashMap::new(), order: Vec::new(), links: BTreeMap::new(), runs_on: BTreeMap::new(), }; // Declared outbounds. for ob in &p.outbounds { if b.taken(&ob.tag) { warnings.push(format!("outbound '{}': the tag is taken; leaving it out", ob.tag)); continue; } let result = if let Some(json) = &ob.sing_box_json { let mut j = json.clone(); j.insert("tag".into(), ob.tag.clone().into()); match p.backend { Backend::Xray => Err("sing-box JSON cannot run on the xray backend".to_owned()), _ => { b.push(Value::Object(j), "static"); Ok(()) } } } else if let Some(json) = &ob.xray_json { let mut j = json.clone(); j.insert("tag".into(), ob.tag.clone().into()); match p.backend { Backend::SingBox => Err("XRay JSON cannot run on the sing-box backend".to_owned()), Backend::Xray => { b.push(Value::Object(j), "static"); Ok(()) } Backend::Hybrid => { b.push_sidecar(Value::Object(j), "static"); Ok(()) } } } else { let url = match (&ob.url, &ob.url_file) { (Some(url), _) => Ok(url.trim().to_owned()), (None, Some(file)) => (input.read_file)(file).map(|s| s.trim().to_owned()), (None, None) => Err("it has no url, urlFile, singBoxJson or xrayJson".to_owned()), }; url.and_then(|url| b.add_url(&ob.tag, &url, ob.backend, "static")) }; if let Err(e) = result { warnings.push(format!("outbound '{}': {e}; leaving it out", ob.tag)); } } // Subscriptions, as last fetched. let link_backends: Vec = match p.backend { Backend::SingBox => vec![LinkBackend::SingBox], Backend::Xray => vec![LinkBackend::Xray], Backend::Hybrid => vec![LinkBackend::SingBox, LinkBackend::Xray], }; for sub in &p.subscriptions { let Some(lines) = input.subscriptions.get(&sub.tag) else { warnings.push(format!("subscription '{}' has not been fetched yet", sub.tag)); continue; }; let opts = subscription::Options { allow_private: sub.allow_private_servers, allow_insecure: sub.allow_insecure }; let parsed = subscription::walk(lines, &sub.tag, &link_backends, opts); warnings.extend(parsed.warnings.into_iter().map(|w| format!("subscription '{}': {w}", sub.tag))); let source = format!("sub:{}", sub.tag); let links: HashMap = parsed.links.into_iter().collect(); for (backend, ob) in parsed.outbounds { let tag = ob["tag"].as_str().unwrap_or_default().to_owned(); if b.taken(&tag) { warnings.push(format!("subscription '{}': entry '{tag}' takes a tag already in use; leaving it out", sub.tag)); continue; } match (p.backend, backend) { (Backend::Hybrid, LinkBackend::Xray) => b.push_sidecar(ob, &source), _ => b.push(ob, &source), } if let Some(line) = links.get(&tag) { b.links.insert(tag, line.clone()); } } } // What the tunnels add. let sing_box = p.backend.runs_sing_box(); for extra in derived::extra_outbounds(cfg) { if b.taken(&extra.tag) { warnings.push(format!("'{}': the tag is taken by an outbound; leaving the tunnel's outbound out", extra.tag)); continue; } match extra.kind { ExtraKind::Ssh => { let s = &cfg.ssh_proxy; if sing_box { let mut ob = json!({ "type": "ssh", "tag": extra.tag, "server": s.server.host.clone().unwrap_or_default(), "server_port": s.server.port, "user": s.server.user.clone().unwrap_or_default(), }); let keys = if input.env.ssh_host_keys.is_empty() { &s.host_key } else { &input.env.ssh_host_keys }; if !keys.is_empty() { ob["host_key"] = json!(keys); } if let Some(path) = &input.env.ssh_identity_path { ob["private_key_path"] = path.clone().into(); } b.push(ob, "ssh"); } else { let ob = b.hop(&extra.tag, s.listener.port, false); b.push(ob, "ssh"); } } ExtraKind::Tor { port } => { let ob = b.hop(&extra.tag, port, false); b.push(ob, "tor"); } ExtraKind::WlJoiner { port, .. } => { let ob = b.hop(&extra.tag, port, true); b.push(ob, "whitelist-bypass"); } ExtraKind::Warp { device } => match device.kind { crate::config::WarpOutboundKind::SingBox => { let Some(profile) = input.env.warp_profiles.get(&device.tag) else { warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag)); continue; }; match crate::wg::sing_box_endpoint(profile, &device.tag, device.endpoint.as_deref()) { Ok((mut ep, _)) => { ep["domain_resolver"] = json!({ "server": "local", "strategy": cfg.warp.domain_strategy.as_str() }); b.push_endpoint(ep, "warp"); } Err(e) => warnings.push(format!("WARP device '{}': {e}; leaving it out", device.tag)), } } crate::config::WarpOutboundKind::Userspace => { let ob = b.hop(&device.tag, device.port, true); b.push(ob, "warp"); } }, ExtraKind::Awg { profile, kind, port } => match kind { crate::config::AwgOutboundKind::SingBox => { let Some(conf) = input.env.awg_profiles.get(&profile) else { warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out")); continue; }; let endpoint = cfg.amnezia_wg.profiles.get(&profile).and_then(|p| p.endpoint.as_deref()); match crate::wg::sing_box_endpoint(conf, &profile, endpoint) { Ok((mut ep, dropped)) => { if !dropped.is_empty() { warnings.push(format!( "AmneziaWG outbound '{profile}': sing-box speaks plain WireGuard; dropping {}. A server that expects them will not answer", dropped.join(", ") )); } let strategy = cfg.amnezia_wg.profiles.get(&profile).and_then(|p| p.domain_strategy); ep["domain_resolver"] = match strategy { Some(s) => json!({ "server": "local", "strategy": s.as_str() }), None => json!("local"), }; b.push_endpoint(ep, "awg"); } Err(e) => warnings.push(format!("AmneziaWG outbound '{profile}': {e}; leaving it out")), } } crate::config::AwgOutboundKind::Userspace => { let ob = b.hop(&profile, port, true); b.push(ob, "awg"); } }, } } chain(&mut b, warnings); if b.order.is_empty() { return Err(RenderError( "no proxy outbounds are available; add one, or a subscription that has been fetched".into(), )); } let disabled: Vec = input.state.disabled.iter().filter(|t| b.sources.contains_key(*t)).cloned().collect(); // Groups, against the outbounds this start has. A group whose name an outbound took, or // that contains itself, is left out. let mut group_cfg = p.groups.clone(); if let Some(warp) = warp_group(cfg) { group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp); } group_cfg.retain(|name, _| { let free = !b.sources.contains_key(name); if !free { warnings.push(format!("group '{name}': an outbound has that tag; leaving the group out")); } free }); let resolved = loop { let r = groups::resolve(&groups::Inputs { tags: &b.order, sources: &b.sources, groups: &group_cfg, priority: &p.priority, disabled: &disabled, pins: &input.state.group_pins, url: &p.url_test.url, interval: &p.url_test.interval, tolerance: p.url_test.tolerance, watched: input.env.groups_watched, }); if r.loops.is_empty() { break r; } for g in &r.loops { warnings.push(format!("group '{g}' contains itself; leaving it out")); group_cfg.remove(g); } }; warnings.extend(resolved.warnings.iter().cloned()); // The pin. let all_tags: Vec<&String> = b.order.iter().chain(resolved.groups.keys()).collect(); let mut pinned = input.state.pin.clone().unwrap_or_default(); if !pinned.is_empty() && !all_tags.contains(&&pinned) { warnings.push(format!("pinned outbound '{pinned}' is not available; picking automatically")); pinned.clear(); } if !pinned.is_empty() && disabled.contains(&pinned) { warnings.push(format!("pinned outbound '{pinned}' is disabled; picking automatically")); pinned.clear(); } // What selection may pick on its own. Tor is only for what is routed to it, unless it is // the one outbound there is. let tor_out = derived::extra_outbounds(cfg).iter().any(|o| o.tag == derived::TOR_OUTBOUND_TAG); let top = &resolved.top; let selectable: Vec = top .iter() .filter(|t| { !p.selection_exclude.contains(t) && !disabled.contains(t) && !(tor_out && top.len() > 1 && *t == derived::TOR_OUTBOUND_TAG) }) .cloned() .collect(); if pinned.is_empty() && selectable.is_empty() { return Err(RenderError( "every outbound is in proxy.selectionExclude or disabled, so there is nothing to select; pin one, enable one, or exclude fewer".into(), )); } // The detours as they stand, for the inventory. let detours: BTreeMap = b .outbounds .iter() .chain(&b.endpoints) .chain(&b.xray) .filter_map(|o| { let hop = o.get("detour").or_else(|| o.pointer("/streamSettings/sockopt/dialerProxy"))?; Some((o["tag"].as_str()?.to_owned(), hop.as_str()?.to_owned())) }) .collect(); let exits: Vec = b .order .iter() .filter(|t| !(tor_out && *t == derived::TOR_OUTBOUND_TAG)) .cloned() .collect(); // "proxy", as the selection mode has it, ahead of everything; the groups after the rest. let mut every: Vec = b.order.clone(); every.extend(resolved.groups.keys().cloned()); let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() }; let wrapper = match p.selection { Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }), Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({ "type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url, "interval": "30s", "tolerance": p.url_test.tolerance, }), Selection::Failover => json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": default, "interrupt_exist_connections": true, }), Selection::Selector => json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": default }), Selection::Urltest if !pinned.is_empty() => { json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": pinned }) } Selection::Urltest => json!({ "type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url, "interval": p.url_test.interval, "tolerance": p.url_test.tolerance, }), }; let mut outbounds = vec![wrapper]; outbounds.append(&mut b.outbounds); outbounds.extend(resolved.outbounds.iter().cloned()); let excluded: Vec = top.iter().filter(|t| !selectable.contains(t)).cloned().collect(); let inventory = Inventory { tags: b.order.clone(), sources: b.sources.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), pinned, selection: p.selection.as_str().into(), detours, excluded, disabled, groups: resolved.groups.clone(), top: top.clone(), priority: p.priority.clone(), url: p.url_test.url.clone(), exits, links: b.links, runs_on: b .order .iter() .map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned()))) .collect(), }; Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory }) } /// With two or more WARP devices, "warp" names a group of them. fn warp_group(cfg: &crate::config::Config) -> Option { let devices = derived::warp_devices(cfg); (devices.len() > 1).then(|| crate::config::Group { outbounds: devices.into_iter().map(|d| d.tag).collect(), strategy: cfg.warp.group.strategy, failback: cfg.warp.group.failback, ..Default::default() }) } /// Chains outbounds through their detour hop: upstream's `outbound-detours.jq`. An outbound /// whose chain cannot be built is left out, and what chained through it is checked again. fn chain(b: &mut Builder, warnings: &mut Vec) { let p = &b.input.cfg.proxy; let declared: HashMap<&str, &str> = p.outbounds.iter().filter_map(|o| Some((o.tag.as_str(), o.detour.as_deref()?))).collect(); let by_sub: HashMap = p.subscriptions.iter().filter_map(|s| Some((format!("sub:{}", s.tag), s.detour.as_deref()?))).collect(); loop { let hops: BTreeMap = b .order .iter() .filter_map(|t| { let hop = declared.get(t.as_str()).copied().or_else(|| by_sub.get(&b.sources[t]).copied())?; Some((t.clone(), hop.to_owned())) }) .collect(); let tags: HashSet<&String> = b.order.iter().collect(); let xray_tags: HashSet = b.xray.iter().filter_map(|o| o["tag"].as_str().map(str::to_owned)).collect(); let mut drop: BTreeMap = BTreeMap::new(); for (t, hop) in &hops { if !tags.contains(hop) { drop.insert(t.clone(), format!("it chains through '{hop}', which is not an outbound")); continue; } // Upstream's test: the chain from t, as long as there are hops plus one, meets t again. let mut cur = hop.clone(); let mut back = false; for _ in 0..=hops.len() { if cur == *t { back = true; break; } match hops.get(&cur) { Some(next) => cur = next.clone(), None => break, } } if back { drop.insert(t.clone(), "it chains back to itself".into()); continue; } if b.backend == Backend::Hybrid && xray_tags.contains(t) && !xray_tags.contains(hop) { drop.insert( t.clone(), format!("it runs on XRay and can only chain through another XRay outbound, not '{hop}'"), ); } } if drop.is_empty() { for (t, hop) in &hops { let set = |ob: &mut Value| { if ob["tag"] == t.as_str() { if xray_tags.contains(t) || b.backend == Backend::Xray { ob["streamSettings"]["sockopt"]["dialerProxy"] = hop.clone().into(); } else { ob["detour"] = hop.clone().into(); } } }; b.outbounds.iter_mut().for_each(set); b.endpoints.iter_mut().for_each(set); b.xray.iter_mut().for_each(set); } return; } for (t, why) in drop { warnings.push(format!("outbound '{t}': {why}; leaving it out")); let keep = |o: &Value| o["tag"] != t.as_str(); b.outbounds.retain(keep); b.endpoints.retain(keep); b.xray.retain(keep); b.order.retain(|x| *x != t); b.sources.remove(&t); b.links.remove(&t); } } }