1
0

outbound.go 29 KB

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