clash_service.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. {"sessionIDPlacement", "session-id-placement", ""},
  367. {"sessionIDKey", "session-id-key", ""},
  368. {"sessionIDTable", "session-id-table", ""},
  369. {"sessionIDLength", "session-id-length", ""},
  370. {"seqPlacement", "seq-placement", ""},
  371. {"seqKey", "seq-key", ""},
  372. {"uplinkDataPlacement", "uplink-data-placement", ""},
  373. {"uplinkDataKey", "uplink-data-key", ""},
  374. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  375. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  376. }
  377. for _, f := range stringFields {
  378. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  379. opts[f.dst] = v
  380. }
  381. }
  382. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  383. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  384. // frontend migration.
  385. for _, f := range []xhttpStringField{
  386. {"sessionPlacement", "session-id-placement", ""},
  387. {"sessionKey", "session-id-key", ""},
  388. } {
  389. if _, exists := opts[f.dst]; exists {
  390. continue
  391. }
  392. if v, ok := xhttp[f.src].(string); ok && v != "" {
  393. opts[f.dst] = v
  394. }
  395. }
  396. // Bool fields (truthy only)
  397. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  398. opts["no-grpc-header"] = true
  399. }
  400. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  401. opts["x-padding-obfs-mode"] = true
  402. // Padding obfs gated fields
  403. for _, field := range []struct{ src, dst string }{
  404. {"xPaddingKey", "x-padding-key"},
  405. {"xPaddingHeader", "x-padding-header"},
  406. {"xPaddingPlacement", "x-padding-placement"},
  407. {"xPaddingMethod", "x-padding-method"},
  408. } {
  409. if v, ok := xhttp[field.src].(string); ok && v != "" {
  410. opts[field.dst] = v
  411. }
  412. }
  413. }
  414. // Non-zero value fields
  415. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  416. opts["uplink-chunk-size"] = v
  417. }
  418. // Nested object: xmux → reuse-settings
  419. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  420. reuse := map[string]any{}
  421. for _, f := range []struct{ src, dst string }{
  422. {"maxConcurrency", "max-concurrency"},
  423. {"maxConnections", "max-connections"},
  424. {"cMaxReuseTimes", "c-max-reuse-times"},
  425. {"hMaxRequestTimes", "h-max-request-times"},
  426. {"hMaxReusableSecs", "h-max-reusable-secs"},
  427. } {
  428. if v, ok := xmux[f.src].(string); ok && v != "" {
  429. reuse[f.dst] = v
  430. }
  431. }
  432. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  433. reuse["h-keep-alive-period"] = v
  434. }
  435. if len(reuse) > 0 {
  436. opts["reuse-settings"] = reuse
  437. }
  438. }
  439. // Headers (drop Host key)
  440. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  441. out := map[string]any{}
  442. for k, v := range rawHeaders {
  443. if strings.EqualFold(k, "host") {
  444. continue
  445. }
  446. out[k] = v
  447. }
  448. if len(out) > 0 {
  449. opts["headers"] = out
  450. }
  451. }
  452. if len(opts) == 0 {
  453. return nil
  454. }
  455. return opts
  456. }
  457. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  458. switch network {
  459. case "", "tcp":
  460. proxy["network"] = "tcp"
  461. tcp, _ := stream["tcpSettings"].(map[string]any)
  462. if tcp != nil {
  463. header, _ := tcp["header"].(map[string]any)
  464. if header != nil {
  465. typeStr, _ := header["type"].(string)
  466. if typeStr != "" && typeStr != "none" {
  467. return false
  468. }
  469. }
  470. }
  471. return true
  472. case "ws":
  473. proxy["network"] = "ws"
  474. ws, _ := stream["wsSettings"].(map[string]any)
  475. wsOpts := map[string]any{}
  476. if ws != nil {
  477. if path, ok := ws["path"].(string); ok && path != "" {
  478. wsOpts["path"] = path
  479. }
  480. host := ""
  481. if v, ok := ws["host"].(string); ok && v != "" {
  482. host = v
  483. } else if headers, ok := ws["headers"].(map[string]any); ok {
  484. host = searchHost(headers)
  485. }
  486. if host != "" {
  487. wsOpts["headers"] = map[string]any{"Host": host}
  488. }
  489. }
  490. if len(wsOpts) > 0 {
  491. proxy["ws-opts"] = wsOpts
  492. }
  493. return true
  494. case "grpc":
  495. proxy["network"] = "grpc"
  496. grpc, _ := stream["grpcSettings"].(map[string]any)
  497. grpcOpts := map[string]any{}
  498. if grpc != nil {
  499. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  500. grpcOpts["grpc-service-name"] = serviceName
  501. }
  502. }
  503. if len(grpcOpts) > 0 {
  504. proxy["grpc-opts"] = grpcOpts
  505. }
  506. return true
  507. case "httpupgrade":
  508. proxy["network"] = "httpupgrade"
  509. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  510. opts := map[string]any{}
  511. if hu != nil {
  512. if path, ok := hu["path"].(string); ok && path != "" {
  513. opts["path"] = path
  514. }
  515. host := ""
  516. if v, ok := hu["host"].(string); ok && v != "" {
  517. host = v
  518. } else if headers, ok := hu["headers"].(map[string]any); ok {
  519. host = searchHost(headers)
  520. }
  521. if host != "" {
  522. opts["headers"] = map[string]any{"Host": host}
  523. }
  524. }
  525. if len(opts) > 0 {
  526. proxy["http-upgrade-opts"] = opts
  527. }
  528. return true
  529. case "xhttp":
  530. proxy["network"] = "xhttp"
  531. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  532. opts := buildXhttpClashOpts(xhttp)
  533. if opts != nil {
  534. proxy["xhttp-opts"] = opts
  535. }
  536. return true
  537. default:
  538. return false
  539. }
  540. }
  541. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  542. switch security {
  543. case "", "none":
  544. proxy["tls"] = false
  545. return true
  546. case "tls":
  547. proxy["tls"] = true
  548. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  549. if tlsSettings != nil {
  550. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  551. proxy["servername"] = serverName
  552. switch proxy["type"] {
  553. case "trojan":
  554. proxy["sni"] = serverName
  555. }
  556. }
  557. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  558. proxy["client-fingerprint"] = fingerprint
  559. }
  560. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  561. out := make([]string, 0, len(alpn))
  562. for _, item := range alpn {
  563. if s, ok := item.(string); ok && s != "" {
  564. out = append(out, s)
  565. }
  566. }
  567. if len(out) > 0 {
  568. proxy["alpn"] = out
  569. }
  570. }
  571. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  572. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  573. proxy["skip-cert-verify"] = true
  574. }
  575. }
  576. }
  577. return true
  578. case "reality":
  579. proxy["tls"] = true
  580. realitySettings, _ := stream["realitySettings"].(map[string]any)
  581. if realitySettings == nil {
  582. return false
  583. }
  584. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  585. proxy["servername"] = serverName
  586. }
  587. realityOpts := map[string]any{}
  588. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  589. realityOpts["public-key"] = publicKey
  590. }
  591. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  592. realityOpts["short-id"] = shortID
  593. }
  594. if len(realityOpts) > 0 {
  595. proxy["reality-opts"] = realityOpts
  596. }
  597. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  598. proxy["client-fingerprint"] = fingerprint
  599. }
  600. return true
  601. default:
  602. return false
  603. }
  604. }
  605. func (s *SubClashService) streamData(stream string) map[string]any {
  606. var streamSettings map[string]any
  607. json.Unmarshal([]byte(stream), &streamSettings)
  608. security, _ := streamSettings["security"].(string)
  609. switch security {
  610. case "tls":
  611. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  612. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  613. }
  614. case "reality":
  615. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  616. streamSettings["realitySettings"] = s.realityData(realitySettings)
  617. }
  618. }
  619. delete(streamSettings, "sockopt")
  620. return streamSettings
  621. }
  622. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  623. tlsData := make(map[string]any, 1)
  624. tlsClientSettings, _ := tData["settings"].(map[string]any)
  625. tlsData["serverName"] = tData["serverName"]
  626. tlsData["alpn"] = tData["alpn"]
  627. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  628. tlsData["fingerprint"] = fingerprint
  629. }
  630. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  631. tlsData["pin-sha256"] = pins
  632. }
  633. return tlsData
  634. }
  635. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  636. rDataOut := make(map[string]any, 1)
  637. realityClientSettings, _ := rData["settings"].(map[string]any)
  638. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  639. rDataOut["publicKey"] = publicKey
  640. }
  641. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  642. rDataOut["fingerprint"] = fingerprint
  643. }
  644. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  645. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  646. }
  647. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  648. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  649. }
  650. return rDataOut
  651. }
  652. func cloneMap(src map[string]any) map[string]any {
  653. if src == nil {
  654. return nil
  655. }
  656. dst := make(map[string]any, len(src))
  657. maps.Copy(dst, src)
  658. return dst
  659. }
  660. func mergeClashRulesYAML(base map[string]any, raw string) error {
  661. raw = strings.TrimSpace(raw)
  662. if raw == "" {
  663. return nil
  664. }
  665. var custom any
  666. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  667. mergeClashRules(base, linesToClashRules(raw))
  668. return nil
  669. }
  670. switch typed := custom.(type) {
  671. case []any:
  672. mergeClashRules(base, typed)
  673. case map[string]any:
  674. for key, value := range typed {
  675. if key == "rules" {
  676. if ruleList, ok := asAnySlice(value); ok {
  677. mergeClashRules(base, ruleList)
  678. }
  679. continue
  680. }
  681. base[key] = value
  682. }
  683. default:
  684. mergeClashRules(base, linesToClashRules(raw))
  685. }
  686. return nil
  687. }
  688. func mergeClashRules(base map[string]any, customRules []any) {
  689. if len(customRules) == 0 {
  690. return
  691. }
  692. baseRules, _ := asAnySlice(base["rules"])
  693. if hasClashMatchRule(customRules) {
  694. base["rules"] = customRules
  695. return
  696. }
  697. merged := make([]any, 0, len(customRules)+len(baseRules))
  698. merged = append(merged, customRules...)
  699. merged = append(merged, baseRules...)
  700. base["rules"] = merged
  701. }
  702. func asAnySlice(value any) ([]any, bool) {
  703. switch typed := value.(type) {
  704. case []any:
  705. return typed, true
  706. case []string:
  707. out := make([]any, 0, len(typed))
  708. for _, item := range typed {
  709. out = append(out, item)
  710. }
  711. return out, true
  712. case []map[string]any:
  713. out := make([]any, 0, len(typed))
  714. for _, item := range typed {
  715. out = append(out, item)
  716. }
  717. return out, true
  718. default:
  719. return nil, false
  720. }
  721. }
  722. func hasClashMatchRule(rules []any) bool {
  723. for _, rule := range rules {
  724. ruleText, ok := rule.(string)
  725. if !ok {
  726. continue
  727. }
  728. parts := strings.SplitN(ruleText, ",", 2)
  729. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  730. return true
  731. }
  732. }
  733. return false
  734. }
  735. func linesToClashRules(raw string) []any {
  736. lines := strings.Split(raw, "\n")
  737. rules := make([]any, 0, len(lines))
  738. for _, line := range lines {
  739. line = strings.TrimSpace(line)
  740. if line == "" || strings.HasPrefix(line, "#") {
  741. continue
  742. }
  743. rules = append(rules, line)
  744. }
  745. return rules
  746. }