outbound.go 33 KB

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