1
0

outbound.go 28 KB

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