clash_service.go 22 KB

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