1
0

outbound.go 33 KB

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