outbound.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. // Package link provides parsers for VPN share links (vmess://, vless://, etc.)
  2. // and subscription bodies (typically base64-encoded newline lists of such links).
  3. // The output shape matches the wire format used by the panel's Xray template
  4. // outbounds array so that parsed objects can be injected directly.
  5. package link
  6. import (
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "maps"
  11. "math"
  12. "net/url"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. // Outbound is the minimal shape we emit for each parsed link.
  19. // Extra fields (mux, etc.) are carried inside settings/streamSettings.
  20. type Outbound map[string]any
  21. // ParseResult holds a parsed outbound together with a stable identity string
  22. // that can be used to correlate the same logical server across refreshes
  23. // (even if the remark changes).
  24. type ParseResult struct {
  25. Outbound Outbound
  26. Identity string
  27. }
  28. // ParseSubscriptionBody accepts the raw body returned by a subscription URL.
  29. // It handles the common case where the body is a base64-encoded blob of
  30. // newline-separated links, and also tolerates an already-decoded text body.
  31. // It returns the list of successfully parsed outbounds (in order) and their
  32. // corresponding identities.
  33. func ParseSubscriptionBody(body []byte) ([]Outbound, []string, error) {
  34. text := strings.TrimSpace(string(body))
  35. if text == "" {
  36. return nil, nil, nil
  37. }
  38. // Try base64 decode first (standard and URL-safe variants).
  39. if decoded, ok := tryBase64(text); ok {
  40. text = strings.TrimSpace(decoded)
  41. }
  42. lines := splitLines(text)
  43. var outbounds []Outbound
  44. var identities []string
  45. for _, ln := range lines {
  46. ln = strings.TrimSpace(ln)
  47. if ln == "" || strings.HasPrefix(ln, "#") {
  48. continue
  49. }
  50. res, err := ParseLink(ln)
  51. if err != nil || res == nil {
  52. // Ignore unparseable lines (comments, unsupported protocols, etc.)
  53. continue
  54. }
  55. outbounds = append(outbounds, res.Outbound)
  56. identities = append(identities, res.Identity)
  57. }
  58. return outbounds, identities, nil
  59. }
  60. func tryBase64(s string) (string, bool) {
  61. // Remove whitespace that some providers insert.
  62. clean := strings.Map(func(r rune) rune {
  63. if r == ' ' || r == '\n' || r == '\r' || r == '\t' {
  64. return -1
  65. }
  66. return r
  67. }, s)
  68. // Common padding fix
  69. for len(clean)%4 != 0 {
  70. clean += "="
  71. }
  72. // Standard
  73. if b, err := base64.StdEncoding.DecodeString(clean); err == nil {
  74. return string(b), true
  75. }
  76. // URL-safe (no padding)
  77. if b, err := base64.RawURLEncoding.DecodeString(clean); err == nil {
  78. return string(b), true
  79. }
  80. // URL-safe with padding
  81. if b, err := base64.URLEncoding.DecodeString(clean); err == nil {
  82. return string(b), true
  83. }
  84. return "", false
  85. }
  86. func splitLines(s string) []string {
  87. // Accept \n, \r\n, and also some providers use literal \n in the text.
  88. s = strings.ReplaceAll(s, `\n`, "\n")
  89. return strings.FieldsFunc(s, func(r rune) bool { return r == '\n' || r == '\r' })
  90. }
  91. // ParseLink parses a single share link and returns the outbound object plus
  92. // a stable identity for tag correlation. Supported schemes:
  93. // - vmess://
  94. // - vless://
  95. // - trojan://
  96. // - ss:// (modern and legacy)
  97. // - hysteria2:// (also hy2://)
  98. // - wireguard:// (also wg://)
  99. func ParseLink(link string) (*ParseResult, error) {
  100. link = strings.TrimSpace(link)
  101. switch {
  102. case strings.HasPrefix(link, "vmess://"):
  103. return parseVmess(link)
  104. case strings.HasPrefix(link, "vless://"):
  105. return parseVless(link)
  106. case strings.HasPrefix(link, "trojan://"):
  107. return parseTrojan(link)
  108. case strings.HasPrefix(link, "ss://"):
  109. return parseShadowsocks(link)
  110. case strings.HasPrefix(link, "hysteria2://"), strings.HasPrefix(link, "hy2://"):
  111. return parseHysteria2(link)
  112. case strings.HasPrefix(link, "wireguard://"), strings.HasPrefix(link, "wg://"):
  113. return parseWireguard(link)
  114. default:
  115. return nil, fmt.Errorf("unsupported link scheme")
  116. }
  117. }
  118. // --- vmess ---
  119. func parseVmess(link string) (*ParseResult, error) {
  120. b64 := strings.TrimPrefix(link, "vmess://")
  121. // vmess:// base64(json)
  122. raw, err := base64.StdEncoding.DecodeString(padBase64(b64))
  123. if err != nil {
  124. // Some providers use raw URL-safe
  125. raw, err = base64.RawURLEncoding.DecodeString(b64)
  126. }
  127. if err != nil {
  128. return nil, fmt.Errorf("vmess decode: %w", err)
  129. }
  130. var j map[string]any
  131. if err := json.Unmarshal(raw, &j); err != nil {
  132. return nil, fmt.Errorf("vmess json: %w", err)
  133. }
  134. identity := vmessIdentity(j)
  135. network := getString(j, "net", "tcp")
  136. security := "none"
  137. if tls, _ := j["tls"].(string); tls == "tls" {
  138. security = "tls"
  139. }
  140. stream := buildStream(network, security)
  141. // Map known fields (best effort, matching frontend parser coverage)
  142. switch network {
  143. case "ws":
  144. host, _ := j["host"].(string)
  145. setWS(stream, host, getString(j, "path", "/"))
  146. case "grpc":
  147. svc := getString(j, "path", "")
  148. if auth, ok := j["authority"].(string); ok && auth != "" {
  149. stream["grpcSettings"].(map[string]any)["authority"] = auth
  150. }
  151. stream["grpcSettings"].(map[string]any)["serviceName"] = svc
  152. stream["grpcSettings"].(map[string]any)["multiMode"] = getString(j, "type", "") == "multi"
  153. case "httpupgrade":
  154. setHTTPUpgrade(stream, getString(j, "host", ""), getString(j, "path", "/"))
  155. case "xhttp":
  156. xh := stream["xhttpSettings"].(map[string]any)
  157. xh["host"] = getString(j, "host", "")
  158. xh["path"] = getString(j, "path", "/")
  159. if m := getString(j, "mode", ""); m != "" {
  160. xh["mode"] = m
  161. }
  162. // xhttp advanced keys are passed through if present in the json
  163. for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs"} {
  164. if v, ok := j[k]; ok {
  165. xh[k] = v
  166. }
  167. }
  168. case "tcp":
  169. if getString(j, "type", "") == "http" {
  170. stream["tcpSettings"] = map[string]any{
  171. "header": map[string]any{
  172. "type": "http",
  173. "request": map[string]any{
  174. "version": "1.1",
  175. "method": "GET",
  176. "path": splitComma(getString(j, "path", "/")),
  177. "headers": map[string]any{"Host": splitComma(getString(j, "host", ""))},
  178. },
  179. },
  180. }
  181. }
  182. }
  183. if security == "tls" {
  184. tls := stream["tlsSettings"].(map[string]any)
  185. tls["serverName"] = getString(j, "sni", "")
  186. tls["fingerprint"] = getString(j, "fp", "")
  187. if alpn := getString(j, "alpn", ""); alpn != "" {
  188. tls["alpn"] = splitComma(alpn)
  189. }
  190. // The vmess object names the certificate checks v2rayN does the same way
  191. // the url-param protocols name them in applySecurity.
  192. tls["echConfigList"] = getString(j, "ech", "")
  193. tls["verifyPeerCertByName"] = getString(j, "vcn", "")
  194. tls["pinnedPeerCertSha256"] = getString(j, "pcs", "")
  195. }
  196. port := num(j["port"])
  197. scy := getString(j, "scy", "auto")
  198. if scy == "none" || scy == "zero" {
  199. scy = "auto"
  200. }
  201. ob := Outbound{
  202. "protocol": "vmess",
  203. "tag": getString(j, "ps", ""),
  204. "settings": map[string]any{
  205. "vnext": []any{
  206. map[string]any{
  207. "address": getString(j, "add", ""),
  208. "port": port,
  209. "users": []any{
  210. map[string]any{
  211. "id": getString(j, "id", ""),
  212. "security": scy,
  213. },
  214. },
  215. },
  216. },
  217. },
  218. "streamSettings": stream,
  219. }
  220. return &ParseResult{Outbound: ob, Identity: identity}, nil
  221. }
  222. func vmessIdentity(j map[string]any) string {
  223. // Remove ps (remark) for identity
  224. core := map[string]any{}
  225. for k, v := range j {
  226. if k == "ps" {
  227. continue
  228. }
  229. core[k] = v
  230. }
  231. b, _ := json.Marshal(core)
  232. return "vmess:" + string(b)
  233. }
  234. // --- vless / trojan (URL forms) ---
  235. func parseVless(link string) (*ParseResult, error) {
  236. u, err := url.Parse(link)
  237. if err != nil {
  238. return nil, err
  239. }
  240. if u.Scheme != "vless" {
  241. return nil, fmt.Errorf("not vless")
  242. }
  243. id := u.User.Username()
  244. host := u.Hostname()
  245. port := defaultPort(u.Port(), 443)
  246. params := u.Query()
  247. network := params.Get("type")
  248. if network == "" {
  249. network = "tcp"
  250. }
  251. security := params.Get("security")
  252. if security == "" {
  253. security = "none"
  254. }
  255. stream := buildStream(network, security)
  256. applyTransport(stream, params)
  257. applySecurity(stream, params)
  258. applyFinalMask(stream, params)
  259. identity := "vless:" + u.Scheme + "://" + id + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  260. ob := Outbound{
  261. "protocol": "vless",
  262. "tag": decodeHash(u.Fragment),
  263. "settings": map[string]any{
  264. "address": host,
  265. "port": port,
  266. "id": id,
  267. "flow": params.Get("flow"),
  268. "encryption": firstNonEmpty(params.Get("encryption"), "none"),
  269. },
  270. "streamSettings": stream,
  271. }
  272. return &ParseResult{Outbound: ob, Identity: identity}, nil
  273. }
  274. func parseTrojan(link string) (*ParseResult, error) {
  275. u, err := url.Parse(link)
  276. if err != nil {
  277. return nil, err
  278. }
  279. if u.Scheme != "trojan" {
  280. return nil, fmt.Errorf("not trojan")
  281. }
  282. pw := u.User.Username()
  283. host := u.Hostname()
  284. port := defaultPort(u.Port(), 443)
  285. params := u.Query()
  286. network := params.Get("type")
  287. if network == "" {
  288. network = "tcp"
  289. }
  290. security := params.Get("security")
  291. if security == "" {
  292. security = "tls"
  293. }
  294. stream := buildStream(network, security)
  295. applyTransport(stream, params)
  296. applySecurity(stream, params)
  297. applyFinalMask(stream, params)
  298. identity := "trojan:" + u.Scheme + "://" + pw + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  299. ob := Outbound{
  300. "protocol": "trojan",
  301. "tag": decodeHash(u.Fragment),
  302. "settings": map[string]any{
  303. "servers": []any{
  304. map[string]any{"address": host, "port": port, "password": pw},
  305. },
  306. },
  307. "streamSettings": stream,
  308. }
  309. return &ParseResult{Outbound: ob, Identity: identity}, nil
  310. }
  311. // --- shadowsocks ---
  312. func parseShadowsocks(link string) (*ParseResult, error) {
  313. // Two shapes:
  314. // ss://base64(method:pass)@host:port#remark
  315. // ss://base64(method:pass@host:port)#remark
  316. // Query may carry Xray-native stream params (type/security/sni/alpn/fp)
  317. // emitted by genShadowsocksLink — preserve them like trojan/vless.
  318. remark := ""
  319. if i := strings.Index(link, "#"); i >= 0 {
  320. remark, _ = url.QueryUnescape(link[i+1:])
  321. link = link[:i]
  322. }
  323. rawQuery := ""
  324. if i := strings.Index(link, "?"); i >= 0 {
  325. rawQuery = link[i+1:]
  326. link = link[:i]
  327. }
  328. params, _ := url.ParseQuery(rawQuery)
  329. core := strings.TrimPrefix(link, "ss://")
  330. at := strings.Index(core, "@")
  331. var host, method, pass string
  332. var port int
  333. if at >= 0 {
  334. // modern
  335. userB64 := core[:at]
  336. hp := strings.TrimRight(core[at+1:], "/")
  337. userInfo, err := base64DecodeFlexible(userB64)
  338. if err != nil {
  339. // SIP022 (2022-blake3-*) userinfo is percent-encoded, not base64.
  340. if dec, uerr := url.QueryUnescape(userB64); uerr == nil {
  341. userInfo = dec
  342. } else {
  343. userInfo = userB64 // not b64, rare
  344. }
  345. }
  346. colon := strings.LastIndex(hp, ":")
  347. if colon < 0 {
  348. return nil, fmt.Errorf("bad ss host:port")
  349. }
  350. host = hp[:colon]
  351. port, err = strconv.Atoi(hp[colon+1:])
  352. if err != nil {
  353. return nil, fmt.Errorf("bad ss port %q: %w", hp[colon+1:], err)
  354. }
  355. method, pass = splitMethodPass(userInfo)
  356. } else {
  357. // legacy: whole thing b64
  358. dec, err := base64DecodeFlexible(core)
  359. if err != nil {
  360. return nil, err
  361. }
  362. at = strings.Index(dec, "@")
  363. if at < 0 {
  364. return nil, fmt.Errorf("bad legacy ss")
  365. }
  366. userInfo := dec[:at]
  367. hp := dec[at+1:]
  368. colon := strings.LastIndex(hp, ":")
  369. if colon < 0 {
  370. return nil, fmt.Errorf("bad legacy ss hp")
  371. }
  372. host = hp[:colon]
  373. port, err = strconv.Atoi(hp[colon+1:])
  374. if err != nil {
  375. return nil, fmt.Errorf("bad legacy ss port %q: %w", hp[colon+1:], err)
  376. }
  377. method, pass = splitMethodPass(userInfo)
  378. }
  379. identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
  380. // The panel and v2rayN express shadowsocks tcp/http obfuscation only as the
  381. // SIP002 plugin, so it has to become the header it stands for.
  382. applyObfsLocalPlugin(params, rawQuery)
  383. network := params.Get("type")
  384. if network == "" {
  385. network = "tcp"
  386. }
  387. security := params.Get("security")
  388. if security == "" {
  389. security = "none"
  390. }
  391. stream := buildStream(network, security)
  392. applyTransport(stream, params)
  393. applySecurity(stream, params)
  394. applyFinalMask(stream, params)
  395. ob := Outbound{
  396. "protocol": "shadowsocks",
  397. "tag": remark,
  398. "settings": map[string]any{
  399. "servers": []any{
  400. map[string]any{"address": host, "port": port, "password": pass, "method": method},
  401. },
  402. },
  403. "streamSettings": stream,
  404. }
  405. return &ParseResult{Outbound: ob, Identity: identity}, nil
  406. }
  407. func splitMethodPass(userInfo string) (string, string) {
  408. before, after, ok := strings.Cut(userInfo, ":")
  409. if !ok {
  410. return "2022-blake3-aes-128-gcm", userInfo // guess
  411. }
  412. return before, after
  413. }
  414. // applyObfsLocalPlugin maps a SIP002 obfs-local=http plugin onto the tcp/http
  415. // response header it stands for; the other plugin values have no Xray header.
  416. func applyObfsLocalPlugin(p url.Values, rawQuery string) {
  417. if p.Get("headerType") != "" || p.Get("type") == "http" {
  418. return
  419. }
  420. plugin := p.Get("plugin")
  421. if plugin == "" {
  422. plugin = rawQueryPlugin(rawQuery)
  423. }
  424. parts := strings.Split(plugin, ";")
  425. if len(parts) == 0 || parts[0] != "obfs-local" {
  426. return
  427. }
  428. obfs, host := "", ""
  429. for _, part := range parts[1:] {
  430. if k, v, ok := strings.Cut(part, "="); ok {
  431. switch k {
  432. case "obfs":
  433. obfs = v
  434. case "obfs-host":
  435. host = v
  436. }
  437. }
  438. }
  439. if obfs != "http" {
  440. return
  441. }
  442. p.Set("type", "tcp")
  443. p.Set("headerType", "http")
  444. if host != "" {
  445. p.Set("host", host)
  446. }
  447. }
  448. // rawQueryPlugin reads the plugin parameter straight out of the query string for
  449. // the pair stdlib discards: a value holding an unencoded semicolon never parses.
  450. func rawQueryPlugin(rawQuery string) string {
  451. for _, segment := range strings.Split(rawQuery, "&") {
  452. if key, value, ok := strings.Cut(segment, "="); ok && key == "plugin" {
  453. if decoded, err := url.QueryUnescape(value); err == nil {
  454. return decoded
  455. }
  456. }
  457. }
  458. return ""
  459. }
  460. // --- hysteria2 ---
  461. func parseHysteria2(link string) (*ParseResult, error) {
  462. u, err := url.Parse(link)
  463. if err != nil {
  464. return nil, err
  465. }
  466. if u.Scheme != "hysteria2" && u.Scheme != "hy2" {
  467. return nil, fmt.Errorf("not hysteria2")
  468. }
  469. auth := u.User.Username()
  470. host := u.Hostname()
  471. port := defaultPort(u.Port(), 443)
  472. params := u.Query()
  473. stream := map[string]any{
  474. "network": "hysteria",
  475. "security": "tls",
  476. "hysteriaSettings": map[string]any{
  477. "version": 2,
  478. "auth": auth,
  479. "udpIdleTimeout": 60,
  480. },
  481. "tlsSettings": map[string]any{
  482. "serverName": params.Get("sni"),
  483. "alpn": splitCommaOrDefault(params.Get("alpn"), []string{"h3"}),
  484. "fingerprint": params.Get("fp"),
  485. "echConfigList": params.Get("ech"),
  486. "verifyPeerCertByName": params.Get("vcn"),
  487. "pinnedPeerCertSha256": params.Get("pinSHA256"),
  488. },
  489. }
  490. applyFinalMask(stream, params)
  491. applyHysteria2Obfs(stream, params)
  492. applyHysteria2Hop(stream, params)
  493. identity := "hysteria2:" + auth + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  494. ob := Outbound{
  495. "protocol": "hysteria",
  496. "tag": decodeHash(u.Fragment),
  497. "settings": map[string]any{"address": host, "port": port, "version": 2},
  498. "streamSettings": stream,
  499. }
  500. return &ParseResult{Outbound: ob, Identity: identity}, nil
  501. }
  502. // --- wireguard ---
  503. func parseWireguard(link string) (*ParseResult, error) {
  504. u, err := url.Parse(link)
  505. if err != nil {
  506. return nil, err
  507. }
  508. if u.Scheme != "wireguard" && u.Scheme != "wg" {
  509. return nil, fmt.Errorf("not wireguard")
  510. }
  511. secret, _ := url.QueryUnescape(u.User.Username())
  512. params := u.Query()
  513. host := u.Hostname()
  514. portStr := u.Port()
  515. endpoint := host
  516. if portStr != "" {
  517. endpoint = host + ":" + portStr
  518. }
  519. addrRaw := firstParam(params, "address", "ip")
  520. allowedRaw := firstParam(params, "allowedips", "allowed_ips")
  521. addrs := splitComma(addrRaw)
  522. if len(addrs) == 0 {
  523. addrs = []string{"0.0.0.0/0", "::/0"}
  524. }
  525. allowed := splitComma(allowedRaw)
  526. if len(allowed) == 0 {
  527. allowed = []string{"0.0.0.0/0", "::/0"}
  528. }
  529. peer := map[string]any{
  530. "publicKey": firstParam(params, "publickey", "publicKey", "public_key", "peerPublicKey"),
  531. "endpoint": endpoint,
  532. "allowedIPs": allowed,
  533. }
  534. if psk := firstParam(params, "presharedkey", "preshared_key", "pre-shared-key", "psk"); psk != "" {
  535. peer["preSharedKey"] = psk
  536. }
  537. if ka := firstParam(params, "keepalive", "persistentkeepalive", "persistent_keepalive"); ka != "" {
  538. if n, err := strconv.Atoi(ka); err == nil {
  539. peer["keepAlive"] = n
  540. }
  541. }
  542. settings := map[string]any{
  543. "secretKey": secret,
  544. "address": addrs,
  545. "peers": []any{peer},
  546. }
  547. if mtu := params.Get("mtu"); mtu != "" {
  548. if n, err := strconv.Atoi(mtu); err == nil {
  549. settings["mtu"] = n
  550. }
  551. }
  552. if res := params.Get("reserved"); res != "" {
  553. parts := splitComma(res)
  554. var iv []int
  555. for _, p := range parts {
  556. if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
  557. iv = append(iv, n)
  558. }
  559. }
  560. if len(iv) > 0 {
  561. settings["reserved"] = iv
  562. }
  563. }
  564. identity := "wireguard:" + secret + "@" + endpoint + "?" + canonicalQuery(params)
  565. ob := Outbound{
  566. "protocol": "wireguard",
  567. "tag": decodeHash(u.Fragment),
  568. "settings": settings,
  569. }
  570. return &ParseResult{Outbound: ob, Identity: identity}, nil
  571. }
  572. // --- helpers ---
  573. func buildStream(network, security string) map[string]any {
  574. stream := map[string]any{"network": network, "security": security}
  575. switch network {
  576. case "tcp":
  577. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  578. case "kcp":
  579. stream["kcpSettings"] = map[string]any{
  580. "mtu": 1350, "tti": 20, "uplinkCapacity": 5, "downlinkCapacity": 20,
  581. "cwndMultiplier": 1, "maxSendingWindow": 2097152,
  582. }
  583. case "ws":
  584. stream["wsSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}, "heartbeatPeriod": 0}
  585. case "grpc":
  586. stream["grpcSettings"] = map[string]any{"serviceName": "", "authority": "", "multiMode": false}
  587. case "httpupgrade":
  588. stream["httpupgradeSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}}
  589. case "xhttp":
  590. // No scMaxEachPostBytes/scMinPostsIntervalMs seed: xray-core's own
  591. // defaults apply, and the literal values fingerprint traffic (#5141).
  592. stream["xhttpSettings"] = map[string]any{
  593. "path": "/", "host": "", "mode": "auto", "headers": map[string]any{},
  594. "xPaddingBytes": "100-1000",
  595. }
  596. default:
  597. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  598. }
  599. switch security {
  600. case "tls":
  601. stream["tlsSettings"] = map[string]any{
  602. "serverName": "", "alpn": []any{}, "fingerprint": "",
  603. "echConfigList": "", "verifyPeerCertByName": "", "pinnedPeerCertSha256": "",
  604. }
  605. case "reality":
  606. stream["realitySettings"] = map[string]any{
  607. "publicKey": "", "fingerprint": "chrome", "serverName": "",
  608. "shortId": "", "spiderX": "", "mldsa65Verify": "",
  609. }
  610. }
  611. return stream
  612. }
  613. func setWS(stream map[string]any, host, path string) {
  614. ws := stream["wsSettings"].(map[string]any)
  615. ws["host"] = host
  616. ws["path"] = path
  617. }
  618. func setHTTPUpgrade(stream map[string]any, host, path string) {
  619. h := stream["httpupgradeSettings"].(map[string]any)
  620. h["host"] = host
  621. h["path"] = path
  622. }
  623. func applyTransport(stream map[string]any, p url.Values) {
  624. net := stream["network"].(string)
  625. host := p.Get("host")
  626. path := firstNonEmpty(p.Get("path"), "/")
  627. switch net {
  628. case "ws":
  629. setWS(stream, host, path)
  630. case "grpc":
  631. gs := stream["grpcSettings"].(map[string]any)
  632. gs["serviceName"] = firstNonEmpty(p.Get("serviceName"), p.Get("path"))
  633. gs["authority"] = p.Get("authority")
  634. gs["multiMode"] = p.Get("mode") == "multi"
  635. case "httpupgrade":
  636. setHTTPUpgrade(stream, host, path)
  637. case "xhttp":
  638. xh := stream["xhttpSettings"].(map[string]any)
  639. xh["host"] = host
  640. xh["path"] = path
  641. if m := p.Get("mode"); m != "" {
  642. xh["mode"] = m
  643. }
  644. if v := p.Get("x_padding_bytes"); v != "" {
  645. xh["xPaddingBytes"] = v
  646. }
  647. if extra := p.Get("extra"); extra != "" {
  648. var parsed map[string]any
  649. if err := json.Unmarshal([]byte(extra), &parsed); err == nil {
  650. maps.Copy(xh, parsed)
  651. }
  652. }
  653. for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs", "uplinkChunkSize"} {
  654. if v := p.Get(k); v != "" {
  655. xh[k] = v
  656. }
  657. }
  658. case "kcp":
  659. // mtu/tti live on kcpSettings; header/seed are finalmask mkcp-legacy (see applyMkcpLegacyFromShare).
  660. kcp := stream["kcpSettings"].(map[string]any)
  661. if n, ok := kcpParamInRange(p.Get("mtu"), kcpMinMTU, kcpMaxMTU); ok {
  662. kcp["mtu"] = n
  663. }
  664. if n, ok := kcpParamInRange(p.Get("tti"), kcpMinTTI, kcpMaxTTI); ok {
  665. kcp["tti"] = n
  666. }
  667. case "tcp":
  668. if p.Get("headerType") == "http" || p.Get("type") == "http" {
  669. stream["tcpSettings"] = map[string]any{
  670. "header": map[string]any{
  671. "type": "http",
  672. "request": map[string]any{
  673. "version": "1.1",
  674. "method": "GET",
  675. "path": splitComma(path),
  676. "headers": map[string]any{"Host": splitComma(host)},
  677. },
  678. },
  679. }
  680. }
  681. }
  682. }
  683. func applySecurity(stream map[string]any, p url.Values) {
  684. sec := stream["security"].(string)
  685. switch sec {
  686. case "tls":
  687. tls := stream["tlsSettings"].(map[string]any)
  688. tls["serverName"] = p.Get("sni")
  689. tls["fingerprint"] = p.Get("fp")
  690. if alpn := p.Get("alpn"); alpn != "" {
  691. tls["alpn"] = splitComma(alpn)
  692. }
  693. tls["echConfigList"] = p.Get("ech")
  694. tls["verifyPeerCertByName"] = p.Get("vcn")
  695. tls["pinnedPeerCertSha256"] = p.Get("pcs")
  696. case "reality":
  697. re := stream["realitySettings"].(map[string]any)
  698. re["serverName"] = p.Get("sni")
  699. re["fingerprint"] = firstNonEmpty(p.Get("fp"), "chrome")
  700. re["publicKey"] = p.Get("pbk")
  701. re["shortId"] = p.Get("sid")
  702. re["spiderX"] = p.Get("spx")
  703. re["mldsa65Verify"] = p.Get("pqv")
  704. }
  705. }
  706. func applyFinalMask(stream map[string]any, p url.Values) {
  707. if fm := p.Get("fm"); fm != "" {
  708. var parsed any
  709. if json.Unmarshal([]byte(fm), &parsed) == nil {
  710. sanitizeFinalMaskQuicParams(parsed)
  711. stream["finalmask"] = parsed
  712. }
  713. }
  714. applyMkcpLegacyFromShare(stream, p)
  715. }
  716. // mKCP bounds mirror xray-core's KCPConfig.Build checks (a value outside them fails
  717. // the whole config load); mtu's ceiling is the int32 that fits its uint32 field everywhere.
  718. const (
  719. kcpMinMTU = 21
  720. kcpMaxMTU = math.MaxInt32
  721. kcpMinTTI = 10
  722. kcpMaxTTI = 1000
  723. )
  724. // kcpParamInRange rejects an out-of-range or malformed link value so buildStream's default stays.
  725. func kcpParamInRange(s string, minVal, maxVal int) (int, bool) {
  726. n, err := strconv.Atoi(s)
  727. return n, err == nil && n >= minVal && n <= maxVal
  728. }
  729. // kcpHeaderTypeToMask maps share-link headerType to mkcp-legacy settings.header
  730. // (inverse of sub.kcpMaskToHeaderType).
  731. var kcpHeaderTypeToMask = map[string]string{
  732. "dns": "dns",
  733. "dtls": "dtls",
  734. "srtp": "srtp",
  735. "utp": "utp",
  736. "wechat-video": "wechat",
  737. "wireguard": "wireguard",
  738. }
  739. // applyMkcpLegacyFromShare restores headerType/seed into finalmask.udp mkcp-legacy,
  740. // matching the shape InboundFormModal / FinalMaskForm emit. fm= mkcp-legacy wins.
  741. func applyMkcpLegacyFromShare(stream map[string]any, p url.Values) {
  742. headerType := strings.TrimSpace(p.Get("headerType"))
  743. seed := p.Get("seed")
  744. if headerType == "" || headerType == "none" {
  745. headerType = ""
  746. }
  747. if headerType == "" && seed == "" {
  748. return
  749. }
  750. if network, _ := stream["network"].(string); network != "" && network != "kcp" {
  751. return
  752. }
  753. maskHeader := ""
  754. if headerType != "" {
  755. mapped, ok := kcpHeaderTypeToMask[headerType]
  756. if !ok {
  757. return
  758. }
  759. maskHeader = mapped
  760. }
  761. finalmask, _ := stream["finalmask"].(map[string]any)
  762. if finalmask == nil {
  763. finalmask = map[string]any{}
  764. }
  765. udp, _ := finalmask["udp"].([]any)
  766. for _, raw := range udp {
  767. m, _ := raw.(map[string]any)
  768. if m != nil {
  769. if t, _ := m["type"].(string); t == "mkcp-legacy" {
  770. return // fm= (or prior) already carries the live mask
  771. }
  772. }
  773. }
  774. // One mask per field, seed first: MkcpLegacy.Build ignores value once header is set,
  775. // and the chain puts the last mask outermost on the wire (header around the cipher).
  776. if seed != "" {
  777. udp = append(udp, mkcpLegacyMask("", seed))
  778. }
  779. if maskHeader != "" {
  780. udp = append(udp, mkcpLegacyMask(maskHeader, ""))
  781. }
  782. finalmask["udp"] = udp
  783. stream["finalmask"] = finalmask
  784. }
  785. func mkcpLegacyMask(header, value string) map[string]any {
  786. return map[string]any{
  787. "type": "mkcp-legacy",
  788. "settings": map[string]any{"header": header, "value": value},
  789. }
  790. }
  791. // gecko packetSize bounds mirror xray-core's salamander buffer cap.
  792. const (
  793. geckoMinPacketSize = 1
  794. geckoMaxPacketSize = 2048
  795. )
  796. // parsePacketSizeRange validates a min/max pair for the Gecko obfs marker.
  797. func parsePacketSizeRange(minStr, maxStr string) (int, int, bool) {
  798. minVal, err1 := strconv.Atoi(minStr)
  799. maxVal, err2 := strconv.Atoi(maxStr)
  800. if err1 != nil || err2 != nil ||
  801. minVal < geckoMinPacketSize || maxVal < minVal || maxVal > geckoMaxPacketSize {
  802. return 0, 0, false
  803. }
  804. return minVal, maxVal, true
  805. }
  806. // applyHysteria2Obfs rebuilds the salamander mask from the standard Hysteria2
  807. // obfs pair. An fm=-carried password wins; gecko adds the packetSize pair.
  808. func applyHysteria2Obfs(stream map[string]any, p url.Values) {
  809. obfs := p.Get("obfs")
  810. isGecko := strings.EqualFold(obfs, "gecko")
  811. if !isGecko && !strings.EqualFold(obfs, "salamander") {
  812. return
  813. }
  814. password := firstParam(p, "obfs-password", "obfs_password", "obfsPassword")
  815. if password == "" {
  816. return
  817. }
  818. packetSize := ""
  819. if isGecko {
  820. // Both halves required with digit+range validation, matching the
  821. // export side; half-specified or non-numeric values are dropped.
  822. minSize := strings.TrimSpace(p.Get("minPacketSize"))
  823. maxSize := strings.TrimSpace(p.Get("maxPacketSize"))
  824. if min, max, ok := parsePacketSizeRange(minSize, maxSize); ok {
  825. packetSize = fmt.Sprintf("%d-%d", min, max)
  826. }
  827. }
  828. finalmask := ensureChildMap(stream, "finalmask")
  829. udp, _ := finalmask["udp"].([]any)
  830. for _, m := range udp {
  831. mask, ok := m.(map[string]any)
  832. if !ok || mask["type"] != "salamander" {
  833. continue
  834. }
  835. settings, ok := mask["settings"].(map[string]any)
  836. if !ok {
  837. settings = map[string]any{}
  838. mask["settings"] = settings
  839. }
  840. if pw, _ := settings["password"].(string); pw == "" {
  841. settings["password"] = password
  842. }
  843. if packetSize != "" {
  844. if ps, _ := settings["packetSize"].(string); ps == "" {
  845. settings["packetSize"] = packetSize
  846. }
  847. }
  848. return
  849. }
  850. settings := map[string]any{"password": password}
  851. if packetSize != "" {
  852. settings["packetSize"] = packetSize
  853. }
  854. finalmask["udp"] = append(udp, map[string]any{
  855. "type": "salamander",
  856. "settings": settings,
  857. })
  858. }
  859. // applyHysteria2Hop rebuilds the UDP port-hopping range from the standard mport
  860. // param. xray-core 26.9.9 replaced finalmask.quicParams.udpHop with a "udphop"
  861. // UDP mask, whose intervalremote mode is what the old key used to do; a mask
  862. // already supplied via fm= wins.
  863. func applyHysteria2Hop(stream map[string]any, p url.Values) {
  864. ports := firstParam(p, "mport")
  865. if ports == "" {
  866. return
  867. }
  868. finalmask := ensureChildMap(stream, "finalmask")
  869. masks, _ := finalmask["udp"].([]any)
  870. for _, rawMask := range masks {
  871. mask, _ := rawMask.(map[string]any)
  872. if maskType, _ := mask["type"].(string); maskType == "udphop" {
  873. return
  874. }
  875. }
  876. finalmask["udp"] = append(masks, map[string]any{
  877. "type": "udphop",
  878. "settings": map[string]any{
  879. "mode": "intervalremote",
  880. "interval": "5-10",
  881. "remotePorts": ports,
  882. },
  883. })
  884. }
  885. func ensureChildMap(parent map[string]any, key string) map[string]any {
  886. m, ok := parent[key].(map[string]any)
  887. if !ok {
  888. m = map[string]any{}
  889. parent[key] = m
  890. }
  891. return m
  892. }
  893. // sanitizeFinalMaskQuicParams coerces the strictly numeric quicParams fields
  894. // of a finalmask blob taken verbatim from a share link's fm= parameter.
  895. // Xray-core rejects the whole config at startup when e.g. keepAlivePeriod
  896. // arrives as a duration string like "10s" or an out-of-range integer, so
  897. // numeric strings are parsed, duration strings are converted to whole
  898. // seconds, the ranged fields are clamped to what xray accepts, and anything
  899. // non-finite, negative, absurdly large, or unparseable is dropped so a bad
  900. // value falls back to xray's default instead of killing the config (#5783).
  901. func sanitizeFinalMaskQuicParams(parsed any) {
  902. fm, ok := parsed.(map[string]any)
  903. if !ok {
  904. return
  905. }
  906. qp, ok := fm["quicParams"].(map[string]any)
  907. if !ok {
  908. return
  909. }
  910. numericKeys := []string{
  911. "initStreamReceiveWindow", "maxStreamReceiveWindow",
  912. "initConnectionReceiveWindow", "maxConnectionReceiveWindow",
  913. "maxIdleTimeout", "keepAlivePeriod", "maxIncomingStreams",
  914. }
  915. for _, key := range numericKeys {
  916. raw, exists := qp[key]
  917. if !exists {
  918. continue
  919. }
  920. n, ok := coerceQuicNumeric(raw)
  921. if ok {
  922. n, ok = clampQuicNumeric(key, n)
  923. }
  924. if !ok {
  925. delete(qp, key)
  926. continue
  927. }
  928. qp[key] = int64(n)
  929. }
  930. }
  931. func coerceQuicNumeric(raw any) (float64, bool) {
  932. switch v := raw.(type) {
  933. case float64:
  934. return math.Trunc(v), true
  935. case string:
  936. if n, err := strconv.ParseFloat(v, 64); err == nil && !math.IsInf(n, 0) && !math.IsNaN(n) {
  937. return math.Trunc(n), true
  938. }
  939. if d, err := time.ParseDuration(v); err == nil {
  940. return math.Trunc(d.Seconds()), true
  941. }
  942. }
  943. return 0, false
  944. }
  945. // clampQuicNumeric enforces xray-core's QuicParamsConfig validation so a
  946. // coerced value cannot still fail the config load: keepAlivePeriod is 0 or
  947. // 2-60, maxIdleTimeout is 0 or 4-120, maxIncomingStreams is 0 or >= 8.
  948. // quicNumericMax keeps values in plain-integer JSON territory and far below
  949. // the uint64 window fields' range.
  950. const quicNumericMax = float64(1e15)
  951. func clampQuicNumeric(key string, n float64) (float64, bool) {
  952. if n < 0 || n > quicNumericMax {
  953. return 0, false
  954. }
  955. if n == 0 {
  956. return 0, true
  957. }
  958. switch key {
  959. case "keepAlivePeriod":
  960. return math.Min(math.Max(n, 2), 60), true
  961. case "maxIdleTimeout":
  962. return math.Min(math.Max(n, 4), 120), true
  963. case "maxIncomingStreams":
  964. return math.Max(n, 8), true
  965. }
  966. return n, true
  967. }
  968. func firstNonEmpty(a, b string) string {
  969. if a != "" {
  970. return a
  971. }
  972. return b
  973. }
  974. func firstParam(p url.Values, keys ...string) string {
  975. for _, k := range keys {
  976. if v := p.Get(k); v != "" {
  977. return v
  978. }
  979. }
  980. return ""
  981. }
  982. func canonicalQuery(p url.Values) string {
  983. // Sort keys for stable identity
  984. keys := make([]string, 0, len(p))
  985. for k := range p {
  986. keys = append(keys, k)
  987. }
  988. // simple sort
  989. for i := 0; i < len(keys); i++ {
  990. for j := i + 1; j < len(keys); j++ {
  991. if keys[j] < keys[i] {
  992. keys[i], keys[j] = keys[j], keys[i]
  993. }
  994. }
  995. }
  996. parts := make([]string, 0, len(keys))
  997. for _, k := range keys {
  998. for _, v := range p[k] {
  999. parts = append(parts, k+"="+v)
  1000. }
  1001. }
  1002. return strings.Join(parts, "&")
  1003. }
  1004. func decodeHash(h string) string {
  1005. if h == "" {
  1006. return ""
  1007. }
  1008. if dec, err := url.QueryUnescape(h); err == nil {
  1009. return dec
  1010. }
  1011. return h
  1012. }
  1013. func defaultPort(p string, def int) int {
  1014. if p == "" {
  1015. return def
  1016. }
  1017. n, err := strconv.Atoi(p)
  1018. if err != nil || n <= 0 {
  1019. return def
  1020. }
  1021. return n
  1022. }
  1023. func num(v any) int {
  1024. switch x := v.(type) {
  1025. case float64:
  1026. return int(x)
  1027. case int:
  1028. return x
  1029. case int64:
  1030. return int(x)
  1031. case string:
  1032. n, _ := strconv.Atoi(x)
  1033. return n
  1034. }
  1035. return 0
  1036. }
  1037. func getString(m map[string]any, key, def string) string {
  1038. if v, ok := m[key]; ok {
  1039. if s, ok := v.(string); ok {
  1040. return s
  1041. }
  1042. }
  1043. return def
  1044. }
  1045. func splitComma(s string) []string {
  1046. if s == "" {
  1047. return nil
  1048. }
  1049. parts := strings.Split(s, ",")
  1050. out := make([]string, 0, len(parts))
  1051. for _, p := range parts {
  1052. p = strings.TrimSpace(p)
  1053. if p != "" {
  1054. out = append(out, p)
  1055. }
  1056. }
  1057. return out
  1058. }
  1059. func splitCommaOrDefault(s string, def []string) []string {
  1060. if s == "" {
  1061. return def
  1062. }
  1063. return splitComma(s)
  1064. }
  1065. func padBase64(s string) string {
  1066. for len(s)%4 != 0 {
  1067. s += "="
  1068. }
  1069. return s
  1070. }
  1071. func base64DecodeFlexible(s string) (string, error) {
  1072. s = padBase64(s)
  1073. if b, err := base64.StdEncoding.DecodeString(s); err == nil {
  1074. return string(b), nil
  1075. }
  1076. if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(s, "=")); err == nil {
  1077. return string(b), nil
  1078. }
  1079. return "", fmt.Errorf("base64 decode failed")
  1080. }
  1081. // SlugRemark turns a free-form remark into a tag segment, keeping Unicode
  1082. // letters and digits (so non-ASCII remarks like Cyrillic stay readable) and
  1083. // replacing every other run of characters with a single dash.
  1084. var slugRe = regexp.MustCompile(`[^\p{L}\p{N}]+`)
  1085. func SlugRemark(remark string) string {
  1086. s := strings.ToLower(strings.TrimSpace(remark))
  1087. s = slugRe.ReplaceAllString(s, "-")
  1088. s = strings.Trim(s, "-")
  1089. if s == "" {
  1090. return ""
  1091. }
  1092. // collapse runs of dashes
  1093. for strings.Contains(s, "--") {
  1094. s = strings.ReplaceAll(s, "--", "-")
  1095. }
  1096. return s
  1097. }
  1098. // SuggestTag builds a tag from a prefix and a remark (or index fallback).
  1099. // It is intended for initial assignment; stability is handled by the service layer.
  1100. func SuggestTag(prefix, remark string, idx int) string {
  1101. base := SlugRemark(remark)
  1102. if base == "" {
  1103. base = fmt.Sprintf("%d", idx)
  1104. }
  1105. p := strings.TrimSuffix(prefix, "-")
  1106. if p != "" {
  1107. return p + "-" + base
  1108. }
  1109. return base
  1110. }