outbound.go 28 KB

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