outbound.go 34 KB

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