outbound.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. }
  191. port := num(j["port"])
  192. scy := getString(j, "scy", "auto")
  193. if scy == "none" || scy == "zero" {
  194. scy = "auto"
  195. }
  196. ob := Outbound{
  197. "protocol": "vmess",
  198. "tag": getString(j, "ps", ""),
  199. "settings": map[string]any{
  200. "vnext": []any{
  201. map[string]any{
  202. "address": getString(j, "add", ""),
  203. "port": port,
  204. "users": []any{
  205. map[string]any{
  206. "id": getString(j, "id", ""),
  207. "security": scy,
  208. },
  209. },
  210. },
  211. },
  212. },
  213. "streamSettings": stream,
  214. }
  215. return &ParseResult{Outbound: ob, Identity: identity}, nil
  216. }
  217. func vmessIdentity(j map[string]any) string {
  218. // Remove ps (remark) for identity
  219. core := map[string]any{}
  220. for k, v := range j {
  221. if k == "ps" {
  222. continue
  223. }
  224. core[k] = v
  225. }
  226. b, _ := json.Marshal(core)
  227. return "vmess:" + string(b)
  228. }
  229. // --- vless / trojan (URL forms) ---
  230. func parseVless(link string) (*ParseResult, error) {
  231. u, err := url.Parse(link)
  232. if err != nil {
  233. return nil, err
  234. }
  235. if u.Scheme != "vless" {
  236. return nil, fmt.Errorf("not vless")
  237. }
  238. id := u.User.Username()
  239. host := u.Hostname()
  240. port := defaultPort(u.Port(), 443)
  241. params := u.Query()
  242. network := params.Get("type")
  243. if network == "" {
  244. network = "tcp"
  245. }
  246. security := params.Get("security")
  247. if security == "" {
  248. security = "none"
  249. }
  250. stream := buildStream(network, security)
  251. applyTransport(stream, params)
  252. applySecurity(stream, params)
  253. applyFinalMask(stream, params)
  254. identity := "vless:" + u.Scheme + "://" + id + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  255. ob := Outbound{
  256. "protocol": "vless",
  257. "tag": decodeHash(u.Fragment),
  258. "settings": map[string]any{
  259. "address": host,
  260. "port": port,
  261. "id": id,
  262. "flow": params.Get("flow"),
  263. "encryption": firstNonEmpty(params.Get("encryption"), "none"),
  264. },
  265. "streamSettings": stream,
  266. }
  267. return &ParseResult{Outbound: ob, Identity: identity}, nil
  268. }
  269. func parseTrojan(link string) (*ParseResult, error) {
  270. u, err := url.Parse(link)
  271. if err != nil {
  272. return nil, err
  273. }
  274. if u.Scheme != "trojan" {
  275. return nil, fmt.Errorf("not trojan")
  276. }
  277. pw := u.User.Username()
  278. host := u.Hostname()
  279. port := defaultPort(u.Port(), 443)
  280. params := u.Query()
  281. network := params.Get("type")
  282. if network == "" {
  283. network = "tcp"
  284. }
  285. security := params.Get("security")
  286. if security == "" {
  287. security = "tls"
  288. }
  289. stream := buildStream(network, security)
  290. applyTransport(stream, params)
  291. applySecurity(stream, params)
  292. applyFinalMask(stream, params)
  293. identity := "trojan:" + u.Scheme + "://" + pw + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  294. ob := Outbound{
  295. "protocol": "trojan",
  296. "tag": decodeHash(u.Fragment),
  297. "settings": map[string]any{
  298. "servers": []any{
  299. map[string]any{"address": host, "port": port, "password": pw},
  300. },
  301. },
  302. "streamSettings": stream,
  303. }
  304. return &ParseResult{Outbound: ob, Identity: identity}, nil
  305. }
  306. // --- shadowsocks ---
  307. func parseShadowsocks(link string) (*ParseResult, error) {
  308. // Two shapes:
  309. // ss://base64(method:pass)@host:port#remark
  310. // ss://base64(method:pass@host:port)#remark
  311. remark := ""
  312. if i := strings.Index(link, "#"); i >= 0 {
  313. remark, _ = url.QueryUnescape(link[i+1:])
  314. link = link[:i]
  315. }
  316. if i := strings.Index(link, "?"); i >= 0 {
  317. link = link[:i]
  318. }
  319. core := strings.TrimPrefix(link, "ss://")
  320. at := strings.Index(core, "@")
  321. if at >= 0 {
  322. // modern
  323. userB64 := core[:at]
  324. hp := strings.TrimRight(core[at+1:], "/")
  325. userInfo, err := base64DecodeFlexible(userB64)
  326. if err != nil {
  327. // SIP022 (2022-blake3-*) userinfo is percent-encoded, not base64.
  328. if dec, uerr := url.QueryUnescape(userB64); uerr == nil {
  329. userInfo = dec
  330. } else {
  331. userInfo = userB64 // not b64, rare
  332. }
  333. }
  334. colon := strings.LastIndex(hp, ":")
  335. if colon < 0 {
  336. return nil, fmt.Errorf("bad ss host:port")
  337. }
  338. host := hp[:colon]
  339. port, err := strconv.Atoi(hp[colon+1:])
  340. if err != nil {
  341. return nil, fmt.Errorf("bad ss port %q: %w", hp[colon+1:], err)
  342. }
  343. method, pass := splitMethodPass(userInfo)
  344. identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
  345. ob := Outbound{
  346. "protocol": "shadowsocks",
  347. "tag": remark,
  348. "settings": map[string]any{
  349. "servers": []any{
  350. map[string]any{"address": host, "port": port, "password": pass, "method": method},
  351. },
  352. },
  353. }
  354. return &ParseResult{Outbound: ob, Identity: identity}, nil
  355. }
  356. // legacy: whole thing b64
  357. dec, err := base64DecodeFlexible(core)
  358. if err != nil {
  359. return nil, err
  360. }
  361. at = strings.Index(dec, "@")
  362. if at < 0 {
  363. return nil, fmt.Errorf("bad legacy ss")
  364. }
  365. userInfo := dec[:at]
  366. hp := dec[at+1:]
  367. colon := strings.LastIndex(hp, ":")
  368. if colon < 0 {
  369. return nil, fmt.Errorf("bad legacy ss hp")
  370. }
  371. host := hp[:colon]
  372. port, err := strconv.Atoi(hp[colon+1:])
  373. if err != nil {
  374. return nil, fmt.Errorf("bad legacy ss port %q: %w", hp[colon+1:], err)
  375. }
  376. method, pass := splitMethodPass(userInfo)
  377. identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
  378. ob := Outbound{
  379. "protocol": "shadowsocks",
  380. "tag": remark,
  381. "settings": map[string]any{
  382. "servers": []any{
  383. map[string]any{"address": host, "port": port, "password": pass, "method": method},
  384. },
  385. },
  386. }
  387. return &ParseResult{Outbound: ob, Identity: identity}, nil
  388. }
  389. func splitMethodPass(userInfo string) (string, string) {
  390. before, after, ok := strings.Cut(userInfo, ":")
  391. if !ok {
  392. return "2022-blake3-aes-128-gcm", userInfo // guess
  393. }
  394. return before, after
  395. }
  396. // --- hysteria2 ---
  397. func parseHysteria2(link string) (*ParseResult, error) {
  398. u, err := url.Parse(link)
  399. if err != nil {
  400. return nil, err
  401. }
  402. if u.Scheme != "hysteria2" && u.Scheme != "hy2" {
  403. return nil, fmt.Errorf("not hysteria2")
  404. }
  405. auth := u.User.Username()
  406. host := u.Hostname()
  407. port := defaultPort(u.Port(), 443)
  408. params := u.Query()
  409. stream := map[string]any{
  410. "network": "hysteria",
  411. "security": "tls",
  412. "hysteriaSettings": map[string]any{
  413. "version": 2,
  414. "auth": auth,
  415. "udpIdleTimeout": 60,
  416. },
  417. "tlsSettings": map[string]any{
  418. "serverName": params.Get("sni"),
  419. "alpn": splitCommaOrDefault(params.Get("alpn"), []string{"h3"}),
  420. "fingerprint": params.Get("fp"),
  421. "echConfigList": params.Get("ech"),
  422. "verifyPeerCertByName": params.Get("vcn"),
  423. "pinnedPeerCertSha256": params.Get("pinSHA256"),
  424. },
  425. }
  426. applyFinalMask(stream, params)
  427. applyHysteria2Obfs(stream, params)
  428. applyHysteria2Hop(stream, params)
  429. identity := "hysteria2:" + auth + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  430. ob := Outbound{
  431. "protocol": "hysteria",
  432. "tag": decodeHash(u.Fragment),
  433. "settings": map[string]any{"address": host, "port": port, "version": 2},
  434. "streamSettings": stream,
  435. }
  436. return &ParseResult{Outbound: ob, Identity: identity}, nil
  437. }
  438. // --- wireguard ---
  439. func parseWireguard(link string) (*ParseResult, error) {
  440. u, err := url.Parse(link)
  441. if err != nil {
  442. return nil, err
  443. }
  444. if u.Scheme != "wireguard" && u.Scheme != "wg" {
  445. return nil, fmt.Errorf("not wireguard")
  446. }
  447. secret, _ := url.QueryUnescape(u.User.Username())
  448. params := u.Query()
  449. host := u.Hostname()
  450. portStr := u.Port()
  451. endpoint := host
  452. if portStr != "" {
  453. endpoint = host + ":" + portStr
  454. }
  455. addrRaw := firstParam(params, "address", "ip")
  456. allowedRaw := firstParam(params, "allowedips", "allowed_ips")
  457. addrs := splitComma(addrRaw)
  458. if len(addrs) == 0 {
  459. addrs = []string{"0.0.0.0/0", "::/0"}
  460. }
  461. allowed := splitComma(allowedRaw)
  462. if len(allowed) == 0 {
  463. allowed = []string{"0.0.0.0/0", "::/0"}
  464. }
  465. peer := map[string]any{
  466. "publicKey": firstParam(params, "publickey", "publicKey", "public_key", "peerPublicKey"),
  467. "endpoint": endpoint,
  468. "allowedIPs": allowed,
  469. }
  470. if psk := firstParam(params, "presharedkey", "preshared_key", "pre-shared-key", "psk"); psk != "" {
  471. peer["preSharedKey"] = psk
  472. }
  473. if ka := firstParam(params, "keepalive", "persistentkeepalive", "persistent_keepalive"); ka != "" {
  474. if n, err := strconv.Atoi(ka); err == nil {
  475. peer["keepAlive"] = n
  476. }
  477. }
  478. settings := map[string]any{
  479. "secretKey": secret,
  480. "address": addrs,
  481. "peers": []any{peer},
  482. }
  483. if mtu := params.Get("mtu"); mtu != "" {
  484. if n, err := strconv.Atoi(mtu); err == nil {
  485. settings["mtu"] = n
  486. }
  487. }
  488. if res := params.Get("reserved"); res != "" {
  489. parts := splitComma(res)
  490. var iv []int
  491. for _, p := range parts {
  492. if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
  493. iv = append(iv, n)
  494. }
  495. }
  496. if len(iv) > 0 {
  497. settings["reserved"] = iv
  498. }
  499. }
  500. identity := "wireguard:" + secret + "@" + endpoint + "?" + canonicalQuery(params)
  501. ob := Outbound{
  502. "protocol": "wireguard",
  503. "tag": decodeHash(u.Fragment),
  504. "settings": settings,
  505. }
  506. return &ParseResult{Outbound: ob, Identity: identity}, nil
  507. }
  508. // --- helpers ---
  509. func buildStream(network, security string) map[string]any {
  510. stream := map[string]any{"network": network, "security": security}
  511. switch network {
  512. case "tcp":
  513. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  514. case "kcp":
  515. stream["kcpSettings"] = map[string]any{
  516. "mtu": 1350, "tti": 20, "uplinkCapacity": 5, "downlinkCapacity": 20,
  517. "cwndMultiplier": 1, "maxSendingWindow": 2097152,
  518. }
  519. case "ws":
  520. stream["wsSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}, "heartbeatPeriod": 0}
  521. case "grpc":
  522. stream["grpcSettings"] = map[string]any{"serviceName": "", "authority": "", "multiMode": false}
  523. case "httpupgrade":
  524. stream["httpupgradeSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}}
  525. case "xhttp":
  526. // No scMaxEachPostBytes/scMinPostsIntervalMs seed: xray-core's own
  527. // defaults apply, and the literal values fingerprint traffic (#5141).
  528. stream["xhttpSettings"] = map[string]any{
  529. "path": "/", "host": "", "mode": "auto", "headers": map[string]any{},
  530. "xPaddingBytes": "100-1000",
  531. }
  532. default:
  533. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  534. }
  535. switch security {
  536. case "tls":
  537. stream["tlsSettings"] = map[string]any{
  538. "serverName": "", "alpn": []any{}, "fingerprint": "",
  539. "echConfigList": "", "verifyPeerCertByName": "", "pinnedPeerCertSha256": "",
  540. }
  541. case "reality":
  542. stream["realitySettings"] = map[string]any{
  543. "publicKey": "", "fingerprint": "chrome", "serverName": "",
  544. "shortId": "", "spiderX": "", "mldsa65Verify": "",
  545. }
  546. }
  547. return stream
  548. }
  549. func setWS(stream map[string]any, host, path string) {
  550. ws := stream["wsSettings"].(map[string]any)
  551. ws["host"] = host
  552. ws["path"] = path
  553. }
  554. func setHTTPUpgrade(stream map[string]any, host, path string) {
  555. h := stream["httpupgradeSettings"].(map[string]any)
  556. h["host"] = host
  557. h["path"] = path
  558. }
  559. func applyTransport(stream map[string]any, p url.Values) {
  560. net := stream["network"].(string)
  561. host := p.Get("host")
  562. path := firstNonEmpty(p.Get("path"), "/")
  563. switch net {
  564. case "ws":
  565. setWS(stream, host, path)
  566. case "grpc":
  567. gs := stream["grpcSettings"].(map[string]any)
  568. gs["serviceName"] = firstNonEmpty(p.Get("serviceName"), p.Get("path"))
  569. gs["authority"] = p.Get("authority")
  570. gs["multiMode"] = p.Get("mode") == "multi"
  571. case "httpupgrade":
  572. setHTTPUpgrade(stream, host, path)
  573. case "xhttp":
  574. xh := stream["xhttpSettings"].(map[string]any)
  575. xh["host"] = host
  576. xh["path"] = path
  577. if m := p.Get("mode"); m != "" {
  578. xh["mode"] = m
  579. }
  580. if v := p.Get("x_padding_bytes"); v != "" {
  581. xh["xPaddingBytes"] = v
  582. }
  583. if extra := p.Get("extra"); extra != "" {
  584. var parsed map[string]any
  585. if err := json.Unmarshal([]byte(extra), &parsed); err == nil {
  586. maps.Copy(xh, parsed)
  587. }
  588. }
  589. for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs", "uplinkChunkSize"} {
  590. if v := p.Get(k); v != "" {
  591. xh[k] = v
  592. }
  593. }
  594. case "tcp":
  595. if p.Get("headerType") == "http" || p.Get("type") == "http" {
  596. stream["tcpSettings"] = map[string]any{
  597. "header": map[string]any{
  598. "type": "http",
  599. "request": map[string]any{
  600. "version": "1.1",
  601. "method": "GET",
  602. "path": splitComma(path),
  603. "headers": map[string]any{"Host": splitComma(host)},
  604. },
  605. },
  606. }
  607. }
  608. }
  609. }
  610. func applySecurity(stream map[string]any, p url.Values) {
  611. sec := stream["security"].(string)
  612. switch sec {
  613. case "tls":
  614. tls := stream["tlsSettings"].(map[string]any)
  615. tls["serverName"] = p.Get("sni")
  616. tls["fingerprint"] = p.Get("fp")
  617. if alpn := p.Get("alpn"); alpn != "" {
  618. tls["alpn"] = splitComma(alpn)
  619. }
  620. tls["echConfigList"] = p.Get("ech")
  621. tls["verifyPeerCertByName"] = p.Get("vcn")
  622. tls["pinnedPeerCertSha256"] = p.Get("pcs")
  623. case "reality":
  624. re := stream["realitySettings"].(map[string]any)
  625. re["serverName"] = p.Get("sni")
  626. re["fingerprint"] = firstNonEmpty(p.Get("fp"), "chrome")
  627. re["publicKey"] = p.Get("pbk")
  628. re["shortId"] = p.Get("sid")
  629. re["spiderX"] = p.Get("spx")
  630. re["mldsa65Verify"] = p.Get("pqv")
  631. }
  632. }
  633. func applyFinalMask(stream map[string]any, p url.Values) {
  634. if fm := p.Get("fm"); fm != "" {
  635. var parsed any
  636. if json.Unmarshal([]byte(fm), &parsed) == nil {
  637. sanitizeFinalMaskQuicParams(parsed)
  638. stream["finalmask"] = parsed
  639. }
  640. }
  641. }
  642. // gecko packetSize bounds mirror xray-core's salamander buffer cap.
  643. const (
  644. geckoMinPacketSize = 1
  645. geckoMaxPacketSize = 2048
  646. )
  647. // parsePacketSizeRange validates a min/max pair for the Gecko obfs marker.
  648. func parsePacketSizeRange(minStr, maxStr string) (int, int, bool) {
  649. minVal, err1 := strconv.Atoi(minStr)
  650. maxVal, err2 := strconv.Atoi(maxStr)
  651. if err1 != nil || err2 != nil ||
  652. minVal < geckoMinPacketSize || maxVal < minVal || maxVal > geckoMaxPacketSize {
  653. return 0, 0, false
  654. }
  655. return minVal, maxVal, true
  656. }
  657. // applyHysteria2Obfs rebuilds the salamander mask from the standard Hysteria2
  658. // obfs pair. An fm=-carried password wins; gecko adds the packetSize pair.
  659. func applyHysteria2Obfs(stream map[string]any, p url.Values) {
  660. obfs := p.Get("obfs")
  661. isGecko := strings.EqualFold(obfs, "gecko")
  662. if !isGecko && !strings.EqualFold(obfs, "salamander") {
  663. return
  664. }
  665. password := firstParam(p, "obfs-password", "obfs_password", "obfsPassword")
  666. if password == "" {
  667. return
  668. }
  669. packetSize := ""
  670. if isGecko {
  671. // Both halves required with digit+range validation, matching the
  672. // export side; half-specified or non-numeric values are dropped.
  673. minSize := strings.TrimSpace(p.Get("minPacketSize"))
  674. maxSize := strings.TrimSpace(p.Get("maxPacketSize"))
  675. if min, max, ok := parsePacketSizeRange(minSize, maxSize); ok {
  676. packetSize = fmt.Sprintf("%d-%d", min, max)
  677. }
  678. }
  679. finalmask := ensureChildMap(stream, "finalmask")
  680. udp, _ := finalmask["udp"].([]any)
  681. for _, m := range udp {
  682. mask, ok := m.(map[string]any)
  683. if !ok || mask["type"] != "salamander" {
  684. continue
  685. }
  686. settings, ok := mask["settings"].(map[string]any)
  687. if !ok {
  688. settings = map[string]any{}
  689. mask["settings"] = settings
  690. }
  691. if pw, _ := settings["password"].(string); pw == "" {
  692. settings["password"] = password
  693. }
  694. if packetSize != "" {
  695. if ps, _ := settings["packetSize"].(string); ps == "" {
  696. settings["packetSize"] = packetSize
  697. }
  698. }
  699. return
  700. }
  701. settings := map[string]any{"password": password}
  702. if packetSize != "" {
  703. settings["packetSize"] = packetSize
  704. }
  705. finalmask["udp"] = append(udp, map[string]any{
  706. "type": "salamander",
  707. "settings": settings,
  708. })
  709. }
  710. // applyHysteria2Hop rebuilds the UDP port-hopping range from the standard mport
  711. // param. xray-core 26.9.9 replaced finalmask.quicParams.udpHop with a "udphop"
  712. // UDP mask, whose intervalremote mode is what the old key used to do; a mask
  713. // already supplied via fm= wins.
  714. func applyHysteria2Hop(stream map[string]any, p url.Values) {
  715. ports := firstParam(p, "mport")
  716. if ports == "" {
  717. return
  718. }
  719. finalmask := ensureChildMap(stream, "finalmask")
  720. masks, _ := finalmask["udp"].([]any)
  721. for _, rawMask := range masks {
  722. mask, _ := rawMask.(map[string]any)
  723. if maskType, _ := mask["type"].(string); maskType == "udphop" {
  724. return
  725. }
  726. }
  727. finalmask["udp"] = append(masks, map[string]any{
  728. "type": "udphop",
  729. "settings": map[string]any{
  730. "mode": "intervalremote",
  731. "interval": "5-10",
  732. "remotePorts": ports,
  733. },
  734. })
  735. }
  736. func ensureChildMap(parent map[string]any, key string) map[string]any {
  737. m, ok := parent[key].(map[string]any)
  738. if !ok {
  739. m = map[string]any{}
  740. parent[key] = m
  741. }
  742. return m
  743. }
  744. // sanitizeFinalMaskQuicParams coerces the strictly numeric quicParams fields
  745. // of a finalmask blob taken verbatim from a share link's fm= parameter.
  746. // Xray-core rejects the whole config at startup when e.g. keepAlivePeriod
  747. // arrives as a duration string like "10s" or an out-of-range integer, so
  748. // numeric strings are parsed, duration strings are converted to whole
  749. // seconds, the ranged fields are clamped to what xray accepts, and anything
  750. // non-finite, negative, absurdly large, or unparseable is dropped so a bad
  751. // value falls back to xray's default instead of killing the config (#5783).
  752. func sanitizeFinalMaskQuicParams(parsed any) {
  753. fm, ok := parsed.(map[string]any)
  754. if !ok {
  755. return
  756. }
  757. qp, ok := fm["quicParams"].(map[string]any)
  758. if !ok {
  759. return
  760. }
  761. numericKeys := []string{
  762. "initStreamReceiveWindow", "maxStreamReceiveWindow",
  763. "initConnectionReceiveWindow", "maxConnectionReceiveWindow",
  764. "maxIdleTimeout", "keepAlivePeriod", "maxIncomingStreams",
  765. }
  766. for _, key := range numericKeys {
  767. raw, exists := qp[key]
  768. if !exists {
  769. continue
  770. }
  771. n, ok := coerceQuicNumeric(raw)
  772. if ok {
  773. n, ok = clampQuicNumeric(key, n)
  774. }
  775. if !ok {
  776. delete(qp, key)
  777. continue
  778. }
  779. qp[key] = int64(n)
  780. }
  781. }
  782. func coerceQuicNumeric(raw any) (float64, bool) {
  783. switch v := raw.(type) {
  784. case float64:
  785. return math.Trunc(v), true
  786. case string:
  787. if n, err := strconv.ParseFloat(v, 64); err == nil && !math.IsInf(n, 0) && !math.IsNaN(n) {
  788. return math.Trunc(n), true
  789. }
  790. if d, err := time.ParseDuration(v); err == nil {
  791. return math.Trunc(d.Seconds()), true
  792. }
  793. }
  794. return 0, false
  795. }
  796. // clampQuicNumeric enforces xray-core's QuicParamsConfig validation so a
  797. // coerced value cannot still fail the config load: keepAlivePeriod is 0 or
  798. // 2-60, maxIdleTimeout is 0 or 4-120, maxIncomingStreams is 0 or >= 8.
  799. // quicNumericMax keeps values in plain-integer JSON territory and far below
  800. // the uint64 window fields' range.
  801. const quicNumericMax = float64(1e15)
  802. func clampQuicNumeric(key string, n float64) (float64, bool) {
  803. if n < 0 || n > quicNumericMax {
  804. return 0, false
  805. }
  806. if n == 0 {
  807. return 0, true
  808. }
  809. switch key {
  810. case "keepAlivePeriod":
  811. return math.Min(math.Max(n, 2), 60), true
  812. case "maxIdleTimeout":
  813. return math.Min(math.Max(n, 4), 120), true
  814. case "maxIncomingStreams":
  815. return math.Max(n, 8), true
  816. }
  817. return n, true
  818. }
  819. func firstNonEmpty(a, b string) string {
  820. if a != "" {
  821. return a
  822. }
  823. return b
  824. }
  825. func firstParam(p url.Values, keys ...string) string {
  826. for _, k := range keys {
  827. if v := p.Get(k); v != "" {
  828. return v
  829. }
  830. }
  831. return ""
  832. }
  833. func canonicalQuery(p url.Values) string {
  834. // Sort keys for stable identity
  835. keys := make([]string, 0, len(p))
  836. for k := range p {
  837. keys = append(keys, k)
  838. }
  839. // simple sort
  840. for i := 0; i < len(keys); i++ {
  841. for j := i + 1; j < len(keys); j++ {
  842. if keys[j] < keys[i] {
  843. keys[i], keys[j] = keys[j], keys[i]
  844. }
  845. }
  846. }
  847. parts := make([]string, 0, len(keys))
  848. for _, k := range keys {
  849. for _, v := range p[k] {
  850. parts = append(parts, k+"="+v)
  851. }
  852. }
  853. return strings.Join(parts, "&")
  854. }
  855. func decodeHash(h string) string {
  856. if h == "" {
  857. return ""
  858. }
  859. if dec, err := url.QueryUnescape(h); err == nil {
  860. return dec
  861. }
  862. return h
  863. }
  864. func defaultPort(p string, def int) int {
  865. if p == "" {
  866. return def
  867. }
  868. n, err := strconv.Atoi(p)
  869. if err != nil || n <= 0 {
  870. return def
  871. }
  872. return n
  873. }
  874. func num(v any) int {
  875. switch x := v.(type) {
  876. case float64:
  877. return int(x)
  878. case int:
  879. return x
  880. case int64:
  881. return int(x)
  882. case string:
  883. n, _ := strconv.Atoi(x)
  884. return n
  885. }
  886. return 0
  887. }
  888. func getString(m map[string]any, key, def string) string {
  889. if v, ok := m[key]; ok {
  890. if s, ok := v.(string); ok {
  891. return s
  892. }
  893. }
  894. return def
  895. }
  896. func splitComma(s string) []string {
  897. if s == "" {
  898. return nil
  899. }
  900. parts := strings.Split(s, ",")
  901. out := make([]string, 0, len(parts))
  902. for _, p := range parts {
  903. p = strings.TrimSpace(p)
  904. if p != "" {
  905. out = append(out, p)
  906. }
  907. }
  908. return out
  909. }
  910. func splitCommaOrDefault(s string, def []string) []string {
  911. if s == "" {
  912. return def
  913. }
  914. return splitComma(s)
  915. }
  916. func padBase64(s string) string {
  917. for len(s)%4 != 0 {
  918. s += "="
  919. }
  920. return s
  921. }
  922. func base64DecodeFlexible(s string) (string, error) {
  923. s = padBase64(s)
  924. if b, err := base64.StdEncoding.DecodeString(s); err == nil {
  925. return string(b), nil
  926. }
  927. if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(s, "=")); err == nil {
  928. return string(b), nil
  929. }
  930. return "", fmt.Errorf("base64 decode failed")
  931. }
  932. // SlugRemark turns a free-form remark into a tag segment, keeping Unicode
  933. // letters and digits (so non-ASCII remarks like Cyrillic stay readable) and
  934. // replacing every other run of characters with a single dash.
  935. var slugRe = regexp.MustCompile(`[^\p{L}\p{N}]+`)
  936. func SlugRemark(remark string) string {
  937. s := strings.ToLower(strings.TrimSpace(remark))
  938. s = slugRe.ReplaceAllString(s, "-")
  939. s = strings.Trim(s, "-")
  940. if s == "" {
  941. return ""
  942. }
  943. // collapse runs of dashes
  944. for strings.Contains(s, "--") {
  945. s = strings.ReplaceAll(s, "--", "-")
  946. }
  947. return s
  948. }
  949. // SuggestTag builds a tag from a prefix and a remark (or index fallback).
  950. // It is intended for initial assignment; stability is handled by the service layer.
  951. func SuggestTag(prefix, remark string, idx int) string {
  952. base := SlugRemark(remark)
  953. if base == "" {
  954. base = fmt.Sprintf("%d", idx)
  955. }
  956. p := strings.TrimSuffix(prefix, "-")
  957. if p != "" {
  958. return p + "-" + base
  959. }
  960. return base
  961. }