clash_service.go 44 KB

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