outbound.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. maskcompat.UpgradeLegacyUDPHop(parsed)
  721. maskcompat.NormalizeUDPHop(parsed)
  722. stream["finalmask"] = parsed
  723. }
  724. }
  725. applyMkcpLegacyFromShare(stream, p)
  726. }
  727. // mKCP bounds mirror xray-core's KCPConfig.Build checks (a value outside them fails
  728. // the whole config load); mtu's ceiling is the int32 that fits its uint32 field everywhere.
  729. const (
  730. kcpMinMTU = 21
  731. kcpMaxMTU = math.MaxInt32
  732. kcpMinTTI = 10
  733. kcpMaxTTI = 1000
  734. )
  735. // kcpParamInRange rejects an out-of-range or malformed link value so buildStream's default stays.
  736. func kcpParamInRange(s string, minVal, maxVal int) (int, bool) {
  737. n, err := strconv.Atoi(s)
  738. return n, err == nil && n >= minVal && n <= maxVal
  739. }
  740. // kcpHeaderTypeToMask maps share-link headerType to mkcp-legacy settings.header
  741. // (inverse of sub.kcpMaskToHeaderType).
  742. var kcpHeaderTypeToMask = map[string]string{
  743. "dns": "dns",
  744. "dtls": "dtls",
  745. "srtp": "srtp",
  746. "utp": "utp",
  747. "wechat-video": "wechat",
  748. "wireguard": "wireguard",
  749. }
  750. // applyMkcpLegacyFromShare restores headerType/seed into finalmask.udp mkcp-legacy,
  751. // matching the shape InboundFormModal / FinalMaskForm emit. fm= mkcp-legacy wins.
  752. func applyMkcpLegacyFromShare(stream map[string]any, p url.Values) {
  753. headerType := strings.TrimSpace(p.Get("headerType"))
  754. seed := p.Get("seed")
  755. if headerType == "" || headerType == "none" {
  756. headerType = ""
  757. }
  758. if headerType == "" && seed == "" {
  759. return
  760. }
  761. if network, _ := stream["network"].(string); network != "" && network != "kcp" {
  762. return
  763. }
  764. maskHeader := ""
  765. if headerType != "" {
  766. mapped, ok := kcpHeaderTypeToMask[headerType]
  767. if !ok {
  768. return
  769. }
  770. maskHeader = mapped
  771. }
  772. finalmask, _ := stream["finalmask"].(map[string]any)
  773. if finalmask == nil {
  774. finalmask = map[string]any{}
  775. }
  776. udp, _ := finalmask["udp"].([]any)
  777. for _, raw := range udp {
  778. m, _ := raw.(map[string]any)
  779. if m != nil {
  780. if t, _ := m["type"].(string); t == "mkcp-legacy" {
  781. return // fm= (or prior) already carries the live mask
  782. }
  783. }
  784. }
  785. // One mask per field, seed first: MkcpLegacy.Build ignores value once header is set,
  786. // and the chain puts the last mask outermost on the wire (header around the cipher).
  787. if seed != "" {
  788. udp = append(udp, mkcpLegacyMask("", seed))
  789. }
  790. if maskHeader != "" {
  791. udp = append(udp, mkcpLegacyMask(maskHeader, ""))
  792. }
  793. finalmask["udp"] = udp
  794. stream["finalmask"] = finalmask
  795. }
  796. func mkcpLegacyMask(header, value string) map[string]any {
  797. return map[string]any{
  798. "type": "mkcp-legacy",
  799. "settings": map[string]any{"header": header, "value": value},
  800. }
  801. }
  802. // gecko packetSize bounds mirror xray-core's salamander buffer cap.
  803. const (
  804. geckoMinPacketSize = 1
  805. geckoMaxPacketSize = 2048
  806. )
  807. // parsePacketSizeRange validates a min/max pair for the Gecko obfs marker.
  808. func parsePacketSizeRange(minStr, maxStr string) (int, int, bool) {
  809. minVal, err1 := strconv.Atoi(minStr)
  810. maxVal, err2 := strconv.Atoi(maxStr)
  811. if err1 != nil || err2 != nil ||
  812. minVal < geckoMinPacketSize || maxVal < minVal || maxVal > geckoMaxPacketSize {
  813. return 0, 0, false
  814. }
  815. return minVal, maxVal, true
  816. }
  817. // applyHysteria2Obfs rebuilds the salamander mask from the standard Hysteria2
  818. // obfs pair. An fm=-carried password wins; gecko adds the packetSize pair.
  819. func applyHysteria2Obfs(stream map[string]any, p url.Values) {
  820. obfs := p.Get("obfs")
  821. isGecko := strings.EqualFold(obfs, "gecko")
  822. if !isGecko && !strings.EqualFold(obfs, "salamander") {
  823. return
  824. }
  825. password := firstParam(p, "obfs-password", "obfs_password", "obfsPassword")
  826. if password == "" {
  827. return
  828. }
  829. packetSize := ""
  830. if isGecko {
  831. // Both halves required with digit+range validation, matching the
  832. // export side; half-specified or non-numeric values are dropped.
  833. minSize := strings.TrimSpace(p.Get("minPacketSize"))
  834. maxSize := strings.TrimSpace(p.Get("maxPacketSize"))
  835. if min, max, ok := parsePacketSizeRange(minSize, maxSize); ok {
  836. packetSize = fmt.Sprintf("%d-%d", min, max)
  837. }
  838. }
  839. finalmask := ensureChildMap(stream, "finalmask")
  840. udp, _ := finalmask["udp"].([]any)
  841. for _, m := range udp {
  842. mask, ok := m.(map[string]any)
  843. if !ok || mask["type"] != "salamander" {
  844. continue
  845. }
  846. settings, ok := mask["settings"].(map[string]any)
  847. if !ok {
  848. settings = map[string]any{}
  849. mask["settings"] = settings
  850. }
  851. if pw, _ := settings["password"].(string); pw == "" {
  852. settings["password"] = password
  853. }
  854. if packetSize != "" {
  855. if ps, _ := settings["packetSize"].(string); ps == "" {
  856. settings["packetSize"] = packetSize
  857. }
  858. }
  859. return
  860. }
  861. settings := map[string]any{"password": password}
  862. if packetSize != "" {
  863. settings["packetSize"] = packetSize
  864. }
  865. finalmask["udp"] = append(udp, map[string]any{
  866. "type": "salamander",
  867. "settings": settings,
  868. })
  869. }
  870. // applyHysteria2Hop rebuilds the UDP port-hopping range from the standard mport
  871. // param. xray-core 26.9.9 replaced finalmask.quicParams.udpHop with a "udphop"
  872. // UDP mask, whose intervalremote mode is what the old key used to do; a mask
  873. // already supplied via fm= wins.
  874. func applyHysteria2Hop(stream map[string]any, p url.Values) {
  875. ports := firstParam(p, "mport")
  876. if ports == "" {
  877. return
  878. }
  879. finalmask := ensureChildMap(stream, "finalmask")
  880. masks, _ := finalmask["udp"].([]any)
  881. for _, rawMask := range masks {
  882. mask, _ := rawMask.(map[string]any)
  883. if maskType, _ := mask["type"].(string); maskType == "udphop" {
  884. return
  885. }
  886. }
  887. finalmask["udp"] = append(masks, map[string]any{
  888. "type": "udphop",
  889. "settings": map[string]any{
  890. "mode": "intervalremote",
  891. "interval": "5-10",
  892. "remotePorts": ports,
  893. },
  894. })
  895. }
  896. func ensureChildMap(parent map[string]any, key string) map[string]any {
  897. m, ok := parent[key].(map[string]any)
  898. if !ok {
  899. m = map[string]any{}
  900. parent[key] = m
  901. }
  902. return m
  903. }
  904. // sanitizeFinalMaskQuicParams coerces the strictly numeric quicParams fields
  905. // of a finalmask blob taken verbatim from a share link's fm= parameter.
  906. // Xray-core rejects the whole config at startup when e.g. keepAlivePeriod
  907. // arrives as a duration string like "10s" or an out-of-range integer, so
  908. // numeric strings are parsed, duration strings are converted to whole
  909. // seconds, the ranged fields are clamped to what xray accepts, and anything
  910. // non-finite, negative, absurdly large, or unparseable is dropped so a bad
  911. // value falls back to xray's default instead of killing the config (#5783).
  912. func sanitizeFinalMaskQuicParams(parsed any) {
  913. fm, ok := parsed.(map[string]any)
  914. if !ok {
  915. return
  916. }
  917. qp, ok := fm["quicParams"].(map[string]any)
  918. if !ok {
  919. return
  920. }
  921. numericKeys := []string{
  922. "initStreamReceiveWindow", "maxStreamReceiveWindow",
  923. "initConnectionReceiveWindow", "maxConnectionReceiveWindow",
  924. "maxIdleTimeout", "keepAlivePeriod", "maxIncomingStreams",
  925. }
  926. for _, key := range numericKeys {
  927. raw, exists := qp[key]
  928. if !exists {
  929. continue
  930. }
  931. n, ok := coerceQuicNumeric(raw)
  932. if ok {
  933. n, ok = clampQuicNumeric(key, n)
  934. }
  935. if !ok {
  936. delete(qp, key)
  937. continue
  938. }
  939. qp[key] = int64(n)
  940. }
  941. }
  942. func coerceQuicNumeric(raw any) (float64, bool) {
  943. switch v := raw.(type) {
  944. case float64:
  945. return math.Trunc(v), true
  946. case string:
  947. if n, err := strconv.ParseFloat(v, 64); err == nil && !math.IsInf(n, 0) && !math.IsNaN(n) {
  948. return math.Trunc(n), true
  949. }
  950. if d, err := time.ParseDuration(v); err == nil {
  951. return math.Trunc(d.Seconds()), true
  952. }
  953. }
  954. return 0, false
  955. }
  956. // clampQuicNumeric enforces xray-core's QuicParamsConfig validation so a
  957. // coerced value cannot still fail the config load: keepAlivePeriod is 0 or
  958. // 2-60, maxIdleTimeout is 0 or 4-120, maxIncomingStreams is 0 or >= 8.
  959. // quicNumericMax keeps values in plain-integer JSON territory and far below
  960. // the uint64 window fields' range.
  961. const quicNumericMax = float64(1e15)
  962. func clampQuicNumeric(key string, n float64) (float64, bool) {
  963. if n < 0 || n > quicNumericMax {
  964. return 0, false
  965. }
  966. if n == 0 {
  967. return 0, true
  968. }
  969. switch key {
  970. case "keepAlivePeriod":
  971. return math.Min(math.Max(n, 2), 60), true
  972. case "maxIdleTimeout":
  973. return math.Min(math.Max(n, 4), 120), true
  974. case "maxIncomingStreams":
  975. return math.Max(n, 8), true
  976. }
  977. return n, true
  978. }
  979. func firstNonEmpty(a, b string) string {
  980. if a != "" {
  981. return a
  982. }
  983. return b
  984. }
  985. func firstParam(p url.Values, keys ...string) string {
  986. for _, k := range keys {
  987. if v := p.Get(k); v != "" {
  988. return v
  989. }
  990. }
  991. return ""
  992. }
  993. // realityPerRequestParams are picked per request by subscription servers (3x-ui randomizes
  994. // sid/sni, older releases spx too), so they must not split one server into new identities.
  995. var realityPerRequestParams = map[string]bool{"sid": true, "sni": true, "spx": true}
  996. func canonicalQuery(p url.Values) string {
  997. // Sort keys for stable identity
  998. reality := p.Get("security") == "reality"
  999. keys := make([]string, 0, len(p))
  1000. for k := range p {
  1001. if reality && realityPerRequestParams[k] {
  1002. continue
  1003. }
  1004. keys = append(keys, k)
  1005. }
  1006. // simple sort
  1007. for i := 0; i < len(keys); i++ {
  1008. for j := i + 1; j < len(keys); j++ {
  1009. if keys[j] < keys[i] {
  1010. keys[i], keys[j] = keys[j], keys[i]
  1011. }
  1012. }
  1013. }
  1014. parts := make([]string, 0, len(keys))
  1015. for _, k := range keys {
  1016. for _, v := range p[k] {
  1017. parts = append(parts, k+"="+v)
  1018. }
  1019. }
  1020. return strings.Join(parts, "&")
  1021. }
  1022. func decodeHash(h string) string {
  1023. if h == "" {
  1024. return ""
  1025. }
  1026. if dec, err := url.QueryUnescape(h); err == nil {
  1027. return dec
  1028. }
  1029. return h
  1030. }
  1031. func defaultPort(p string, def int) int {
  1032. if p == "" {
  1033. return def
  1034. }
  1035. n, err := strconv.Atoi(p)
  1036. if err != nil || n <= 0 {
  1037. return def
  1038. }
  1039. return n
  1040. }
  1041. func num(v any) int {
  1042. switch x := v.(type) {
  1043. case float64:
  1044. return int(x)
  1045. case int:
  1046. return x
  1047. case int64:
  1048. return int(x)
  1049. case string:
  1050. n, _ := strconv.Atoi(x)
  1051. return n
  1052. }
  1053. return 0
  1054. }
  1055. func getString(m map[string]any, key, def string) string {
  1056. if v, ok := m[key]; ok {
  1057. if s, ok := v.(string); ok {
  1058. return s
  1059. }
  1060. }
  1061. return def
  1062. }
  1063. func splitComma(s string) []string {
  1064. if s == "" {
  1065. return nil
  1066. }
  1067. parts := strings.Split(s, ",")
  1068. out := make([]string, 0, len(parts))
  1069. for _, p := range parts {
  1070. p = strings.TrimSpace(p)
  1071. if p != "" {
  1072. out = append(out, p)
  1073. }
  1074. }
  1075. return out
  1076. }
  1077. func splitCommaOrDefault(s string, def []string) []string {
  1078. if s == "" {
  1079. return def
  1080. }
  1081. return splitComma(s)
  1082. }
  1083. func padBase64(s string) string {
  1084. for len(s)%4 != 0 {
  1085. s += "="
  1086. }
  1087. return s
  1088. }
  1089. func base64DecodeFlexible(s string) (string, error) {
  1090. s = padBase64(s)
  1091. if b, err := base64.StdEncoding.DecodeString(s); err == nil {
  1092. return string(b), nil
  1093. }
  1094. if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(s, "=")); err == nil {
  1095. return string(b), nil
  1096. }
  1097. return "", fmt.Errorf("base64 decode failed")
  1098. }
  1099. // SlugRemark turns a free-form remark into a tag segment, keeping Unicode
  1100. // letters and digits (so non-ASCII remarks like Cyrillic stay readable) and
  1101. // replacing every other run of characters with a single dash.
  1102. var slugRe = regexp.MustCompile(`[^\p{L}\p{N}]+`)
  1103. func SlugRemark(remark string) string {
  1104. s := strings.ToLower(strings.TrimSpace(remark))
  1105. s = slugRe.ReplaceAllString(s, "-")
  1106. s = strings.Trim(s, "-")
  1107. if s == "" {
  1108. return ""
  1109. }
  1110. // collapse runs of dashes
  1111. for strings.Contains(s, "--") {
  1112. s = strings.ReplaceAll(s, "--", "-")
  1113. }
  1114. return s
  1115. }
  1116. // SuggestTag builds a tag from a prefix and a remark (or index fallback).
  1117. // It is intended for initial assignment; stability is handled by the service layer.
  1118. func SuggestTag(prefix, remark string, idx int) string {
  1119. base := SlugRemark(remark)
  1120. if base == "" {
  1121. base = fmt.Sprintf("%d", idx)
  1122. }
  1123. p := strings.TrimSuffix(prefix, "-")
  1124. if p != "" {
  1125. return p + "-" + base
  1126. }
  1127. return base
  1128. }