clash_service.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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"] = applyVlessRoute(client.ID, hostVlessRoute(ep))
  217. inboundSettings := subReq.linkSettings(inbound)
  218. streamSecurity, _ := stream["security"].(string)
  219. if client.Flow != "" && vlessFlowAllowed(network, streamSecurity, inboundSettings) {
  220. proxy["flow"] = client.Flow
  221. }
  222. if encryption, ok := inboundSettings["encryption"].(string); ok {
  223. encryption = strings.TrimSpace(encryption)
  224. if encryption != "" && encryption != "none" {
  225. proxy["encryption"] = encryption
  226. }
  227. }
  228. case model.Trojan:
  229. proxy["type"] = "trojan"
  230. proxy["password"] = client.Password
  231. case model.Shadowsocks:
  232. proxy["type"] = "ss"
  233. proxy["password"] = client.Password
  234. inboundSettings := subReq.linkSettings(inbound)
  235. method, _ := inboundSettings["method"].(string)
  236. if method == "" {
  237. return nil
  238. }
  239. proxy["cipher"] = method
  240. if strings.HasPrefix(method, "2022") {
  241. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  242. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  243. }
  244. }
  245. default:
  246. return nil
  247. }
  248. security, _ := stream["security"].(string)
  249. if !s.applySecurity(proxy, security, stream) {
  250. return nil
  251. }
  252. return proxy
  253. }
  254. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  255. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  256. // directly instead of going through streamData/tlsData, because those
  257. // helpers prune fields (like `allowInsecure` / the salamander obfs
  258. // block) that the hysteria proxy wants preserved.
  259. func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  260. inboundSettings := subReq.linkSettings(inbound)
  261. proxyType := "hysteria2"
  262. authKey := "password"
  263. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  264. proxyType = "hysteria"
  265. authKey = "auth-str"
  266. }
  267. proxy := map[string]any{
  268. "name": subReq.endpointRemark(inbound, client.Email, ep, "quic"),
  269. "type": proxyType,
  270. "server": inbound.Listen,
  271. "port": inbound.Port,
  272. "udp": true,
  273. authKey: client.Auth,
  274. }
  275. var rawStream map[string]any
  276. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  277. // TLS details — hysteria always uses TLS.
  278. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  279. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  280. proxy["sni"] = serverName
  281. }
  282. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  283. out := make([]string, 0, len(alpnList))
  284. for _, a := range alpnList {
  285. if s, ok := a.(string); ok && s != "" {
  286. out = append(out, s)
  287. }
  288. }
  289. if len(out) > 0 {
  290. proxy["alpn"] = out
  291. }
  292. }
  293. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  294. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  295. proxy["skip-cert-verify"] = true
  296. }
  297. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  298. proxy["client-fingerprint"] = fp
  299. }
  300. }
  301. }
  302. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  303. // block the subscription link generator uses.
  304. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  305. if udpMasks, ok := finalmask["udp"].([]any); ok {
  306. for _, m := range udpMasks {
  307. mask, _ := m.(map[string]any)
  308. if mask == nil || mask["type"] != "salamander" {
  309. continue
  310. }
  311. settings, _ := mask["settings"].(map[string]any)
  312. if pw, ok := settings["password"].(string); ok && pw != "" {
  313. proxy["obfs"] = "salamander"
  314. proxy["obfs-password"] = pw
  315. break
  316. }
  317. }
  318. }
  319. }
  320. // UDP port hopping. mihomo reads the range from a dedicated `ports`
  321. // field (the base `port` stays as the redirect target).
  322. if hopPorts := hysteriaHopPorts(rawStream); hopPorts != "" {
  323. proxy["ports"] = hopPorts
  324. }
  325. return proxy
  326. }
  327. // buildXhttpClashOpts converts xhttpSettings from 3x-ui's camelCase JSON
  328. // storage into the kebab-case map that Mihomo expects under xhttp-opts.
  329. //
  330. // Only client-relevant fields are included (allowlist approach).
  331. // Server-only fields (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  332. // serverMaxHeaderBytes) are automatically excluded because they are not in
  333. // the mapping. This is intentional — when Mihomo adds new fields, the mapping
  334. // must be updated explicitly rather than leaking unverified fields to clients.
  335. //
  336. // Returns nil if no non-trivial fields are present.
  337. func buildXhttpClashOpts(xhttp map[string]any) map[string]any {
  338. if xhttp == nil {
  339. return nil
  340. }
  341. opts := map[string]any{}
  342. // Direct fields: path, mode
  343. if v, ok := xhttp["path"].(string); ok && v != "" {
  344. opts["path"] = v
  345. }
  346. if v, ok := xhttp["mode"].(string); ok && v != "" {
  347. opts["mode"] = v
  348. }
  349. // Host: explicit host field wins, then fall back to headers.Host
  350. host := ""
  351. if v, ok := xhttp["host"].(string); ok && v != "" {
  352. host = v
  353. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  354. host = searchHost(headers)
  355. }
  356. if host != "" {
  357. opts["host"] = host
  358. }
  359. type xhttpStringField struct{ src, dst, skipValue string }
  360. stringFields := []xhttpStringField{
  361. {"xPaddingBytes", "x-padding-bytes", ""},
  362. {"uplinkHTTPMethod", "uplink-http-method", ""},
  363. {"sessionIDPlacement", "session-id-placement", ""},
  364. {"sessionIDKey", "session-id-key", ""},
  365. {"sessionIDTable", "session-id-table", ""},
  366. {"sessionIDLength", "session-id-length", ""},
  367. {"seqPlacement", "seq-placement", ""},
  368. {"seqKey", "seq-key", ""},
  369. {"uplinkDataPlacement", "uplink-data-placement", ""},
  370. {"uplinkDataKey", "uplink-data-key", ""},
  371. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  372. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  373. }
  374. for _, f := range stringFields {
  375. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  376. opts[f.dst] = v
  377. }
  378. }
  379. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  380. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  381. // frontend migration.
  382. for _, f := range []xhttpStringField{
  383. {"sessionPlacement", "session-id-placement", ""},
  384. {"sessionKey", "session-id-key", ""},
  385. } {
  386. if _, exists := opts[f.dst]; exists {
  387. continue
  388. }
  389. if v, ok := xhttp[f.src].(string); ok && v != "" {
  390. opts[f.dst] = v
  391. }
  392. }
  393. // Bool fields (truthy only)
  394. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  395. opts["no-grpc-header"] = true
  396. }
  397. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  398. opts["x-padding-obfs-mode"] = true
  399. // Padding obfs gated fields
  400. for _, field := range []struct{ src, dst string }{
  401. {"xPaddingKey", "x-padding-key"},
  402. {"xPaddingHeader", "x-padding-header"},
  403. {"xPaddingPlacement", "x-padding-placement"},
  404. {"xPaddingMethod", "x-padding-method"},
  405. } {
  406. if v, ok := xhttp[field.src].(string); ok && v != "" {
  407. opts[field.dst] = v
  408. }
  409. }
  410. }
  411. // Non-zero value fields
  412. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  413. opts["uplink-chunk-size"] = v
  414. }
  415. // Nested object: xmux → reuse-settings
  416. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  417. reuse := map[string]any{}
  418. for _, f := range []struct{ src, dst string }{
  419. {"maxConcurrency", "max-concurrency"},
  420. {"maxConnections", "max-connections"},
  421. {"cMaxReuseTimes", "c-max-reuse-times"},
  422. {"hMaxRequestTimes", "h-max-request-times"},
  423. {"hMaxReusableSecs", "h-max-reusable-secs"},
  424. } {
  425. if v, ok := xmux[f.src].(string); ok && v != "" {
  426. reuse[f.dst] = v
  427. }
  428. }
  429. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  430. reuse["h-keep-alive-period"] = v
  431. }
  432. if len(reuse) > 0 {
  433. opts["reuse-settings"] = reuse
  434. }
  435. }
  436. // Headers (drop Host key)
  437. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  438. out := map[string]any{}
  439. for k, v := range rawHeaders {
  440. if strings.EqualFold(k, "host") {
  441. continue
  442. }
  443. out[k] = v
  444. }
  445. if len(out) > 0 {
  446. opts["headers"] = out
  447. }
  448. }
  449. if len(opts) == 0 {
  450. return nil
  451. }
  452. return opts
  453. }
  454. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  455. switch network {
  456. case "", "tcp":
  457. proxy["network"] = "tcp"
  458. tcp, _ := stream["tcpSettings"].(map[string]any)
  459. if tcp != nil {
  460. header, _ := tcp["header"].(map[string]any)
  461. if header != nil {
  462. typeStr, _ := header["type"].(string)
  463. if typeStr != "" && typeStr != "none" {
  464. return false
  465. }
  466. }
  467. }
  468. return true
  469. case "ws":
  470. proxy["network"] = "ws"
  471. ws, _ := stream["wsSettings"].(map[string]any)
  472. wsOpts := map[string]any{}
  473. if ws != nil {
  474. if path, ok := ws["path"].(string); ok && path != "" {
  475. wsOpts["path"] = path
  476. }
  477. host := ""
  478. if v, ok := ws["host"].(string); ok && v != "" {
  479. host = v
  480. } else if headers, ok := ws["headers"].(map[string]any); ok {
  481. host = searchHost(headers)
  482. }
  483. if host != "" {
  484. wsOpts["headers"] = map[string]any{"Host": host}
  485. }
  486. }
  487. if len(wsOpts) > 0 {
  488. proxy["ws-opts"] = wsOpts
  489. }
  490. return true
  491. case "grpc":
  492. proxy["network"] = "grpc"
  493. grpc, _ := stream["grpcSettings"].(map[string]any)
  494. grpcOpts := map[string]any{}
  495. if grpc != nil {
  496. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  497. grpcOpts["grpc-service-name"] = serviceName
  498. }
  499. }
  500. if len(grpcOpts) > 0 {
  501. proxy["grpc-opts"] = grpcOpts
  502. }
  503. return true
  504. case "httpupgrade":
  505. proxy["network"] = "httpupgrade"
  506. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  507. opts := map[string]any{}
  508. if hu != nil {
  509. if path, ok := hu["path"].(string); ok && path != "" {
  510. opts["path"] = path
  511. }
  512. host := ""
  513. if v, ok := hu["host"].(string); ok && v != "" {
  514. host = v
  515. } else if headers, ok := hu["headers"].(map[string]any); ok {
  516. host = searchHost(headers)
  517. }
  518. if host != "" {
  519. opts["headers"] = map[string]any{"Host": host}
  520. }
  521. }
  522. if len(opts) > 0 {
  523. proxy["http-upgrade-opts"] = opts
  524. }
  525. return true
  526. case "xhttp":
  527. proxy["network"] = "xhttp"
  528. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  529. opts := buildXhttpClashOpts(xhttp)
  530. if opts != nil {
  531. proxy["xhttp-opts"] = opts
  532. }
  533. return true
  534. default:
  535. return false
  536. }
  537. }
  538. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  539. switch security {
  540. case "", "none":
  541. proxy["tls"] = false
  542. return true
  543. case "tls":
  544. proxy["tls"] = true
  545. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  546. if tlsSettings != nil {
  547. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  548. proxy["servername"] = serverName
  549. switch proxy["type"] {
  550. case "trojan":
  551. proxy["sni"] = serverName
  552. }
  553. }
  554. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  555. proxy["client-fingerprint"] = fingerprint
  556. }
  557. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  558. out := make([]string, 0, len(alpn))
  559. for _, item := range alpn {
  560. if s, ok := item.(string); ok && s != "" {
  561. out = append(out, s)
  562. }
  563. }
  564. if len(out) > 0 {
  565. proxy["alpn"] = out
  566. }
  567. }
  568. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  569. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  570. proxy["skip-cert-verify"] = true
  571. }
  572. }
  573. }
  574. return true
  575. case "reality":
  576. proxy["tls"] = true
  577. realitySettings, _ := stream["realitySettings"].(map[string]any)
  578. if realitySettings == nil {
  579. return false
  580. }
  581. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  582. proxy["servername"] = serverName
  583. }
  584. realityOpts := map[string]any{}
  585. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  586. realityOpts["public-key"] = publicKey
  587. }
  588. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  589. realityOpts["short-id"] = shortID
  590. }
  591. if len(realityOpts) > 0 {
  592. proxy["reality-opts"] = realityOpts
  593. }
  594. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  595. proxy["client-fingerprint"] = fingerprint
  596. }
  597. return true
  598. default:
  599. return false
  600. }
  601. }
  602. func (s *SubClashService) streamData(stream string) map[string]any {
  603. var streamSettings map[string]any
  604. _ = json.Unmarshal([]byte(stream), &streamSettings)
  605. security, _ := streamSettings["security"].(string)
  606. switch security {
  607. case "tls":
  608. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  609. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  610. }
  611. case "reality":
  612. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  613. streamSettings["realitySettings"] = s.realityData(realitySettings)
  614. }
  615. }
  616. delete(streamSettings, "sockopt")
  617. return streamSettings
  618. }
  619. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  620. tlsData := make(map[string]any, 1)
  621. tlsClientSettings, _ := tData["settings"].(map[string]any)
  622. tlsData["serverName"] = tData["serverName"]
  623. tlsData["alpn"] = tData["alpn"]
  624. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  625. tlsData["fingerprint"] = fingerprint
  626. }
  627. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  628. tlsData["pin-sha256"] = pins
  629. }
  630. return tlsData
  631. }
  632. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  633. rDataOut := make(map[string]any, 1)
  634. realityClientSettings, _ := rData["settings"].(map[string]any)
  635. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  636. rDataOut["publicKey"] = publicKey
  637. }
  638. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  639. rDataOut["fingerprint"] = fingerprint
  640. }
  641. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  642. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  643. }
  644. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  645. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  646. }
  647. return rDataOut
  648. }
  649. func cloneMap(src map[string]any) map[string]any {
  650. if src == nil {
  651. return nil
  652. }
  653. dst := make(map[string]any, len(src))
  654. maps.Copy(dst, src)
  655. return dst
  656. }
  657. func mergeClashRulesYAML(base map[string]any, raw string) error {
  658. raw = strings.TrimSpace(raw)
  659. if raw == "" {
  660. return nil
  661. }
  662. var custom any
  663. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  664. mergeClashRules(base, linesToClashRules(raw))
  665. return nil
  666. }
  667. switch typed := custom.(type) {
  668. case []any:
  669. mergeClashRules(base, typed)
  670. case map[string]any:
  671. for key, value := range typed {
  672. if key == "rules" {
  673. if ruleList, ok := asAnySlice(value); ok {
  674. mergeClashRules(base, ruleList)
  675. }
  676. continue
  677. }
  678. base[key] = value
  679. }
  680. default:
  681. mergeClashRules(base, linesToClashRules(raw))
  682. }
  683. return nil
  684. }
  685. func mergeClashRules(base map[string]any, customRules []any) {
  686. if len(customRules) == 0 {
  687. return
  688. }
  689. baseRules, _ := asAnySlice(base["rules"])
  690. if hasClashMatchRule(customRules) {
  691. base["rules"] = customRules
  692. return
  693. }
  694. merged := make([]any, 0, len(customRules)+len(baseRules))
  695. merged = append(merged, customRules...)
  696. merged = append(merged, baseRules...)
  697. base["rules"] = merged
  698. }
  699. func asAnySlice(value any) ([]any, bool) {
  700. switch typed := value.(type) {
  701. case []any:
  702. return typed, true
  703. case []string:
  704. out := make([]any, 0, len(typed))
  705. for _, item := range typed {
  706. out = append(out, item)
  707. }
  708. return out, true
  709. case []map[string]any:
  710. out := make([]any, 0, len(typed))
  711. for _, item := range typed {
  712. out = append(out, item)
  713. }
  714. return out, true
  715. default:
  716. return nil, false
  717. }
  718. }
  719. func hasClashMatchRule(rules []any) bool {
  720. for _, rule := range rules {
  721. ruleText, ok := rule.(string)
  722. if !ok {
  723. continue
  724. }
  725. parts := strings.SplitN(ruleText, ",", 2)
  726. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  727. return true
  728. }
  729. }
  730. return false
  731. }
  732. func linesToClashRules(raw string) []any {
  733. lines := strings.Split(raw, "\n")
  734. rules := make([]any, 0, len(lines))
  735. for _, line := range lines {
  736. line = strings.TrimSpace(line)
  737. if line == "" || strings.HasPrefix(line, "#") {
  738. continue
  739. }
  740. rules = append(rules, line)
  741. }
  742. return rules
  743. }