//! Share links to backend outbounds: upstream's `scripts/proxy_url_parsers.py` and //! `proxy_parsing.py`, ported with their checks and messages. //! //! A link becomes a sing-box-shaped outbound first; for XRay it is then rendered into XRay's //! shape. Each parser refuses what the backend would refuse to start on, so one bad //! subscription entry is skipped instead of taking every other outbound down with it. //! //! Upstream's `routing_mark` (Linux SO_MARK) has no Windows counterpart and is left out. mod parsers; pub mod py; pub mod subscription; mod xray; use std::fmt; use serde_json::{Map, Value}; pub use parsers::SCHEMES; pub use xray::render_xray_outbound; /// Which backend an outbound is built for. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LinkBackend { SingBox, Xray, } impl LinkBackend { pub fn as_str(self) -> &'static str { match self { Self::SingBox => "sing-box", Self::Xray => "xray", } } } /// Why a link was refused. The message never quotes a credential. #[derive(Debug, Clone, PartialEq, Eq)] pub enum LinkError { /// The link is malformed, or the backend would refuse it. Invalid(String), /// A subscription entry whose server is this host, its link, or (unless allowed) a /// private network: whichever backend reads it, it is skipped. RefusedServer(String), } impl LinkError { pub(crate) fn invalid(message: impl Into) -> Self { Self::Invalid(message.into()) } pub fn message(&self) -> &str { match self { Self::Invalid(m) | Self::RefusedServer(m) => m, } } } impl fmt::Display for LinkError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.message()) } } impl std::error::Error for LinkError {} pub type Result = std::result::Result; /// The scheme of a link, lowercased: what comes before `://`. pub fn detect_scheme(url: &str) -> String { url.split("://").next().unwrap_or("").to_lowercase() } /// Parses a link into a sing-box-shaped outbound tagged `tag`, checked against `backend`. pub fn parse_url(url: &str, tag: &str, backend: LinkBackend) -> Result> { let scheme = detect_scheme(url); parsers::parse(&scheme, url, tag, backend) } /// A link as the backend's outbound: sing-box's shape, or XRay's. pub fn build_outbound(url: &str, tag: &str, backend: LinkBackend) -> Result { let ob = parse_url(url, tag, backend)?; finish_outbound(ob, backend) } pub(crate) fn finish_outbound(ob: Map, backend: LinkBackend) -> Result { match backend { LinkBackend::Xray => render_xray_outbound(&ob), LinkBackend::SingBox => Ok(Value::Object(ob)), } } /// Every key anywhere in `value`, lowercased. fn all_keys(value: &Value) -> Vec { let mut found = Vec::new(); let mut stack = vec![value]; while let Some(item) = stack.pop() { match item { Value::Object(map) => { for (k, v) in map { found.push(py_lower(k)); stack.push(v); } } Value::Array(list) => stack.extend(list), _ => {} } } found } /// `str.lower()`, which folds the Kelvin sign to `k` as Go's JSON decoding does. fn py_lower(s: &str) -> String { s.to_lowercase() } /// The keys anywhere in `value` that point a backend at a local file or program. The /// backends run as SYSTEM here, and a share link is whatever a subscription serves: an xhttp /// `extra` carries a whole streamSettings, where `certificateFile` is a file XRay reads and /// `masterKeyLog` one it writes. Any non-ASCII key counts too: Go's JSON folds case, reading /// "maſterKeyLog" as masterKeyLog. pub fn local_file_keys(value: &Value) -> Vec { let mut keys: Vec = all_keys(value) .into_iter() .filter(|k| { !k.is_ascii() || k.ends_with("file") || k.ends_with("directory") || (k.ends_with("path") && k != "path") || matches!(k.as_str(), "masterkeylog" | "torrc" | "extra_args") }) .collect(); keys.sort(); keys.dedup(); keys } /// Socket options a share link must not set: a mark or interface steers around the routing, /// a dialerProxy chains elsewhere. Other socket options stay. const SOCKET_KEYS: [&str; 5] = ["customsockopt", "dialerproxy", "interface", "mark", "tproxy"]; fn strip_socket_keys(value: &mut Value) { match value { Value::Object(map) => { map.retain(|k, _| !SOCKET_KEYS.contains(&py_lower(k).as_str())); for v in map.values_mut() { strip_socket_keys(v); } } Value::Array(list) => list.iter_mut().for_each(strip_socket_keys), _ => {} } } /// A JSON object carried in a link parameter (xhttp's `extra`), checked as upstream does. fn parse_json_param(value: &str, name: &str) -> Result { let mut parsed: Value = serde_json::from_str(value) .map_err(|e| LinkError::invalid(format!("invalid {name} JSON: {e}")))?; if !parsed.is_object() { return Err(LinkError::invalid(format!("invalid {name} JSON: expected object"))); } let unsafe_keys = local_file_keys(&parsed); if !unsafe_keys.is_empty() { return Err(LinkError::invalid(format!("{name} JSON names local files: {}", unsafe_keys.join(", ")))); } strip_socket_keys(&mut parsed); if all_keys(&parsed).iter().any(|k| k == "allowinsecure") { return Err(LinkError::invalid(format!("{name} JSON sets allowInsecure, which XRay no longer accepts"))); } Ok(parsed) } #[cfg(test)] mod tests;