outbound.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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. "math"
  11. "net/url"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. // Outbound is the minimal shape we emit for each parsed link.
  18. // Extra fields (mux, etc.) are carried inside settings/streamSettings.
  19. type Outbound map[string]any
  20. // ParseResult holds a parsed outbound together with a stable identity string
  21. // that can be used to correlate the same logical server across refreshes
  22. // (even if the remark changes).
  23. type ParseResult struct {
  24. Outbound Outbound
  25. Identity string
  26. }
  27. // ParseSubscriptionBody accepts the raw body returned by a subscription URL.
  28. // It handles the common case where the body is a base64-encoded blob of
  29. // newline-separated links, and also tolerates an already-decoded text body.
  30. // It returns the list of successfully parsed outbounds (in order) and their
  31. // corresponding identities.
  32. func ParseSubscriptionBody(body []byte) ([]Outbound, []string, error) {
  33. text := strings.TrimSpace(string(body))
  34. if text == "" {
  35. return nil, nil, nil
  36. }
  37. // Try base64 decode first (standard and URL-safe variants).
  38. if decoded, ok := tryBase64(text); ok {
  39. text = strings.TrimSpace(decoded)
  40. }
  41. lines := splitLines(text)
  42. var outbounds []Outbound
  43. var identities []string
  44. for _, ln := range lines {
  45. ln = strings.TrimSpace(ln)
  46. if ln == "" || strings.HasPrefix(ln, "#") {
  47. continue
  48. }
  49. res, err := ParseLink(ln)
  50. if err != nil || res == nil {
  51. // Ignore unparseable lines (comments, unsupported protocols, etc.)
  52. continue
  53. }
  54. outbounds = append(outbounds, res.Outbound)
  55. identities = append(identities, res.Identity)
  56. }
  57. return outbounds, identities, nil
  58. }
  59. func tryBase64(s string) (string, bool) {
  60. // Remove whitespace that some providers insert.
  61. clean := strings.Map(func(r rune) rune {
  62. if r == ' ' || r == '\n' || r == '\r' || r == '\t' {
  63. return -1
  64. }
  65. return r
  66. }, s)
  67. // Common padding fix
  68. for len(clean)%4 != 0 {
  69. clean += "="
  70. }
  71. // Standard
  72. if b, err := base64.StdEncoding.DecodeString(clean); err == nil {
  73. return string(b), true
  74. }
  75. // URL-safe (no padding)
  76. if b, err := base64.RawURLEncoding.DecodeString(clean); err == nil {
  77. return string(b), true
  78. }
  79. // URL-safe with padding
  80. if b, err := base64.URLEncoding.DecodeString(clean); err == nil {
  81. return string(b), true
  82. }
  83. return "", false
  84. }
  85. func splitLines(s string) []string {
  86. // Accept \n, \r\n, and also some providers use literal \n in the text.
  87. s = strings.ReplaceAll(s, `\n`, "\n")
  88. return strings.FieldsFunc(s, func(r rune) bool { return r == '\n' || r == '\r' })
  89. }
  90. // ParseLink parses a single share link and returns the outbound object plus
  91. // a stable identity for tag correlation. Supported schemes:
  92. // - vmess://
  93. // - vless://
  94. // - trojan://
  95. // - ss:// (modern and legacy)
  96. // - hysteria2:// (also hy2://)
  97. // - wireguard:// (also wg://)
  98. func ParseLink(link string) (*ParseResult, error) {
  99. link = strings.TrimSpace(link)
  100. switch {
  101. case strings.HasPrefix(link, "vmess://"):
  102. return parseVmess(link)
  103. case strings.HasPrefix(link, "vless://"):
  104. return parseVless(link)
  105. case strings.HasPrefix(link, "trojan://"):
  106. return parseTrojan(link)
  107. case strings.HasPrefix(link, "ss://"):
  108. return parseShadowsocks(link)
  109. case strings.HasPrefix(link, "hysteria2://"), strings.HasPrefix(link, "hy2://"):
  110. return parseHysteria2(link)
  111. case strings.HasPrefix(link, "wireguard://"), strings.HasPrefix(link, "wg://"):
  112. return parseWireguard(link)
  113. default:
  114. return nil, fmt.Errorf("unsupported link scheme")
  115. }
  116. }
  117. // --- vmess ---
  118. func parseVmess(link string) (*ParseResult, error) {
  119. b64 := strings.TrimPrefix(link, "vmess://")
  120. // vmess:// base64(json)
  121. raw, err := base64.StdEncoding.DecodeString(padBase64(b64))
  122. if err != nil {
  123. // Some providers use raw URL-safe
  124. raw, err = base64.RawURLEncoding.DecodeString(b64)
  125. }
  126. if err != nil {
  127. return nil, fmt.Errorf("vmess decode: %w", err)
  128. }
  129. var j map[string]any
  130. if err := json.Unmarshal(raw, &j); err != nil {
  131. return nil, fmt.Errorf("vmess json: %w", err)
  132. }
  133. identity := vmessIdentity(j)
  134. network := getString(j, "net", "tcp")
  135. security := "none"
  136. if tls, _ := j["tls"].(string); tls == "tls" {
  137. security = "tls"
  138. }
  139. stream := buildStream(network, security)
  140. // Map known fields (best effort, matching frontend parser coverage)
  141. switch network {
  142. case "ws":
  143. if host, ok := j["host"].(string); ok {
  144. setWS(stream, host, getString(j, "path", "/"))
  145. }
  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. ob := Outbound{
  193. "protocol": "vmess",
  194. "tag": getString(j, "ps", ""),
  195. "settings": map[string]any{
  196. "vnext": []any{
  197. map[string]any{
  198. "address": getString(j, "add", ""),
  199. "port": port,
  200. "users": []any{
  201. map[string]any{
  202. "id": getString(j, "id", ""),
  203. "security": getString(j, "scy", "auto"),
  204. },
  205. },
  206. },
  207. },
  208. },
  209. "streamSettings": stream,
  210. }
  211. return &ParseResult{Outbound: ob, Identity: identity}, nil
  212. }
  213. func vmessIdentity(j map[string]any) string {
  214. // Remove ps (remark) for identity
  215. core := map[string]any{}
  216. for k, v := range j {
  217. if k == "ps" {
  218. continue
  219. }
  220. core[k] = v
  221. }
  222. b, _ := json.Marshal(core)
  223. return "vmess:" + string(b)
  224. }
  225. // --- vless / trojan (URL forms) ---
  226. func parseVless(link string) (*ParseResult, error) {
  227. u, err := url.Parse(link)
  228. if err != nil {
  229. return nil, err
  230. }
  231. if u.Scheme != "vless" {
  232. return nil, fmt.Errorf("not vless")
  233. }
  234. id := u.User.Username()
  235. host := u.Hostname()
  236. port := defaultPort(u.Port(), 443)
  237. params := u.Query()
  238. network := params.Get("type")
  239. if network == "" {
  240. network = "tcp"
  241. }
  242. security := params.Get("security")
  243. if security == "" {
  244. security = "none"
  245. }
  246. stream := buildStream(network, security)
  247. applyTransport(stream, params)
  248. applySecurity(stream, params)
  249. applyFinalMask(stream, params)
  250. identity := "vless:" + u.Scheme + "://" + id + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  251. ob := Outbound{
  252. "protocol": "vless",
  253. "tag": decodeHash(u.Fragment),
  254. "settings": map[string]any{
  255. "address": host,
  256. "port": port,
  257. "id": id,
  258. "flow": params.Get("flow"),
  259. "encryption": firstNonEmpty(params.Get("encryption"), "none"),
  260. },
  261. "streamSettings": stream,
  262. }
  263. return &ParseResult{Outbound: ob, Identity: identity}, nil
  264. }
  265. func parseTrojan(link string) (*ParseResult, error) {
  266. u, err := url.Parse(link)
  267. if err != nil {
  268. return nil, err
  269. }
  270. if u.Scheme != "trojan" {
  271. return nil, fmt.Errorf("not trojan")
  272. }
  273. pw := u.User.Username()
  274. host := u.Hostname()
  275. port := defaultPort(u.Port(), 443)
  276. params := u.Query()
  277. network := params.Get("type")
  278. if network == "" {
  279. network = "tcp"
  280. }
  281. security := params.Get("security")
  282. if security == "" {
  283. security = "tls"
  284. }
  285. stream := buildStream(network, security)
  286. applyTransport(stream, params)
  287. applySecurity(stream, params)
  288. applyFinalMask(stream, params)
  289. identity := "trojan:" + u.Scheme + "://" + pw + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  290. ob := Outbound{
  291. "protocol": "trojan",
  292. "tag": decodeHash(u.Fragment),
  293. "settings": map[string]any{
  294. "servers": []any{
  295. map[string]any{"address": host, "port": port, "password": pw},
  296. },
  297. },
  298. "streamSettings": stream,
  299. }
  300. return &ParseResult{Outbound: ob, Identity: identity}, nil
  301. }
  302. // --- shadowsocks ---
  303. func parseShadowsocks(link string) (*ParseResult, error) {
  304. // Two shapes:
  305. // ss://base64(method:pass)@host:port#remark
  306. // ss://base64(method:pass@host:port)#remark
  307. remark := ""
  308. if i := strings.Index(link, "#"); i >= 0 {
  309. remark, _ = url.QueryUnescape(link[i+1:])
  310. link = link[:i]
  311. }
  312. core := strings.TrimPrefix(link, "ss://")
  313. at := strings.Index(core, "@")
  314. if at >= 0 {
  315. // modern
  316. userB64 := core[:at]
  317. hp := core[at+1:]
  318. userInfo, err := base64DecodeFlexible(userB64)
  319. if err != nil {
  320. // SIP022 (2022-blake3-*) userinfo is percent-encoded, not base64.
  321. if dec, uerr := url.QueryUnescape(userB64); uerr == nil {
  322. userInfo = dec
  323. } else {
  324. userInfo = userB64 // not b64, rare
  325. }
  326. }
  327. colon := strings.LastIndex(hp, ":")
  328. if colon < 0 {
  329. return nil, fmt.Errorf("bad ss host:port")
  330. }
  331. host := hp[:colon]
  332. port, _ := strconv.Atoi(hp[colon+1:])
  333. method, pass := splitMethodPass(userInfo)
  334. identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
  335. ob := Outbound{
  336. "protocol": "shadowsocks",
  337. "tag": remark,
  338. "settings": map[string]any{
  339. "servers": []any{
  340. map[string]any{"address": host, "port": port, "password": pass, "method": method},
  341. },
  342. },
  343. }
  344. return &ParseResult{Outbound: ob, Identity: identity}, nil
  345. }
  346. // legacy: whole thing b64
  347. dec, err := base64DecodeFlexible(core)
  348. if err != nil {
  349. return nil, err
  350. }
  351. at = strings.Index(dec, "@")
  352. if at < 0 {
  353. return nil, fmt.Errorf("bad legacy ss")
  354. }
  355. userInfo := dec[:at]
  356. hp := dec[at+1:]
  357. colon := strings.LastIndex(hp, ":")
  358. if colon < 0 {
  359. return nil, fmt.Errorf("bad legacy ss hp")
  360. }
  361. host := hp[:colon]
  362. port, _ := strconv.Atoi(hp[colon+1:])
  363. method, pass := splitMethodPass(userInfo)
  364. identity := "ss:" + method + ":" + pass + "@" + host + ":" + strconv.Itoa(port)
  365. ob := Outbound{
  366. "protocol": "shadowsocks",
  367. "tag": remark,
  368. "settings": map[string]any{
  369. "servers": []any{
  370. map[string]any{"address": host, "port": port, "password": pass, "method": method},
  371. },
  372. },
  373. }
  374. return &ParseResult{Outbound: ob, Identity: identity}, nil
  375. }
  376. func splitMethodPass(userInfo string) (string, string) {
  377. before, after, ok := strings.Cut(userInfo, ":")
  378. if !ok {
  379. return "2022-blake3-aes-128-gcm", userInfo // guess
  380. }
  381. return before, after
  382. }
  383. // --- hysteria2 ---
  384. func parseHysteria2(link string) (*ParseResult, error) {
  385. u, err := url.Parse(link)
  386. if err != nil {
  387. return nil, err
  388. }
  389. if u.Scheme != "hysteria2" && u.Scheme != "hy2" {
  390. return nil, fmt.Errorf("not hysteria2")
  391. }
  392. auth := u.User.Username()
  393. host := u.Hostname()
  394. port := defaultPort(u.Port(), 443)
  395. params := u.Query()
  396. stream := map[string]any{
  397. "network": "hysteria",
  398. "security": "tls",
  399. "hysteriaSettings": map[string]any{
  400. "version": 2,
  401. "auth": auth,
  402. "udpIdleTimeout": 60,
  403. },
  404. "tlsSettings": map[string]any{
  405. "serverName": params.Get("sni"),
  406. "alpn": splitCommaOrDefault(params.Get("alpn"), []string{"h3"}),
  407. "fingerprint": params.Get("fp"),
  408. "echConfigList": params.Get("ech"),
  409. "verifyPeerCertByName": "",
  410. "pinnedPeerCertSha256": params.Get("pinSHA256"),
  411. },
  412. }
  413. applyFinalMask(stream, params)
  414. identity := "hysteria2:" + auth + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  415. ob := Outbound{
  416. "protocol": "hysteria",
  417. "tag": decodeHash(u.Fragment),
  418. "settings": map[string]any{"address": host, "port": port, "version": 2},
  419. "streamSettings": stream,
  420. }
  421. return &ParseResult{Outbound: ob, Identity: identity}, nil
  422. }
  423. // --- wireguard ---
  424. func parseWireguard(link string) (*ParseResult, error) {
  425. u, err := url.Parse(link)
  426. if err != nil {
  427. return nil, err
  428. }
  429. if u.Scheme != "wireguard" && u.Scheme != "wg" {
  430. return nil, fmt.Errorf("not wireguard")
  431. }
  432. secret, _ := url.QueryUnescape(u.User.Username())
  433. params := u.Query()
  434. host := u.Hostname()
  435. portStr := u.Port()
  436. endpoint := host
  437. if portStr != "" {
  438. endpoint = host + ":" + portStr
  439. }
  440. addrRaw := firstParam(params, "address", "ip")
  441. allowedRaw := firstParam(params, "allowedips", "allowed_ips")
  442. addrs := splitComma(addrRaw)
  443. if len(addrs) == 0 {
  444. addrs = []string{"0.0.0.0/0", "::/0"}
  445. }
  446. allowed := splitComma(allowedRaw)
  447. if len(allowed) == 0 {
  448. allowed = []string{"0.0.0.0/0", "::/0"}
  449. }
  450. peer := map[string]any{
  451. "publicKey": firstParam(params, "publickey", "publicKey", "public_key", "peerPublicKey"),
  452. "endpoint": endpoint,
  453. "allowedIPs": allowed,
  454. }
  455. if psk := firstParam(params, "presharedkey", "preshared_key", "pre-shared-key", "psk"); psk != "" {
  456. peer["preSharedKey"] = psk
  457. }
  458. if ka := firstParam(params, "keepalive", "persistentkeepalive", "persistent_keepalive"); ka != "" {
  459. if n, err := strconv.Atoi(ka); err == nil {
  460. peer["keepAlive"] = n
  461. }
  462. }
  463. settings := map[string]any{
  464. "secretKey": secret,
  465. "address": addrs,
  466. "peers": []any{peer},
  467. }
  468. if mtu := params.Get("mtu"); mtu != "" {
  469. if n, err := strconv.Atoi(mtu); err == nil {
  470. settings["mtu"] = n
  471. }
  472. }
  473. if res := params.Get("reserved"); res != "" {
  474. parts := splitComma(res)
  475. var iv []int
  476. for _, p := range parts {
  477. if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
  478. iv = append(iv, n)
  479. }
  480. }
  481. if len(iv) > 0 {
  482. settings["reserved"] = iv
  483. }
  484. }
  485. identity := "wireguard:" + secret + "@" + endpoint + "?" + canonicalQuery(params)
  486. ob := Outbound{
  487. "protocol": "wireguard",
  488. "tag": decodeHash(u.Fragment),
  489. "settings": settings,
  490. }
  491. return &ParseResult{Outbound: ob, Identity: identity}, nil
  492. }
  493. // --- helpers ---
  494. func buildStream(network, security string) map[string]any {
  495. stream := map[string]any{"network": network, "security": security}
  496. switch network {
  497. case "tcp":
  498. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  499. case "kcp":
  500. stream["kcpSettings"] = map[string]any{
  501. "mtu": 1350, "tti": 20, "uplinkCapacity": 5, "downlinkCapacity": 20,
  502. "cwndMultiplier": 1, "maxSendingWindow": 2097152,
  503. }
  504. case "ws":
  505. stream["wsSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}, "heartbeatPeriod": 0}
  506. case "grpc":
  507. stream["grpcSettings"] = map[string]any{"serviceName": "", "authority": "", "multiMode": false}
  508. case "httpupgrade":
  509. stream["httpupgradeSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}}
  510. case "xhttp":
  511. // No scMaxEachPostBytes/scMinPostsIntervalMs seed: xray-core's own
  512. // defaults apply, and the literal values fingerprint traffic (#5141).
  513. stream["xhttpSettings"] = map[string]any{
  514. "path": "/", "host": "", "mode": "auto", "headers": map[string]any{},
  515. "xPaddingBytes": "100-1000",
  516. }
  517. default:
  518. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  519. }
  520. switch security {
  521. case "tls":
  522. stream["tlsSettings"] = map[string]any{
  523. "serverName": "", "alpn": []any{}, "fingerprint": "",
  524. "echConfigList": "", "verifyPeerCertByName": "", "pinnedPeerCertSha256": "",
  525. }
  526. case "reality":
  527. stream["realitySettings"] = map[string]any{
  528. "publicKey": "", "fingerprint": "chrome", "serverName": "",
  529. "shortId": "", "spiderX": "", "mldsa65Verify": "",
  530. }
  531. }
  532. return stream
  533. }
  534. func setWS(stream map[string]any, host, path string) {
  535. ws := stream["wsSettings"].(map[string]any)
  536. ws["host"] = host
  537. ws["path"] = path
  538. }
  539. func setHTTPUpgrade(stream map[string]any, host, path string) {
  540. h := stream["httpupgradeSettings"].(map[string]any)
  541. h["host"] = host
  542. h["path"] = path
  543. }
  544. func applyTransport(stream map[string]any, p url.Values) {
  545. net := stream["network"].(string)
  546. host := p.Get("host")
  547. path := firstNonEmpty(p.Get("path"), "/")
  548. switch net {
  549. case "ws":
  550. setWS(stream, host, path)
  551. case "grpc":
  552. gs := stream["grpcSettings"].(map[string]any)
  553. gs["serviceName"] = firstNonEmpty(p.Get("serviceName"), p.Get("path"))
  554. gs["authority"] = p.Get("authority")
  555. gs["multiMode"] = p.Get("mode") == "multi"
  556. case "httpupgrade":
  557. setHTTPUpgrade(stream, host, path)
  558. case "xhttp":
  559. xh := stream["xhttpSettings"].(map[string]any)
  560. xh["host"] = host
  561. xh["path"] = path
  562. if m := p.Get("mode"); m != "" {
  563. xh["mode"] = m
  564. }
  565. // A few advanced xhttp fields that are commonly carried
  566. for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs", "uplinkChunkSize"} {
  567. if v := p.Get(k); v != "" {
  568. xh[k] = v
  569. }
  570. }
  571. case "tcp":
  572. if p.Get("headerType") == "http" || p.Get("type") == "http" {
  573. stream["tcpSettings"] = map[string]any{
  574. "header": map[string]any{
  575. "type": "http",
  576. "request": map[string]any{
  577. "version": "1.1",
  578. "method": "GET",
  579. "path": splitComma(path),
  580. "headers": map[string]any{"Host": splitComma(host)},
  581. },
  582. },
  583. }
  584. }
  585. }
  586. }
  587. func applySecurity(stream map[string]any, p url.Values) {
  588. sec := stream["security"].(string)
  589. switch sec {
  590. case "tls":
  591. tls := stream["tlsSettings"].(map[string]any)
  592. tls["serverName"] = p.Get("sni")
  593. tls["fingerprint"] = p.Get("fp")
  594. if alpn := p.Get("alpn"); alpn != "" {
  595. tls["alpn"] = splitComma(alpn)
  596. }
  597. tls["echConfigList"] = p.Get("ech")
  598. tls["pinnedPeerCertSha256"] = p.Get("pcs")
  599. case "reality":
  600. re := stream["realitySettings"].(map[string]any)
  601. re["serverName"] = p.Get("sni")
  602. re["fingerprint"] = firstNonEmpty(p.Get("fp"), "chrome")
  603. re["publicKey"] = p.Get("pbk")
  604. re["shortId"] = p.Get("sid")
  605. re["spiderX"] = p.Get("spx")
  606. re["mldsa65Verify"] = p.Get("pqv")
  607. }
  608. }
  609. func applyFinalMask(stream map[string]any, p url.Values) {
  610. if fm := p.Get("fm"); fm != "" {
  611. var parsed any
  612. if json.Unmarshal([]byte(fm), &parsed) == nil {
  613. sanitizeFinalMaskQuicParams(parsed)
  614. stream["finalmask"] = parsed
  615. }
  616. }
  617. }
  618. // sanitizeFinalMaskQuicParams coerces the strictly numeric quicParams fields
  619. // of a finalmask blob taken verbatim from a share link's fm= parameter.
  620. // Xray-core rejects the whole config at startup when e.g. keepAlivePeriod
  621. // arrives as a duration string like "10s", so numeric strings are parsed,
  622. // duration strings are converted to whole seconds, and anything else is
  623. // dropped rather than passed through (#5783).
  624. func sanitizeFinalMaskQuicParams(parsed any) {
  625. fm, ok := parsed.(map[string]any)
  626. if !ok {
  627. return
  628. }
  629. qp, ok := fm["quicParams"].(map[string]any)
  630. if !ok {
  631. return
  632. }
  633. numericKeys := []string{
  634. "initStreamReceiveWindow", "maxStreamReceiveWindow",
  635. "initConnectionReceiveWindow", "maxConnectionReceiveWindow",
  636. "maxIdleTimeout", "keepAlivePeriod", "maxIncomingStreams",
  637. }
  638. for _, key := range numericKeys {
  639. raw, exists := qp[key]
  640. if !exists {
  641. continue
  642. }
  643. switch v := raw.(type) {
  644. case float64:
  645. qp[key] = math.Trunc(v)
  646. case string:
  647. if n, err := strconv.ParseFloat(v, 64); err == nil {
  648. qp[key] = math.Trunc(n)
  649. } else if d, err := time.ParseDuration(v); err == nil {
  650. qp[key] = math.Trunc(d.Seconds())
  651. } else {
  652. delete(qp, key)
  653. }
  654. default:
  655. delete(qp, key)
  656. }
  657. }
  658. }
  659. func firstNonEmpty(a, b string) string {
  660. if a != "" {
  661. return a
  662. }
  663. return b
  664. }
  665. func firstParam(p url.Values, keys ...string) string {
  666. for _, k := range keys {
  667. if v := p.Get(k); v != "" {
  668. return v
  669. }
  670. }
  671. return ""
  672. }
  673. func canonicalQuery(p url.Values) string {
  674. // Sort keys for stable identity
  675. keys := make([]string, 0, len(p))
  676. for k := range p {
  677. keys = append(keys, k)
  678. }
  679. // simple sort
  680. for i := 0; i < len(keys); i++ {
  681. for j := i + 1; j < len(keys); j++ {
  682. if keys[j] < keys[i] {
  683. keys[i], keys[j] = keys[j], keys[i]
  684. }
  685. }
  686. }
  687. parts := make([]string, 0, len(keys))
  688. for _, k := range keys {
  689. for _, v := range p[k] {
  690. parts = append(parts, k+"="+v)
  691. }
  692. }
  693. return strings.Join(parts, "&")
  694. }
  695. func decodeHash(h string) string {
  696. if h == "" {
  697. return ""
  698. }
  699. if dec, err := url.QueryUnescape(h); err == nil {
  700. return dec
  701. }
  702. return h
  703. }
  704. func defaultPort(p string, def int) int {
  705. if p == "" {
  706. return def
  707. }
  708. n, err := strconv.Atoi(p)
  709. if err != nil || n <= 0 {
  710. return def
  711. }
  712. return n
  713. }
  714. func num(v any) int {
  715. switch x := v.(type) {
  716. case float64:
  717. return int(x)
  718. case int:
  719. return x
  720. case int64:
  721. return int(x)
  722. case string:
  723. n, _ := strconv.Atoi(x)
  724. return n
  725. }
  726. return 0
  727. }
  728. func getString(m map[string]any, key, def string) string {
  729. if v, ok := m[key]; ok {
  730. if s, ok := v.(string); ok {
  731. return s
  732. }
  733. }
  734. return def
  735. }
  736. func splitComma(s string) []string {
  737. if s == "" {
  738. return nil
  739. }
  740. parts := strings.Split(s, ",")
  741. out := make([]string, 0, len(parts))
  742. for _, p := range parts {
  743. p = strings.TrimSpace(p)
  744. if p != "" {
  745. out = append(out, p)
  746. }
  747. }
  748. return out
  749. }
  750. func splitCommaOrDefault(s string, def []string) []string {
  751. if s == "" {
  752. return def
  753. }
  754. return splitComma(s)
  755. }
  756. func padBase64(s string) string {
  757. for len(s)%4 != 0 {
  758. s += "="
  759. }
  760. return s
  761. }
  762. func base64DecodeFlexible(s string) (string, error) {
  763. s = padBase64(s)
  764. if b, err := base64.StdEncoding.DecodeString(s); err == nil {
  765. return string(b), nil
  766. }
  767. if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(s, "=")); err == nil {
  768. return string(b), nil
  769. }
  770. return "", fmt.Errorf("base64 decode failed")
  771. }
  772. // SlugRemark turns a free-form remark into a tag segment, keeping Unicode
  773. // letters and digits (so non-ASCII remarks like Cyrillic stay readable) and
  774. // replacing every other run of characters with a single dash.
  775. var slugRe = regexp.MustCompile(`[^\p{L}\p{N}]+`)
  776. func SlugRemark(remark string) string {
  777. s := strings.ToLower(strings.TrimSpace(remark))
  778. s = slugRe.ReplaceAllString(s, "-")
  779. s = strings.Trim(s, "-")
  780. if s == "" {
  781. return ""
  782. }
  783. // collapse runs of dashes
  784. for strings.Contains(s, "--") {
  785. s = strings.ReplaceAll(s, "--", "-")
  786. }
  787. return s
  788. }
  789. // SuggestTag builds a tag from a prefix and a remark (or index fallback).
  790. // It is intended for initial assignment; stability is handled by the service layer.
  791. func SuggestTag(prefix, remark string, idx int) string {
  792. base := SlugRemark(remark)
  793. if base == "" {
  794. base = fmt.Sprintf("%d", idx)
  795. }
  796. p := strings.TrimSuffix(prefix, "-")
  797. if p != "" {
  798. return p + "-" + base
  799. }
  800. return base
  801. }