-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
217 lines (179 loc) · 7.45 KB
/
parser.py
File metadata and controls
217 lines (179 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""
parser.py
Parse vless / vmess / trojan / ss URLs into normalized dicts,
then build Xray-compatible outbound objects.
"""
import base64
import json
from urllib.parse import urlparse, parse_qs, unquote
# ── URL parser ────────────────────────────────────────────────────────────────
def parse_proxy_url(url: str) -> dict:
"""
Parse any of: vless, vmess, trojan, ss / shadowsocks
Returns a normalized dict:
protocol str — vless | vmess | trojan | ss
addr str — server hostname / IP
port int — server port
uuid str — user ID / password (vless / vmess / trojan)
method str — cipher method (ss only)
password str — password (ss only)
params dict[str] — transport / security query params
Raises ValueError on unsupported or malformed input.
"""
url = url.strip()
# Strip fragment (#emoji channel name, etc.)
if "#" in url:
url = url[: url.index("#")]
if "://" not in url:
raise ValueError("Not a valid proxy URL (missing '://')")
protocol = url.split("://")[0].lower()
# ── VMess (Base64-encoded JSON) ──────────────────────────────
if protocol == "vmess":
return _parse_vmess(url)
# ── Shadowsocks ───────────────────────────────────────────────
if protocol in ("ss", "shadowsocks"):
return _parse_ss(url)
# ── VLESS / Trojan (standard URI) ────────────────────────────
if protocol in ("vless", "trojan"):
return _parse_uri(url, protocol)
raise ValueError(f"Unsupported protocol: '{protocol}'")
def _parse_vmess(url: str) -> dict:
b64 = url[len("vmess://"):]
b64 += "=" * (-len(b64) % 4) # fix padding
try:
d = json.loads(base64.b64decode(b64).decode("utf-8"))
except Exception as ex:
raise ValueError(f"Invalid VMess base64: {ex}") from ex
return {
"protocol": "vmess",
"addr": d.get("add", ""),
"port": int(d.get("port", 443)),
"uuid": d.get("id", ""),
"params": {
"type": d.get("net", "tcp"),
"security": d.get("tls", ""),
"path": d.get("path", ""),
"host": d.get("host", ""),
"sni": d.get("sni", ""),
"aid": str(d.get("aid", "0")),
},
}
def _parse_ss(url: str) -> dict:
parsed = urlparse(url)
userinfo = parsed.username or ""
# userinfo may be base64(method:password) OR plain method:password
method = "aes-256-gcm"
password = ""
try:
decoded = base64.b64decode(
userinfo + "=" * (-len(userinfo) % 4)
).decode("utf-8")
if ":" in decoded:
method, password = decoded.split(":", 1)
else:
password = decoded
except Exception:
if ":" in userinfo:
method, password = userinfo.split(":", 1)
else:
password = userinfo
return {
"protocol": "ss",
"addr": parsed.hostname or "",
"port": parsed.port or 443,
"method": method,
"password": password,
"params": {},
}
def _parse_uri(url: str, protocol: str) -> dict:
parsed = urlparse(url)
query = parse_qs(parsed.query)
params = {k: unquote(v[0]) for k, v in query.items()}
return {
"protocol": protocol,
"addr": parsed.hostname or "",
"port": parsed.port or 443,
"uuid": unquote(parsed.username or ""),
"params": params,
}
# ── Outbound builder ──────────────────────────────────────────────────────────
def build_outbound(info: dict, dialer_tag: str) -> dict:
"""
Convert a parsed proxy dict (from parse_proxy_url) into an
Xray-compatible outbound object with dialerProxy set to dialer_tag.
"""
protocol = info["protocol"]
addr = info["addr"]
port = info["port"]
params = info.get("params", {})
outbound: dict = {
"tag": "proxy-chain",
"protocol": protocol,
"settings": {},
"streamSettings": {
"network": params.get("type", "tcp"),
"security": params.get("security", "none") or "none",
"sockopt": {"dialerProxy": dialer_tag},
},
}
# ── Protocol-level settings ───────────────────────────────────
if protocol == "vless":
outbound["settings"] = {
"vnext": [{"address": addr, "port": port, "users": [{
"id": info["uuid"],
"encryption": "none",
"flow": params.get("flow", ""),
}]}]
}
elif protocol == "vmess":
outbound["settings"] = {
"vnext": [{"address": addr, "port": port, "users": [{
"id": info["uuid"],
"alterId": int(params.get("aid", 0)),
"security": "auto",
}]}]
}
elif protocol == "trojan":
outbound["settings"] = {
"servers": [{"address": addr, "port": port, "password": info["uuid"]}]
}
elif protocol == "ss":
outbound["settings"] = {
"servers": [{"address": addr, "port": port,
"method": info["method"],
"password": info["password"]}]
}
# ── Security settings ─────────────────────────────────────────
sec = params.get("security", "").lower()
if sec == "tls":
outbound["streamSettings"]["tlsSettings"] = {
"serverName": params.get("sni", ""),
"allowInsecure": params.get("allowInsecure", "0") == "1",
"alpn": [a for a in params.get("alpn", "").split(",") if a],
"fingerprint": params.get("fp", ""),
}
elif sec == "reality":
outbound["streamSettings"]["realitySettings"] = {
"serverName": params.get("sni", ""),
"fingerprint": params.get("fp", "chrome"),
"publicKey": params.get("pbk", ""),
"shortId": params.get("sid", ""),
"spiderX": params.get("spx", "/"),
}
# ── Transport settings ────────────────────────────────────────
net = params.get("type", "tcp").lower()
if net == "ws":
outbound["streamSettings"]["wsSettings"] = {
"path": unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", "")},
}
elif net == "grpc":
outbound["streamSettings"]["grpcSettings"] = {
"serviceName": params.get("serviceName", params.get("path", "")),
}
elif net == "h2":
outbound["streamSettings"]["httpSettings"] = {
"host": [params.get("host", "")],
"path": params.get("path", "/"),
}
return outbound