outbound.go 33 KB

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