Files
proxy-suite-flake/windows/crates/ps-core/src/links/parsers.rs
T
faumarayandClaude Opus 5.5 77d4cefe0e windows: share-link and subscription parsing, admin-only edits
ps-core::links ports upstream's proxy_url_parsers.py and proxy_parsing.py:
every scheme, each backend's refusals, XRay rendering, subscription
decoding, tags and the server checks. Upstream's build-outbound tests
are ported case for case, and tools/parity/links.py runs ~750 links
through both implementations: no differences.

config::privileged_changes names the edits only an administrator may
make: anything that runs a program, passes arguments through, or names
a local file, since the service runs as LocalSystem. Names that become
paths or service names are validated.

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

879 lines
36 KiB
Rust

//! One parser per scheme, as `proxy_url_parsers.py` has them.
use std::collections::HashMap;
use std::sync::LazyLock;
use regex::Regex;
use serde_json::{Map, Value, json};
use super::py::{self, b64decode, b64decode_strict, pad, prefix, repr, unquote, urlsafe_b64decode};
use super::{LinkBackend, LinkError, Result, parse_json_param};
/// Every scheme a link may have.
pub const SCHEMES: [&str; 16] = [
"vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic",
"socks5", "socks5h", "socks4", "socks4a", "http", "https",
];
pub(super) fn parse(scheme: &str, url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
match scheme {
"vless" => parse_vless(url, tag, backend),
"vmess" => parse_vmess(url, tag, backend),
"trojan" => parse_trojan(url, tag, backend),
"ss" => parse_shadowsocks(url, tag, backend),
"hysteria2" | "hy2" => parse_hysteria2(url, tag, backend),
"tuic" => parse_tuic(url, tag),
"anytls" => parse_anytls(url, tag),
"naive+https" | "naive+quic" => parse_naive(url, tag),
"socks5" | "socks5h" | "socks4" | "socks4a" => parse_plain_proxy(url, tag, "socks"),
"http" | "https" => parse_plain_proxy(url, tag, "http"),
_ => Err(LinkError::invalid(format!("unsupported scheme '{scheme}'"))),
}
}
const SUPPORTED_VLESS_TRANSPORTS: [&str; 9] = ["", "tcp", "raw", "ws", "grpc", "h2", "http", "httpupgrade", "quic"];
// XRay 26 removed the HTTP/2 and QUIC transports and refuses to start on them.
const SUPPORTED_XRAY_TRANSPORTS: [&str; 8] = ["", "tcp", "raw", "ws", "grpc", "httpupgrade", "xhttp", "splithttp"];
const SING_BOX_VLESS_FLOWS: [&str; 2] = ["", "xtls-rprx-vision"];
const XRAY_VLESS_FLOWS: [&str; 3] = ["", "xtls-rprx-vision", "xtls-rprx-vision-udp443"];
const SING_BOX_VMESS_SECURITY: [&str; 6] = ["auto", "none", "zero", "aes-128-cfb", "aes-128-gcm", "chacha20-poly1305"];
const TUIC_CONGESTION_CONTROLS: [&str; 3] = ["cubic", "new_reno", "bbr"];
const XHTTP_MODES: [&str; 5] = ["", "auto", "packet-up", "stream-up", "stream-one"];
fn ss2022_key_bytes(method: &str) -> Option<usize> {
match method {
"2022-blake3-aes-128-gcm" => Some(16),
"2022-blake3-aes-256-gcm" | "2022-blake3-chacha20-poly1305" => Some(32),
_ => None,
}
}
const SING_BOX_SS_METHODS: [&str; 18] = [
"2022-blake3-aes-128-gcm",
"2022-blake3-aes-256-gcm",
"2022-blake3-chacha20-poly1305",
"none",
"aes-128-gcm",
"aes-192-gcm",
"aes-256-gcm",
"chacha20-ietf-poly1305",
"xchacha20-ietf-poly1305",
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"rc4-md5",
"chacha20-ietf",
"xchacha20",
];
// XRay lowercases these; its 2022 methods are matched as written.
const XRAY_SS_METHODS: [&str; 10] = [
"aes-128-gcm",
"aes-256-gcm",
"chacha20-poly1305",
"chacha20-ietf-poly1305",
"xchacha20-poly1305",
"xchacha20-ietf-poly1305",
"aead_aes_128_gcm",
"aead_aes_256_gcm",
"aead_chacha20_poly1305",
"aead_xchacha20_poly1305",
];
fn re(pattern: &str) -> Regex {
Regex::new(&format!("^(?:{pattern})$")).expect("a valid pattern")
}
pub(super) static UUID_RE: LazyLock<Regex> =
LazyLock::new(|| re(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}|[0-9a-fA-F]{32}"));
// REALITY's x25519 key, unpadded base64url; its short id, whole hex bytes, at most 8.
static REALITY_PUBLIC_KEY_RE: LazyLock<Regex> = LazyLock::new(|| re(r"[A-Za-z0-9_-]{43}"));
static REALITY_SHORT_ID_RE: LazyLock<Regex> = LazyLock::new(|| re(r"(?:[0-9a-fA-F]{2}){0,8}"));
// A path Go's url.Parse takes: no control characters, and % only as an escape. XRay ignores
// the parse error on spiderX and dies on the nil URL, taking every outbound with it.
static REALITY_SPIDER_X_RE: LazyLock<Regex> =
LazyLock::new(|| re(r"/(?:[^\x00-\x1f\x7f%]|%[0-9A-Fa-f]{2})*"));
// hysteria2's pinSHA256: the certificate's SHA-256, hex, colons optional.
static CERT_SHA256_RE: LazyLock<Regex> =
LazyLock::new(|| re(r"[0-9A-Fa-f]{64}|[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){31}"));
static PORT_RANGE_RE: LazyLock<Regex> = LazyLock::new(|| re(r"([0-9]+)(?:-([0-9]+))?"));
fn one_of<'a>(value: &'a str, allowed: &[&str], what: &str) -> Result<&'a str> {
if allowed.contains(&value) {
Ok(value)
} else {
Err(LinkError::invalid(format!("unsupported {what} {}", repr(prefix(value, 80)))))
}
}
// sing-box takes any string as a VLESS/VMess id; XRay a UUID, or 1-30 characters it hashes
// into one.
fn user_id(value: &str, backend: LinkBackend, protocol: &str) -> Result<String> {
let chars = value.chars().count();
if backend == LinkBackend::Xray && !(UUID_RE.is_match(value) || (1..=30).contains(&chars)) {
// Not quoted: the id is the credential.
return Err(LinkError::invalid(format!(
"invalid {protocol} id ({chars} characters): XRay takes a UUID or 1-30 characters"
)));
}
Ok(value.to_owned())
}
type Params = HashMap<String, String>;
// Panels write the unset half of a share link as "&sni=&host=&path=", so a blank parameter
// is an absent one.
fn param<'a>(params: &'a Params, name: &str, default: &'a str) -> &'a str {
match params.get(name) {
Some(v) if !v.is_empty() => v,
_ => default,
}
}
fn get<'a>(params: &'a Params, name: &str) -> &'a str {
params.get(name).map(String::as_str).unwrap_or("")
}
// sing-box stores a port as uint16 and refuses to start on anything else.
fn port(value: &str) -> Result<u16> {
let trimmed = value.trim();
let parsed: i128 = parse_py_int(trimmed)
.ok_or_else(|| LinkError::invalid(format!("invalid port {}", repr(prefix(value, 20)))))?;
if !(1..=65535).contains(&parsed) {
return Err(LinkError::invalid(format!("port {parsed} is out of range (1-65535)")));
}
Ok(parsed as u16)
}
/// `int(str)`: an optional sign, decimal digits, `_` between them.
fn parse_py_int(s: &str) -> Option<i128> {
let (sign, digits) = match s.strip_prefix('-') {
Some(rest) => (-1, rest),
None => (1, s.strip_prefix('+').unwrap_or(s)),
};
if digits.is_empty() || digits.starts_with('_') || digits.ends_with('_') || digits.contains("__") {
return None;
}
let clean: String = digits.chars().filter(|c| *c != '_').collect();
if !clean.chars().all(|c| c.is_ascii_digit()) {
return None;
}
clean.parse::<i128>().ok().map(|n| sign * n)
}
fn port_value(value: &Value) -> Result<u16> {
match value {
Value::Number(n) => {
if let Some(i) = n.as_i64() {
if !(1..=65535).contains(&i) {
return Err(LinkError::invalid(format!("port {i} is out of range (1-65535)")));
}
Ok(i as u16)
} else if let Some(f) = n.as_f64() {
// int(443.9) is 443.
port(&(f.trunc() as i64).to_string())
} else {
Err(LinkError::invalid("invalid port"))
}
}
Value::String(s) => port(s),
Value::Bool(b) => port(if *b { "1" } else { "0" }),
other => Err(LinkError::invalid(format!("invalid port {}", repr(prefix(&py_str(other), 20))))),
}
}
fn split_host_port(hostpart: &str) -> Result<(String, String)> {
let (host, port) = match hostpart.rfind(':') {
Some(i) => (&hostpart[..i], &hostpart[i + 1..]),
None => ("", ""),
};
if host.is_empty() || port.is_empty() {
return Err(LinkError::invalid("URL must include host and port"));
}
let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
Ok((host.to_owned(), port.to_owned()))
}
/// userinfo, host, port and the query of `scheme://userinfo@host:port/?query#name`.
fn parse_url_parts(url: &str, scheme: &str) -> Result<(String, String, String, Params)> {
let rest = url.get(scheme.len() + 3..).unwrap_or("");
let rest = rest.split('#').next().unwrap_or("");
// The query goes before the userinfo: links carry '@' in their parameters
// (Telegram=@handle), and an rpartition over the whole string would swallow the host.
let (authority, query) = rest.split_once('?').unwrap_or((rest, ""));
let (userinfo, hostpart) = match authority.rfind('@') {
Some(i) => (&authority[..i], &authority[i + 1..]),
None => ("", authority),
};
// "host:443/?type=tcp": a trailing path is not part of the port.
let hostpart = hostpart.split('/').next().unwrap_or("");
let (host, port) = split_host_port(hostpart)?;
Ok((userinfo.to_owned(), host, port, py::parse_qs(query)))
}
#[allow(clippy::too_many_arguments)]
fn mk_transport(
transport_type: &str,
path: &str,
host_header: &str,
service_name: &str,
mode: &str,
extra: &str,
x_padding_bytes: &str,
) -> Result<Option<Value>> {
let t = transport_type.to_lowercase();
Ok(match t.as_str() {
"" | "tcp" | "raw" => None,
"ws" => Some(json!({ "type": "ws", "path": unquote(path), "headers": { "Host": host_header } })),
"grpc" => Some(json!({ "type": "grpc", "service_name": unquote(service_name) })),
"h2" | "http" => Some(json!({ "type": "http", "host": [host_header], "path": unquote(path) })),
"httpupgrade" => Some(json!({ "type": "httpupgrade", "host": host_header, "path": unquote(path) })),
"quic" => Some(json!({ "type": "quic" })),
"xhttp" | "splithttp" => {
let mut tr = Map::new();
tr.insert("type".into(), "xhttp".into());
tr.insert("path".into(), unquote(path).into());
if !host_header.is_empty() {
tr.insert("host".into(), host_header.into());
}
if !one_of(mode, &XHTTP_MODES, "xhttp mode")?.is_empty() {
tr.insert("mode".into(), mode.into());
}
if !extra.is_empty() {
tr.insert("extra".into(), parse_json_param(extra, "xhttp extra")?);
} else if !x_padding_bytes.is_empty() {
tr.insert("extra".into(), json!({ "xPaddingBytes": x_padding_bytes }));
}
Some(Value::Object(tr))
}
_ => None,
})
}
// sing-box refuses to start on a transport it does not know.
fn check_transport(transport: &str, backend: LinkBackend, protocol: &str) -> Result<String> {
let normalized = transport.to_lowercase();
let supported: &[&str] = match backend {
LinkBackend::Xray => &SUPPORTED_XRAY_TRANSPORTS,
LinkBackend::SingBox => &SUPPORTED_VLESS_TRANSPORTS,
};
if !supported.contains(&normalized.as_str()) {
return Err(LinkError::invalid(format!(
"unsupported {protocol} transport '{transport}': proxy-suite only maps {}-documented \
transports; use raw JSON or another client/core",
backend.as_str()
)));
}
Ok(normalized)
}
fn require<'a>(params: &'a Params, name: &str, security: &str) -> Result<&'a str> {
params
.get(name)
.map(String::as_str)
.ok_or_else(|| LinkError::invalid(format!("{security} link is missing the '{name}' parameter")))
}
const SING_BOX_FINGERPRINTS: [&str; 10] =
["chrome", "firefox", "edge", "safari", "360", "qq", "ios", "android", "random", "randomized"];
// XRay's own names (transport/internet/tls), matched lowercased.
const XRAY_HELLO_FINGERPRINTS: &str = "firefox_120 firefox_148 chrome_120 chrome_131 chrome_133 ios_13 ios_14 \
edge_106 safari_26_3 360_11_0 qq_11_1 golang randomized randomizedalpn randomizednoalpn firefox_auto \
firefox_55 firefox_56 firefox_63 firefox_65 firefox_99 firefox_102 firefox_105 chrome_auto chrome_58 \
chrome_62 chrome_70 chrome_72 chrome_83 chrome_87 chrome_96 chrome_100 chrome_102 chrome_106_shuffle \
ios_auto ios_11_1 ios_12_1 android_11_okhttp edge_85 edge_auto safari_16_0 safari_auto 360_auto 360_7_5 \
qq_auto chrome_100_psk chrome_112_psk_shuf chrome_114_padding_psk_shuf chrome_115_pq chrome_115_pq_psk \
chrome_120_pq";
fn xray_fingerprint_known(fp: &str) -> bool {
SING_BOX_FINGERPRINTS.contains(&fp)
|| matches!(fp, "randomizednoalpn" | "unsafe")
|| fp
.strip_prefix("hello")
.is_some_and(|name| XRAY_HELLO_FINGERPRINTS.split_whitespace().any(|n| n == name))
}
fn check_fingerprint(fp: &str, backend: LinkBackend, reality: bool) -> Result<String> {
match backend {
LinkBackend::SingBox => {
if !SING_BOX_FINGERPRINTS.contains(&fp) {
return Err(LinkError::invalid(format!(
"unsupported uTLS fingerprint '{fp}': sing-box would refuse to start"
)));
}
}
LinkBackend::Xray => {
let lower = fp.to_lowercase();
if !xray_fingerprint_known(&lower) || (reality && matches!(lower.as_str(), "unsafe" | "hellogolang")) {
return Err(LinkError::invalid(format!(
"unsupported uTLS fingerprint '{fp}': XRay would refuse to start"
)));
}
}
}
Ok(fp.to_owned())
}
// Panels write alpn either as "h2,http/1.1" or as a JSON list.
fn alpn_list(value: &Value) -> Vec<Value> {
let items: Vec<String> = match value {
Value::Array(list) => list.iter().map(py_str).collect(),
other => py_str(other).split(',').map(str::to_owned).collect(),
};
items.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).map(Value::from).collect()
}
/// `str(value)` for the JSON values a VMess link carries.
fn py_str(value: &Value) -> String {
match value {
Value::String(s) => s.clone(),
Value::Null => "None".into(),
Value::Bool(true) => "True".into(),
Value::Bool(false) => "False".into(),
other => other.to_string(),
}
}
/// Python truthiness of a JSON value.
fn truthy(value: Option<&Value>) -> bool {
match value {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
}
}
fn mk_tls(server_name: &str, fp: Option<&str>, alpn: Option<&Value>, backend: LinkBackend) -> Result<Map<String, Value>> {
let mut tls = Map::new();
tls.insert("enabled".into(), true.into());
tls.insert("server_name".into(), server_name.into());
if let Some(fp) = fp.filter(|f| !f.is_empty()) {
tls.insert("utls".into(), json!({ "enabled": true, "fingerprint": check_fingerprint(fp, backend, false)? }));
}
if let Some(alpn) = alpn.filter(|a| truthy(Some(a))) {
tls.insert("alpn".into(), Value::Array(alpn_list(alpn)));
}
Ok(tls)
}
// SOCKS4 authenticates with a bare userid: "socks4://me@host" has a username and no password.
fn mk_auth(userinfo: &str) -> (Option<String>, Option<String>) {
if userinfo.is_empty() {
return (None, None);
}
match userinfo.split_once(':') {
Some((u, p)) => (Some(unquote(u)), Some(unquote(p))),
None => (Some(unquote(userinfo)), None),
}
}
fn set_auth(ob: &mut Map<String, Value>, userinfo: &str) {
let (username, password) = mk_auth(userinfo);
if let Some(username) = username {
ob.insert("username".into(), username.into());
if let Some(password) = password {
ob.insert("password".into(), password.into());
}
}
}
// XRay's GetPrivateIPMatcher and GetPrivateDomainMatcher: the only servers it lets VLESS
// reach in the clear.
const XRAY_PRIVATE_NETWORKS: [&str; 18] = [
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24",
"192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24",
"224.0.0.0/3", "::/127", "fc00::/7", "fe80::/10", "ff00::/8",
];
const XRAY_PRIVATE_SUFFIXES: [&str; 9] =
["lan", "localdomain", "example", "invalid", "localhost", "test", "local", "home.arpa", "internal"];
static SINGLE_LABEL_RE: LazyLock<Regex> = LazyLock::new(|| re(r"[a-z]([a-z0-9-]{0,61}[a-z0-9])?"));
fn xray_wants_transport_security(host: &str) -> bool {
match super::subscription::py_ip_address(host) {
None => {
let domain = host.to_lowercase();
let domain = domain.trim_end_matches('.');
if SINGLE_LABEL_RE.is_match(domain) {
return false;
}
!XRAY_PRIVATE_SUFFIXES.iter().any(|s| domain == *s || domain.ends_with(&format!(".{s}")))
}
Some(address) => {
let address = super::subscription::unmap(address);
!XRAY_PRIVATE_NETWORKS.iter().any(|net| {
let net: ipnet::IpNet = net.parse().expect("a valid network");
net.contains(&address)
})
}
}
}
fn parse_vless(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let (userinfo, host, port_s, params) = parse_url_parts(url, "vless")?;
let security = param(&params, "security", "none");
if params.contains_key("ech") && backend != LinkBackend::Xray {
return Err(LinkError::invalid(
"unsupported VLESS parameter 'ech': proxy-suite does not translate share-link ECH blobs into sing-box TLS config",
));
}
let transport = check_transport(param(&params, "type", "tcp"), backend, "VLESS")?;
let mut ob = Map::new();
ob.insert("type".into(), "vless".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("uuid".into(), user_id(&userinfo, backend, "VLESS")?.into());
ob.insert("packet_encoding".into(), "xudp".into());
if security == "reality" {
let fp = check_fingerprint(param(&params, "fp", "chrome"), backend, true)?;
let mut tls = mk_tls(param(&params, "sni", &host), Some(&fp), None, backend)?;
let public_key = require(&params, "pbk", "reality")?;
if !REALITY_PUBLIC_KEY_RE.is_match(public_key) {
return Err(LinkError::invalid(format!(
"invalid reality pbk '{public_key}': expected a 43-character base64url key"
)));
}
let short_id = get(&params, "sid");
if !REALITY_SHORT_ID_RE.is_match(short_id) {
return Err(LinkError::invalid(format!(
"invalid reality sid '{short_id}': expected up to 16 hex digits, in pairs"
)));
}
let mut reality = Map::new();
reality.insert("enabled".into(), true.into());
reality.insert("public_key".into(), public_key.into());
reality.insert("short_id".into(), short_id.into());
let spx = get(&params, "spx");
if backend == LinkBackend::Xray && !spx.is_empty() {
if !REALITY_SPIDER_X_RE.is_match(spx) {
return Err(LinkError::invalid(format!("invalid reality spx {}: XRay wants a URL path", repr(spx))));
}
reality.insert("spider_x".into(), spx.into());
}
tls.insert("reality".into(), Value::Object(reality));
ob.insert("tls".into(), Value::Object(tls));
} else if security == "tls" {
let alpn = params.get("alpn").map(|a| Value::String(a.clone()));
let mut tls = mk_tls(param(&params, "sni", &host), params.get("fp").map(String::as_str), alpn.as_ref(), backend)?;
if backend == LinkBackend::Xray
&& let Some(ech) = params.get("ech") {
tls.insert("ech_config_list".into(), unquote(ech).into());
}
ob.insert("tls".into(), Value::Object(tls));
}
if backend == LinkBackend::Xray && !ob.contains_key("tls") && xray_wants_transport_security(&host) {
return Err(LinkError::invalid("XRay refuses VLESS without TLS or REALITY to a public server"));
}
if let Some(tr) = mk_transport(
&transport,
param(&params, "path", "/"),
param(&params, "host", &host),
get(&params, "serviceName"),
get(&params, "mode"),
get(&params, "extra"),
get(&params, "x_padding_bytes"),
)? {
ob.insert("transport".into(), tr);
}
let flow = unquote(get(&params, "flow"));
let flows: &[&str] = match backend {
LinkBackend::SingBox => &SING_BOX_VLESS_FLOWS,
LinkBackend::Xray => &XRAY_VLESS_FLOWS,
};
if !one_of(&flow, flows, &format!("{} VLESS flow", backend.as_str()))?.is_empty() {
ob.insert("flow".into(), flow.into());
}
Ok(ob)
}
/// VMess alterId as the backends take it: an int a subscription cannot make so large (or
/// fractional, or negative) that the backend refuses the whole configuration.
fn alter_id(value: Option<&Value>) -> Result<i64> {
let invalid = |v: &Value| LinkError::invalid(format!("invalid VMess aid {}", py_repr_value(v)));
let n: i128 = match value {
None | Some(Value::Null) => 0,
Some(v) if !truthy(Some(v)) => 0,
Some(Value::Number(n)) => {
if let Some(i) = n.as_i64() {
i as i128
} else {
n.as_f64().map(|f| f.trunc() as i128).ok_or_else(|| invalid(value.unwrap()))?
}
}
Some(Value::Bool(true)) => 1,
Some(v @ Value::String(s)) => parse_py_int(s.trim()).ok_or_else(|| invalid(v))?,
Some(v) => return Err(invalid(v)),
};
if !(0..=65535).contains(&n) {
return Err(LinkError::invalid("VMess aid must be in 0-65535"));
}
Ok(n as i64)
}
fn py_repr_value(v: &Value) -> String {
match v {
Value::String(s) => repr(s),
other => py_str(other),
}
}
fn parse_vmess(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let b64 = url.get("vmess://".len()..).unwrap_or("");
let b64 = b64.split('#').next().unwrap_or("");
let b64 = b64.split('?').next().unwrap_or("");
let b64 = unquote(b64);
let padded = format!("{b64}{}", pad(b64.chars().count()));
let decode = |bytes: Option<Vec<u8>>| -> Option<Value> {
let text = String::from_utf8(bytes?).ok()?;
serde_json::from_str(&text).ok()
};
let data = decode(b64decode(padded.as_bytes()))
.or_else(|| decode(urlsafe_b64decode(padded.as_bytes())))
.ok_or_else(|| LinkError::invalid("failed to parse vmess URL: not base64 JSON"))?;
let data = data.as_object().ok_or_else(|| LinkError::invalid("failed to parse vmess URL: not a JSON object"))?;
let missing = |k: &str| LinkError::invalid(format!("failed to parse vmess URL: '{k}'"));
let mut host = py_str(data.get("add").ok_or_else(|| missing("add"))?).trim().to_owned();
// "[::1]", as the URL schemes write it: the backends dial it unbracketed.
if host.starts_with('[') && host.ends_with(']') && host.len() >= 2 {
host = host[1..host.len() - 1].to_owned();
}
let port = port_value(data.get("port").ok_or_else(|| missing("port"))?)?;
let net_raw = data.get("net").map(py_str).unwrap_or_else(|| "tcp".into());
let net = check_transport(&net_raw, backend, "VMess")?;
let tls_field = data.get("tls").map(py_str).unwrap_or_default();
let sni = if truthy(data.get("sni")) {
py_str(&data["sni"])
} else if truthy(data.get("host")) {
py_str(&data["host"])
} else {
host.clone()
};
// Panels write unset fields as "": that is the default, not a value.
let security = if truthy(data.get("scy")) { data["scy"].clone() } else { Value::from("auto") };
match backend {
LinkBackend::SingBox => {
let s = py_str(&security);
if !security.is_string() || !SING_BOX_VMESS_SECURITY.contains(&s.as_str()) {
return Err(LinkError::invalid(format!(
"unsupported sing-box VMess security {}",
repr(prefix(&s, 80))
)));
}
}
LinkBackend::Xray => {
if !security.is_string() {
return Err(LinkError::invalid("VMess scy must be a string"));
}
}
}
let id = match data.get("id") {
Some(Value::String(s)) => user_id(s, backend, "VMess")?,
_ => return Err(LinkError::invalid("VMess id must be a string")),
};
let mut ob = Map::new();
ob.insert("type".into(), "vmess".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port.into());
ob.insert("uuid".into(), id.into());
ob.insert("security".into(), security);
ob.insert("alter_id".into(), alter_id(data.get("aid"))?.into());
if tls_field == "tls" || tls_field == "reality" {
let fp = truthy(data.get("fp")).then(|| py_str(&data["fp"]));
let alpn = data.get("alpn").filter(|a| truthy(Some(a)));
ob.insert("tls".into(), Value::Object(mk_tls(&sni, fp.as_deref(), alpn, backend)?));
}
let path = if truthy(data.get("path")) { py_str(&data["path"]) } else { "/".into() };
let h_host = if truthy(data.get("host")) { py_str(&data["host"]) } else { host.clone() };
let net = if net == "http" { "h2".to_owned() } else { net };
if let Some(tr) = mk_transport(&net, &path, &h_host, path.trim_start_matches('/'), "", "", "")? {
ob.insert("transport".into(), tr);
}
Ok(ob)
}
fn parse_trojan(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let (userinfo, host, port_s, params) = parse_url_parts(url, "trojan")?;
let transport = check_transport(param(&params, "type", "tcp"), backend, "Trojan")?;
let alpn = params.get("alpn").map(|a| Value::String(a.clone()));
let mut ob = Map::new();
ob.insert("type".into(), "trojan".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("password".into(), nonempty_password(unquote(&userinfo), "Trojan")?.into());
ob.insert(
"tls".into(),
Value::Object(mk_tls(param(&params, "sni", &host), params.get("fp").map(String::as_str), alpn.as_ref(), backend)?),
);
if let Some(tr) = mk_transport(
&transport,
param(&params, "path", "/"),
param(&params, "host", &host),
get(&params, "serviceName"),
"",
"",
"",
)? {
ob.insert("transport".into(), tr);
}
Ok(ob)
}
fn decode_ss_userinfo(userinfo: &str) -> Result<(String, String)> {
let plain = unquote(userinfo);
if let Some((m, p)) = plain.split_once(':') {
return Ok((m.to_owned(), p.to_owned()));
}
let padded = format!("{userinfo}{}", pad(userinfo.chars().count()));
urlsafe_b64decode(padded.as_bytes())
.and_then(|b| String::from_utf8(b).ok())
.and_then(|d| d.split_once(':').map(|(m, p)| (m.to_owned(), p.to_owned())))
.ok_or_else(|| LinkError::invalid("invalid shadowsocks userinfo"))
}
// XRay refuses its whole configuration over one empty password.
fn nonempty_password(password: String, protocol: &str) -> Result<String> {
if password.is_empty() {
return Err(LinkError::invalid(format!("{protocol} password is empty")));
}
Ok(password)
}
fn check_ss(method: &str, password: &str, backend: LinkBackend) -> Result<()> {
match backend {
LinkBackend::Xray => {
if ss2022_key_bytes(method).is_none() && !XRAY_SS_METHODS.contains(&method.to_lowercase().as_str()) {
return Err(LinkError::invalid(format!("unsupported XRay shadowsocks method '{method}'")));
}
}
LinkBackend::SingBox => {
one_of(method, &SING_BOX_SS_METHODS, "sing-box shadowsocks method")?;
}
}
if method.to_lowercase() != "none" {
nonempty_password(password.to_owned(), "Shadowsocks")?;
}
let Some(bytes) = ss2022_key_bytes(method) else { return Ok(()) };
// A 2022 password is the key itself, padded base64 ("iPSK:uPSK" for EIH, AES only).
let keys: Vec<&str> = password.split(':').collect();
if keys.len() > 1 && !method.contains("aes") {
return Err(LinkError::invalid(format!("{method} takes a single key")));
}
for key in keys {
if b64decode_strict(key).map(|d| d.len()) != Some(bytes) {
return Err(LinkError::invalid(format!("{method} needs a base64 key of {bytes} bytes")));
}
}
Ok(())
}
fn parse_shadowsocks(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
// SIP002 (ss://base64(method:password)@host:port#name) and legacy links that encode the
// whole endpoint (ss://base64(method:password@host:port)#name).
let rest = url.get("ss://".len()..).unwrap_or("");
let rest = rest.split('#').next().unwrap_or("");
let endpoint = rest.split('?').next().unwrap_or("");
let (userinfo, host, port_s) = if endpoint.contains('@') {
let (u, h, p, _) = parse_url_parts(url, "ss")?;
(u, h, p)
} else {
let padded = format!("{endpoint}{}", pad(endpoint.chars().count()));
let decoded = urlsafe_b64decode(padded.as_bytes())
.and_then(|b| String::from_utf8(b).ok())
.ok_or_else(|| LinkError::invalid("invalid shadowsocks URL"))?;
let at = decoded.rfind('@').ok_or_else(|| LinkError::invalid("invalid legacy shadowsocks URL"))?;
let (h, p) = split_host_port(&decoded[at + 1..])?;
(decoded[..at].to_owned(), h, p)
};
let (method, password) = decode_ss_userinfo(&userinfo)?;
check_ss(&method, &password, backend)?;
let mut ob = Map::new();
ob.insert("type".into(), "shadowsocks".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("method".into(), method.into());
ob.insert("password".into(), password.into());
Ok(ob)
}
// "20000-30000" or a lone "443" in sing-box's "a:b" form: it refuses a bare port.
fn port_range(part: &str, mport: &str) -> Result<String> {
let (low, high) = PORT_RANGE_RE
.captures(part)
.and_then(|c| {
let low: u64 = c.get(1)?.as_str().parse().ok()?;
let high: u64 = c.get(2).map_or(Some(low), |m| m.as_str().parse().ok())?;
Some((low, high))
})
.unwrap_or((0, 0));
if !(1 <= low && low <= high && high <= 65535) {
return Err(LinkError::invalid(format!("invalid hysteria2 mport {}", repr(prefix(mport, 40)))));
}
Ok(format!("{low}:{high}"))
}
fn parse_hysteria2(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let scheme = if url.to_lowercase().starts_with("hysteria2://") { "hysteria2" } else { "hy2" };
let (userinfo, host, port_s, params) = parse_url_parts(url, scheme)?;
let mut tls = Map::new();
tls.insert("enabled".into(), true.into());
tls.insert("server_name".into(), param(&params, "sni", &host).into());
tls.insert("insecure".into(), (params.get("insecure").map(String::as_str).unwrap_or("0") == "1").into());
// XRay checks the certificate against the pin instead (sing-box pins only a public key).
let pin = get(&params, "pinSHA256");
if backend == LinkBackend::Xray && !pin.is_empty() {
if !CERT_SHA256_RE.is_match(pin) {
return Err(LinkError::invalid(format!("invalid hysteria2 pinSHA256 {}", repr(prefix(pin, 100)))));
}
tls.insert("insecure".into(), false.into());
tls.insert("certificate_sha256".into(), pin.replace(':', "").to_lowercase().into());
}
let mut ob = Map::new();
ob.insert("type".into(), "hysteria2".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("password".into(), unquote(&userinfo).into());
ob.insert("tls".into(), Value::Object(tls));
if get(&params, "obfs") == "salamander" {
let password = get(&params, "obfs-password");
if password.is_empty() {
return Err(LinkError::invalid("hysteria2 salamander obfs is missing its obfs-password"));
}
ob.insert("obfs".into(), json!({ "type": "salamander", "password": password }));
}
// Port hopping, as v2rayN writes it: "20000-30000", or several joined by commas.
let mport = get(&params, "mport");
if !mport.is_empty() {
let ranges = mport
.split(',')
.map(str::trim)
.filter(|r| !r.is_empty())
.map(|r| port_range(r, mport).map(Value::from))
.collect::<Result<Vec<_>>>()?;
ob.insert("server_ports".into(), Value::Array(ranges));
ob.insert("hop_interval".into(), "30s".into());
}
Ok(ob)
}
fn parse_tuic(url: &str, tag: &str) -> Result<Map<String, Value>> {
let (userinfo, host, port_s, params) = parse_url_parts(url, "tuic")?;
let (uuid, password) = userinfo.split_once(':').unwrap_or((&userinfo, ""));
let alpn = alpn_list(&Value::from(param(&params, "alpn", "h3")));
// Unlike VLESS, sing-box's TUIC takes nothing but a UUID.
if !UUID_RE.is_match(uuid) {
return Err(LinkError::invalid("invalid TUIC uuid: not a UUID"));
}
let mut ob = Map::new();
ob.insert("type".into(), "tuic".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("uuid".into(), uuid.into());
ob.insert("password".into(), unquote(password).into());
ob.insert(
"congestion_control".into(),
one_of(param(&params, "congestion_control", "bbr"), &TUIC_CONGESTION_CONTROLS, "TUIC congestion_control")?.into(),
);
ob.insert("udp_relay_mode".into(), param(&params, "udp_relay_mode", "native").into());
ob.insert(
"tls".into(),
json!({ "enabled": true, "server_name": param(&params, "sni", &host), "alpn": alpn }),
);
Ok(ob)
}
fn parse_anytls(url: &str, tag: &str) -> Result<Map<String, Value>> {
// anytls://password@host:port?sni=example.com&insecure=1&fp=chrome&alpn=h2
let (userinfo, host, port_s, params) = parse_url_parts(url, "anytls")?;
if userinfo.is_empty() {
return Err(LinkError::invalid("anytls link is missing the password"));
}
let sni = [get(&params, "sni"), get(&params, "peer")]
.into_iter()
.find(|s| !s.is_empty())
.unwrap_or(&host)
.to_owned();
let alpn = params.get("alpn").map(|a| Value::String(a.clone()));
let mut tls = mk_tls(&sni, params.get("fp").map(String::as_str), alpn.as_ref(), LinkBackend::SingBox)?;
let insecure = params.get("insecure").or_else(|| params.get("allowInsecure")).map(String::as_str).unwrap_or("0");
if insecure == "1" {
tls.insert("insecure".into(), true.into());
}
let mut ob = Map::new();
ob.insert("type".into(), "anytls".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("password".into(), unquote(&userinfo).into());
ob.insert("tls".into(), Value::Object(tls));
Ok(ob)
}
fn parse_naive(url: &str, tag: &str) -> Result<Map<String, Value>> {
// naive+https://user:pass@host:port, or naive+quic:// for HTTP/3 (NekoBox's form).
let scheme = super::detect_scheme(url);
let (userinfo, host, port_s, params) = parse_url_parts(url, &scheme)?;
let sni = Some(get(&params, "sni")).filter(|s| !s.is_empty()).unwrap_or(&host).to_owned();
let mut ob = Map::new();
ob.insert("type".into(), "naive".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("tls".into(), json!({ "enabled": true, "server_name": sni }));
set_auth(&mut ob, &userinfo);
if scheme == "naive+quic" {
ob.insert("quic".into(), true.into());
}
Ok(ob)
}
/// socks:// and http(s)://: host, port and optional credentials, nothing else.
fn parse_plain_proxy(url: &str, tag: &str, kind: &str) -> Result<Map<String, Value>> {
let scheme = super::detect_scheme(url);
let (userinfo, host, port_s, _) = parse_url_parts(url, &scheme)?;
let mut ob = Map::new();
ob.insert("type".into(), kind.into());
ob.insert("tag".into(), tag.into());
if kind == "socks" {
ob.insert("version".into(), (if scheme.starts_with("socks4") { "4" } else { "5" }).into());
}
set_auth(&mut ob, &userinfo);
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
if kind == "http" && scheme == "https" {
ob.insert("tls".into(), json!({ "enabled": true, "server_name": host }));
}
Ok(ob)
}