outbound.go 27 KB

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