clash_service.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. package sub
  2. import (
  3. "errors"
  4. "fmt"
  5. "maps"
  6. "net/netip"
  7. "slices"
  8. "strings"
  9. "github.com/goccy/go-json"
  10. yaml "github.com/goccy/go-yaml"
  11. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  14. )
  15. type SubClashService struct {
  16. enableRouting bool
  17. clashRules string
  18. SubService *SubService
  19. }
  20. func NewSubClashService(enableRouting bool, clashRules string, subService *SubService) *SubClashService {
  21. return &SubClashService{enableRouting: enableRouting, clashRules: clashRules, SubService: subService}
  22. }
  23. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  24. subReq := s.SubService.ForRequest(host)
  25. subReq.subscriptionBody = true
  26. inbounds, err := subReq.getInboundsBySubId(subId)
  27. if err != nil {
  28. return "", "", err
  29. }
  30. externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
  31. if err != nil {
  32. return "", "", err
  33. }
  34. if len(inbounds) == 0 && len(externalLinks) == 0 {
  35. return "", "", nil
  36. }
  37. var proxies []map[string]any
  38. var hasInactiveExternal bool
  39. var hasEnabledClient bool
  40. seenEmails := make(map[string]struct{})
  41. for _, inbound := range inbounds {
  42. clients := subReq.matchingClients(inbound, subId)
  43. if len(clients) == 0 {
  44. continue
  45. }
  46. subReq.projectThroughFallbackMaster(inbound)
  47. if hostEps := subReq.hostEndpoints(inbound, "clash"); len(hostEps) > 0 {
  48. injectExternalProxy(inbound, hostEps)
  49. }
  50. for _, client := range clients {
  51. if client.Enable {
  52. hasEnabledClient = true
  53. }
  54. seenEmails[client.Email] = struct{}{}
  55. proxies = append(proxies, s.getProxies(subReq, inbound, client, host)...)
  56. }
  57. }
  58. for _, ext := range externalLinks {
  59. if ext.Enable {
  60. hasEnabledClient = true
  61. }
  62. if !ext.Active {
  63. seenEmails[ext.Email] = struct{}{}
  64. hasInactiveExternal = true
  65. continue
  66. }
  67. for _, el := range expandEntry(ext) {
  68. name := el.Name
  69. if name == "" {
  70. name = ext.Email
  71. }
  72. if proxy := s.clashProxyFromExternal(el.Link, name); proxy != nil {
  73. seenEmails[ext.Email] = struct{}{}
  74. proxies = append(proxies, proxy)
  75. }
  76. }
  77. }
  78. if len(proxies) == 0 && !hasInactiveExternal {
  79. return "", "", nil
  80. }
  81. emails := make([]string, 0, len(seenEmails))
  82. for e := range seenEmails {
  83. emails = append(emails, e)
  84. }
  85. slices.Sort(emails)
  86. traffic, _ := subReq.AggregateTrafficByEmails(emails)
  87. traffic.Enable = hasEnabledClient
  88. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  89. if mode, remark := subReq.resolveInfoNodeRemark(subId, emails, traffic, len(proxies) > 0); mode != infoNodeNone {
  90. dummyProxy := map[string]any{
  91. "name": remark,
  92. "type": "socks5",
  93. "server": "127.0.0.1",
  94. "port": 1080,
  95. }
  96. if mode == infoNodeExpired || mode == infoNodeDepleted {
  97. proxies = []map[string]any{dummyProxy}
  98. } else {
  99. proxies = append([]map[string]any{dummyProxy}, proxies...)
  100. }
  101. }
  102. if len(proxies) == 0 {
  103. return "", header, nil
  104. }
  105. ensureUniqueProxyNames(proxies)
  106. proxyNames := make([]string, 0, len(proxies)+1)
  107. for _, proxy := range proxies {
  108. if isDummyProxy(proxy) && len(proxies) > 1 {
  109. continue
  110. }
  111. if name, ok := proxy["name"].(string); ok && name != "" {
  112. proxyNames = append(proxyNames, name)
  113. }
  114. }
  115. proxyNames = append(proxyNames, "DIRECT")
  116. config := map[string]any{
  117. "proxies": proxies,
  118. "proxy-groups": []map[string]any{{
  119. "name": "PROXY",
  120. "type": "select",
  121. "proxies": proxyNames,
  122. }},
  123. "rules": []string{"MATCH,PROXY"},
  124. }
  125. if s.enableRouting {
  126. resolved, remoteDocument, remote, resolveErr := resolveClashRoutingSource(s.clashRules)
  127. if resolveErr == nil && strings.TrimSpace(resolved) != "" {
  128. if remote {
  129. if err := mergeRemoteClashRules(config, remoteDocument); err != nil {
  130. return "", "", err
  131. }
  132. } else if err := mergeClashRulesYAML(config, resolved); err != nil {
  133. return "", "", err
  134. }
  135. }
  136. }
  137. finalYAML, err := marshalClashYAML(config)
  138. if err != nil {
  139. return "", "", err
  140. }
  141. return string(finalYAML), header, nil
  142. }
  143. // ensureUniqueProxyNames keeps every proxy "name" non-empty and unique:
  144. // mihomo rejects the whole config on a duplicate name (the empty string
  145. // genRemark returns for a remark-less inbound counts), vanishing the Clash
  146. // profile on refresh. See issue #4641.
  147. func ensureUniqueProxyNames(proxies []map[string]any) {
  148. seen := make(map[string]struct{}, len(proxies))
  149. for i, proxy := range proxies {
  150. base, _ := proxy["name"].(string)
  151. if base == "" {
  152. base = fallbackProxyName(proxy, i)
  153. }
  154. name := base
  155. for n := 2; ; n++ {
  156. if _, dup := seen[name]; !dup {
  157. break
  158. }
  159. name = fmt.Sprintf("%s-%d", base, n)
  160. }
  161. seen[name] = struct{}{}
  162. proxy["name"] = name
  163. }
  164. }
  165. func isDummyProxy(proxy map[string]any) bool {
  166. typ, _ := proxy["type"].(string)
  167. server, _ := proxy["server"].(string)
  168. var port int
  169. switch p := proxy["port"].(type) {
  170. case int:
  171. port = p
  172. case float64:
  173. port = int(p)
  174. }
  175. return typ == "socks5" && server == "127.0.0.1" && port == 1080
  176. }
  177. func fallbackProxyName(proxy map[string]any, idx int) string {
  178. typ, _ := proxy["type"].(string)
  179. server, _ := proxy["server"].(string)
  180. if typ != "" && server != "" {
  181. return fmt.Sprintf("%s-%s-%v", typ, server, proxy["port"])
  182. }
  183. return fmt.Sprintf("proxy-%d", idx+1)
  184. }
  185. func (s *SubClashService) getProxies(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []map[string]any {
  186. stream := s.streamData(inbound.StreamSettings)
  187. // For node-managed inbounds the Clash proxy "server" must be the
  188. // node's address, not the request host. resolveInboundAddress handles
  189. // the node→subscriber-host fallback chain.
  190. defaultDest := subReq.resolveInboundAddress(inbound)
  191. if defaultDest == "" {
  192. defaultDest = host
  193. }
  194. externalProxies, ok := stream["externalProxy"].([]any)
  195. hasExternalProxy := ok && len(externalProxies) > 0
  196. if !hasExternalProxy {
  197. externalProxies = []any{map[string]any{
  198. "forceTls": "same",
  199. "dest": defaultDest,
  200. "port": float64(inbound.Port),
  201. "remark": "",
  202. }}
  203. }
  204. delete(stream, "externalProxy")
  205. network, _ := stream["network"].(string)
  206. proxies := make([]map[string]any, 0, len(externalProxies))
  207. for _, ep := range externalProxies {
  208. extPrxy, ok := ep.(map[string]any)
  209. if !ok {
  210. continue
  211. }
  212. // Expand the host's {{VAR}} remark template for this client (no-op for
  213. // the synthetic/legacy entry) before it becomes the proxy name.
  214. subReq.renderHostRemark(inbound, client, extPrxy, network)
  215. workingInbound := *inbound
  216. // A Clash "server" is a bare host, not a URI authority, and the custom
  217. // share address stores IPv6 literals bracketed.
  218. dest, _ := extPrxy["dest"].(string)
  219. workingInbound.Listen = strings.Trim(dest, "[]")
  220. if port, ok := extPrxy["port"].(float64); ok {
  221. workingInbound.Port = int(port)
  222. }
  223. workingStream := cloneStreamForExternalProxy(stream)
  224. forceTls, _ := extPrxy["forceTls"].(string)
  225. switch forceTls {
  226. case "tls":
  227. if workingStream["security"] != "tls" {
  228. workingStream["security"] = "tls"
  229. workingStream["tlsSettings"] = map[string]any{}
  230. }
  231. case "none":
  232. if workingStream["security"] != "none" {
  233. workingStream["security"] = "none"
  234. delete(workingStream, "tlsSettings")
  235. delete(workingStream, "realitySettings")
  236. }
  237. }
  238. security, _ := workingStream["security"].(string)
  239. if hasExternalProxy {
  240. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  241. }
  242. applyHostStreamOverrides(extPrxy, workingStream)
  243. proxy := s.buildProxy(subReq, &workingInbound, client, workingStream, extPrxy)
  244. if len(proxy) > 0 {
  245. // Host-only mihomo knob: ip-version is a top-level proxy field, set
  246. // last so it cannot be clobbered. Absent for legacy externalProxy.
  247. if v, _ := extPrxy["mihomoIpVersion"].(string); v != "" {
  248. proxy["ip-version"] = v
  249. }
  250. proxies = append(proxies, proxy)
  251. }
  252. }
  253. return proxies
  254. }
  255. func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound, client model.Client, stream map[string]any, ep map[string]any) map[string]any {
  256. // Hysteria has its own transport + TLS model, applyTransport /
  257. // applySecurity don't fit.
  258. if inbound.Protocol == model.Hysteria {
  259. return s.buildHysteriaProxy(subReq, inbound, client, ep)
  260. }
  261. if inbound.Protocol == model.WireGuard {
  262. return s.buildWireguardProxy(subReq, inbound, client, ep)
  263. }
  264. if inbound.Protocol == model.AmneziaWG {
  265. return s.buildAmneziaWGProxy(subReq, inbound, client, ep)
  266. }
  267. network, _ := stream["network"].(string)
  268. proxy := map[string]any{
  269. "name": subReq.endpointRemark(inbound, client.Email, ep, network),
  270. "server": inbound.Listen,
  271. "port": inbound.Port,
  272. "udp": true,
  273. }
  274. if !s.applyTransport(proxy, network, stream) {
  275. return nil
  276. }
  277. switch inbound.Protocol {
  278. case model.VMESS:
  279. proxy["type"] = "vmess"
  280. proxy["uuid"] = client.ID
  281. proxy["alterId"] = 0
  282. proxy["cipher"] = normalizeVmessSecurity(client.Security)
  283. case model.VLESS:
  284. proxy["type"] = "vless"
  285. proxy["uuid"] = applyVlessRoute(client.ID, hostVlessRoute(ep))
  286. inboundSettings := subReq.linkSettings(inbound)
  287. streamSecurity, _ := stream["security"].(string)
  288. if client.Flow != "" && !inbound.DisableFlow && vlessFlowAllowed(network, streamSecurity, inboundSettings) {
  289. proxy["flow"] = client.Flow
  290. }
  291. if encryption, ok := inboundSettings["encryption"].(string); ok {
  292. encryption = strings.TrimSpace(encryption)
  293. if encryption != "" && encryption != "none" {
  294. proxy["encryption"] = encryption
  295. }
  296. }
  297. case model.Trojan:
  298. proxy["type"] = "trojan"
  299. proxy["password"] = client.Password
  300. case model.Shadowsocks:
  301. proxy["type"] = "ss"
  302. proxy["password"] = client.Password
  303. inboundSettings := subReq.linkSettings(inbound)
  304. method, _ := inboundSettings["method"].(string)
  305. if method == "" {
  306. return nil
  307. }
  308. proxy["cipher"] = method
  309. if strings.HasPrefix(method, "2022") {
  310. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  311. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  312. }
  313. }
  314. default:
  315. return nil
  316. }
  317. security, _ := stream["security"].(string)
  318. if !s.applySecurity(proxy, security, stream) {
  319. return nil
  320. }
  321. return proxy
  322. }
  323. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  324. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  325. // directly instead of going through streamData/tlsData, because those
  326. // helpers prune fields (like `allowInsecure` / the salamander obfs
  327. // block) that the hysteria proxy wants preserved.
  328. func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  329. inboundSettings := subReq.linkSettings(inbound)
  330. proxyType := "hysteria2"
  331. authKey := "password"
  332. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  333. proxyType = "hysteria"
  334. authKey = "auth-str"
  335. }
  336. proxy := map[string]any{
  337. "name": subReq.endpointRemark(inbound, client.Email, ep, "quic"),
  338. "type": proxyType,
  339. "server": inbound.Listen,
  340. "port": inbound.Port,
  341. "udp": true,
  342. authKey: client.Auth,
  343. }
  344. var rawStream map[string]any
  345. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  346. // TLS details — hysteria always uses TLS.
  347. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  348. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  349. proxy["sni"] = serverName
  350. }
  351. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  352. out := make([]string, 0, len(alpnList))
  353. for _, a := range alpnList {
  354. if s, ok := a.(string); ok && s != "" {
  355. out = append(out, s)
  356. }
  357. }
  358. if len(out) > 0 {
  359. proxy["alpn"] = out
  360. }
  361. }
  362. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  363. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  364. proxy["skip-cert-verify"] = true
  365. }
  366. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  367. proxy["client-fingerprint"] = fp
  368. }
  369. }
  370. }
  371. if insecure, ok := ep["allowInsecure"].(bool); ok && insecure {
  372. proxy["skip-cert-verify"] = true
  373. }
  374. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  375. // block the subscription link generator uses.
  376. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  377. if udpMasks, ok := finalmask["udp"].([]any); ok {
  378. for _, m := range udpMasks {
  379. mask, _ := m.(map[string]any)
  380. if mask == nil || mask["type"] != "salamander" {
  381. continue
  382. }
  383. settings, _ := mask["settings"].(map[string]any)
  384. if pw, ok := settings["password"].(string); ok && pw != "" {
  385. proxy["obfs"] = "salamander"
  386. proxy["obfs-password"] = pw
  387. break
  388. }
  389. }
  390. }
  391. }
  392. // UDP port hopping. mihomo reads the range from a dedicated `ports`
  393. // field (the base `port` stays as the redirect target).
  394. if hopPorts := hysteriaHopPorts(rawStream); hopPorts != "" {
  395. proxy["ports"] = hopPorts
  396. }
  397. return proxy
  398. }
  399. // buildWireguardProxy produces a mihomo-compatible Clash entry for a native
  400. // WireGuard inbound, mirroring genWireguardLink: the peer public key is derived
  401. // from the inbound secretKey, while the private key, tunnel address, and
  402. // pre-shared key come from the client. Returns nil when the client has no key.
  403. func (s *SubClashService) buildWireguardProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  404. if client.PrivateKey == "" {
  405. return nil
  406. }
  407. var inboundSettings map[string]any
  408. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  409. secretKey, _ := inboundSettings["secretKey"].(string)
  410. proxy := map[string]any{
  411. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  412. "type": "wireguard",
  413. "server": inbound.Listen,
  414. "port": inbound.Port,
  415. "udp": true,
  416. "private-key": client.PrivateKey,
  417. }
  418. if secretKey != "" {
  419. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  420. proxy["public-key"] = pub
  421. }
  422. }
  423. if client.PreSharedKey != "" {
  424. proxy["pre-shared-key"] = client.PreSharedKey
  425. }
  426. if client.KeepAlive > 0 {
  427. proxy["persistent-keepalive"] = client.KeepAlive
  428. }
  429. for _, addr := range client.AllowedIPs {
  430. ip := stripCIDR(addr)
  431. if ip == "" {
  432. continue
  433. }
  434. if strings.Contains(ip, ":") {
  435. proxy["ipv6"] = ip
  436. } else {
  437. proxy["ip"] = ip
  438. }
  439. }
  440. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  441. proxy["mtu"] = int(mtu)
  442. }
  443. if dns, _ := inboundSettings["dns"].(string); dns != "" {
  444. servers := make([]string, 0)
  445. for server := range strings.SplitSeq(dns, ",") {
  446. if server = strings.TrimSpace(server); server != "" {
  447. servers = append(servers, server)
  448. }
  449. }
  450. if len(servers) > 0 {
  451. proxy["dns"] = servers
  452. }
  453. }
  454. return proxy
  455. }
  456. // amneziaWGClientAddresses prefers this inbound's own settings entry over the
  457. // shared clients.wg_allowed_ips column, which for an identity attached to both
  458. // a wireguard and an amneziawg inbound holds the other one's address.
  459. func amneziaWGClientAddresses(settingsClients []model.Client, client model.Client) []string {
  460. for i := range settingsClients {
  461. if !strings.EqualFold(settingsClients[i].Email, client.Email) {
  462. continue
  463. }
  464. if len(settingsClients[i].AllowedIPs) > 0 {
  465. return settingsClients[i].AllowedIPs
  466. }
  467. break
  468. }
  469. return client.AllowedIPs
  470. }
  471. // allBareIPs reports whether every entry is a plain IP address — no port,
  472. // scheme, and no zone, which mihomo brackets into a udp:// URL it then rejects.
  473. func allBareIPs(servers []string) bool {
  474. for _, s := range servers {
  475. addr, err := netip.ParseAddr(s)
  476. if err != nil || addr.Zone() != "" {
  477. return false
  478. }
  479. }
  480. return true
  481. }
  482. // buildAmneziaWGProxy emits a mihomo Clash entry for an AmneziaWG inbound:
  483. // type stays "wireguard", the obfuscation rides in amnezia-wg-option.
  484. func (s *SubClashService) buildAmneziaWGProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  485. if client.PrivateKey == "" {
  486. return nil
  487. }
  488. var parsed amneziawg.InboundSettings
  489. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
  490. return nil
  491. }
  492. server := parsed.Server
  493. proxy := map[string]any{
  494. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  495. "type": "wireguard",
  496. "server": inbound.Listen,
  497. "port": inbound.Port,
  498. "udp": true,
  499. "private-key": client.PrivateKey,
  500. }
  501. if server.PublicKey != "" {
  502. proxy["public-key"] = server.PublicKey
  503. }
  504. if client.PreSharedKey != "" {
  505. proxy["pre-shared-key"] = client.PreSharedKey
  506. }
  507. if client.KeepAlive > 0 {
  508. proxy["persistent-keepalive"] = client.KeepAlive
  509. }
  510. for _, addr := range amneziaWGClientAddresses(parsed.Clients, client) {
  511. ip := stripCIDR(addr)
  512. if ip == "" {
  513. continue
  514. }
  515. if strings.Contains(ip, ":") {
  516. proxy["ipv6"] = ip
  517. } else {
  518. proxy["ip"] = ip
  519. }
  520. }
  521. // Always emitted: mihomo's own 1408 default sits above the interface
  522. // amneziawgnet actually runs once s4 passes 12, so the tunnel fragments.
  523. proxy["mtu"] = amneziawg.EffectiveMTU(server.MTU, server.S4)
  524. var dns []string
  525. if server.PrimaryDNS != "" {
  526. dns = append(dns, server.PrimaryDNS)
  527. }
  528. if server.SecondaryDNS != "" {
  529. dns = append(dns, server.SecondaryDNS)
  530. }
  531. if len(dns) > 0 {
  532. proxy["dns"] = dns
  533. // mihomo ignores dns without this flag, but aborts the whole config on
  534. // a value its dns.ParseNameServer rejects, so only bare IPs opt in.
  535. if allBareIPs(dns) {
  536. proxy["remote-dns-resolve"] = true
  537. }
  538. }
  539. awg := map[string]any{}
  540. if server.Jc != 0 {
  541. awg["jc"] = server.Jc
  542. }
  543. if server.Jmin != 0 {
  544. awg["jmin"] = server.Jmin
  545. }
  546. if server.Jmax != 0 {
  547. awg["jmax"] = server.Jmax
  548. }
  549. if server.S1 != 0 {
  550. awg["s1"] = server.S1
  551. }
  552. if server.S2 != 0 {
  553. awg["s2"] = server.S2
  554. }
  555. if server.S3 != 0 {
  556. awg["s3"] = server.S3
  557. }
  558. if server.S4 != 0 {
  559. awg["s4"] = server.S4
  560. }
  561. if server.H1 != "" {
  562. awg["h1"] = server.H1
  563. }
  564. if server.H2 != "" {
  565. awg["h2"] = server.H2
  566. }
  567. if server.H3 != "" {
  568. awg["h3"] = server.H3
  569. }
  570. if server.H4 != "" {
  571. awg["h4"] = server.H4
  572. }
  573. for i, v := range []string{server.I1, server.I2, server.I3, server.I4, server.I5} {
  574. if v != "" {
  575. awg[fmt.Sprintf("i%d", i+1)] = v
  576. }
  577. }
  578. needsV3 := false
  579. if server.HeaderProtectionKey != "" {
  580. awg["header-protection-key"] = server.HeaderProtectionKey
  581. needsV3 = true
  582. }
  583. if server.ContentPaddingAddition != "" {
  584. awg["content-padding-addition"] = server.ContentPaddingAddition
  585. needsV3 = true
  586. }
  587. if server.RekeyAfterTime != "" {
  588. awg["rekey-after-time"] = server.RekeyAfterTime
  589. needsV3 = true
  590. }
  591. if server.RekeyTimeout != "" {
  592. awg["rekey-timeout"] = server.RekeyTimeout
  593. needsV3 = true
  594. }
  595. if server.RejectAfterTime != "" {
  596. awg["reject-after-time"] = server.RejectAfterTime
  597. needsV3 = true
  598. }
  599. if server.KeepaliveTimeout != "" {
  600. awg["keepalive-timeout"] = server.KeepaliveTimeout
  601. needsV3 = true
  602. }
  603. if server.MaxHandshakeAttempts != "" {
  604. awg["max-handshake-attempts"] = server.MaxHandshakeAttempts
  605. needsV3 = true
  606. }
  607. if server.RandomTrailers {
  608. awg["random-trailers"] = true
  609. needsV3 = true
  610. }
  611. if server.DisableCookies {
  612. awg["disable-cookies"] = true
  613. needsV3 = true
  614. }
  615. if needsV3 {
  616. awg["version"] = 3
  617. }
  618. if len(awg) > 0 {
  619. proxy["amnezia-wg-option"] = awg
  620. }
  621. return proxy
  622. }
  623. // buildXhttpClashOpts converts xhttpSettings from 3x-ui's camelCase JSON
  624. // storage into the kebab-case map that Mihomo expects under xhttp-opts.
  625. //
  626. // Only client-relevant fields are included (allowlist approach).
  627. // Server-only fields (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  628. // serverMaxHeaderBytes) are automatically excluded because they are not in
  629. // the mapping. This is intentional — when Mihomo adds new fields, the mapping
  630. // must be updated explicitly rather than leaking unverified fields to clients.
  631. //
  632. // Returns nil if no non-trivial fields are present.
  633. func buildXhttpClashOpts(xhttp map[string]any) map[string]any {
  634. if xhttp == nil {
  635. return nil
  636. }
  637. opts := map[string]any{}
  638. // Direct fields: path, mode
  639. if v, ok := xhttp["path"].(string); ok && v != "" {
  640. opts["path"] = v
  641. }
  642. if v, ok := xhttp["mode"].(string); ok && v != "" {
  643. opts["mode"] = v
  644. }
  645. // Host: explicit host field wins, then fall back to headers.Host
  646. host := ""
  647. if v, ok := xhttp["host"].(string); ok && v != "" {
  648. host = v
  649. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  650. host = searchHost(headers)
  651. }
  652. if host != "" {
  653. opts["host"] = host
  654. }
  655. type xhttpStringField struct{ src, dst, skipValue string }
  656. stringFields := []xhttpStringField{
  657. {"xPaddingBytes", "x-padding-bytes", ""},
  658. {"uplinkHTTPMethod", "uplink-http-method", ""},
  659. {"sessionIDPlacement", "session-id-placement", ""},
  660. {"sessionIDKey", "session-id-key", ""},
  661. {"sessionIDTable", "session-id-table", ""},
  662. {"sessionIDLength", "session-id-length", ""},
  663. {"seqPlacement", "seq-placement", ""},
  664. {"seqKey", "seq-key", ""},
  665. {"uplinkDataPlacement", "uplink-data-placement", ""},
  666. {"uplinkDataKey", "uplink-data-key", ""},
  667. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  668. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  669. }
  670. for _, f := range stringFields {
  671. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  672. opts[f.dst] = v
  673. }
  674. }
  675. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  676. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  677. // frontend migration.
  678. for _, f := range []xhttpStringField{
  679. {"sessionPlacement", "session-id-placement", ""},
  680. {"sessionKey", "session-id-key", ""},
  681. } {
  682. if _, exists := opts[f.dst]; exists {
  683. continue
  684. }
  685. if v, ok := xhttp[f.src].(string); ok && v != "" {
  686. opts[f.dst] = v
  687. }
  688. }
  689. // Bool fields (truthy only)
  690. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  691. opts["no-grpc-header"] = true
  692. }
  693. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  694. opts["x-padding-obfs-mode"] = true
  695. // Padding obfs gated fields
  696. for _, field := range []struct{ src, dst string }{
  697. {"xPaddingKey", "x-padding-key"},
  698. {"xPaddingHeader", "x-padding-header"},
  699. {"xPaddingPlacement", "x-padding-placement"},
  700. {"xPaddingMethod", "x-padding-method"},
  701. } {
  702. if v, ok := xhttp[field.src].(string); ok && v != "" {
  703. opts[field.dst] = v
  704. }
  705. }
  706. }
  707. // Non-zero value fields
  708. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  709. opts["uplink-chunk-size"] = v
  710. }
  711. // Nested object: xmux → reuse-settings
  712. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  713. reuse := map[string]any{}
  714. for _, f := range []struct{ src, dst string }{
  715. {"maxConcurrency", "max-concurrency"},
  716. {"maxConnections", "max-connections"},
  717. {"cMaxReuseTimes", "c-max-reuse-times"},
  718. {"hMaxRequestTimes", "h-max-request-times"},
  719. {"hMaxReusableSecs", "h-max-reusable-secs"},
  720. } {
  721. if v, ok := xmux[f.src].(string); ok && v != "" {
  722. reuse[f.dst] = v
  723. }
  724. }
  725. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  726. reuse["h-keep-alive-period"] = v
  727. }
  728. if len(reuse) > 0 {
  729. opts["reuse-settings"] = reuse
  730. }
  731. }
  732. // Headers (drop Host key)
  733. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  734. out := map[string]any{}
  735. for k, v := range rawHeaders {
  736. if strings.EqualFold(k, "host") {
  737. continue
  738. }
  739. out[k] = v
  740. }
  741. if len(out) > 0 {
  742. opts["headers"] = out
  743. }
  744. }
  745. if len(opts) == 0 {
  746. return nil
  747. }
  748. return opts
  749. }
  750. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  751. switch network {
  752. case "", "tcp":
  753. proxy["network"] = "tcp"
  754. tcp, _ := stream["tcpSettings"].(map[string]any)
  755. if tcp != nil {
  756. header, _ := tcp["header"].(map[string]any)
  757. if header != nil {
  758. typeStr, _ := header["type"].(string)
  759. if typeStr != "" && typeStr != "none" {
  760. return false
  761. }
  762. }
  763. }
  764. return true
  765. case "ws":
  766. proxy["network"] = "ws"
  767. ws, _ := stream["wsSettings"].(map[string]any)
  768. wsOpts := map[string]any{}
  769. if ws != nil {
  770. if path, ok := ws["path"].(string); ok && path != "" {
  771. wsOpts["path"] = path
  772. }
  773. host := ""
  774. if v, ok := ws["host"].(string); ok && v != "" {
  775. host = v
  776. } else if headers, ok := ws["headers"].(map[string]any); ok {
  777. host = searchHost(headers)
  778. }
  779. if host != "" {
  780. wsOpts["headers"] = map[string]any{"Host": host}
  781. }
  782. }
  783. if len(wsOpts) > 0 {
  784. proxy["ws-opts"] = wsOpts
  785. }
  786. return true
  787. case "grpc":
  788. proxy["network"] = "grpc"
  789. grpc, _ := stream["grpcSettings"].(map[string]any)
  790. grpcOpts := map[string]any{}
  791. if grpc != nil {
  792. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  793. grpcOpts["grpc-service-name"] = serviceName
  794. }
  795. }
  796. if len(grpcOpts) > 0 {
  797. proxy["grpc-opts"] = grpcOpts
  798. }
  799. return true
  800. case "httpupgrade":
  801. proxy["network"] = "httpupgrade"
  802. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  803. opts := map[string]any{}
  804. if hu != nil {
  805. if path, ok := hu["path"].(string); ok && path != "" {
  806. opts["path"] = path
  807. }
  808. host := ""
  809. if v, ok := hu["host"].(string); ok && v != "" {
  810. host = v
  811. } else if headers, ok := hu["headers"].(map[string]any); ok {
  812. host = searchHost(headers)
  813. }
  814. if host != "" {
  815. opts["headers"] = map[string]any{"Host": host}
  816. }
  817. }
  818. if len(opts) > 0 {
  819. proxy["http-upgrade-opts"] = opts
  820. }
  821. return true
  822. case "xhttp":
  823. proxy["network"] = "xhttp"
  824. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  825. opts := buildXhttpClashOpts(xhttp)
  826. if opts != nil {
  827. proxy["xhttp-opts"] = opts
  828. }
  829. return true
  830. default:
  831. return false
  832. }
  833. }
  834. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  835. switch security {
  836. case "", "none":
  837. proxy["tls"] = false
  838. return true
  839. case "tls":
  840. proxy["tls"] = true
  841. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  842. if tlsSettings != nil {
  843. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  844. proxy["servername"] = serverName
  845. switch proxy["type"] {
  846. case "trojan":
  847. proxy["sni"] = serverName
  848. }
  849. }
  850. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  851. proxy["client-fingerprint"] = fingerprint
  852. }
  853. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  854. out := make([]string, 0, len(alpn))
  855. for _, item := range alpn {
  856. if s, ok := item.(string); ok && s != "" {
  857. out = append(out, s)
  858. }
  859. }
  860. if len(out) > 0 {
  861. proxy["alpn"] = out
  862. }
  863. }
  864. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  865. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  866. proxy["skip-cert-verify"] = true
  867. }
  868. }
  869. if pins, ok := tlsSettings["pin-sha256"].([]any); ok && len(pins) > 0 {
  870. proxy["pin-sha256"] = pins
  871. }
  872. }
  873. return true
  874. case "reality":
  875. proxy["tls"] = true
  876. realitySettings, _ := stream["realitySettings"].(map[string]any)
  877. if realitySettings == nil {
  878. return false
  879. }
  880. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  881. proxy["servername"] = serverName
  882. }
  883. realityOpts := map[string]any{}
  884. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  885. realityOpts["public-key"] = publicKey
  886. }
  887. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  888. realityOpts["short-id"] = shortID
  889. }
  890. if len(realityOpts) > 0 {
  891. proxy["reality-opts"] = realityOpts
  892. }
  893. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  894. proxy["client-fingerprint"] = fingerprint
  895. }
  896. return true
  897. default:
  898. return false
  899. }
  900. }
  901. func (s *SubClashService) streamData(stream string) map[string]any {
  902. var streamSettings map[string]any
  903. _ = json.Unmarshal([]byte(stream), &streamSettings)
  904. security, _ := streamSettings["security"].(string)
  905. switch security {
  906. case "tls":
  907. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  908. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  909. }
  910. case "reality":
  911. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  912. streamSettings["realitySettings"] = s.realityData(realitySettings)
  913. }
  914. }
  915. delete(streamSettings, "sockopt")
  916. return streamSettings
  917. }
  918. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  919. tlsData := make(map[string]any, 1)
  920. tlsClientSettings, _ := tData["settings"].(map[string]any)
  921. tlsData["serverName"] = tData["serverName"]
  922. tlsData["alpn"] = tData["alpn"]
  923. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  924. tlsData["fingerprint"] = fingerprint
  925. }
  926. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  927. tlsData["pin-sha256"] = pins
  928. }
  929. return tlsData
  930. }
  931. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  932. rDataOut := make(map[string]any, 1)
  933. realityClientSettings, _ := rData["settings"].(map[string]any)
  934. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  935. rDataOut["publicKey"] = publicKey
  936. }
  937. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  938. rDataOut["fingerprint"] = fingerprint
  939. }
  940. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  941. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  942. }
  943. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  944. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  945. }
  946. return rDataOut
  947. }
  948. func cloneMap(src map[string]any) map[string]any {
  949. if src == nil {
  950. return nil
  951. }
  952. dst := make(map[string]any, len(src))
  953. maps.Copy(dst, src)
  954. return dst
  955. }
  956. func mergeClashRulesYAML(base map[string]any, raw string) error {
  957. raw = strings.TrimSpace(raw)
  958. if raw == "" {
  959. return nil
  960. }
  961. var custom any
  962. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  963. mergeClashRules(base, linesToClashRules(raw))
  964. return nil
  965. }
  966. switch typed := custom.(type) {
  967. case []any:
  968. mergeClashRules(base, typed)
  969. case map[string]any:
  970. for key, value := range typed {
  971. if key == "rules" {
  972. if ruleList, ok := asAnySlice(value); ok {
  973. mergeClashRules(base, ruleList)
  974. }
  975. continue
  976. }
  977. base[key] = value
  978. }
  979. default:
  980. mergeClashRules(base, linesToClashRules(raw))
  981. }
  982. return nil
  983. }
  984. // mergeRemoteClashRules lets remote update only the route graph (see
  985. // remoteClashAllowedKey) and never mutates remote: cached documents are shared.
  986. func mergeRemoteClashRules(base map[string]any, remote map[string]any) error {
  987. if len(remote) == 0 {
  988. return fmt.Errorf("remote Clash routing source must be a YAML map")
  989. }
  990. for key, value := range remote {
  991. if !remoteClashAllowedKey(key) {
  992. continue
  993. }
  994. if err := validateRemoteClashValue(key, value); err != nil {
  995. return err
  996. }
  997. switch key {
  998. case "rules":
  999. rules, _ := asAnySlice(value)
  1000. mergeClashRules(base, rules)
  1001. case "proxy-groups":
  1002. groups, _ := asAnySlice(value)
  1003. base["proxy-groups"] = mergeClashProxyGroups(base["proxy-groups"], groups)
  1004. default:
  1005. base[key] = value
  1006. }
  1007. }
  1008. return validateClashRouteGraph(base)
  1009. }
  1010. func validateRemoteClashValue(key string, value any) error {
  1011. switch key {
  1012. case "rules":
  1013. rules, ok := asAnySlice(value)
  1014. if !ok {
  1015. return fmt.Errorf("remote Clash rules must be a list")
  1016. }
  1017. for _, rule := range rules {
  1018. text, ok := rule.(string)
  1019. if !ok || strings.TrimSpace(text) == "" {
  1020. return fmt.Errorf("remote Clash rules must contain non-empty strings")
  1021. }
  1022. }
  1023. case "proxy-groups":
  1024. groups, ok := asAnySlice(value)
  1025. if !ok {
  1026. return fmt.Errorf("remote Clash proxy-groups must be a list")
  1027. }
  1028. seen := make(map[string]struct{}, len(groups))
  1029. for _, groupValue := range groups {
  1030. group, ok := groupValue.(map[string]any)
  1031. if !ok {
  1032. return fmt.Errorf("remote Clash proxy-groups must contain named group maps with a type")
  1033. }
  1034. name, nameOK := group["name"].(string)
  1035. groupType, typeOK := group["type"].(string)
  1036. if !nameOK || !typeOK || strings.TrimSpace(name) == "" || strings.TrimSpace(groupType) == "" {
  1037. return fmt.Errorf("remote Clash proxy-groups must contain named group maps with a type")
  1038. }
  1039. name = strings.TrimSpace(name)
  1040. if _, duplicate := seen[name]; duplicate {
  1041. return fmt.Errorf("remote Clash proxy-group name %q is duplicated", name)
  1042. }
  1043. seen[name] = struct{}{}
  1044. if useValue, exists := group["use"]; exists {
  1045. use, ok := asAnySlice(useValue)
  1046. if !ok || len(use) > 0 {
  1047. return fmt.Errorf("remote Clash proxy-group %q cannot use proxy-providers", name)
  1048. }
  1049. }
  1050. }
  1051. case "rule-providers":
  1052. providers, ok := value.(map[string]any)
  1053. if !ok {
  1054. return fmt.Errorf("remote Clash rule-providers must be a map")
  1055. }
  1056. for name, provider := range providers {
  1057. if strings.TrimSpace(name) == "" {
  1058. return fmt.Errorf("remote Clash rule-provider name must not be empty")
  1059. }
  1060. if _, ok := provider.(map[string]any); !ok {
  1061. return fmt.Errorf("remote Clash rule-provider %q must be a map", name)
  1062. }
  1063. }
  1064. }
  1065. return nil
  1066. }
  1067. func remoteClashAllowedKey(key string) bool {
  1068. switch key {
  1069. case "proxy-groups", "rule-providers", "rules":
  1070. return true
  1071. default:
  1072. return false
  1073. }
  1074. }
  1075. func validateClashRouteGraph(config map[string]any) error {
  1076. known := map[string]struct{}{
  1077. "DIRECT": {}, "REJECT": {}, "REJECT-DROP": {}, "REJECT-TINYGIF": {}, "PASS": {}, "GLOBAL": {},
  1078. }
  1079. if proxies, ok := asAnySlice(config["proxies"]); ok {
  1080. for _, value := range proxies {
  1081. proxy, ok := value.(map[string]any)
  1082. if !ok {
  1083. continue
  1084. }
  1085. if name, ok := proxy["name"].(string); ok && strings.TrimSpace(name) != "" {
  1086. known[strings.TrimSpace(name)] = struct{}{}
  1087. }
  1088. }
  1089. }
  1090. groups, _ := asAnySlice(config["proxy-groups"])
  1091. for _, value := range groups {
  1092. if name := clashProxyGroupName(value); name != "" {
  1093. known[name] = struct{}{}
  1094. }
  1095. }
  1096. for _, value := range groups {
  1097. group, ok := value.(map[string]any)
  1098. if !ok {
  1099. continue
  1100. }
  1101. name := clashProxyGroupName(group)
  1102. refs, exists := group["proxies"]
  1103. if !exists {
  1104. continue
  1105. }
  1106. proxies, ok := asAnySlice(refs)
  1107. if !ok {
  1108. return fmt.Errorf("Clash proxy-group %q proxies must be a list", name)
  1109. }
  1110. for _, refValue := range proxies {
  1111. ref, ok := refValue.(string)
  1112. if !ok || strings.TrimSpace(ref) == "" {
  1113. return fmt.Errorf("Clash proxy-group %q contains an invalid proxy reference", name)
  1114. }
  1115. ref = strings.TrimSpace(ref)
  1116. if _, exists := known[ref]; !exists {
  1117. return fmt.Errorf("Clash proxy-group %q references unknown proxy or group %q", name, ref)
  1118. }
  1119. }
  1120. }
  1121. providers, _ := config["rule-providers"].(map[string]any)
  1122. for providerName, value := range providers {
  1123. provider, ok := value.(map[string]any)
  1124. if !ok {
  1125. continue
  1126. }
  1127. via, ok := provider["proxy"].(string)
  1128. if !ok || strings.TrimSpace(via) == "" {
  1129. continue
  1130. }
  1131. via = strings.TrimSpace(via)
  1132. if _, exists := known[via]; !exists {
  1133. return fmt.Errorf("Clash rule-provider %q references unknown proxy or group %q", providerName, via)
  1134. }
  1135. }
  1136. rules, _ := asAnySlice(config["rules"])
  1137. for _, value := range rules {
  1138. rule, ok := value.(string)
  1139. if !ok || strings.TrimSpace(rule) == "" {
  1140. return errors.New("Clash rules must contain non-empty strings")
  1141. }
  1142. parts := strings.Split(rule, ",")
  1143. for i := range parts {
  1144. parts[i] = strings.TrimSpace(parts[i])
  1145. }
  1146. if len(parts) < 2 {
  1147. return fmt.Errorf("invalid Clash rule %q", rule)
  1148. }
  1149. if strings.EqualFold(parts[0], "RULE-SET") {
  1150. if len(parts) < 3 {
  1151. return fmt.Errorf("invalid Clash RULE-SET rule %q", rule)
  1152. }
  1153. if _, exists := providers[parts[1]]; !exists {
  1154. return fmt.Errorf("Clash rule references unknown rule-provider %q", parts[1])
  1155. }
  1156. }
  1157. targetIndex := len(parts) - 1
  1158. // Mihomo IP rules may carry trailing no-resolve / src option flags.
  1159. for targetIndex >= 1 && (strings.EqualFold(parts[targetIndex], "no-resolve") || strings.EqualFold(parts[targetIndex], "src")) {
  1160. targetIndex--
  1161. }
  1162. if targetIndex < 1 {
  1163. return fmt.Errorf("invalid Clash rule target in %q", rule)
  1164. }
  1165. target := parts[targetIndex]
  1166. if _, exists := known[target]; !exists {
  1167. return fmt.Errorf("Clash rule references unknown proxy or group %q", target)
  1168. }
  1169. }
  1170. return nil
  1171. }
  1172. func mergeClashProxyGroups(baseValue any, remoteGroups []any) []any {
  1173. baseGroups, _ := asAnySlice(baseValue)
  1174. baseByName := make(map[string]any, len(baseGroups))
  1175. baseOrder := make([]string, 0, len(baseGroups))
  1176. for _, group := range baseGroups {
  1177. name := clashProxyGroupName(group)
  1178. if name == "" {
  1179. continue
  1180. }
  1181. baseByName[name] = group
  1182. baseOrder = append(baseOrder, name)
  1183. }
  1184. merged := make([]any, 0, len(remoteGroups)+len(baseGroups))
  1185. seen := make(map[string]struct{}, len(remoteGroups)+len(baseGroups))
  1186. for _, group := range remoteGroups {
  1187. name := clashProxyGroupName(group)
  1188. if name == "" {
  1189. continue
  1190. }
  1191. if _, duplicate := seen[name]; duplicate {
  1192. continue
  1193. }
  1194. seen[name] = struct{}{}
  1195. merged = append(merged, group)
  1196. }
  1197. for _, name := range baseOrder {
  1198. if _, replaced := seen[name]; replaced {
  1199. continue
  1200. }
  1201. merged = append(merged, baseByName[name])
  1202. }
  1203. return merged
  1204. }
  1205. func clashProxyGroupName(value any) string {
  1206. group, ok := value.(map[string]any)
  1207. if !ok {
  1208. return ""
  1209. }
  1210. name, _ := group["name"].(string)
  1211. return strings.TrimSpace(name)
  1212. }
  1213. func mergeClashRules(base map[string]any, customRules []any) {
  1214. if len(customRules) == 0 {
  1215. return
  1216. }
  1217. baseRules, _ := asAnySlice(base["rules"])
  1218. if hasClashMatchRule(customRules) {
  1219. base["rules"] = customRules
  1220. return
  1221. }
  1222. merged := make([]any, 0, len(customRules)+len(baseRules))
  1223. merged = append(merged, customRules...)
  1224. merged = append(merged, baseRules...)
  1225. base["rules"] = merged
  1226. }
  1227. func asAnySlice(value any) ([]any, bool) {
  1228. switch typed := value.(type) {
  1229. case []any:
  1230. return typed, true
  1231. case []string:
  1232. out := make([]any, 0, len(typed))
  1233. for _, item := range typed {
  1234. out = append(out, item)
  1235. }
  1236. return out, true
  1237. case []map[string]any:
  1238. out := make([]any, 0, len(typed))
  1239. for _, item := range typed {
  1240. out = append(out, item)
  1241. }
  1242. return out, true
  1243. default:
  1244. return nil, false
  1245. }
  1246. }
  1247. func hasClashMatchRule(rules []any) bool {
  1248. for _, rule := range rules {
  1249. ruleText, ok := rule.(string)
  1250. if !ok {
  1251. continue
  1252. }
  1253. parts := strings.SplitN(ruleText, ",", 2)
  1254. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  1255. return true
  1256. }
  1257. }
  1258. return false
  1259. }
  1260. func linesToClashRules(raw string) []any {
  1261. lines := strings.Split(raw, "\n")
  1262. rules := make([]any, 0, len(lines))
  1263. for _, line := range lines {
  1264. line = strings.TrimSpace(line)
  1265. if line == "" || strings.HasPrefix(line, "#") {
  1266. continue
  1267. }
  1268. rules = append(rules, line)
  1269. }
  1270. return rules
  1271. }