clash_service.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  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. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  307. // block the subscription link generator uses.
  308. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  309. if udpMasks, ok := finalmask["udp"].([]any); ok {
  310. for _, m := range udpMasks {
  311. mask, _ := m.(map[string]any)
  312. if mask == nil || mask["type"] != "salamander" {
  313. continue
  314. }
  315. settings, _ := mask["settings"].(map[string]any)
  316. if pw, ok := settings["password"].(string); ok && pw != "" {
  317. proxy["obfs"] = "salamander"
  318. proxy["obfs-password"] = pw
  319. break
  320. }
  321. }
  322. }
  323. }
  324. // UDP port hopping. mihomo reads the range from a dedicated `ports`
  325. // field (the base `port` stays as the redirect target).
  326. if hopPorts := hysteriaHopPorts(rawStream); hopPorts != "" {
  327. proxy["ports"] = hopPorts
  328. }
  329. return proxy
  330. }
  331. // buildWireguardProxy produces a mihomo-compatible Clash entry for a native
  332. // WireGuard inbound, mirroring genWireguardLink: the peer public key is derived
  333. // from the inbound secretKey, while the private key, tunnel address, and
  334. // pre-shared key come from the client. Returns nil when the client has no key.
  335. func (s *SubClashService) buildWireguardProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  336. if client.PrivateKey == "" {
  337. return nil
  338. }
  339. var inboundSettings map[string]any
  340. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  341. secretKey, _ := inboundSettings["secretKey"].(string)
  342. proxy := map[string]any{
  343. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  344. "type": "wireguard",
  345. "server": inbound.Listen,
  346. "port": inbound.Port,
  347. "udp": true,
  348. "private-key": client.PrivateKey,
  349. }
  350. if secretKey != "" {
  351. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  352. proxy["public-key"] = pub
  353. }
  354. }
  355. if client.PreSharedKey != "" {
  356. proxy["pre-shared-key"] = client.PreSharedKey
  357. }
  358. if client.KeepAlive > 0 {
  359. proxy["persistent-keepalive"] = client.KeepAlive
  360. }
  361. for _, addr := range client.AllowedIPs {
  362. ip := stripCIDR(addr)
  363. if ip == "" {
  364. continue
  365. }
  366. if strings.Contains(ip, ":") {
  367. proxy["ipv6"] = ip
  368. } else {
  369. proxy["ip"] = ip
  370. }
  371. }
  372. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  373. proxy["mtu"] = int(mtu)
  374. }
  375. if dns, _ := inboundSettings["dns"].(string); dns != "" {
  376. servers := make([]string, 0)
  377. for _, server := range strings.Split(dns, ",") {
  378. if server = strings.TrimSpace(server); server != "" {
  379. servers = append(servers, server)
  380. }
  381. }
  382. if len(servers) > 0 {
  383. proxy["dns"] = servers
  384. }
  385. }
  386. return proxy
  387. }
  388. // buildXhttpClashOpts converts xhttpSettings from 3x-ui's camelCase JSON
  389. // storage into the kebab-case map that Mihomo expects under xhttp-opts.
  390. //
  391. // Only client-relevant fields are included (allowlist approach).
  392. // Server-only fields (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  393. // serverMaxHeaderBytes) are automatically excluded because they are not in
  394. // the mapping. This is intentional — when Mihomo adds new fields, the mapping
  395. // must be updated explicitly rather than leaking unverified fields to clients.
  396. //
  397. // Returns nil if no non-trivial fields are present.
  398. func buildXhttpClashOpts(xhttp map[string]any) map[string]any {
  399. if xhttp == nil {
  400. return nil
  401. }
  402. opts := map[string]any{}
  403. // Direct fields: path, mode
  404. if v, ok := xhttp["path"].(string); ok && v != "" {
  405. opts["path"] = v
  406. }
  407. if v, ok := xhttp["mode"].(string); ok && v != "" {
  408. opts["mode"] = v
  409. }
  410. // Host: explicit host field wins, then fall back to headers.Host
  411. host := ""
  412. if v, ok := xhttp["host"].(string); ok && v != "" {
  413. host = v
  414. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  415. host = searchHost(headers)
  416. }
  417. if host != "" {
  418. opts["host"] = host
  419. }
  420. type xhttpStringField struct{ src, dst, skipValue string }
  421. stringFields := []xhttpStringField{
  422. {"xPaddingBytes", "x-padding-bytes", ""},
  423. {"uplinkHTTPMethod", "uplink-http-method", ""},
  424. {"sessionIDPlacement", "session-id-placement", ""},
  425. {"sessionIDKey", "session-id-key", ""},
  426. {"sessionIDTable", "session-id-table", ""},
  427. {"sessionIDLength", "session-id-length", ""},
  428. {"seqPlacement", "seq-placement", ""},
  429. {"seqKey", "seq-key", ""},
  430. {"uplinkDataPlacement", "uplink-data-placement", ""},
  431. {"uplinkDataKey", "uplink-data-key", ""},
  432. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  433. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  434. }
  435. for _, f := range stringFields {
  436. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  437. opts[f.dst] = v
  438. }
  439. }
  440. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  441. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  442. // frontend migration.
  443. for _, f := range []xhttpStringField{
  444. {"sessionPlacement", "session-id-placement", ""},
  445. {"sessionKey", "session-id-key", ""},
  446. } {
  447. if _, exists := opts[f.dst]; exists {
  448. continue
  449. }
  450. if v, ok := xhttp[f.src].(string); ok && v != "" {
  451. opts[f.dst] = v
  452. }
  453. }
  454. // Bool fields (truthy only)
  455. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  456. opts["no-grpc-header"] = true
  457. }
  458. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  459. opts["x-padding-obfs-mode"] = true
  460. // Padding obfs gated fields
  461. for _, field := range []struct{ src, dst string }{
  462. {"xPaddingKey", "x-padding-key"},
  463. {"xPaddingHeader", "x-padding-header"},
  464. {"xPaddingPlacement", "x-padding-placement"},
  465. {"xPaddingMethod", "x-padding-method"},
  466. } {
  467. if v, ok := xhttp[field.src].(string); ok && v != "" {
  468. opts[field.dst] = v
  469. }
  470. }
  471. }
  472. // Non-zero value fields
  473. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  474. opts["uplink-chunk-size"] = v
  475. }
  476. // Nested object: xmux → reuse-settings
  477. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  478. reuse := map[string]any{}
  479. for _, f := range []struct{ src, dst string }{
  480. {"maxConcurrency", "max-concurrency"},
  481. {"maxConnections", "max-connections"},
  482. {"cMaxReuseTimes", "c-max-reuse-times"},
  483. {"hMaxRequestTimes", "h-max-request-times"},
  484. {"hMaxReusableSecs", "h-max-reusable-secs"},
  485. } {
  486. if v, ok := xmux[f.src].(string); ok && v != "" {
  487. reuse[f.dst] = v
  488. }
  489. }
  490. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  491. reuse["h-keep-alive-period"] = v
  492. }
  493. if len(reuse) > 0 {
  494. opts["reuse-settings"] = reuse
  495. }
  496. }
  497. // Headers (drop Host key)
  498. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  499. out := map[string]any{}
  500. for k, v := range rawHeaders {
  501. if strings.EqualFold(k, "host") {
  502. continue
  503. }
  504. out[k] = v
  505. }
  506. if len(out) > 0 {
  507. opts["headers"] = out
  508. }
  509. }
  510. if len(opts) == 0 {
  511. return nil
  512. }
  513. return opts
  514. }
  515. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  516. switch network {
  517. case "", "tcp":
  518. proxy["network"] = "tcp"
  519. tcp, _ := stream["tcpSettings"].(map[string]any)
  520. if tcp != nil {
  521. header, _ := tcp["header"].(map[string]any)
  522. if header != nil {
  523. typeStr, _ := header["type"].(string)
  524. if typeStr != "" && typeStr != "none" {
  525. return false
  526. }
  527. }
  528. }
  529. return true
  530. case "ws":
  531. proxy["network"] = "ws"
  532. ws, _ := stream["wsSettings"].(map[string]any)
  533. wsOpts := map[string]any{}
  534. if ws != nil {
  535. if path, ok := ws["path"].(string); ok && path != "" {
  536. wsOpts["path"] = path
  537. }
  538. host := ""
  539. if v, ok := ws["host"].(string); ok && v != "" {
  540. host = v
  541. } else if headers, ok := ws["headers"].(map[string]any); ok {
  542. host = searchHost(headers)
  543. }
  544. if host != "" {
  545. wsOpts["headers"] = map[string]any{"Host": host}
  546. }
  547. }
  548. if len(wsOpts) > 0 {
  549. proxy["ws-opts"] = wsOpts
  550. }
  551. return true
  552. case "grpc":
  553. proxy["network"] = "grpc"
  554. grpc, _ := stream["grpcSettings"].(map[string]any)
  555. grpcOpts := map[string]any{}
  556. if grpc != nil {
  557. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  558. grpcOpts["grpc-service-name"] = serviceName
  559. }
  560. }
  561. if len(grpcOpts) > 0 {
  562. proxy["grpc-opts"] = grpcOpts
  563. }
  564. return true
  565. case "httpupgrade":
  566. proxy["network"] = "httpupgrade"
  567. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  568. opts := map[string]any{}
  569. if hu != nil {
  570. if path, ok := hu["path"].(string); ok && path != "" {
  571. opts["path"] = path
  572. }
  573. host := ""
  574. if v, ok := hu["host"].(string); ok && v != "" {
  575. host = v
  576. } else if headers, ok := hu["headers"].(map[string]any); ok {
  577. host = searchHost(headers)
  578. }
  579. if host != "" {
  580. opts["headers"] = map[string]any{"Host": host}
  581. }
  582. }
  583. if len(opts) > 0 {
  584. proxy["http-upgrade-opts"] = opts
  585. }
  586. return true
  587. case "xhttp":
  588. proxy["network"] = "xhttp"
  589. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  590. opts := buildXhttpClashOpts(xhttp)
  591. if opts != nil {
  592. proxy["xhttp-opts"] = opts
  593. }
  594. return true
  595. default:
  596. return false
  597. }
  598. }
  599. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  600. switch security {
  601. case "", "none":
  602. proxy["tls"] = false
  603. return true
  604. case "tls":
  605. proxy["tls"] = true
  606. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  607. if tlsSettings != nil {
  608. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  609. proxy["servername"] = serverName
  610. switch proxy["type"] {
  611. case "trojan":
  612. proxy["sni"] = serverName
  613. }
  614. }
  615. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  616. proxy["client-fingerprint"] = fingerprint
  617. }
  618. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  619. out := make([]string, 0, len(alpn))
  620. for _, item := range alpn {
  621. if s, ok := item.(string); ok && s != "" {
  622. out = append(out, s)
  623. }
  624. }
  625. if len(out) > 0 {
  626. proxy["alpn"] = out
  627. }
  628. }
  629. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  630. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  631. proxy["skip-cert-verify"] = true
  632. }
  633. }
  634. }
  635. return true
  636. case "reality":
  637. proxy["tls"] = true
  638. realitySettings, _ := stream["realitySettings"].(map[string]any)
  639. if realitySettings == nil {
  640. return false
  641. }
  642. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  643. proxy["servername"] = serverName
  644. }
  645. realityOpts := map[string]any{}
  646. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  647. realityOpts["public-key"] = publicKey
  648. }
  649. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  650. realityOpts["short-id"] = shortID
  651. }
  652. if len(realityOpts) > 0 {
  653. proxy["reality-opts"] = realityOpts
  654. }
  655. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  656. proxy["client-fingerprint"] = fingerprint
  657. }
  658. return true
  659. default:
  660. return false
  661. }
  662. }
  663. func (s *SubClashService) streamData(stream string) map[string]any {
  664. var streamSettings map[string]any
  665. _ = json.Unmarshal([]byte(stream), &streamSettings)
  666. security, _ := streamSettings["security"].(string)
  667. switch security {
  668. case "tls":
  669. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  670. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  671. }
  672. case "reality":
  673. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  674. streamSettings["realitySettings"] = s.realityData(realitySettings)
  675. }
  676. }
  677. delete(streamSettings, "sockopt")
  678. return streamSettings
  679. }
  680. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  681. tlsData := make(map[string]any, 1)
  682. tlsClientSettings, _ := tData["settings"].(map[string]any)
  683. tlsData["serverName"] = tData["serverName"]
  684. tlsData["alpn"] = tData["alpn"]
  685. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  686. tlsData["fingerprint"] = fingerprint
  687. }
  688. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  689. tlsData["pin-sha256"] = pins
  690. }
  691. return tlsData
  692. }
  693. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  694. rDataOut := make(map[string]any, 1)
  695. realityClientSettings, _ := rData["settings"].(map[string]any)
  696. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  697. rDataOut["publicKey"] = publicKey
  698. }
  699. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  700. rDataOut["fingerprint"] = fingerprint
  701. }
  702. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  703. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  704. }
  705. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  706. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  707. }
  708. return rDataOut
  709. }
  710. func cloneMap(src map[string]any) map[string]any {
  711. if src == nil {
  712. return nil
  713. }
  714. dst := make(map[string]any, len(src))
  715. maps.Copy(dst, src)
  716. return dst
  717. }
  718. func mergeClashRulesYAML(base map[string]any, raw string) error {
  719. raw = strings.TrimSpace(raw)
  720. if raw == "" {
  721. return nil
  722. }
  723. var custom any
  724. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  725. mergeClashRules(base, linesToClashRules(raw))
  726. return nil
  727. }
  728. switch typed := custom.(type) {
  729. case []any:
  730. mergeClashRules(base, typed)
  731. case map[string]any:
  732. for key, value := range typed {
  733. if key == "rules" {
  734. if ruleList, ok := asAnySlice(value); ok {
  735. mergeClashRules(base, ruleList)
  736. }
  737. continue
  738. }
  739. base[key] = value
  740. }
  741. default:
  742. mergeClashRules(base, linesToClashRules(raw))
  743. }
  744. return nil
  745. }
  746. func mergeClashRules(base map[string]any, customRules []any) {
  747. if len(customRules) == 0 {
  748. return
  749. }
  750. baseRules, _ := asAnySlice(base["rules"])
  751. if hasClashMatchRule(customRules) {
  752. base["rules"] = customRules
  753. return
  754. }
  755. merged := make([]any, 0, len(customRules)+len(baseRules))
  756. merged = append(merged, customRules...)
  757. merged = append(merged, baseRules...)
  758. base["rules"] = merged
  759. }
  760. func asAnySlice(value any) ([]any, bool) {
  761. switch typed := value.(type) {
  762. case []any:
  763. return typed, true
  764. case []string:
  765. out := make([]any, 0, len(typed))
  766. for _, item := range typed {
  767. out = append(out, item)
  768. }
  769. return out, true
  770. case []map[string]any:
  771. out := make([]any, 0, len(typed))
  772. for _, item := range typed {
  773. out = append(out, item)
  774. }
  775. return out, true
  776. default:
  777. return nil, false
  778. }
  779. }
  780. func hasClashMatchRule(rules []any) bool {
  781. for _, rule := range rules {
  782. ruleText, ok := rule.(string)
  783. if !ok {
  784. continue
  785. }
  786. parts := strings.SplitN(ruleText, ",", 2)
  787. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  788. return true
  789. }
  790. }
  791. return false
  792. }
  793. func linesToClashRules(raw string) []any {
  794. lines := strings.Split(raw, "\n")
  795. rules := make([]any, 0, len(lines))
  796. for _, line := range lines {
  797. line = strings.TrimSpace(line)
  798. if line == "" || strings.HasPrefix(line, "#") {
  799. continue
  800. }
  801. rules = append(rules, line)
  802. }
  803. return rules
  804. }