clash_service.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. package sub
  2. import (
  3. "fmt"
  4. "maps"
  5. "strings"
  6. "github.com/goccy/go-json"
  7. yaml "github.com/goccy/go-yaml"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  10. )
  11. type SubClashService struct {
  12. enableRouting bool
  13. clashRules string
  14. SubService *SubService
  15. }
  16. func NewSubClashService(enableRouting bool, clashRules string, subService *SubService) *SubClashService {
  17. return &SubClashService{enableRouting: enableRouting, clashRules: clashRules, SubService: subService}
  18. }
  19. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  20. subReq := s.SubService.ForRequest(host)
  21. subReq.subscriptionBody = true
  22. inbounds, err := subReq.getInboundsBySubId(subId)
  23. if err != nil {
  24. return "", "", err
  25. }
  26. externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
  27. if err != nil {
  28. return "", "", err
  29. }
  30. if len(inbounds) == 0 && len(externalLinks) == 0 {
  31. return "", "", nil
  32. }
  33. var proxies []map[string]any
  34. seenEmails := make(map[string]struct{})
  35. for _, inbound := range inbounds {
  36. clients := subReq.matchingClients(inbound, subId)
  37. if len(clients) == 0 {
  38. continue
  39. }
  40. subReq.projectThroughFallbackMaster(inbound)
  41. if hostEps := subReq.hostEndpoints(inbound, "clash"); len(hostEps) > 0 {
  42. injectExternalProxy(inbound, hostEps)
  43. }
  44. for _, client := range clients {
  45. seenEmails[client.Email] = struct{}{}
  46. proxies = append(proxies, s.getProxies(subReq, inbound, client, host)...)
  47. }
  48. }
  49. for _, ext := range externalLinks {
  50. for _, el := range expandEntry(ext) {
  51. name := el.Name
  52. if name == "" {
  53. name = ext.Email
  54. }
  55. if proxy := s.clashProxyFromExternal(el.Link, name); proxy != nil {
  56. seenEmails[ext.Email] = struct{}{}
  57. proxies = append(proxies, proxy)
  58. }
  59. }
  60. }
  61. if len(proxies) == 0 {
  62. return "", "", nil
  63. }
  64. ensureUniqueProxyNames(proxies)
  65. emails := make([]string, 0, len(seenEmails))
  66. for e := range seenEmails {
  67. emails = append(emails, e)
  68. }
  69. traffic, _ := subReq.AggregateTrafficByEmails(emails)
  70. proxyNames := make([]string, 0, len(proxies)+1)
  71. for _, proxy := range proxies {
  72. if name, ok := proxy["name"].(string); ok && name != "" {
  73. proxyNames = append(proxyNames, name)
  74. }
  75. }
  76. proxyNames = append(proxyNames, "DIRECT")
  77. config := map[string]any{
  78. "proxies": proxies,
  79. "proxy-groups": []map[string]any{{
  80. "name": "PROXY",
  81. "type": "select",
  82. "proxies": proxyNames,
  83. }},
  84. "rules": []string{"MATCH,PROXY"},
  85. }
  86. if s.enableRouting {
  87. if err := mergeClashRulesYAML(config, s.clashRules); err != nil {
  88. return "", "", err
  89. }
  90. }
  91. finalYAML, err := yaml.Marshal(config)
  92. if err != nil {
  93. return "", "", err
  94. }
  95. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  96. return string(finalYAML), header, nil
  97. }
  98. // ensureUniqueProxyNames keeps every proxy "name" non-empty and unique:
  99. // mihomo rejects the whole config on a duplicate name (the empty string
  100. // genRemark returns for a remark-less inbound counts), vanishing the Clash
  101. // profile on refresh. See issue #4641.
  102. func ensureUniqueProxyNames(proxies []map[string]any) {
  103. seen := make(map[string]struct{}, len(proxies))
  104. for i, proxy := range proxies {
  105. base, _ := proxy["name"].(string)
  106. if base == "" {
  107. base = fallbackProxyName(proxy, i)
  108. }
  109. name := base
  110. for n := 2; ; n++ {
  111. if _, dup := seen[name]; !dup {
  112. break
  113. }
  114. name = fmt.Sprintf("%s-%d", base, n)
  115. }
  116. seen[name] = struct{}{}
  117. proxy["name"] = name
  118. }
  119. }
  120. func fallbackProxyName(proxy map[string]any, idx int) string {
  121. typ, _ := proxy["type"].(string)
  122. server, _ := proxy["server"].(string)
  123. if typ != "" && server != "" {
  124. return fmt.Sprintf("%s-%s-%v", typ, server, proxy["port"])
  125. }
  126. return fmt.Sprintf("proxy-%d", idx+1)
  127. }
  128. func (s *SubClashService) getProxies(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []map[string]any {
  129. stream := s.streamData(inbound.StreamSettings)
  130. // For node-managed inbounds the Clash proxy "server" must be the
  131. // node's address, not the request host. resolveInboundAddress handles
  132. // the node→subscriber-host fallback chain.
  133. defaultDest := subReq.resolveInboundAddress(inbound)
  134. if defaultDest == "" {
  135. defaultDest = host
  136. }
  137. externalProxies, ok := stream["externalProxy"].([]any)
  138. hasExternalProxy := ok && len(externalProxies) > 0
  139. if !hasExternalProxy {
  140. externalProxies = []any{map[string]any{
  141. "forceTls": "same",
  142. "dest": defaultDest,
  143. "port": float64(inbound.Port),
  144. "remark": "",
  145. }}
  146. }
  147. delete(stream, "externalProxy")
  148. network, _ := stream["network"].(string)
  149. proxies := make([]map[string]any, 0, len(externalProxies))
  150. for _, ep := range externalProxies {
  151. extPrxy := ep.(map[string]any)
  152. // Expand the host's {{VAR}} remark template for this client (no-op for
  153. // the synthetic/legacy entry) before it becomes the proxy name.
  154. subReq.renderHostRemark(inbound, client, extPrxy, network)
  155. workingInbound := *inbound
  156. workingInbound.Listen = extPrxy["dest"].(string)
  157. workingInbound.Port = int(extPrxy["port"].(float64))
  158. workingStream := cloneStreamForExternalProxy(stream)
  159. switch extPrxy["forceTls"].(string) {
  160. case "tls":
  161. if workingStream["security"] != "tls" {
  162. workingStream["security"] = "tls"
  163. workingStream["tlsSettings"] = map[string]any{}
  164. }
  165. case "none":
  166. if workingStream["security"] != "none" {
  167. workingStream["security"] = "none"
  168. delete(workingStream, "tlsSettings")
  169. delete(workingStream, "realitySettings")
  170. }
  171. }
  172. security, _ := workingStream["security"].(string)
  173. if hasExternalProxy {
  174. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  175. }
  176. applyHostStreamOverrides(extPrxy, workingStream)
  177. proxy := s.buildProxy(subReq, &workingInbound, client, workingStream, extPrxy)
  178. if len(proxy) > 0 {
  179. // Host-only mihomo knob: ip-version is a top-level proxy field, set
  180. // last so it cannot be clobbered. Absent for legacy externalProxy.
  181. if v, _ := extPrxy["mihomoIpVersion"].(string); v != "" {
  182. proxy["ip-version"] = v
  183. }
  184. proxies = append(proxies, proxy)
  185. }
  186. }
  187. return proxies
  188. }
  189. func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound, client model.Client, stream map[string]any, ep map[string]any) map[string]any {
  190. // Hysteria has its own transport + TLS model, applyTransport /
  191. // applySecurity don't fit.
  192. if inbound.Protocol == model.Hysteria {
  193. return s.buildHysteriaProxy(subReq, inbound, client, ep)
  194. }
  195. if inbound.Protocol == model.WireGuard {
  196. return s.buildWireguardProxy(subReq, inbound, client, ep)
  197. }
  198. network, _ := stream["network"].(string)
  199. proxy := map[string]any{
  200. "name": subReq.endpointRemark(inbound, client.Email, ep, network),
  201. "server": inbound.Listen,
  202. "port": inbound.Port,
  203. "udp": true,
  204. }
  205. if !s.applyTransport(proxy, network, stream) {
  206. return nil
  207. }
  208. switch inbound.Protocol {
  209. case model.VMESS:
  210. proxy["type"] = "vmess"
  211. proxy["uuid"] = client.ID
  212. proxy["alterId"] = 0
  213. cipher := client.Security
  214. if cipher == "" {
  215. cipher = "auto"
  216. }
  217. proxy["cipher"] = cipher
  218. case model.VLESS:
  219. proxy["type"] = "vless"
  220. proxy["uuid"] = applyVlessRoute(client.ID, hostVlessRoute(ep))
  221. inboundSettings := subReq.linkSettings(inbound)
  222. streamSecurity, _ := stream["security"].(string)
  223. if client.Flow != "" && vlessFlowAllowed(network, streamSecurity, inboundSettings) {
  224. proxy["flow"] = client.Flow
  225. }
  226. if encryption, ok := inboundSettings["encryption"].(string); ok {
  227. encryption = strings.TrimSpace(encryption)
  228. if encryption != "" && encryption != "none" {
  229. proxy["encryption"] = encryption
  230. }
  231. }
  232. case model.Trojan:
  233. proxy["type"] = "trojan"
  234. proxy["password"] = client.Password
  235. case model.Shadowsocks:
  236. proxy["type"] = "ss"
  237. proxy["password"] = client.Password
  238. inboundSettings := subReq.linkSettings(inbound)
  239. method, _ := inboundSettings["method"].(string)
  240. if method == "" {
  241. return nil
  242. }
  243. proxy["cipher"] = method
  244. if strings.HasPrefix(method, "2022") {
  245. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  246. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  247. }
  248. }
  249. default:
  250. return nil
  251. }
  252. security, _ := stream["security"].(string)
  253. if !s.applySecurity(proxy, security, stream) {
  254. return nil
  255. }
  256. return proxy
  257. }
  258. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  259. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  260. // directly instead of going through streamData/tlsData, because those
  261. // helpers prune fields (like `allowInsecure` / the salamander obfs
  262. // block) that the hysteria proxy wants preserved.
  263. func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  264. inboundSettings := subReq.linkSettings(inbound)
  265. proxyType := "hysteria2"
  266. authKey := "password"
  267. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  268. proxyType = "hysteria"
  269. authKey = "auth-str"
  270. }
  271. proxy := map[string]any{
  272. "name": subReq.endpointRemark(inbound, client.Email, ep, "quic"),
  273. "type": proxyType,
  274. "server": inbound.Listen,
  275. "port": inbound.Port,
  276. "udp": true,
  277. authKey: client.Auth,
  278. }
  279. var rawStream map[string]any
  280. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  281. // TLS details — hysteria always uses TLS.
  282. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  283. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  284. proxy["sni"] = serverName
  285. }
  286. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  287. out := make([]string, 0, len(alpnList))
  288. for _, a := range alpnList {
  289. if s, ok := a.(string); ok && s != "" {
  290. out = append(out, s)
  291. }
  292. }
  293. if len(out) > 0 {
  294. proxy["alpn"] = out
  295. }
  296. }
  297. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  298. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  299. proxy["skip-cert-verify"] = true
  300. }
  301. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  302. proxy["client-fingerprint"] = fp
  303. }
  304. }
  305. }
  306. if insecure, ok := ep["allowInsecure"].(bool); ok && insecure {
  307. proxy["skip-cert-verify"] = true
  308. }
  309. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  310. // block the subscription link generator uses.
  311. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  312. if udpMasks, ok := finalmask["udp"].([]any); ok {
  313. for _, m := range udpMasks {
  314. mask, _ := m.(map[string]any)
  315. if mask == nil || mask["type"] != "salamander" {
  316. continue
  317. }
  318. settings, _ := mask["settings"].(map[string]any)
  319. if pw, ok := settings["password"].(string); ok && pw != "" {
  320. proxy["obfs"] = "salamander"
  321. proxy["obfs-password"] = pw
  322. break
  323. }
  324. }
  325. }
  326. }
  327. // UDP port hopping. mihomo reads the range from a dedicated `ports`
  328. // field (the base `port` stays as the redirect target).
  329. if hopPorts := hysteriaHopPorts(rawStream); hopPorts != "" {
  330. proxy["ports"] = hopPorts
  331. }
  332. return proxy
  333. }
  334. // buildWireguardProxy produces a mihomo-compatible Clash entry for a native
  335. // WireGuard inbound, mirroring genWireguardLink: the peer public key is derived
  336. // from the inbound secretKey, while the private key, tunnel address, and
  337. // pre-shared key come from the client. Returns nil when the client has no key.
  338. func (s *SubClashService) buildWireguardProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  339. if client.PrivateKey == "" {
  340. return nil
  341. }
  342. var inboundSettings map[string]any
  343. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  344. secretKey, _ := inboundSettings["secretKey"].(string)
  345. proxy := map[string]any{
  346. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  347. "type": "wireguard",
  348. "server": inbound.Listen,
  349. "port": inbound.Port,
  350. "udp": true,
  351. "private-key": client.PrivateKey,
  352. }
  353. if secretKey != "" {
  354. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  355. proxy["public-key"] = pub
  356. }
  357. }
  358. if client.PreSharedKey != "" {
  359. proxy["pre-shared-key"] = client.PreSharedKey
  360. }
  361. if client.KeepAlive > 0 {
  362. proxy["persistent-keepalive"] = client.KeepAlive
  363. }
  364. for _, addr := range client.AllowedIPs {
  365. ip := stripCIDR(addr)
  366. if ip == "" {
  367. continue
  368. }
  369. if strings.Contains(ip, ":") {
  370. proxy["ipv6"] = ip
  371. } else {
  372. proxy["ip"] = ip
  373. }
  374. }
  375. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  376. proxy["mtu"] = int(mtu)
  377. }
  378. if dns, _ := inboundSettings["dns"].(string); dns != "" {
  379. servers := make([]string, 0)
  380. for _, server := range strings.Split(dns, ",") {
  381. if server = strings.TrimSpace(server); server != "" {
  382. servers = append(servers, server)
  383. }
  384. }
  385. if len(servers) > 0 {
  386. proxy["dns"] = servers
  387. }
  388. }
  389. return proxy
  390. }
  391. // buildXhttpClashOpts converts xhttpSettings from 3x-ui's camelCase JSON
  392. // storage into the kebab-case map that Mihomo expects under xhttp-opts.
  393. //
  394. // Only client-relevant fields are included (allowlist approach).
  395. // Server-only fields (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  396. // serverMaxHeaderBytes) are automatically excluded because they are not in
  397. // the mapping. This is intentional — when Mihomo adds new fields, the mapping
  398. // must be updated explicitly rather than leaking unverified fields to clients.
  399. //
  400. // Returns nil if no non-trivial fields are present.
  401. func buildXhttpClashOpts(xhttp map[string]any) map[string]any {
  402. if xhttp == nil {
  403. return nil
  404. }
  405. opts := map[string]any{}
  406. // Direct fields: path, mode
  407. if v, ok := xhttp["path"].(string); ok && v != "" {
  408. opts["path"] = v
  409. }
  410. if v, ok := xhttp["mode"].(string); ok && v != "" {
  411. opts["mode"] = v
  412. }
  413. // Host: explicit host field wins, then fall back to headers.Host
  414. host := ""
  415. if v, ok := xhttp["host"].(string); ok && v != "" {
  416. host = v
  417. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  418. host = searchHost(headers)
  419. }
  420. if host != "" {
  421. opts["host"] = host
  422. }
  423. type xhttpStringField struct{ src, dst, skipValue string }
  424. stringFields := []xhttpStringField{
  425. {"xPaddingBytes", "x-padding-bytes", ""},
  426. {"uplinkHTTPMethod", "uplink-http-method", ""},
  427. {"sessionIDPlacement", "session-id-placement", ""},
  428. {"sessionIDKey", "session-id-key", ""},
  429. {"sessionIDTable", "session-id-table", ""},
  430. {"sessionIDLength", "session-id-length", ""},
  431. {"seqPlacement", "seq-placement", ""},
  432. {"seqKey", "seq-key", ""},
  433. {"uplinkDataPlacement", "uplink-data-placement", ""},
  434. {"uplinkDataKey", "uplink-data-key", ""},
  435. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  436. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  437. }
  438. for _, f := range stringFields {
  439. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  440. opts[f.dst] = v
  441. }
  442. }
  443. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  444. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  445. // frontend migration.
  446. for _, f := range []xhttpStringField{
  447. {"sessionPlacement", "session-id-placement", ""},
  448. {"sessionKey", "session-id-key", ""},
  449. } {
  450. if _, exists := opts[f.dst]; exists {
  451. continue
  452. }
  453. if v, ok := xhttp[f.src].(string); ok && v != "" {
  454. opts[f.dst] = v
  455. }
  456. }
  457. // Bool fields (truthy only)
  458. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  459. opts["no-grpc-header"] = true
  460. }
  461. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  462. opts["x-padding-obfs-mode"] = true
  463. // Padding obfs gated fields
  464. for _, field := range []struct{ src, dst string }{
  465. {"xPaddingKey", "x-padding-key"},
  466. {"xPaddingHeader", "x-padding-header"},
  467. {"xPaddingPlacement", "x-padding-placement"},
  468. {"xPaddingMethod", "x-padding-method"},
  469. } {
  470. if v, ok := xhttp[field.src].(string); ok && v != "" {
  471. opts[field.dst] = v
  472. }
  473. }
  474. }
  475. // Non-zero value fields
  476. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  477. opts["uplink-chunk-size"] = v
  478. }
  479. // Nested object: xmux → reuse-settings
  480. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  481. reuse := map[string]any{}
  482. for _, f := range []struct{ src, dst string }{
  483. {"maxConcurrency", "max-concurrency"},
  484. {"maxConnections", "max-connections"},
  485. {"cMaxReuseTimes", "c-max-reuse-times"},
  486. {"hMaxRequestTimes", "h-max-request-times"},
  487. {"hMaxReusableSecs", "h-max-reusable-secs"},
  488. } {
  489. if v, ok := xmux[f.src].(string); ok && v != "" {
  490. reuse[f.dst] = v
  491. }
  492. }
  493. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  494. reuse["h-keep-alive-period"] = v
  495. }
  496. if len(reuse) > 0 {
  497. opts["reuse-settings"] = reuse
  498. }
  499. }
  500. // Headers (drop Host key)
  501. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  502. out := map[string]any{}
  503. for k, v := range rawHeaders {
  504. if strings.EqualFold(k, "host") {
  505. continue
  506. }
  507. out[k] = v
  508. }
  509. if len(out) > 0 {
  510. opts["headers"] = out
  511. }
  512. }
  513. if len(opts) == 0 {
  514. return nil
  515. }
  516. return opts
  517. }
  518. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  519. switch network {
  520. case "", "tcp":
  521. proxy["network"] = "tcp"
  522. tcp, _ := stream["tcpSettings"].(map[string]any)
  523. if tcp != nil {
  524. header, _ := tcp["header"].(map[string]any)
  525. if header != nil {
  526. typeStr, _ := header["type"].(string)
  527. if typeStr != "" && typeStr != "none" {
  528. return false
  529. }
  530. }
  531. }
  532. return true
  533. case "ws":
  534. proxy["network"] = "ws"
  535. ws, _ := stream["wsSettings"].(map[string]any)
  536. wsOpts := map[string]any{}
  537. if ws != nil {
  538. if path, ok := ws["path"].(string); ok && path != "" {
  539. wsOpts["path"] = path
  540. }
  541. host := ""
  542. if v, ok := ws["host"].(string); ok && v != "" {
  543. host = v
  544. } else if headers, ok := ws["headers"].(map[string]any); ok {
  545. host = searchHost(headers)
  546. }
  547. if host != "" {
  548. wsOpts["headers"] = map[string]any{"Host": host}
  549. }
  550. }
  551. if len(wsOpts) > 0 {
  552. proxy["ws-opts"] = wsOpts
  553. }
  554. return true
  555. case "grpc":
  556. proxy["network"] = "grpc"
  557. grpc, _ := stream["grpcSettings"].(map[string]any)
  558. grpcOpts := map[string]any{}
  559. if grpc != nil {
  560. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  561. grpcOpts["grpc-service-name"] = serviceName
  562. }
  563. }
  564. if len(grpcOpts) > 0 {
  565. proxy["grpc-opts"] = grpcOpts
  566. }
  567. return true
  568. case "httpupgrade":
  569. proxy["network"] = "httpupgrade"
  570. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  571. opts := map[string]any{}
  572. if hu != nil {
  573. if path, ok := hu["path"].(string); ok && path != "" {
  574. opts["path"] = path
  575. }
  576. host := ""
  577. if v, ok := hu["host"].(string); ok && v != "" {
  578. host = v
  579. } else if headers, ok := hu["headers"].(map[string]any); ok {
  580. host = searchHost(headers)
  581. }
  582. if host != "" {
  583. opts["headers"] = map[string]any{"Host": host}
  584. }
  585. }
  586. if len(opts) > 0 {
  587. proxy["http-upgrade-opts"] = opts
  588. }
  589. return true
  590. case "xhttp":
  591. proxy["network"] = "xhttp"
  592. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  593. opts := buildXhttpClashOpts(xhttp)
  594. if opts != nil {
  595. proxy["xhttp-opts"] = opts
  596. }
  597. return true
  598. default:
  599. return false
  600. }
  601. }
  602. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  603. switch security {
  604. case "", "none":
  605. proxy["tls"] = false
  606. return true
  607. case "tls":
  608. proxy["tls"] = true
  609. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  610. if tlsSettings != nil {
  611. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  612. proxy["servername"] = serverName
  613. switch proxy["type"] {
  614. case "trojan":
  615. proxy["sni"] = serverName
  616. }
  617. }
  618. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  619. proxy["client-fingerprint"] = fingerprint
  620. }
  621. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  622. out := make([]string, 0, len(alpn))
  623. for _, item := range alpn {
  624. if s, ok := item.(string); ok && s != "" {
  625. out = append(out, s)
  626. }
  627. }
  628. if len(out) > 0 {
  629. proxy["alpn"] = out
  630. }
  631. }
  632. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  633. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  634. proxy["skip-cert-verify"] = true
  635. }
  636. }
  637. }
  638. return true
  639. case "reality":
  640. proxy["tls"] = true
  641. realitySettings, _ := stream["realitySettings"].(map[string]any)
  642. if realitySettings == nil {
  643. return false
  644. }
  645. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  646. proxy["servername"] = serverName
  647. }
  648. realityOpts := map[string]any{}
  649. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  650. realityOpts["public-key"] = publicKey
  651. }
  652. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  653. realityOpts["short-id"] = shortID
  654. }
  655. if len(realityOpts) > 0 {
  656. proxy["reality-opts"] = realityOpts
  657. }
  658. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  659. proxy["client-fingerprint"] = fingerprint
  660. }
  661. return true
  662. default:
  663. return false
  664. }
  665. }
  666. func (s *SubClashService) streamData(stream string) map[string]any {
  667. var streamSettings map[string]any
  668. _ = json.Unmarshal([]byte(stream), &streamSettings)
  669. security, _ := streamSettings["security"].(string)
  670. switch security {
  671. case "tls":
  672. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  673. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  674. }
  675. case "reality":
  676. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  677. streamSettings["realitySettings"] = s.realityData(realitySettings)
  678. }
  679. }
  680. delete(streamSettings, "sockopt")
  681. return streamSettings
  682. }
  683. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  684. tlsData := make(map[string]any, 1)
  685. tlsClientSettings, _ := tData["settings"].(map[string]any)
  686. tlsData["serverName"] = tData["serverName"]
  687. tlsData["alpn"] = tData["alpn"]
  688. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  689. tlsData["fingerprint"] = fingerprint
  690. }
  691. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  692. tlsData["pin-sha256"] = pins
  693. }
  694. return tlsData
  695. }
  696. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  697. rDataOut := make(map[string]any, 1)
  698. realityClientSettings, _ := rData["settings"].(map[string]any)
  699. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  700. rDataOut["publicKey"] = publicKey
  701. }
  702. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  703. rDataOut["fingerprint"] = fingerprint
  704. }
  705. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  706. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  707. }
  708. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  709. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  710. }
  711. return rDataOut
  712. }
  713. func cloneMap(src map[string]any) map[string]any {
  714. if src == nil {
  715. return nil
  716. }
  717. dst := make(map[string]any, len(src))
  718. maps.Copy(dst, src)
  719. return dst
  720. }
  721. func mergeClashRulesYAML(base map[string]any, raw string) error {
  722. raw = strings.TrimSpace(raw)
  723. if raw == "" {
  724. return nil
  725. }
  726. var custom any
  727. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  728. mergeClashRules(base, linesToClashRules(raw))
  729. return nil
  730. }
  731. switch typed := custom.(type) {
  732. case []any:
  733. mergeClashRules(base, typed)
  734. case map[string]any:
  735. for key, value := range typed {
  736. if key == "rules" {
  737. if ruleList, ok := asAnySlice(value); ok {
  738. mergeClashRules(base, ruleList)
  739. }
  740. continue
  741. }
  742. base[key] = value
  743. }
  744. default:
  745. mergeClashRules(base, linesToClashRules(raw))
  746. }
  747. return nil
  748. }
  749. func mergeClashRules(base map[string]any, customRules []any) {
  750. if len(customRules) == 0 {
  751. return
  752. }
  753. baseRules, _ := asAnySlice(base["rules"])
  754. if hasClashMatchRule(customRules) {
  755. base["rules"] = customRules
  756. return
  757. }
  758. merged := make([]any, 0, len(customRules)+len(baseRules))
  759. merged = append(merged, customRules...)
  760. merged = append(merged, baseRules...)
  761. base["rules"] = merged
  762. }
  763. func asAnySlice(value any) ([]any, bool) {
  764. switch typed := value.(type) {
  765. case []any:
  766. return typed, true
  767. case []string:
  768. out := make([]any, 0, len(typed))
  769. for _, item := range typed {
  770. out = append(out, item)
  771. }
  772. return out, true
  773. case []map[string]any:
  774. out := make([]any, 0, len(typed))
  775. for _, item := range typed {
  776. out = append(out, item)
  777. }
  778. return out, true
  779. default:
  780. return nil, false
  781. }
  782. }
  783. func hasClashMatchRule(rules []any) bool {
  784. for _, rule := range rules {
  785. ruleText, ok := rule.(string)
  786. if !ok {
  787. continue
  788. }
  789. parts := strings.SplitN(ruleText, ",", 2)
  790. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  791. return true
  792. }
  793. }
  794. return false
  795. }
  796. func linesToClashRules(raw string) []any {
  797. lines := strings.Split(raw, "\n")
  798. rules := make([]any, 0, len(lines))
  799. for _, line := range lines {
  800. line = strings.TrimSpace(line)
  801. if line == "" || strings.HasPrefix(line, "#") {
  802. continue
  803. }
  804. rules = append(rules, line)
  805. }
  806. return rules
  807. }