clash_service.go 22 KB

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