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>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 22:38:56 +03:00
1 parent c837db1c18
commit 77d4cefe0e
12 files changed
+2821 -3

No files matched your search

@@ -0,0 +1,22 @@
//! For the parity check against upstream (tools/parity/links.py): JSON lines in,
//! `{"url", "tag", "backend"}`, JSON lines out, `{"ok": outbound}` or `{"error": message}`.
use std::io::{BufRead, Write};
use ps_core::links::{LinkBackend, build_outbound};
use serde_json::{Value, json};
fn main() {
let stdout = std::io::stdout();
let mut out = stdout.lock();
for line in std::io::stdin().lock().lines() {
let line = line.expect("stdin");
let req: Value = serde_json::from_str(&line).expect("a JSON request");
let backend = if req["backend"] == "xray" { LinkBackend::Xray } else { LinkBackend::SingBox };
let result = match build_outbound(req["url"].as_str().unwrap(), req["tag"].as_str().unwrap(), backend) {
Ok(ob) => json!({ "ok": ob }),
Err(e) => json!({ "error": e.to_string() }),
};
writeln!(out, "{result}").unwrap();
}
}
+2
View File
@@ -10,6 +10,7 @@
mod inbounds;
mod misc;
mod privilege;
mod proxy;
mod tunnels;
mod validate;
@@ -17,6 +18,7 @@ mod zapret;
pub use inbounds::*;
pub use misc::*;
pub use privilege::privileged_changes;
pub use proxy::*;
pub use tunnels::*;
pub use validate::{Issue, Severity, validate};
@@ -0,0 +1,171 @@
//! Which edits only an administrator may make.
//!
//! Upstream changes its configuration with a rebuild, as root; here the signed-in user edits
//! it in the app, and the service that runs it is LocalSystem. So whatever `userControl`
//! grants, a change to an option that makes the service run a program, pass arguments
//! through to one, or read or write a file of the caller's choosing needs an administrator:
//! otherwise it is a way to run code or read files as SYSTEM.
use serde_json::Value;
use super::Config;
/// Keys whose value is passed to a program as it stands, or makes one run something.
const RAW_KEYS: [&str; 4] = ["extraArgs", "extraConfig", "nfqwsArgs", "allowConfigHooks"];
/// Option paths (`.`-separated, `*` for any key or index) privileged as a whole.
const PRIVILEGED_PATHS: [&str; 5] = [
"userControl",
"proxy.dns.singBox",
"zapret.zapret2.profiles",
"zapret.zapret2.blobs",
"inbounds.manager.api",
];
/// Where a value of `new` that differs from `old` needs an administrator, as option paths.
pub fn privileged_changes(old: &Config, new: &Config) -> Vec<String> {
let old = serde_json::to_value(old).expect("the config always serializes");
let new = serde_json::to_value(new).expect("the config always serializes");
let mut found = Vec::new();
walk(&mut Vec::new(), Some(&old), Some(&new), &mut found);
found
}
fn walk(path: &mut Vec<String>, old: Option<&Value>, new: Option<&Value>, found: &mut Vec<String>) {
// An unset option serializes as null, or not at all: either way it is unset.
let unset = |v: Option<&Value>| v.is_none_or(Value::is_null);
if old == new || (unset(old) && unset(new)) {
return;
}
match privileged_here(path, new) {
Some(true) => {
found.push(path.join("."));
return;
}
Some(false) => return,
None => {}
}
match (old, new) {
(Some(Value::Object(a)), Some(Value::Object(b))) => {
let keys: Vec<&String> = a.keys().chain(b.keys().filter(|k| !a.contains_key(*k))).collect();
for key in keys {
path.push(key.clone());
walk(path, a.get(key), b.get(key), found);
path.pop();
}
}
(Some(Value::Array(a)), Some(Value::Array(b))) => {
for i in 0..a.len().max(b.len()) {
path.push(i.to_string());
walk(path, a.get(i), b.get(i), found);
path.pop();
}
}
// An object or list appearing or going: what it holds decides.
(None, Some(v @ (Value::Object(_) | Value::Array(_)))) => walk_new(path, v, found),
(Some(v @ (Value::Object(_) | Value::Array(_))), None) => walk_new(path, v, found),
_ => {}
}
}
/// A whole subtree added or removed: every privileged value in it counts.
fn walk_new(path: &mut Vec<String>, value: &Value, found: &mut Vec<String>) {
let empty = match value {
Value::Object(_) => Value::Object(Default::default()),
_ => Value::Array(Vec::new()),
};
walk(path, Some(&empty), Some(value), found);
}
/// `Some(true)`: a change at `path` is privileged. `Some(false)`: it is not, and nothing
/// below it is either. `None`: look deeper.
fn privileged_here(path: &[String], new: Option<&Value>) -> Option<bool> {
if PRIVILEGED_PATHS.iter().any(|p| matches_path(p, path)) {
return Some(true);
}
let key = path.last()?.as_str();
if key.ends_with("File") || key.ends_with("Directory") {
return Some(true);
}
if RAW_KEYS.contains(&key) {
return Some(true);
}
// Raw backend JSON is fine as long as it names no local file or program, as upstream
// takes it at runtime from its userControl group.
if key.ends_with("Json") {
return Some(new.is_some_and(|v| !crate::links::local_file_keys(v).is_empty()));
}
None
}
fn matches_path(pattern: &str, path: &[String]) -> bool {
let parts: Vec<&str> = pattern.split('.').collect();
path.len() >= parts.len() && parts.iter().zip(path).all(|(p, s)| *p == "*" || *p == s)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{AwgProfile, Outbound};
#[test]
fn plain_edits_need_no_administrator() {
let old = Config::default();
let mut new = old.clone();
new.proxy.enable = true;
new.proxy.listener.port = 2080;
new.proxy.outbounds.push(Outbound {
tag: "nl".into(),
url: Some("hy2://pw@example.com:443".into()),
..Default::default()
});
new.zapret.enable = true;
assert_eq!(privileged_changes(&old, &new), Vec::<String>::new());
}
#[test]
fn files_programs_and_access_need_one() {
let old = Config::default();
let mut new = old.clone();
new.ssh_proxy.extra_args = vec!["-oProxyCommand=calc.exe".into()];
new.tor.extra_config = "ClientTransportPlugin x exec C:\\evil.exe".into();
new.proxy.listener.auth.password_file = Some(r"C:\Windows\System32\config\SAM".into());
new.user_control.scopes = vec![crate::config::Scope::Config];
new.amnezia_wg.profiles.insert(
"home".into(),
AwgProfile { allow_config_hooks: true, config_file: Some("x".into()), ..Default::default() },
);
let found = privileged_changes(&old, &new);
for path in [
"sshProxy.extraArgs",
"tor.extraConfig",
"proxy.listener.auth.passwordFile",
"userControl",
"amneziaWg.profiles.home.allowConfigHooks",
"amneziaWg.profiles.home.configFile",
] {
assert!(found.iter().any(|f| f == path), "{path} not in {found:?}");
}
}
#[test]
fn raw_json_is_privileged_only_when_it_names_files() {
let old = Config::default();
let mut new = old.clone();
let mut json = serde_json::Map::new();
json.insert("type".into(), "vless".into());
new.proxy.outbounds.push(Outbound { tag: "a".into(), sing_box_json: Some(json.clone()), ..Default::default() });
assert_eq!(privileged_changes(&old, &new), Vec::<String>::new());
json.insert("tls".into(), serde_json::json!({ "certificate_path": "C:\\x" }));
new.proxy.outbounds[0].sing_box_json = Some(json);
assert_eq!(privileged_changes(&old, &new), ["proxy.outbounds.0.singBoxJson"]);
}
#[test]
fn removing_a_privileged_value_counts_too() {
let mut old = Config::default();
old.ssh_proxy.extra_args = vec!["-v".into()];
let new = Config::default();
assert_eq!(privileged_changes(&old, &new), ["sshProxy.extraArgs"]);
}
}
+46 -3
View File
@@ -48,6 +48,15 @@ fn tag_pattern_ok(tag: &str) -> bool {
&& 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())
@@ -172,6 +181,9 @@ fn proxy(cfg: &Config, v: &mut Issues) {
}
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"));
}
@@ -257,6 +269,11 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
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;
@@ -275,10 +292,14 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
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
&& (iface.is_empty() || iface.len() > 32 || !iface.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))) {
v.error(format!("{path}.interfaceName"), "a tunnel name takes letters, digits, '_', '-' and '.' (at most 32)");
}
&& (!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");
@@ -349,6 +370,11 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
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");
@@ -447,6 +473,9 @@ fn inbounds(cfg: &Config, v: &mut Issues) {
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"));
@@ -498,6 +527,9 @@ fn inbounds(cfg: &Config, v: &mut Issues) {
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}"));
@@ -641,6 +673,17 @@ mod tests {
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();
+1
View File
@@ -6,3 +6,4 @@
pub mod config;
pub mod derived;
pub mod links;
+175
View File
@@ -0,0 +1,175 @@
//! 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<String>) -> 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<T> = std::result::Result<T, LinkError>;
/// 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<Map<String, Value>> {
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<Value> {
let ob = parse_url(url, tag, backend)?;
finish_outbound(ob, backend)
}
pub(crate) fn finish_outbound(ob: Map<String, Value>, backend: LinkBackend) -> Result<Value> {
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<String> {
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<String> {
let mut keys: Vec<String> = 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<Value> {
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;
+878
View File
@@ -0,0 +1,878 @@
//! 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)
}
+231
View File
@@ -0,0 +1,231 @@
//! The few pieces of Python's standard library upstream's parsers lean on, with Python's
//! edge cases: share links in the wild depend on them (lenient base64, `+` in queries,
//! percent escapes that are not).
use std::collections::HashMap;
/// `urllib.parse.unquote`: `%XX` escapes decoded as UTF-8, invalid sequences replaced,
/// a `%` without two hex digits kept as it is. `+` stays `+`.
pub fn unquote(s: &str) -> String {
if !s.contains('%') {
return s.to_owned();
}
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len()
&& let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
out.push(h << 4 | l);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn hex(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
/// `dict(urllib.parse.parse_qsl(query, keep_blank_values=True))`: pairs split on `&`,
/// `+` read as a space, a name without `=` kept with an empty value, the last of a
/// repeated name winning.
pub fn parse_qs(query: &str) -> HashMap<String, String> {
let mut out = HashMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
out.insert(unquote(&name.replace('+', " ")), unquote(&value.replace('+', " ")));
}
out
}
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn b64_value(c: u8) -> Option<u8> {
B64.iter().position(|&x| x == c).map(|p| p as u8)
}
/// `base64.b64decode(s)` (not `validate`): characters outside the alphabet are skipped, a
/// complete padding ends the input, and a leftover partial quad is an error, as CPython's
/// `binascii.a2b_base64` does.
pub fn b64decode(s: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() * 3 / 4);
let mut quad_pos = 0u8;
let mut left = 0u32;
let mut pads = 0u8;
for &c in s {
if c == b'=' {
if quad_pos >= 2 {
pads += 1;
if quad_pos + pads >= 4 {
return Some(out);
}
}
continue;
}
let Some(v) = b64_value(c) else { continue };
pads = 0;
match quad_pos {
0 => {
left = v as u32;
quad_pos = 1;
}
1 => {
left = left << 6 | v as u32;
out.push((left >> 4) as u8);
left &= 0x0f;
quad_pos = 2;
}
2 => {
left = left << 6 | v as u32;
out.push((left >> 2) as u8);
left &= 0x03;
quad_pos = 3;
}
_ => {
out.push((left << 6 | v as u32) as u8);
left = 0;
quad_pos = 0;
}
}
}
if quad_pos == 0 { Some(out) } else { None }
}
/// `base64.urlsafe_b64decode(s)`: `-` and `_` read as `+` and `/` first.
pub fn urlsafe_b64decode(s: &[u8]) -> Option<Vec<u8>> {
let translated: Vec<u8> = s
.iter()
.map(|&c| match c {
b'-' => b'+',
b'_' => b'/',
c => c,
})
.collect();
b64decode(&translated)
}
/// `base64.b64decode(s, validate=True)`: only the alphabet, then at most two `=`.
pub fn b64decode_strict(s: &str) -> Option<Vec<u8>> {
let body = s.trim_end_matches('=');
if s.len() - body.len() > 2 || !body.bytes().all(|c| b64_value(c).is_some()) {
return None;
}
b64decode(s.as_bytes())
}
/// `"=" * (-len(s) % 4)`, the padding upstream appends before decoding.
pub fn pad(len: usize) -> &'static str {
["", "===", "==", "="][len % 4]
}
/// `str.splitlines()`: every line boundary Python knows.
pub fn splitlines(s: &str) -> Vec<&str> {
let mut lines = Vec::new();
let mut start = 0;
let mut chars = s.char_indices().peekable();
while let Some((i, c)) = chars.next() {
let boundary = matches!(
c,
'\n' | '\r' | '\x0b' | '\x0c' | '\x1c' | '\x1d' | '\x1e' | '\u{85}' | '\u{2028}' | '\u{2029}'
);
if boundary {
lines.push(&s[start..i]);
let mut end = i + c.len_utf8();
if c == '\r'
&& let Some(&(j, '\n')) = chars.peek() {
chars.next();
end = j + 1;
}
start = end;
}
}
if start < s.len() {
lines.push(&s[start..]);
}
lines
}
/// `repr()` of a short string, for error messages that quote a link's value: escapes,
/// not raw control characters, reach the terminal.
pub fn repr(s: &str) -> String {
let quote = if s.contains('\'') && !s.contains('"') { '"' } else { '\'' };
let mut out = String::new();
out.push(quote);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c == quote => {
out.push('\\');
out.push(c);
}
c if (c as u32) < 0x20 || c == '\x7f' => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push(c),
}
}
out.push(quote);
out
}
/// The first `n` characters (code points, as Python slices).
pub fn prefix(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((i, _)) => &s[..i],
None => s,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unquote_matches_python() {
assert_eq!(unquote("%2Fa%20b%C3%A9"), "/a b\u{e9}");
assert_eq!(unquote("100%"), "100%");
assert_eq!(unquote("%zz%4"), "%zz%4");
assert_eq!(unquote("a+b"), "a+b");
assert_eq!(unquote("%C3"), "\u{fffd}");
}
#[test]
fn query_reads_plus_as_space_and_keeps_blanks() {
let q = parse_qs("sni=&a=1&a=2&flag&x=a+b%2B&&");
assert_eq!(q["sni"], "");
assert_eq!(q["a"], "2");
assert_eq!(q["flag"], "");
assert_eq!(q["x"], "a b+");
}
#[test]
fn base64_is_lenient_like_cpython() {
assert_eq!(b64decode(b"aGVsbG8=").unwrap(), b"hello");
assert_eq!(b64decode(b"aGVs\nbG8=").unwrap(), b"hello");
assert_eq!(b64decode(b"aGVsbG8=garbage").unwrap(), b"hello");
assert!(b64decode(b"aGVsbG8").is_none());
assert_eq!(b64decode(format!("aGVsbG8{}", pad(7)).as_bytes()).unwrap(), b"hello");
assert_eq!(urlsafe_b64decode(b"-_8=").unwrap(), vec![0xfb, 0xff]);
assert!(b64decode_strict("aGVs bG8=").is_none());
assert_eq!(b64decode_strict("aGVsbG8=").unwrap(), b"hello");
}
#[test]
fn splitlines_knows_every_boundary() {
assert_eq!(splitlines("a\r\nb\rc\nd\u{2028}e\n"), ["a", "b", "c", "d", "e"]);
assert_eq!(splitlines("a\n\nb"), ["a", "", "b"]);
}
}
@@ -0,0 +1,497 @@
//! Subscriptions: a list of share links, plain or base64, each becoming an outbound tagged
//! after the subscription and the link's remark. Upstream's `proxy_parsing.py` half.
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::LazyLock;
use regex::Regex;
use serde_json::{Map, Value};
use super::py::{self, b64decode, pad, prefix, unquote};
use super::{LinkBackend, LinkError, Result, SCHEMES, detect_scheme, finish_outbound, parse_url};
/// A subscription is a list of share links; the biggest real ones are tens of KiB.
pub const MAX_SUBSCRIPTION_BYTES: usize = 8 * 1024 * 1024;
/// Real subscriptions hold hundreds; more would be minutes of parsing and gigabytes of config.
pub const MAX_SUBSCRIPTION_ENTRIES: usize = 5000;
/// What upstream presents itself as: providers serve v2rayN's format to it.
pub const USER_AGENT: &str = "v2rayN/6.0";
/// `ipaddress.ip_address(host)`: a literal IPv4 (dotted decimal, no leading zeros) or IPv6
/// address, an IPv6 zone ignored.
pub fn py_ip_address(host: &str) -> Option<IpAddr> {
if let Ok(v4) = host.parse::<Ipv4Addr>() {
return Some(IpAddr::V4(v4));
}
let unscoped = host.split('%').next().unwrap_or(host);
unscoped.parse::<Ipv6Addr>().ok().map(IpAddr::V6)
}
/// An IPv4-mapped IPv6 address as the IPv4 address it maps.
pub fn unmap(address: IpAddr) -> IpAddr {
match address {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(address),
v4 => v4,
}
}
/// glibc's `inet_aton`: one to four parts, each decimal, octal (`0` first) or hex (`0x`),
/// the last filling what the others leave.
fn inet_aton(s: &str) -> Option<Ipv4Addr> {
let parts: Vec<&str> = s.split('.').collect();
if parts.is_empty() || parts.len() > 4 {
return None;
}
let mut values = Vec::with_capacity(parts.len());
for part in &parts {
let value = if let Some(hex) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) {
if hex.is_empty() { 0 } else { u64::from_str_radix(hex, 16).ok()? }
} else if part.len() > 1 && part.starts_with('0') {
u64::from_str_radix(&part[1..], 8).ok()?
} else if part.is_empty() {
return None;
} else {
part.parse::<u64>().ok()?
};
values.push(value);
}
let (last, head) = values.split_last()?;
if head.iter().any(|v| *v > 0xff) {
return None;
}
let max_last = [0xffff_ffffu64, 0xff_ffff, 0xffff, 0xff][head.len()];
if *last > max_last {
return None;
}
let mut n: u64 = 0;
for (i, v) in head.iter().enumerate() {
n |= v << (24 - 8 * i);
}
Some(Ipv4Addr::from((n | last) as u32))
}
/// A server name as the backends would dial it: a literal address, or one of `inet_aton`'s
/// forms (2130706433, 0x7f.1, 127.1), which a resolver may still take.
fn server_address(host: &str) -> Option<IpAddr> {
let address = match py_ip_address(host) {
Some(a) => a,
None => {
static ATON_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[0-9A-Fa-fXx.]+$").unwrap());
if !ATON_RE.is_match(host) {
return None;
}
IpAddr::V4(inet_aton(host)?)
}
};
Some(unmap(address))
}
fn in_net(address: IpAddr, net: &str) -> bool {
net.parse::<ipnet::IpNet>().is_ok_and(|n| n.contains(&address))
}
// Opt-in per subscription (allowPrivateServers): a provider's servers are not on the LAN.
const PRIVATE_NETWORKS: [&str; 5] = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "fc00::/7"];
fn is_loopback(a: IpAddr) -> bool {
a.is_loopback()
}
fn is_unspecified(a: IpAddr) -> bool {
a.is_unspecified()
}
fn is_link_local(a: IpAddr) -> bool {
match a {
IpAddr::V4(v4) => v4.is_link_local(),
IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
}
}
fn is_private(a: IpAddr) -> bool {
PRIVATE_NETWORKS.iter().any(|n| in_net(a, n))
}
fn check_address(host: &str, address: IpAddr, allow_private: bool) -> Result<()> {
if is_loopback(address) || is_unspecified(address) || in_net(address, "0.0.0.0/8") {
return Err(LinkError::RefusedServer(format!("server {host} is this host")));
}
if is_link_local(address) || address.is_multicast() {
return Err(LinkError::RefusedServer(format!("server {host} is a link-local or multicast address")));
}
if !allow_private && is_private(address) {
return Err(LinkError::RefusedServer(format!(
"server {host} is a private address (see allowPrivateServers)"
)));
}
Ok(())
}
/// Refuses a literal address (or localhost) on this host, its link, or, unless
/// `allow_private`, a private network: urltest would pick a loopback entry as the exit.
pub fn check_server(host: &Value, allow_private: bool) -> Result<()> {
let Some(host) = host.as_str() else { return Ok(()) };
let mut name = host.trim().trim_end_matches('.').to_lowercase();
// The backends dial "[127.0.0.1]" as 127.0.0.1.
if name.starts_with('[') && name.ends_with(']') && name.len() >= 2 {
name = name[1..name.len() - 1].trim_end_matches('.').to_owned();
}
if name == "localhost" || name.ends_with(".localhost") {
return Err(LinkError::RefusedServer(format!("server {host} is this host")));
}
if let Some(address) = server_address(&name) {
check_address(host, address, allow_private)?;
}
Ok(())
}
/// How close to this host a URL's host is: 2 for this host or its link, 1 for a private
/// network, 0 for anywhere else or a name other than localhost.
pub fn nearness(host: Option<&str>) -> u8 {
let Some(host) = host else { return 0 };
let name = host.trim().trim_end_matches('.').to_lowercase();
if name == "localhost" || name.ends_with(".localhost") {
return 2;
}
let Some(address) = server_address(&name) else { return 0 };
if is_loopback(address) || is_unspecified(address) || is_link_local(address) || in_net(address, "0.0.0.0/8") {
return 2;
}
u8::from(is_private(address))
}
/// Whether a subscription fetch may follow a redirect: http and https only, never from
/// https down to http, never nearer to this host than where it came from.
pub fn redirect_allowed(from: &url_parts::Url, to: &url_parts::Url) -> std::result::Result<(), &'static str> {
if to.scheme != "http" && to.scheme != "https" {
return Err("subscription redirected off http:// and https://");
}
if to.scheme == "http" && from.scheme == "https" {
return Err("subscription redirected from https:// to http://");
}
if nearness(to.hostname.as_deref()) > nearness(from.hostname.as_deref()) {
return Err("subscription redirected to this host or a private network");
}
Ok(())
}
/// The bits of `urllib.parse.urlsplit` upstream reads.
pub mod url_parts {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Url {
pub scheme: String,
pub hostname: Option<String>,
}
/// Scheme (lowercased) and hostname (lowercased, unbracketed) of a URL.
pub fn split(url: &str) -> Result<Url, &'static str> {
let (scheme, rest) = match url.find(':') {
Some(i)
if i > 0
&& url[..i].chars().next().is_some_and(|c| c.is_ascii_alphabetic())
&& url[..i].chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) =>
{
(url[..i].to_lowercase(), &url[i + 1..])
}
_ => (String::new(), url),
};
let netloc = match rest.strip_prefix("//") {
Some(after) => after.split(['/', '?', '#']).next().unwrap_or(""),
None => "",
};
if netloc.contains('[') != netloc.contains(']') {
return Err("Invalid IPv6 URL");
}
let hostinfo = netloc.rsplit_once('@').map_or(netloc, |(_, h)| h);
let hostname = match hostinfo.split_once('[') {
Some((_, bracketed)) => bracketed.split(']').next().unwrap_or(""),
None => hostinfo.split(':').next().unwrap_or(""),
};
let hostname = (!hostname.is_empty()).then(|| match hostname.split_once('%') {
Some((h, zone)) => format!("{}%{zone}", h.to_lowercase()),
None => hostname.to_lowercase(),
});
Ok(Url { scheme, hostname })
}
}
/// The links of a subscription body: base64 (line-wrapped or URL-safe) or plain text.
pub fn decode_subscription(data: &[u8]) -> Vec<String> {
let stripped: Vec<u8> = data
.iter()
.filter(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c'))
.map(|&b| match b {
b'-' => b'+',
b'_' => b'/',
b => b,
})
.collect();
let mut padded = stripped.clone();
padded.extend_from_slice(pad(stripped.len()).as_bytes());
let decoded = b64decode(&padded)
.and_then(|d| String::from_utf8(d).ok())
.filter(|text| SCHEMES.iter().any(|s| text.contains(&format!("{s}://"))));
let text = decoded.unwrap_or_else(|| String::from_utf8_lossy(data).into_owned());
py::splitlines(&text).into_iter().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()
}
/// A remark as a tag: letters (any script), digits, `_` and `-`, at most 60 characters.
pub fn slugify_tag(remark: &str) -> String {
static NON_WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[^\w-]").unwrap());
static DASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-{2,}").unwrap());
let slug = NON_WORD.replace_all(remark, "-");
let slug = DASHES.replace_all(&slug, "-");
let slug = prefix(slug.trim_matches('-'), 60);
if slug.is_empty() { "proxy".into() } else { slug.to_owned() }
}
pub fn make_tag(prefix: &str, remark: &str, index: usize) -> String {
if remark.is_empty() {
format!("{prefix}-{index}")
} else {
format!("{prefix}-{}", slugify_tag(&unquote(remark)))
}
}
fn remark_from_line(line: &str) -> &str {
line.split_once('#').map_or("", |(_, r)| r)
}
fn unique_tag(base: String, seen: &HashSet<String>) -> String {
if !seen.contains(&base) {
return base;
}
(2..).map(|n| format!("{base}-{n}")).find(|t| !seen.contains(t)).expect("an unused suffix")
}
/// The resolver XRay asks for the ECH config, when echConfigList names one instead of
/// holding the config: "[name+]udp://1.1.1.1:53", "https://dns.example/dns-query".
fn ech_dns_server(value: &Value) -> Option<String> {
let value = value.as_str()?;
if !value.contains("://") {
return None;
}
let scheme_part = value.split("://").next().unwrap_or("");
let url = if scheme_part.contains('+') { value.split_once('+').map_or(value, |(_, r)| r) } else { value };
let host = url_parts::split(url).ok().and_then(|u| u.hostname);
Some(host.unwrap_or_else(|| value.to_owned()))
}
/// Every address the outbound dials: its server, any "address" in an xhttp extra's
/// downloadSettings, and the resolver an ECH config is fetched from.
fn dialed_servers(ob: &Map<String, Value>) -> Vec<Value> {
let mut servers = vec![ob.get("server").cloned().unwrap_or(Value::Null)];
if let Some(ech) = ob.get("tls").and_then(Value::as_object).and_then(|t| t.get("ech_config_list")).and_then(ech_dns_server) {
servers.push(ech.into());
}
let mut stack: Vec<&Value> =
ob.get("transport").and_then(Value::as_object).and_then(|t| t.get("extra")).into_iter().collect();
while let Some(item) = stack.pop() {
match item {
Value::Object(map) => {
for (key, value) in map {
let lower = key.to_lowercase();
if lower == "address" {
servers.push(match value {
Value::String(_) => value.clone(),
other => Value::String(other.to_string()),
});
} else if lower == "echconfiglist"
&& let Some(ech) = ech_dns_server(value) {
servers.push(ech.into());
}
stack.push(value);
}
}
Value::Array(list) => stack.extend(list),
_ => {}
}
}
servers
}
/// What reading a subscription gave.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Parsed {
/// Each entry with the backend that took it, in the subscription's order.
pub outbounds: Vec<(LinkBackend, Value)>,
/// tag -> the line it came from, to share it back.
pub links: Vec<(String, String)>,
/// One line per entry left out.
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Options {
pub allow_private: bool,
pub allow_insecure: bool,
}
/// Parses every supported line, trying each backend in turn. A line no backend accepts is
/// reported with every backend's complaint and skipped, as is one whose server is refused.
pub fn walk(lines: &[String], tag_prefix: &str, backends: &[LinkBackend], opts: Options) -> Parsed {
let mut parsed = Parsed::default();
let mut seen: HashSet<String> = HashSet::new();
for (index, line) in lines.iter().enumerate() {
let scheme = detect_scheme(line);
if !SCHEMES.contains(&scheme.as_str()) {
continue;
}
if seen.len() >= MAX_SUBSCRIPTION_ENTRIES {
parsed.warnings.push(format!(
"subscription has more than {MAX_SUBSCRIPTION_ENTRIES} entries: the rest are left out"
));
break;
}
let tag = unique_tag(make_tag(tag_prefix, remark_from_line(line), index), &seen);
let mut errors = Vec::new();
let mut taken = false;
for &backend in backends {
let attempt = (|| -> Result<Value> {
let ob = parse_url(line, &tag, backend)?;
for server in dialed_servers(&ob) {
check_server(&server, opts.allow_private)?;
}
// Whoever serves the list could otherwise have the tunnel trust any certificate.
let insecure = ob.get("tls").and_then(Value::as_object).and_then(|t| t.get("insecure"));
if !opts.allow_insecure && insecure.is_some_and(|v| v.as_bool().unwrap_or(!v.is_null())) {
return Err(LinkError::invalid("it turns certificate checks off (insecure=1; see allowInsecure)"));
}
finish_outbound(ob, backend)
})();
match attempt {
Ok(ob) => {
seen.insert(tag.clone());
parsed.outbounds.push((backend, ob));
parsed.links.push((tag.clone(), line.clone()));
taken = true;
break;
}
Err(LinkError::RefusedServer(message)) => {
// The same server whichever backend reads the line.
parsed.warnings.push(format!("skipping entry {index} ({scheme}): {message}"));
taken = true;
break;
}
Err(LinkError::Invalid(message)) => {
errors.push(if backends.len() > 1 { format!("{}: {message}", backend.as_str()) } else { message });
}
}
}
if !taken {
parsed.warnings.push(format!("skipping entry {index} ({scheme}): {}", errors.join("; ")));
}
}
parsed
}
/// A subscription for one backend.
pub fn parse_subscription(lines: &[String], tag_prefix: &str, backend: LinkBackend, opts: Options) -> Parsed {
walk(lines, tag_prefix, &[backend], opts)
}
/// A subscription for the hybrid backend: each line goes to whichever backend can dial it,
/// sing-box first.
pub fn parse_hybrid_subscription(lines: &[String], tag_prefix: &str, opts: Options) -> Parsed {
walk(lines, tag_prefix, &[LinkBackend::SingBox, LinkBackend::Xray], opts)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn inet_aton_takes_the_short_forms() {
assert_eq!(inet_aton("2130706433"), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(inet_aton("0x7f.1"), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(inet_aton("127.1"), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(inet_aton("010.0.0.1"), Some(Ipv4Addr::new(8, 0, 0, 1)));
assert_eq!(inet_aton("1.2.3.4.5"), None);
assert_eq!(inet_aton("256.1"), None);
}
#[test]
fn servers_on_this_host_or_its_lan_are_refused() {
for host in ["127.0.0.1", "localhost", "a.localhost", "[::1]", "0x7f.1", "::ffff:127.0.0.1", "169.254.1.1", "0.0.0.0"] {
assert!(matches!(check_server(&json!(host), true), Err(LinkError::RefusedServer(_))), "{host}");
}
assert!(check_server(&json!("192.168.1.10"), false).is_err());
assert!(check_server(&json!("192.168.1.10"), true).is_ok());
assert!(check_server(&json!("example.com"), false).is_ok());
assert!(check_server(&json!(null), false).is_ok());
}
#[test]
fn redirects_never_come_nearer() {
let u = |s| url_parts::split(s).unwrap();
assert!(redirect_allowed(&u("https://sub.example.com/x"), &u("https://cdn.example.com/y")).is_ok());
assert!(redirect_allowed(&u("https://sub.example.com/x"), &u("http://cdn.example.com/y")).is_err());
assert!(redirect_allowed(&u("https://sub.example.com/x"), &u("http://127.0.0.1/y")).is_err());
assert!(redirect_allowed(&u("http://192.168.1.1/x"), &u("ftp://192.168.1.1/y")).is_err());
assert_eq!(u("https://user@[::1]:8443/p").hostname.as_deref(), Some("::1"));
}
#[test]
fn base64_and_plain_bodies_decode() {
let links = "vless://u@a.example:443?security=tls#A\nhy2://p@b.example:443#B\n";
assert_eq!(decode_subscription(links.as_bytes()).len(), 2);
let b64 = base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE, links);
let wrapped: String = b64.as_bytes().chunks(20).map(|c| String::from_utf8_lossy(c) + "\n").collect();
assert_eq!(decode_subscription(wrapped.as_bytes()), ["vless://u@a.example:443?security=tls#A", "hy2://p@b.example:443#B"]);
}
#[test]
fn tags_follow_remarks() {
assert_eq!(slugify_tag("🇩🇪 Germany | Frankfurt"), "Germany-Frankfurt");
assert_eq!(slugify_tag("Нидерланды 1"), "Нидерланды-1");
assert_eq!(slugify_tag("!!!"), "proxy");
assert_eq!(make_tag("sub", "", 3), "sub-3");
assert_eq!(make_tag("sub", "Fast%20One", 3), "sub-Fast-One");
}
#[test]
fn a_walk_skips_bad_entries_and_numbers_duplicates() {
let lines: Vec<String> = [
"hy2://p@a.example.com:443#Same",
"hy2://p@b.example.com:443#Same",
"hy2://p@127.0.0.1:443#Loop",
"vless://u@c.example.com:70000#Bad",
"garbage",
"hy2://p@d.example.com:443?insecure=1#Insecure",
]
.map(String::from)
.to_vec();
let parsed = parse_subscription(&lines, "s", LinkBackend::SingBox, Options::default());
let tags: Vec<&str> = parsed.links.iter().map(|(t, _)| t.as_str()).collect();
assert_eq!(tags, ["s-Same", "s-Same-2"]);
assert_eq!(parsed.warnings.len(), 3, "{:?}", parsed.warnings);
assert!(parsed.warnings[0].contains("is this host"));
assert!(parsed.warnings[1].contains("out of range"));
assert!(parsed.warnings[2].contains("certificate checks off"));
}
#[test]
fn hybrid_hands_xray_only_links_to_xray() {
let lines = vec![
"vless://u@a.example.com:443?security=tls&type=xhttp&path=%2Fx#X".to_owned(),
"hy2://p@b.example.com:443#H".to_owned(),
];
let parsed = parse_hybrid_subscription(&lines, "s", Options::default());
assert_eq!(parsed.outbounds[0].0, LinkBackend::Xray);
assert_eq!(parsed.outbounds[1].0, LinkBackend::SingBox);
}
#[test]
fn xhttp_download_servers_are_checked_too() {
let extra = py::unquote("%7B%22downloadSettings%22%3A%7B%22address%22%3A%22127.0.0.1%22%7D%7D");
let line = format!(
"vless://u@a.example.com:443?security=tls&type=xhttp&extra={}#X",
percent_encoding::utf8_percent_encode(&extra, percent_encoding::NON_ALPHANUMERIC)
);
let parsed = parse_subscription(&[line], "s", LinkBackend::Xray, Options::default());
assert!(parsed.outbounds.is_empty());
assert!(parsed.warnings[0].contains("is this host"));
}
}
+436
View File
@@ -0,0 +1,436 @@
//! Upstream's `scripts/test-build-outbound.py`, case for case.
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use serde_json::{Value, json};
use super::*;
fn sing(url: &str) -> Value {
build_outbound(url, "test-outbound", LinkBackend::SingBox).unwrap_or_else(|e| panic!("{url}: {e}"))
}
fn xray(url: &str) -> Value {
build_outbound(url, "test-outbound", LinkBackend::Xray).unwrap_or_else(|e| panic!("{url}: {e}"))
}
fn err(url: &str, backend: LinkBackend) -> String {
match build_outbound(url, "test-outbound", backend) {
Ok(ob) => panic!("{url} ({}) parsed: {ob}", backend.as_str()),
Err(e) => e.to_string(),
}
}
fn vmess_url(extra: Value) -> String {
let mut body = json!({ "add": "example.com", "port": 443, "id": "uuid", "net": "tcp" });
for (k, v) in extra.as_object().unwrap() {
body[k] = v.clone();
}
format!("vmess://{}", STANDARD.encode(body.to_string()))
}
const PBK: &str = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc";
#[test]
fn vless_reality() {
let ob = sing(&format!(
"vless://uuid@example.com:443?security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com&sid=abcd"
));
assert_eq!(ob["type"], "vless");
assert_eq!(ob["server"], "example.com");
assert_eq!(ob["tls"]["reality"]["public_key"], PBK);
}
#[test]
fn vless_reality_germany_main_shape() {
let url = format!(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=qq&sni=last.fm&sid=8a54\
&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
);
let ob = sing(&url);
assert_eq!(ob["server_port"], 443);
assert_eq!(ob["flow"], "xtls-rprx-vision");
assert_eq!(ob["tls"]["server_name"], "last.fm");
assert_eq!(ob["tls"]["utls"]["fingerprint"], "qq");
assert_eq!(ob["tls"]["reality"]["short_id"], "8a54");
assert!(ob["tls"]["reality"].get("spider_x").is_none());
assert!(ob.get("transport").is_none());
let ob = xray(&url);
assert_eq!(ob["protocol"], "vless");
assert_eq!(ob["settings"]["address"], "example.com");
assert_eq!(ob["settings"]["flow"], "xtls-rprx-vision");
assert_eq!(ob["streamSettings"]["network"], "raw");
assert_eq!(ob["streamSettings"]["sockopt"]["domainStrategy"], "UseIP");
assert_eq!(ob["streamSettings"]["realitySettings"]["serverName"], "last.fm");
assert_eq!(ob["streamSettings"]["realitySettings"]["fingerprint"], "qq");
assert_eq!(ob["streamSettings"]["realitySettings"]["spiderX"], "/-/en/gp/bestsellers");
}
#[test]
fn vless_raw_transport_is_tcp() {
let ob = sing(&format!("vless://uuid@example.com:443?type=raw&security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com"));
assert!(ob.get("transport").is_none());
}
#[test]
fn at_sign_in_query_does_not_eat_the_host() {
let ob = sing(&format!(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com&Telegram=@somechannel,@somechannel"
));
assert_eq!(ob["server"], "example.com");
assert_eq!(ob["server_port"], 443);
}
#[test]
fn trailing_path_is_not_part_of_the_port() {
let ob = sing(&format!("vless://uuid@example.com:23576/?type=tcp&security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com"));
assert_eq!(ob["server_port"], 23576);
}
#[test]
fn port_out_of_range_is_rejected() {
for url in ["vless://uuid@example.com:70000?type=tcp", "trojan://pw@example.com:0", "ss://YWVzLTI1Ni1nY206cHc@example.com:99999"] {
assert!(err(url, LinkBackend::SingBox).contains("out of range"), "{url}");
}
}
#[test]
fn reality_empty_fingerprint_falls_back_to_chrome() {
let ob = sing(&format!("vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=&sni=cdn.example.com"));
assert_eq!(ob["tls"]["utls"]["fingerprint"], "chrome");
}
#[test]
fn xray_only_fingerprint_rejected_for_sing_box() {
let url = format!("vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=hellochrome_120&sni=cdn.example.com");
err(&url, LinkBackend::SingBox);
assert_eq!(xray(&url)["streamSettings"]["realitySettings"]["fingerprint"], "hellochrome_120");
for fp in ["unsafe", "hellogolang", "bogus"] {
assert!(err(&url.replace("hellochrome_120", fp), LinkBackend::Xray).contains("XRay would refuse"), "{fp}");
}
}
#[test]
fn values_a_backend_refuses_to_start_on_are_rejected() {
let reality = format!("vless://uuid@example.com:443?security=reality&sni=a.example.com&pbk={PBK}&sid=ab");
let tuic = "tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443";
let k16 = STANDARD.encode(b"k".repeat(16));
let k32 = STANDARD.encode(b"k".repeat(32));
let cases: Vec<(String, &str, &str)> = vec![
(format!("{reality}&flow=xtls-rprx-direct"), "both", "flow"),
(format!("{reality}&flow=xtls-rprx-vision-udp443"), "sing-box", "flow"),
(reality.replace("pbk=SbVK", "pbk=SbV+"), "both", "pbk"),
(reality.replace(&format!("pbk={PBK}"), "pbk=pubkey"), "both", "pbk"),
(reality.replace("sid=ab", "sid=abc"), "both", "sid"),
(reality.replace("sid=ab", "sid=0123456789abcdef00"), "both", "sid"),
(reality.replace("sid=ab", "sid=zz"), "both", "sid"),
(format!("{reality}&spx=nopath"), "xray", "spx"),
(format!("{reality}&spx=%2F%25zz"), "xray", "spx"),
(format!("{reality}&spx=%2Fa%01b"), "xray", "spx"),
(reality.replace("uuid@", &format!("{}@", "x".repeat(31))), "xray", "VLESS id"),
("vless://uuid@example.com:443?type=xhttp&security=tls&mode=bogus".into(), "xray", "xhttp mode"),
("vless://uuid@example.com:443?type=h2&security=tls".into(), "xray", "transport"),
("vless://uuid@example.com:443?type=quic&security=tls".into(), "xray", "transport"),
("trojan://pw@example.com:443?security=tls&fp=bogus".into(), "both", "fingerprint"),
(vmess_url(json!({ "scy": "aes-128-ctr" })), "sing-box", "VMess security"),
(vmess_url(json!({ "scy": "bogus" })), "sing-box", "VMess security"),
(vmess_url(json!({ "id": 123 })), "both", "VMess id"),
(vmess_url(json!({ "id": null })), "xray", "VMess id"),
(format!("{tuic}?congestion_control=reno"), "sing-box", "congestion_control"),
("tuic://not-a-uuid:pw@example.com:443".into(), "sing-box", "TUIC uuid"),
("hy2://pw@example.com:443?mport=a-b".into(), "both", "mport"),
("hy2://pw@example.com:443?mport=1-70000".into(), "both", "mport"),
("hy2://pw@example.com:443?mport=0-5".into(), "both", "mport"),
("hy2://pw@example.com:443?mport=30000-20000".into(), "both", "mport"),
("hy2://pw@example.com:443?insecure=1&pinSHA256=abcd".into(), "xray", "pinSHA256"),
("trojan://@example.com:443?security=tls".into(), "both", "password is empty"),
("hy2://pw@example.com:443?obfs=salamander".into(), "both", "obfs-password"),
("ss://plain:pw@example.com:8388".into(), "both", "method"),
("ss://aes-128-ctr:pw@example.com:8388".into(), "xray", "method"),
("ss://chacha20-poly1305:pw@example.com:8388".into(), "sing-box", "method"),
("ss://2022-blake3-aes-128-gcm:pw@example.com:8388".into(), "both", "base64 key"),
(format!("ss://2022-blake3-aes-128-gcm:{k32}@example.com:8388"), "both", "base64 key"),
(format!("ss://2022-blake3-chacha20-poly1305:{k16}%3A{k16}@example.com:8388"), "both", "single key"),
];
for (url, backends, message) in cases {
let list: &[LinkBackend] = match backends {
"both" => &[LinkBackend::SingBox, LinkBackend::Xray],
"sing-box" => &[LinkBackend::SingBox],
_ => &[LinkBackend::Xray],
};
for &backend in list {
let e = err(&url, backend);
assert!(e.contains(message), "{url} ({}): {e:?} lacks {message:?}", backend.as_str());
}
}
}
#[test]
fn values_one_backend_takes_still_parse() {
let reality = format!("vless://uuid@example.com:443?security=reality&sni=a.example.com&pbk={PBK}&sid=0123456789ABCDEF");
assert_eq!(xray(&format!("{reality}&flow=xtls-rprx-vision-udp443"))["settings"]["flow"], "xtls-rprx-vision-udp443");
assert_eq!(sing(&reality)["tls"]["reality"]["short_id"], "0123456789ABCDEF");
assert_eq!(xray(&vmess_url(json!({ "scy": "aes-128-ctr" })))["settings"]["security"], "aes-128-ctr");
assert_eq!(sing(&vmess_url(json!({ "scy": "aes-128-cfb" })))["security"], "aes-128-cfb");
// XRay takes a space (and non-ASCII) in spiderX; only control characters and bad escapes kill it.
let spx = xray(&format!("{reality}&spx=%2Fa%20b%C3%A9"));
assert_eq!(spx["streamSettings"]["realitySettings"]["spiderX"], "/a b\u{e9}");
assert_eq!(xray("ss://chacha20-poly1305:pw@example.com:8388")["settings"]["method"], "chacha20-poly1305");
assert_eq!(sing("ss://aes-128-ctr:pw@example.com:8388")["method"], "aes-128-ctr");
let k16 = STANDARD.encode(b"k".repeat(16));
let ss2022 = sing(&format!("ss://2022-blake3-aes-128-gcm:{k16}%3A{k16}@example.com:8388"));
assert_eq!(ss2022["password"], format!("{k16}:{k16}"));
}
#[test]
fn hysteria2_port_hopping_takes_lone_ports() {
let ob = sing("hy2://pw@example.com:443?mport=443, 20000-30000");
assert_eq!(ob["server_ports"], json!(["443:443", "20000:30000"]));
let remote = xray("hy2://pw@example.com:443?mport=443,20000-30000");
assert_eq!(remote["streamSettings"]["finalmask"]["udp"][0]["settings"]["remotePorts"], "443-443,20000-30000");
}
#[test]
fn hysteria2_pin_replaces_insecure_for_xray() {
let pin = vec!["AB"; 32].join(":");
let url = format!("hy2://pw@example.com:443?sni=a.example.com&insecure=1&pinSHA256={pin}");
let ob = xray(&url);
assert_eq!(ob["streamSettings"]["tlsSettings"]["pinnedPeerCertSha256"], "ab".repeat(32));
// sing-box pins only a public key: the link stays insecure there.
assert_eq!(sing(&url)["tls"]["insecure"], true);
}
#[test]
fn reality_without_pbk_is_rejected_clearly() {
assert!(err("vless://uuid@example.com:443?security=reality&type=tcp", LinkBackend::SingBox).contains("pbk"));
}
#[test]
fn vless_httpupgrade_and_quic_transports() {
let ob = sing("vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade");
assert_eq!(ob["transport"], json!({ "type": "httpupgrade", "host": "cdn.example.com", "path": "/upgrade" }));
let ob = sing("vless://uuid@example.com:443?type=quic&security=tls&sni=cdn.example.com");
assert_eq!(ob["transport"]["type"], "quic");
}
#[test]
fn vless_xhttp_fails_loudly_on_sing_box() {
assert!(
err("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com", LinkBackend::SingBox)
.contains("unsupported VLESS transport 'xhttp'")
);
}
#[test]
fn xray_vless_xhttp() {
let ob = xray("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx");
assert_eq!(ob["settings"]["id"], "uuid");
assert_eq!(ob["streamSettings"]["network"], "xhttp");
assert_eq!(ob["streamSettings"]["xhttpSettings"]["path"], "/x");
}
fn quote(s: &str) -> String {
percent_encoding::utf8_percent_encode(s, percent_encoding::NON_ALPHANUMERIC).to_string()
}
#[test]
fn xray_xhttp_extra_keeps_ordinary_settings() {
let extra = json!({ "xPaddingBytes": "100-1000", "downloadSettings": { "address": "dl.example.com" } });
let ob = xray(&format!(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}",
quote(&extra.to_string())
));
assert_eq!(ob["streamSettings"]["xhttpSettings"]["extra"]["xPaddingBytes"], "100-1000");
}
#[test]
fn xray_xhttp_extra_cannot_name_local_files() {
let extra = json!({ "downloadSettings": { "tlsSettings": { "masterKeyLog": "/etc/x", "certificates": [{ "keyFile": "/root/k" }] } } });
let e = err(
&format!("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}", quote(&extra.to_string())),
LinkBackend::Xray,
);
assert!(e.contains("keyfile, masterkeylog"), "{e}");
}
#[test]
fn xray_xhttp_extra_cannot_set_socket_options() {
let cases = [
(
json!({ "downloadSettings": { "address": "dl.example.com", "sockopt": { "mark": 0, "tcpFastOpen": true } } }),
json!({ "downloadSettings": { "address": "dl.example.com", "sockopt": { "tcpFastOpen": true } } }),
),
(json!({ "downloadSettings": { "sockopt": { "customSockopt": [], "TProxy": "redirect" } } }), json!({ "downloadSettings": { "sockopt": {} } })),
(json!({ "downloadSettings": { "sockopt": { "dialerProxy": "direct", "interface": "eth0" } } }), json!({ "downloadSettings": { "sockopt": {} } })),
(json!({ "Mark": 1, "xPaddingBytes": "100-1000" }), json!({ "xPaddingBytes": "100-1000" })),
// The Kelvin sign, which Go folds to k as Python's lower() does.
(json!({ "downloadSettings": { "sockopt": { "mar\u{212a}": 0 } } }), json!({ "downloadSettings": { "sockopt": {} } })),
];
for (extra, left) in cases {
let ob = xray(&format!(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}",
quote(&extra.to_string())
));
assert_eq!(ob["streamSettings"]["xhttpSettings"]["extra"], left, "{extra}");
}
// Go's JSON decoding folds U+017F to s: a non-ASCII key is refused outright.
let extra = json!({ "downloadSettings": { "tlsSettings": { "ma\u{17f}terKeyLog": "/etc/x" } } });
let e = err(
&format!("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}", quote(&extra.to_string())),
LinkBackend::Xray,
);
assert!(e.contains("names local files"), "{e}");
}
#[test]
fn xray_vless_ech() {
let ob = xray("vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1");
assert_eq!(ob["streamSettings"]["tlsSettings"]["echConfigList"], "udp://1.1.1.1");
assert!(
err("vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=blob", LinkBackend::SingBox)
.contains("unsupported VLESS parameter 'ech'")
);
}
#[test]
fn xray_socks_and_shadowsocks_use_flat_settings() {
let ob = xray("socks5://user:pass@example.com:1080");
assert_eq!(ob["protocol"], "socks");
assert_eq!(ob["settings"]["address"], "example.com");
assert_eq!(ob["settings"]["user"], "user");
assert!(ob["settings"].get("servers").is_none());
let creds = URL_SAFE_NO_PAD.encode("chacha20-ietf-poly1305:passw0rd");
let ob = xray(&format!("ss://{creds}@ss.example.com:8388"));
assert_eq!(ob["protocol"], "shadowsocks");
assert_eq!(ob["settings"]["method"], "chacha20-ietf-poly1305");
}
#[test]
fn vmess_forms() {
let payload = json!({
"add": "vmess.example.com", "port": "443", "id": "00000000-0000-0000-0000-000000000000", "aid": "0",
"scy": "auto", "net": "ws", "host": "cdn.example.com", "path": "/ws", "tls": "tls", "sni": "cdn.example.com",
});
let ob = sing(&format!("vmess://{}", STANDARD.encode(payload.to_string())));
assert_eq!(ob["transport"]["type"], "ws");
assert_eq!(ob["tls"]["server_name"], "cdn.example.com");
let payload = json!({ "add": "vmess.example.com", "port": "443", "id": "00000000-0000-0000-0000-000000000000", "aid": "0", "scy": "auto" });
let ob = sing(&format!("vmess://{}#Subscription Remark", URL_SAFE_NO_PAD.encode(payload.to_string())));
assert_eq!(ob["server"], "vmess.example.com");
let payload = json!({ "add": "vmess.example.com", "port": 443, "id": "u", "aid": "", "scy": "" });
let ob = sing(&format!("vmess://{}", STANDARD.encode(payload.to_string())));
assert_eq!((ob["alter_id"].clone(), ob["security"].clone()), (json!(0), json!("auto")));
let as_list = sing(&vmess_url(json!({ "tls": "tls", "alpn": ["h2", "http/1.1"] })));
let as_text = sing(&vmess_url(json!({ "tls": "tls", "alpn": "h2, http/1.1" })));
assert_eq!(as_list["tls"]["alpn"], json!(["h2", "http/1.1"]));
assert_eq!(as_text["tls"]["alpn"], json!(["h2", "http/1.1"]));
assert!(err(&vmess_url(json!({ "net": "kcp" })), LinkBackend::SingBox).contains("unsupported VMess transport 'kcp'"));
}
#[test]
fn socks4_keeps_its_bare_userid() {
let ob = sing("socks4://me@10.0.0.1:1080");
assert_eq!((ob["version"].clone(), ob["username"].clone()), (json!("4"), json!("me")));
assert!(ob.get("password").is_none());
}
#[test]
fn blank_parameters_fall_back_to_the_server() {
let ob = sing("vless://uuid@example.com:443?security=tls&sni=&type=ws&host=&path=");
assert_eq!(ob["tls"]["server_name"], "example.com");
assert_eq!(ob["transport"]["headers"]["Host"], "example.com");
assert_eq!(ob["transport"]["path"], "/");
let tuic = sing("tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443?alpn=&congestion_control=&udp_relay_mode=");
assert_eq!(tuic["tls"]["alpn"], json!(["h3"]));
assert_eq!((tuic["congestion_control"].clone(), tuic["udp_relay_mode"].clone()), (json!("bbr"), json!("native")));
}
#[test]
fn trojan_shadowsocks_and_friends() {
let ob = sing("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome");
assert_eq!(ob["password"], "secret");
assert_eq!(ob["tls"]["server_name"], "tls.example.com");
let creds = URL_SAFE_NO_PAD.encode("chacha20-ietf-poly1305:passw0rd");
assert_eq!(sing(&format!("ss://{creds}@ss.example.com:8388"))["method"], "chacha20-ietf-poly1305");
let legacy = URL_SAFE_NO_PAD.encode("chacha20-ietf-poly1305:passw0rd@legacy.example.com:8388");
let ob = sing(&format!("ss://{legacy}#Legacy Server"));
assert_eq!((ob["server"].clone(), ob["server_port"].clone()), (json!("legacy.example.com"), json!(8388)));
assert_eq!(ob["password"], "passw0rd");
let ob = sing("ss://none:plain%20pass@plain.example.com:8388");
assert_eq!((ob["method"].clone(), ob["password"].clone()), (json!("none"), json!("plain pass")));
let legacy = URL_SAFE_NO_PAD.encode("none:pass@[2001:db8::1]:8388");
assert_eq!(sing(&format!("ss://{legacy}#Legacy IPv6"))["server"], "2001:db8::1");
}
#[test]
fn hysteria2_both_backends() {
let ob = sing("hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask");
assert_eq!(ob["tls"]["insecure"], true);
assert_eq!(ob["obfs"]["password"], "mask");
let ob = xray("hy2://secret@example.com:443?sni=hy.example.com&obfs=salamander&obfs-password=mask");
assert_eq!(ob["protocol"], "hysteria");
assert!(ob["settings"].get("password").is_none());
assert_eq!(ob["streamSettings"]["network"], "hysteria");
assert_eq!(ob["streamSettings"]["tlsSettings"]["serverName"], "hy.example.com");
assert_eq!(ob["streamSettings"]["hysteriaSettings"]["auth"], "secret");
assert_eq!(ob["streamSettings"]["finalmask"]["udp"], json!([{ "type": "salamander", "settings": { "password": "mask" } }]));
assert!(err("hy2://secret@example.com:443?sni=hy.example.com&insecure=1", LinkBackend::Xray).contains("allowInsecure"));
}
#[test]
fn tuic_anytls_naive_and_plain_proxies() {
let ob = sing("tuic://00000000-0000-0000-0000-000000000000:secret@example.com:443?sni=tuic.example.com&alpn=h3,hq-29");
assert_eq!(ob["tls"]["alpn"], json!(["h3", "hq-29"]));
let ob = sing("anytls://p%40ss@example.com:443?sni=a.example.com&insecure=1&fp=chrome#name");
assert_eq!(ob["password"], "p@ss");
assert_eq!(
ob["tls"],
json!({ "enabled": true, "server_name": "a.example.com", "insecure": true, "utls": { "enabled": true, "fingerprint": "chrome" } })
);
assert!(err("anytls://pw@example.com:443", LinkBackend::Xray).contains("unsupported XRay outbound type"));
let ob = sing("naive+https://user:pass@example.com:443#name");
assert_eq!((ob["type"].clone(), ob["username"].clone(), ob["password"].clone()), (json!("naive"), json!("user"), json!("pass")));
assert!(ob.get("quic").is_none());
assert_eq!(sing("naive+quic://user:pass@example.com:443")["quic"], true);
let ob = sing("socks5://user:p@ss@example.com:1080");
assert_eq!((ob["username"].clone(), ob["password"].clone(), ob["server"].clone()), (json!("user"), json!("p@ss"), json!("example.com")));
let ob = sing("https://proxy.example.com:8443");
assert_eq!(ob["type"], "http");
assert_eq!(ob["tls"]["server_name"], "proxy.example.com");
}
#[test]
fn invalid_scheme_and_transports_fail_loudly() {
assert!(err("wireguard://example.com", LinkBackend::SingBox).contains("unsupported scheme"));
let url = "trojan://pw@example.com:443?security=tls&type=xhttp&path=/p";
assert!(err(url, LinkBackend::SingBox).contains("unsupported Trojan transport 'xhttp'"));
assert_eq!(xray(url)["streamSettings"]["network"], "xhttp");
}
#[test]
fn xray_only_fingerprint_for_trojan_and_vmess() {
let trojan = "trojan://pw@example.com:443?security=tls&fp=unsafe";
err(trojan, LinkBackend::SingBox);
assert_eq!(xray(trojan)["streamSettings"]["tlsSettings"]["fingerprint"], "unsafe");
let vmess = vmess_url(json!({ "tls": "tls", "fp": "unsafe" }));
err(&vmess, LinkBackend::SingBox);
assert_eq!(xray(&vmess)["streamSettings"]["tlsSettings"]["fingerprint"], "unsafe");
}
#[test]
fn local_file_keys_catch_what_upstream_does() {
let v = json!({ "a": { "certificatePath": 1, "path": "/", "x": [{ "torrc": 1, "logFile": 2 }] }, "ß": 0 });
assert_eq!(local_file_keys(&v), ["certificatepath", "logfile", "torrc", "ß"]);
}
+253
View File
@@ -0,0 +1,253 @@
//! A sing-box-shaped outbound in XRay's shape: upstream's `render_xray_outbound`.
use serde_json::{Map, Value, json};
use super::{LinkError, Result};
fn s<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {
map.get(key)
}
fn str_of<'a>(map: &'a Map<String, Value>, key: &str) -> &'a str {
map.get(key).and_then(Value::as_str).unwrap_or("")
}
fn truthy(v: Option<&Value>) -> bool {
match v {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
}
}
fn utls_fingerprint(tls: &Map<String, Value>) -> Option<Value> {
let utls = tls.get("utls")?.as_object()?;
(truthy(utls.get("enabled")) && truthy(utls.get("fingerprint"))).then(|| utls["fingerprint"].clone())
}
fn xray_tls(tls: Option<&Value>) -> Result<(&'static str, Map<String, Value>)> {
let Some(tls) = tls.and_then(Value::as_object).filter(|t| truthy(t.get("enabled"))) else {
return Ok(("none", Map::new()));
};
let mut out = Map::new();
if let Some(reality) = tls.get("reality").and_then(Value::as_object).filter(|r| truthy(r.get("enabled"))) {
let mut settings = Map::new();
settings.insert("serverName".into(), str_of(tls, "server_name").into());
settings.insert("publicKey".into(), reality.get("public_key").cloned().unwrap_or(Value::Null));
settings.insert("shortId".into(), str_of(reality, "short_id").into());
if truthy(reality.get("spider_x")) {
settings.insert("spiderX".into(), reality["spider_x"].clone());
}
if let Some(fp) = utls_fingerprint(tls) {
settings.insert("fingerprint".into(), fp);
}
out.insert("realitySettings".into(), Value::Object(settings));
return Ok(("reality", out));
}
let mut settings = Map::new();
settings.insert("serverName".into(), str_of(tls, "server_name").into());
if truthy(tls.get("alpn")) {
settings.insert("alpn".into(), tls["alpn"].clone());
}
if truthy(tls.get("insecure")) {
return Err(LinkError::invalid(
"XRay no longer supports tlsSettings.allowInsecure; remove insecure=1 or use a supported certificate verification option",
));
}
if truthy(tls.get("certificate_sha256")) {
settings.insert("pinnedPeerCertSha256".into(), tls["certificate_sha256"].clone());
}
if truthy(tls.get("ech_config_list")) {
settings.insert("echConfigList".into(), tls["ech_config_list"].clone());
}
if let Some(fp) = utls_fingerprint(tls) {
settings.insert("fingerprint".into(), fp);
}
out.insert("tlsSettings".into(), Value::Object(settings));
Ok(("tls", out))
}
fn xray_transport(transport: Option<&Value>) -> (String, Map<String, Value>) {
let Some(t) = transport.and_then(Value::as_object).filter(|t| !t.is_empty()) else {
return ("raw".into(), Map::new());
};
let kind = str_of(t, "type");
let mut out = Map::new();
let path = || t.get("path").cloned().unwrap_or_else(|| "/".into());
match kind {
"ws" => {
out.insert(
"wsSettings".into(),
json!({ "path": path(), "headers": t.get("headers").cloned().unwrap_or_else(|| json!({})) }),
);
}
"grpc" => {
out.insert("grpcSettings".into(), json!({ "serviceName": t.get("service_name").cloned().unwrap_or_else(|| "".into()) }));
}
"http" => {
out.insert(
"httpSettings".into(),
json!({ "host": t.get("host").cloned().unwrap_or_else(|| json!([])), "path": path() }),
);
}
"httpupgrade" => {
out.insert(
"httpupgradeSettings".into(),
json!({ "host": t.get("host").cloned().unwrap_or_else(|| "".into()), "path": path() }),
);
}
"quic" => {}
"xhttp" => {
let mut settings = Map::new();
settings.insert("path".into(), path());
if truthy(t.get("host")) {
settings.insert("host".into(), t["host"].clone());
}
if truthy(t.get("mode")) {
settings.insert("mode".into(), t["mode"].clone());
}
if let Some(extra) = t.get("extra").filter(|e| !e.is_null()) {
settings.insert("extra".into(), extra.clone());
}
out.insert("xhttpSettings".into(), Value::Object(settings));
}
_ => {}
}
(kind.to_owned(), out)
}
/// `{"protocol", "tag", "settings", "streamSettings"}` for XRay, from a sing-box-shaped
/// outbound as the parsers make them.
pub fn render_xray_outbound(ob: &Map<String, Value>) -> Result<Value> {
let typ = str_of(ob, "type");
let tag = s(ob, "tag").cloned().unwrap_or(Value::Null);
let server = || s(ob, "server").cloned().unwrap_or(Value::Null);
let port = || s(ob, "server_port").cloned().unwrap_or(Value::Null);
let stream_settings = || -> Result<Map<String, Value>> {
let (security, sec) = xray_tls(ob.get("tls"))?;
let (network, net) = xray_transport(ob.get("transport"));
let mut stream = Map::new();
stream.insert("network".into(), network.into());
stream.insert("security".into(), security.into());
stream.extend(sec);
stream.extend(net);
stream.insert("sockopt".into(), json!({ "domainStrategy": "UseIP" }));
Ok(stream)
};
let mut out = Map::new();
match typ {
"vless" => {
let mut settings = Map::new();
settings.insert("address".into(), server());
settings.insert("port".into(), port());
settings.insert("id".into(), ob.get("uuid").cloned().unwrap_or(Value::Null));
settings.insert("encryption".into(), "none".into());
if truthy(ob.get("flow")) {
settings.insert("flow".into(), ob["flow"].clone());
}
out.insert("protocol".into(), "vless".into());
out.insert("tag".into(), tag);
out.insert("settings".into(), Value::Object(settings));
out.insert("streamSettings".into(), Value::Object(stream_settings()?));
}
"vmess" => {
out.insert("protocol".into(), "vmess".into());
out.insert("tag".into(), tag);
out.insert(
"settings".into(),
json!({
"address": server(),
"port": port(),
"id": ob.get("uuid").cloned().unwrap_or(Value::Null),
"security": ob.get("security").cloned().unwrap_or_else(|| "auto".into()),
"alterId": ob.get("alter_id").cloned().unwrap_or_else(|| 0.into()),
}),
);
out.insert("streamSettings".into(), Value::Object(stream_settings()?));
}
"trojan" => {
out.insert("protocol".into(), "trojan".into());
out.insert("tag".into(), tag);
out.insert(
"settings".into(),
json!({ "address": server(), "port": port(), "password": ob.get("password").cloned().unwrap_or(Value::Null) }),
);
out.insert("streamSettings".into(), Value::Object(stream_settings()?));
}
"shadowsocks" => {
out.insert("protocol".into(), "shadowsocks".into());
out.insert("tag".into(), tag);
out.insert(
"settings".into(),
json!({
"address": server(),
"port": port(),
"method": ob.get("method").cloned().unwrap_or(Value::Null),
"password": ob.get("password").cloned().unwrap_or(Value::Null),
}),
);
}
"hysteria2" => {
let mut stream = stream_settings()?;
stream.insert("network".into(), "hysteria".into());
stream.insert("security".into(), "tls".into());
let mut hysteria = Map::new();
hysteria.insert("version".into(), 2.into());
if truthy(ob.get("password")) {
hysteria.insert("auth".into(), ob["password"].clone());
}
stream.insert("hysteriaSettings".into(), Value::Object(hysteria));
let mut udp_masks = Vec::new();
// XRay wants udphop outermost, ahead of any other UDP mask.
if let Some(ports) = ob.get("server_ports").and_then(Value::as_array).filter(|p| !p.is_empty()) {
let remote: Vec<String> =
ports.iter().filter_map(Value::as_str).map(|r| r.replace(':', "-")).collect();
udp_masks.push(json!({
"type": "udphop",
"settings": { "mode": "intervalRemote", "interval": "20-40", "remotePorts": remote.join(",") },
}));
}
if let Some(obfs) = ob.get("obfs").and_then(Value::as_object)
&& str_of(obfs, "type") == "salamander" {
udp_masks.push(json!({
"type": "salamander",
"settings": { "password": obfs.get("password").cloned().unwrap_or_else(|| "".into()) },
}));
}
if !udp_masks.is_empty() {
stream.insert("finalmask".into(), json!({ "udp": udp_masks }));
}
out.insert("protocol".into(), "hysteria".into());
out.insert("tag".into(), tag);
out.insert("settings".into(), json!({ "version": 2, "address": server(), "port": port() }));
out.insert("streamSettings".into(), Value::Object(stream));
}
"socks" | "http" => {
let mut settings = Map::new();
settings.insert("address".into(), server());
settings.insert("port".into(), port());
if truthy(ob.get("username")) {
settings.insert("user".into(), ob["username"].clone());
settings.insert("pass".into(), ob.get("password").cloned().unwrap_or_else(|| "".into()));
}
out.insert("protocol".into(), typ.into());
out.insert("tag".into(), tag);
out.insert("settings".into(), Value::Object(settings));
if typ == "http" && truthy(ob.get("tls")) {
let (security, sec) = xray_tls(ob.get("tls"))?;
let mut stream = Map::new();
stream.insert("security".into(), security.into());
stream.extend(sec);
out.insert("streamSettings".into(), Value::Object(stream));
}
}
_ => return Err(LinkError::invalid(format!("unsupported XRay outbound type '{typ}'"))),
}
Ok(Value::Object(out))
}
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Parity check: upstream's link parsers (scripts/proxy_parsing.py) against ps-core's.
Feeds the same links to both and reports every link where one accepts and the other
refuses, or both accept with different outbounds. Run from windows/:
python3 -I tools/parity/links.py
"""
import base64
import json
import random
import re
import subprocess
import sys
import urllib.parse
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "scripts"))
from proxy_parsing import build_outbound # noqa: E402
PBK = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"
def corpus():
links = set()
# Every link literal in upstream's tests.
for name in ("test-build-outbound.py", "test-fetch-subscription.py"):
text = (ROOT / "scripts" / name).read_text()
links.update(re.findall(r'"((?:vless|vmess|trojan|ss|hy2|hysteria2|tuic|anytls|naive\+https|naive\+quic|socks[45]h?a?|https?)://[^"]*)"', text))
# VMess bodies, which the tests build in code.
for extra in (
{}, {"net": "ws", "path": "/ws", "host": "cdn.example.com", "tls": "tls"}, {"scy": ""}, {"aid": "7"},
{"aid": 70000}, {"net": "grpc", "path": "/svc"}, {"net": "http", "tls": "tls", "alpn": "h2,http/1.1"},
{"port": "0"}, {"port": 443.5}, {"add": "[2001:db8::1]"}, {"fp": "firefox", "tls": "tls"}, {"id": 5},
{"scy": "zero"}, {"net": "kcp"}, {"tls": "reality", "sni": "a.example.com"},
):
body = {"add": "example.com", "port": 443, "id": "00000000-0000-0000-0000-000000000000", "net": "tcp", **extra}
raw = json.dumps(body).encode()
links.add("vmess://" + base64.b64encode(raw).decode())
links.add("vmess://" + base64.urlsafe_b64encode(raw).decode().rstrip("=") + "#Remark")
# Shadowsocks in its three shapes.
for method, pw in (("aes-256-gcm", "pw"), ("chacha20-ietf-poly1305", "p@ss:w"), ("2022-blake3-aes-128-gcm", base64.b64encode(b"k" * 16).decode()), ("none", "")):
cred = f"{method}:{pw}".encode()
links.add(f"ss://{base64.urlsafe_b64encode(cred).decode().rstrip('=')}@ss.example.com:8388#n")
links.add(f"ss://{urllib.parse.quote(method)}:{urllib.parse.quote(pw)}@ss.example.com:8388")
links.add(f"ss://{base64.urlsafe_b64encode(cred + b'@[2001:db8::1]:8388').decode().rstrip('=')}#legacy")
# Mutations of a few rich links: drop, blank or duplicate parameters, change case.
rng = random.Random(1)
seeds = [
f"vless://uuid@example.com:443?type=ws&security=tls&sni=a.example.com&host=h.example.com&path=%2Fp&fp=chrome&alpn=h2,http/1.1&flow=xtls-rprx-vision",
f"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&sid=ab12&fp=qq&sni=last.fm&spx=%2Fx",
"vless://uuid@example.com:443?type=xhttp&security=tls&mode=packet-up&host=h.example.com&path=%2Fx&x_padding_bytes=100-1000",
"trojan://p%40ss@example.com:443?type=grpc&serviceName=svc&sni=s.example.com&fp=firefox",
"hy2://pw@example.com:443?sni=s.example.com&obfs=salamander&obfs-password=m&mport=20000-30000&insecure=0",
"tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443?sni=s.example.com&alpn=h3&congestion_control=cubic&udp_relay_mode=quic",
"anytls://pw@example.com:443?peer=p.example.com&allowInsecure=1&fp=edge",
"socks5://u%20x:p%3Aw@[2001:db8::2]:1080",
]
for seed in seeds:
links.add(seed)
base, _, query = seed.partition("?")
params = query.split("&") if query else []
for _ in range(60):
p = list(params)
op = rng.randrange(5)
if p and op == 0:
p.pop(rng.randrange(len(p)))
elif p and op == 1:
i = rng.randrange(len(p))
p[i] = p[i].split("=", 1)[0] + "="
elif p and op == 2:
p.append(rng.choice(p))
elif op == 3:
p.append(rng.choice(["type=h2", "type=quic", "type=httpupgrade", "security=none", "fp=random", "fp=unsafe", "ech=udp%3A%2F%2F1.1.1.1", "mode=bogus", "flow=", "sid=zz", "alpn=%5B%22h2%22%5D", "insecure=1", "pinSHA256=" + "ab" * 32]))
else:
base = base.upper() if rng.random() < 0.2 else base
links.add(base + ("?" + "&".join(p) if p else ""))
return sorted(links)
def main():
requests = [
{"url": url, "tag": "t", "backend": backend}
for url in corpus()
for backend in ("sing-box", "xray")
]
rust = subprocess.run(
["cargo", "run", "-q", "-p", "ps-core", "--example", "links_json"],
input="\n".join(json.dumps(r) for r in requests) + "\n",
capture_output=True, text=True, check=True, cwd=ROOT / "windows",
).stdout.splitlines()
mismatches = 0
for req, line in zip(requests, rust):
got = json.loads(line)
try:
want = {"ok": build_outbound(req["url"], req["tag"], backend=req["backend"])}
except Exception as exc: # noqa: BLE001 - every refusal counts
want = {"error": str(exc)}
if ("ok" in got) != ("ok" in want) or ("ok" in got and got["ok"] != want["ok"]):
mismatches += 1
print(f"MISMATCH {req['backend']} {req['url']}\n python: {json.dumps(want)[:300]}\n rust: {json.dumps(got)[:300]}")
accepted = sum("ok" in json.loads(line) for line in rust)
print(f"{len(requests)} cases ({accepted} accepted, {len(requests) - accepted} refused), {mismatches} mismatches")
sys.exit(1 if mismatches else 0)
if __name__ == "__main__":
main()