outbound.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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. identity := "hysteria2:" + auth + "@" + host + ":" + strconv.Itoa(port) + "?" + canonicalQuery(params)
  428. ob := Outbound{
  429. "protocol": "hysteria",
  430. "tag": decodeHash(u.Fragment),
  431. "settings": map[string]any{"address": host, "port": port, "version": 2},
  432. "streamSettings": stream,
  433. }
  434. return &ParseResult{Outbound: ob, Identity: identity}, nil
  435. }
  436. // --- wireguard ---
  437. func parseWireguard(link string) (*ParseResult, error) {
  438. u, err := url.Parse(link)
  439. if err != nil {
  440. return nil, err
  441. }
  442. if u.Scheme != "wireguard" && u.Scheme != "wg" {
  443. return nil, fmt.Errorf("not wireguard")
  444. }
  445. secret, _ := url.QueryUnescape(u.User.Username())
  446. params := u.Query()
  447. host := u.Hostname()
  448. portStr := u.Port()
  449. endpoint := host
  450. if portStr != "" {
  451. endpoint = host + ":" + portStr
  452. }
  453. addrRaw := firstParam(params, "address", "ip")
  454. allowedRaw := firstParam(params, "allowedips", "allowed_ips")
  455. addrs := splitComma(addrRaw)
  456. if len(addrs) == 0 {
  457. addrs = []string{"0.0.0.0/0", "::/0"}
  458. }
  459. allowed := splitComma(allowedRaw)
  460. if len(allowed) == 0 {
  461. allowed = []string{"0.0.0.0/0", "::/0"}
  462. }
  463. peer := map[string]any{
  464. "publicKey": firstParam(params, "publickey", "publicKey", "public_key", "peerPublicKey"),
  465. "endpoint": endpoint,
  466. "allowedIPs": allowed,
  467. }
  468. if psk := firstParam(params, "presharedkey", "preshared_key", "pre-shared-key", "psk"); psk != "" {
  469. peer["preSharedKey"] = psk
  470. }
  471. if ka := firstParam(params, "keepalive", "persistentkeepalive", "persistent_keepalive"); ka != "" {
  472. if n, err := strconv.Atoi(ka); err == nil {
  473. peer["keepAlive"] = n
  474. }
  475. }
  476. settings := map[string]any{
  477. "secretKey": secret,
  478. "address": addrs,
  479. "peers": []any{peer},
  480. }
  481. if mtu := params.Get("mtu"); mtu != "" {
  482. if n, err := strconv.Atoi(mtu); err == nil {
  483. settings["mtu"] = n
  484. }
  485. }
  486. if res := params.Get("reserved"); res != "" {
  487. parts := splitComma(res)
  488. var iv []int
  489. for _, p := range parts {
  490. if n, err := strconv.Atoi(strings.TrimSpace(p)); err == nil {
  491. iv = append(iv, n)
  492. }
  493. }
  494. if len(iv) > 0 {
  495. settings["reserved"] = iv
  496. }
  497. }
  498. identity := "wireguard:" + secret + "@" + endpoint + "?" + canonicalQuery(params)
  499. ob := Outbound{
  500. "protocol": "wireguard",
  501. "tag": decodeHash(u.Fragment),
  502. "settings": settings,
  503. }
  504. return &ParseResult{Outbound: ob, Identity: identity}, nil
  505. }
  506. // --- helpers ---
  507. func buildStream(network, security string) map[string]any {
  508. stream := map[string]any{"network": network, "security": security}
  509. switch network {
  510. case "tcp":
  511. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  512. case "kcp":
  513. stream["kcpSettings"] = map[string]any{
  514. "mtu": 1350, "tti": 20, "uplinkCapacity": 5, "downlinkCapacity": 20,
  515. "cwndMultiplier": 1, "maxSendingWindow": 2097152,
  516. }
  517. case "ws":
  518. stream["wsSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}, "heartbeatPeriod": 0}
  519. case "grpc":
  520. stream["grpcSettings"] = map[string]any{"serviceName": "", "authority": "", "multiMode": false}
  521. case "httpupgrade":
  522. stream["httpupgradeSettings"] = map[string]any{"path": "/", "host": "", "headers": map[string]any{}}
  523. case "xhttp":
  524. // No scMaxEachPostBytes/scMinPostsIntervalMs seed: xray-core's own
  525. // defaults apply, and the literal values fingerprint traffic (#5141).
  526. stream["xhttpSettings"] = map[string]any{
  527. "path": "/", "host": "", "mode": "auto", "headers": map[string]any{},
  528. "xPaddingBytes": "100-1000",
  529. }
  530. default:
  531. stream["tcpSettings"] = map[string]any{"header": map[string]any{"type": "none"}}
  532. }
  533. switch security {
  534. case "tls":
  535. stream["tlsSettings"] = map[string]any{
  536. "serverName": "", "alpn": []any{}, "fingerprint": "",
  537. "echConfigList": "", "verifyPeerCertByName": "", "pinnedPeerCertSha256": "",
  538. }
  539. case "reality":
  540. stream["realitySettings"] = map[string]any{
  541. "publicKey": "", "fingerprint": "chrome", "serverName": "",
  542. "shortId": "", "spiderX": "", "mldsa65Verify": "",
  543. }
  544. }
  545. return stream
  546. }
  547. func setWS(stream map[string]any, host, path string) {
  548. ws := stream["wsSettings"].(map[string]any)
  549. ws["host"] = host
  550. ws["path"] = path
  551. }
  552. func setHTTPUpgrade(stream map[string]any, host, path string) {
  553. h := stream["httpupgradeSettings"].(map[string]any)
  554. h["host"] = host
  555. h["path"] = path
  556. }
  557. func applyTransport(stream map[string]any, p url.Values) {
  558. net := stream["network"].(string)
  559. host := p.Get("host")
  560. path := firstNonEmpty(p.Get("path"), "/")
  561. switch net {
  562. case "ws":
  563. setWS(stream, host, path)
  564. case "grpc":
  565. gs := stream["grpcSettings"].(map[string]any)
  566. gs["serviceName"] = firstNonEmpty(p.Get("serviceName"), p.Get("path"))
  567. gs["authority"] = p.Get("authority")
  568. gs["multiMode"] = p.Get("mode") == "multi"
  569. case "httpupgrade":
  570. setHTTPUpgrade(stream, host, path)
  571. case "xhttp":
  572. xh := stream["xhttpSettings"].(map[string]any)
  573. xh["host"] = host
  574. xh["path"] = path
  575. if m := p.Get("mode"); m != "" {
  576. xh["mode"] = m
  577. }
  578. if v := p.Get("x_padding_bytes"); v != "" {
  579. xh["xPaddingBytes"] = v
  580. }
  581. if extra := p.Get("extra"); extra != "" {
  582. var parsed map[string]any
  583. if err := json.Unmarshal([]byte(extra), &parsed); err == nil {
  584. maps.Copy(xh, parsed)
  585. }
  586. }
  587. for _, k := range []string{"xPaddingBytes", "scMaxEachPostBytes", "scMinPostsIntervalMs", "uplinkChunkSize"} {
  588. if v := p.Get(k); v != "" {
  589. xh[k] = v
  590. }
  591. }
  592. case "tcp":
  593. if p.Get("headerType") == "http" || p.Get("type") == "http" {
  594. stream["tcpSettings"] = map[string]any{
  595. "header": map[string]any{
  596. "type": "http",
  597. "request": map[string]any{
  598. "version": "1.1",
  599. "method": "GET",
  600. "path": splitComma(path),
  601. "headers": map[string]any{"Host": splitComma(host)},
  602. },
  603. },
  604. }
  605. }
  606. }
  607. }
  608. func applySecurity(stream map[string]any, p url.Values) {
  609. sec := stream["security"].(string)
  610. switch sec {
  611. case "tls":
  612. tls := stream["tlsSettings"].(map[string]any)
  613. tls["serverName"] = p.Get("sni")
  614. tls["fingerprint"] = p.Get("fp")
  615. if alpn := p.Get("alpn"); alpn != "" {
  616. tls["alpn"] = splitComma(alpn)
  617. }
  618. tls["echConfigList"] = p.Get("ech")
  619. tls["pinnedPeerCertSha256"] = p.Get("pcs")
  620. case "reality":
  621. re := stream["realitySettings"].(map[string]any)
  622. re["serverName"] = p.Get("sni")
  623. re["fingerprint"] = firstNonEmpty(p.Get("fp"), "chrome")
  624. re["publicKey"] = p.Get("pbk")
  625. re["shortId"] = p.Get("sid")
  626. re["spiderX"] = p.Get("spx")
  627. re["mldsa65Verify"] = p.Get("pqv")
  628. }
  629. }
  630. func applyFinalMask(stream map[string]any, p url.Values) {
  631. if fm := p.Get("fm"); fm != "" {
  632. var parsed any
  633. if json.Unmarshal([]byte(fm), &parsed) == nil {
  634. sanitizeFinalMaskQuicParams(parsed)
  635. stream["finalmask"] = parsed
  636. }
  637. }
  638. }
  639. // sanitizeFinalMaskQuicParams coerces the strictly numeric quicParams fields
  640. // of a finalmask blob taken verbatim from a share link's fm= parameter.
  641. // Xray-core rejects the whole config at startup when e.g. keepAlivePeriod
  642. // arrives as a duration string like "10s" or an out-of-range integer, so
  643. // numeric strings are parsed, duration strings are converted to whole
  644. // seconds, the ranged fields are clamped to what xray accepts, and anything
  645. // non-finite, negative, absurdly large, or unparseable is dropped so a bad
  646. // value falls back to xray's default instead of killing the config (#5783).
  647. func sanitizeFinalMaskQuicParams(parsed any) {
  648. fm, ok := parsed.(map[string]any)
  649. if !ok {
  650. return
  651. }
  652. qp, ok := fm["quicParams"].(map[string]any)
  653. if !ok {
  654. return
  655. }
  656. numericKeys := []string{
  657. "initStreamReceiveWindow", "maxStreamReceiveWindow",
  658. "initConnectionReceiveWindow", "maxConnectionReceiveWindow",
  659. "maxIdleTimeout", "keepAlivePeriod", "maxIncomingStreams",
  660. }
  661. for _, key := range numericKeys {
  662. raw, exists := qp[key]
  663. if !exists {
  664. continue
  665. }
  666. n, ok := coerceQuicNumeric(raw)
  667. if ok {
  668. n, ok = clampQuicNumeric(key, n)
  669. }
  670. if !ok {
  671. delete(qp, key)
  672. continue
  673. }
  674. qp[key] = int64(n)
  675. }
  676. }
  677. func coerceQuicNumeric(raw any) (float64, bool) {
  678. switch v := raw.(type) {
  679. case float64:
  680. return math.Trunc(v), true
  681. case string:
  682. if n, err := strconv.ParseFloat(v, 64); err == nil && !math.IsInf(n, 0) && !math.IsNaN(n) {
  683. return math.Trunc(n), true
  684. }
  685. if d, err := time.ParseDuration(v); err == nil {
  686. return math.Trunc(d.Seconds()), true
  687. }
  688. }
  689. return 0, false
  690. }
  691. // clampQuicNumeric enforces xray-core's QuicParamsConfig validation so a
  692. // coerced value cannot still fail the config load: keepAlivePeriod is 0 or
  693. // 2-60, maxIdleTimeout is 0 or 4-120, maxIncomingStreams is 0 or >= 8.
  694. // quicNumericMax keeps values in plain-integer JSON territory and far below
  695. // the uint64 window fields' range.
  696. const quicNumericMax = float64(1e15)
  697. func clampQuicNumeric(key string, n float64) (float64, bool) {
  698. if n < 0 || n > quicNumericMax {
  699. return 0, false
  700. }
  701. if n == 0 {
  702. return 0, true
  703. }
  704. switch key {
  705. case "keepAlivePeriod":
  706. return math.Min(math.Max(n, 2), 60), true
  707. case "maxIdleTimeout":
  708. return math.Min(math.Max(n, 4), 120), true
  709. case "maxIncomingStreams":
  710. return math.Max(n, 8), true
  711. }
  712. return n, true
  713. }
  714. func firstNonEmpty(a, b string) string {
  715. if a != "" {
  716. return a
  717. }
  718. return b
  719. }
  720. func firstParam(p url.Values, keys ...string) string {
  721. for _, k := range keys {
  722. if v := p.Get(k); v != "" {
  723. return v
  724. }
  725. }
  726. return ""
  727. }
  728. func canonicalQuery(p url.Values) string {
  729. // Sort keys for stable identity
  730. keys := make([]string, 0, len(p))
  731. for k := range p {
  732. keys = append(keys, k)
  733. }
  734. // simple sort
  735. for i := 0; i < len(keys); i++ {
  736. for j := i + 1; j < len(keys); j++ {
  737. if keys[j] < keys[i] {
  738. keys[i], keys[j] = keys[j], keys[i]
  739. }
  740. }
  741. }
  742. parts := make([]string, 0, len(keys))
  743. for _, k := range keys {
  744. for _, v := range p[k] {
  745. parts = append(parts, k+"="+v)
  746. }
  747. }
  748. return strings.Join(parts, "&")
  749. }
  750. func decodeHash(h string) string {
  751. if h == "" {
  752. return ""
  753. }
  754. if dec, err := url.QueryUnescape(h); err == nil {
  755. return dec
  756. }
  757. return h
  758. }
  759. func defaultPort(p string, def int) int {
  760. if p == "" {
  761. return def
  762. }
  763. n, err := strconv.Atoi(p)
  764. if err != nil || n <= 0 {
  765. return def
  766. }
  767. return n
  768. }
  769. func num(v any) int {
  770. switch x := v.(type) {
  771. case float64:
  772. return int(x)
  773. case int:
  774. return x
  775. case int64:
  776. return int(x)
  777. case string:
  778. n, _ := strconv.Atoi(x)
  779. return n
  780. }
  781. return 0
  782. }
  783. func getString(m map[string]any, key, def string) string {
  784. if v, ok := m[key]; ok {
  785. if s, ok := v.(string); ok {
  786. return s
  787. }
  788. }
  789. return def
  790. }
  791. func splitComma(s string) []string {
  792. if s == "" {
  793. return nil
  794. }
  795. parts := strings.Split(s, ",")
  796. out := make([]string, 0, len(parts))
  797. for _, p := range parts {
  798. p = strings.TrimSpace(p)
  799. if p != "" {
  800. out = append(out, p)
  801. }
  802. }
  803. return out
  804. }
  805. func splitCommaOrDefault(s string, def []string) []string {
  806. if s == "" {
  807. return def
  808. }
  809. return splitComma(s)
  810. }
  811. func padBase64(s string) string {
  812. for len(s)%4 != 0 {
  813. s += "="
  814. }
  815. return s
  816. }
  817. func base64DecodeFlexible(s string) (string, error) {
  818. s = padBase64(s)
  819. if b, err := base64.StdEncoding.DecodeString(s); err == nil {
  820. return string(b), nil
  821. }
  822. if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(s, "=")); err == nil {
  823. return string(b), nil
  824. }
  825. return "", fmt.Errorf("base64 decode failed")
  826. }
  827. // SlugRemark turns a free-form remark into a tag segment, keeping Unicode
  828. // letters and digits (so non-ASCII remarks like Cyrillic stay readable) and
  829. // replacing every other run of characters with a single dash.
  830. var slugRe = regexp.MustCompile(`[^\p{L}\p{N}]+`)
  831. func SlugRemark(remark string) string {
  832. s := strings.ToLower(strings.TrimSpace(remark))
  833. s = slugRe.ReplaceAllString(s, "-")
  834. s = strings.Trim(s, "-")
  835. if s == "" {
  836. return ""
  837. }
  838. // collapse runs of dashes
  839. for strings.Contains(s, "--") {
  840. s = strings.ReplaceAll(s, "--", "-")
  841. }
  842. return s
  843. }
  844. // SuggestTag builds a tag from a prefix and a remark (or index fallback).
  845. // It is intended for initial assignment; stability is handled by the service layer.
  846. func SuggestTag(prefix, remark string, idx int) string {
  847. base := SlugRemark(remark)
  848. if base == "" {
  849. base = fmt.Sprintf("%d", idx)
  850. }
  851. p := strings.TrimSuffix(prefix, "-")
  852. if p != "" {
  853. return p + "-" + base
  854. }
  855. return base
  856. }