clash_service.go 25 KB

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