clash_service.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  330. switch network {
  331. case "", "tcp":
  332. proxy["network"] = "tcp"
  333. tcp, _ := stream["tcpSettings"].(map[string]any)
  334. if tcp != nil {
  335. header, _ := tcp["header"].(map[string]any)
  336. if header != nil {
  337. typeStr, _ := header["type"].(string)
  338. if typeStr != "" && typeStr != "none" {
  339. return false
  340. }
  341. }
  342. }
  343. return true
  344. case "ws":
  345. proxy["network"] = "ws"
  346. ws, _ := stream["wsSettings"].(map[string]any)
  347. wsOpts := map[string]any{}
  348. if ws != nil {
  349. if path, ok := ws["path"].(string); ok && path != "" {
  350. wsOpts["path"] = path
  351. }
  352. host := ""
  353. if v, ok := ws["host"].(string); ok && v != "" {
  354. host = v
  355. } else if headers, ok := ws["headers"].(map[string]any); ok {
  356. host = searchHost(headers)
  357. }
  358. if host != "" {
  359. wsOpts["headers"] = map[string]any{"Host": host}
  360. }
  361. }
  362. if len(wsOpts) > 0 {
  363. proxy["ws-opts"] = wsOpts
  364. }
  365. return true
  366. case "grpc":
  367. proxy["network"] = "grpc"
  368. grpc, _ := stream["grpcSettings"].(map[string]any)
  369. grpcOpts := map[string]any{}
  370. if grpc != nil {
  371. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  372. grpcOpts["grpc-service-name"] = serviceName
  373. }
  374. }
  375. if len(grpcOpts) > 0 {
  376. proxy["grpc-opts"] = grpcOpts
  377. }
  378. return true
  379. case "httpupgrade":
  380. proxy["network"] = "httpupgrade"
  381. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  382. opts := map[string]any{}
  383. if hu != nil {
  384. if path, ok := hu["path"].(string); ok && path != "" {
  385. opts["path"] = path
  386. }
  387. host := ""
  388. if v, ok := hu["host"].(string); ok && v != "" {
  389. host = v
  390. } else if headers, ok := hu["headers"].(map[string]any); ok {
  391. host = searchHost(headers)
  392. }
  393. if host != "" {
  394. opts["headers"] = map[string]any{"Host": host}
  395. }
  396. }
  397. if len(opts) > 0 {
  398. proxy["http-upgrade-opts"] = opts
  399. }
  400. return true
  401. case "xhttp":
  402. proxy["network"] = "xhttp"
  403. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  404. opts := map[string]any{}
  405. if xhttp != nil {
  406. if path, ok := xhttp["path"].(string); ok && path != "" {
  407. opts["path"] = path
  408. }
  409. host := ""
  410. if v, ok := xhttp["host"].(string); ok && v != "" {
  411. host = v
  412. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  413. host = searchHost(headers)
  414. }
  415. if host != "" {
  416. opts["host"] = host
  417. }
  418. if mode, ok := xhttp["mode"].(string); ok && mode != "" {
  419. opts["mode"] = mode
  420. }
  421. }
  422. if len(opts) > 0 {
  423. proxy["xhttp-opts"] = opts
  424. }
  425. return true
  426. default:
  427. return false
  428. }
  429. }
  430. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  431. switch security {
  432. case "", "none":
  433. proxy["tls"] = false
  434. return true
  435. case "tls":
  436. proxy["tls"] = true
  437. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  438. if tlsSettings != nil {
  439. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  440. proxy["servername"] = serverName
  441. switch proxy["type"] {
  442. case "trojan":
  443. proxy["sni"] = serverName
  444. }
  445. }
  446. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  447. proxy["client-fingerprint"] = fingerprint
  448. }
  449. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  450. out := make([]string, 0, len(alpn))
  451. for _, item := range alpn {
  452. if s, ok := item.(string); ok && s != "" {
  453. out = append(out, s)
  454. }
  455. }
  456. if len(out) > 0 {
  457. proxy["alpn"] = out
  458. }
  459. }
  460. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  461. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  462. proxy["skip-cert-verify"] = true
  463. }
  464. }
  465. }
  466. return true
  467. case "reality":
  468. proxy["tls"] = true
  469. realitySettings, _ := stream["realitySettings"].(map[string]any)
  470. if realitySettings == nil {
  471. return false
  472. }
  473. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  474. proxy["servername"] = serverName
  475. }
  476. realityOpts := map[string]any{}
  477. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  478. realityOpts["public-key"] = publicKey
  479. }
  480. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  481. realityOpts["short-id"] = shortID
  482. }
  483. if len(realityOpts) > 0 {
  484. proxy["reality-opts"] = realityOpts
  485. }
  486. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  487. proxy["client-fingerprint"] = fingerprint
  488. }
  489. return true
  490. default:
  491. return false
  492. }
  493. }
  494. func (s *SubClashService) streamData(stream string) map[string]any {
  495. var streamSettings map[string]any
  496. json.Unmarshal([]byte(stream), &streamSettings)
  497. security, _ := streamSettings["security"].(string)
  498. switch security {
  499. case "tls":
  500. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  501. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  502. }
  503. case "reality":
  504. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  505. streamSettings["realitySettings"] = s.realityData(realitySettings)
  506. }
  507. }
  508. delete(streamSettings, "sockopt")
  509. return streamSettings
  510. }
  511. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  512. tlsData := make(map[string]any, 1)
  513. tlsClientSettings, _ := tData["settings"].(map[string]any)
  514. tlsData["serverName"] = tData["serverName"]
  515. tlsData["alpn"] = tData["alpn"]
  516. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  517. tlsData["fingerprint"] = fingerprint
  518. }
  519. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  520. tlsData["pin-sha256"] = pins
  521. }
  522. return tlsData
  523. }
  524. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  525. rDataOut := make(map[string]any, 1)
  526. realityClientSettings, _ := rData["settings"].(map[string]any)
  527. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  528. rDataOut["publicKey"] = publicKey
  529. }
  530. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  531. rDataOut["fingerprint"] = fingerprint
  532. }
  533. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  534. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  535. }
  536. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  537. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  538. }
  539. return rDataOut
  540. }
  541. func cloneMap(src map[string]any) map[string]any {
  542. if src == nil {
  543. return nil
  544. }
  545. dst := make(map[string]any, len(src))
  546. maps.Copy(dst, src)
  547. return dst
  548. }
  549. func mergeClashRulesYAML(base map[string]any, raw string) error {
  550. raw = strings.TrimSpace(raw)
  551. if raw == "" {
  552. return nil
  553. }
  554. var custom any
  555. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  556. mergeClashRules(base, linesToClashRules(raw))
  557. return nil
  558. }
  559. switch typed := custom.(type) {
  560. case []any:
  561. mergeClashRules(base, typed)
  562. case map[string]any:
  563. for key, value := range typed {
  564. if key == "rules" {
  565. if ruleList, ok := asAnySlice(value); ok {
  566. mergeClashRules(base, ruleList)
  567. }
  568. continue
  569. }
  570. base[key] = value
  571. }
  572. default:
  573. mergeClashRules(base, linesToClashRules(raw))
  574. }
  575. return nil
  576. }
  577. func mergeClashRules(base map[string]any, customRules []any) {
  578. if len(customRules) == 0 {
  579. return
  580. }
  581. baseRules, _ := asAnySlice(base["rules"])
  582. if hasClashMatchRule(customRules) {
  583. base["rules"] = customRules
  584. return
  585. }
  586. merged := make([]any, 0, len(customRules)+len(baseRules))
  587. merged = append(merged, customRules...)
  588. merged = append(merged, baseRules...)
  589. base["rules"] = merged
  590. }
  591. func asAnySlice(value any) ([]any, bool) {
  592. switch typed := value.(type) {
  593. case []any:
  594. return typed, true
  595. case []string:
  596. out := make([]any, 0, len(typed))
  597. for _, item := range typed {
  598. out = append(out, item)
  599. }
  600. return out, true
  601. case []map[string]any:
  602. out := make([]any, 0, len(typed))
  603. for _, item := range typed {
  604. out = append(out, item)
  605. }
  606. return out, true
  607. default:
  608. return nil, false
  609. }
  610. }
  611. func hasClashMatchRule(rules []any) bool {
  612. for _, rule := range rules {
  613. ruleText, ok := rule.(string)
  614. if !ok {
  615. continue
  616. }
  617. parts := strings.SplitN(ruleText, ",", 2)
  618. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  619. return true
  620. }
  621. }
  622. return false
  623. }
  624. func linesToClashRules(raw string) []any {
  625. lines := strings.Split(raw, "\n")
  626. rules := make([]any, 0, len(lines))
  627. for _, line := range lines {
  628. line = strings.TrimSpace(line)
  629. if line == "" || strings.HasPrefix(line, "#") {
  630. continue
  631. }
  632. rules = append(rules, line)
  633. }
  634. return rules
  635. }