1
0

clash_service.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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 := ep.(map[string]any)
  152. // Expand the host's {{VAR}} remark template for this client (no-op for
  153. // the synthetic/legacy entry) before it becomes the proxy name.
  154. subReq.renderHostRemark(inbound, client, extPrxy, network)
  155. workingInbound := *inbound
  156. workingInbound.Listen = extPrxy["dest"].(string)
  157. workingInbound.Port = int(extPrxy["port"].(float64))
  158. workingStream := cloneStreamForExternalProxy(stream)
  159. switch extPrxy["forceTls"].(string) {
  160. case "tls":
  161. if workingStream["security"] != "tls" {
  162. workingStream["security"] = "tls"
  163. workingStream["tlsSettings"] = map[string]any{}
  164. }
  165. case "none":
  166. if workingStream["security"] != "none" {
  167. workingStream["security"] = "none"
  168. delete(workingStream, "tlsSettings")
  169. delete(workingStream, "realitySettings")
  170. }
  171. }
  172. security, _ := workingStream["security"].(string)
  173. if hasExternalProxy {
  174. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  175. }
  176. applyHostStreamOverrides(extPrxy, workingStream)
  177. proxy := s.buildProxy(subReq, &workingInbound, client, workingStream, extPrxy)
  178. if len(proxy) > 0 {
  179. // Host-only mihomo knob: ip-version is a top-level proxy field, set
  180. // last so it cannot be clobbered. Absent for legacy externalProxy.
  181. if v, _ := extPrxy["mihomoIpVersion"].(string); v != "" {
  182. proxy["ip-version"] = v
  183. }
  184. proxies = append(proxies, proxy)
  185. }
  186. }
  187. return proxies
  188. }
  189. func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound, client model.Client, stream map[string]any, ep map[string]any) map[string]any {
  190. // Hysteria has its own transport + TLS model, applyTransport /
  191. // applySecurity don't fit.
  192. if inbound.Protocol == model.Hysteria {
  193. return s.buildHysteriaProxy(subReq, inbound, client, ep)
  194. }
  195. if inbound.Protocol == model.WireGuard {
  196. return s.buildWireguardProxy(subReq, inbound, client, ep)
  197. }
  198. network, _ := stream["network"].(string)
  199. proxy := map[string]any{
  200. "name": subReq.endpointRemark(inbound, client.Email, ep, network),
  201. "server": inbound.Listen,
  202. "port": inbound.Port,
  203. "udp": true,
  204. }
  205. if !s.applyTransport(proxy, network, stream) {
  206. return nil
  207. }
  208. switch inbound.Protocol {
  209. case model.VMESS:
  210. proxy["type"] = "vmess"
  211. proxy["uuid"] = client.ID
  212. proxy["alterId"] = 0
  213. proxy["cipher"] = normalizeVmessSecurity(client.Security)
  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. if insecure, ok := ep["allowInsecure"].(bool); ok && insecure {
  303. proxy["skip-cert-verify"] = true
  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. // buildWireguardProxy produces a mihomo-compatible Clash entry for a native
  331. // WireGuard inbound, mirroring genWireguardLink: the peer public key is derived
  332. // from the inbound secretKey, while the private key, tunnel address, and
  333. // pre-shared key come from the client. Returns nil when the client has no key.
  334. func (s *SubClashService) buildWireguardProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
  335. if client.PrivateKey == "" {
  336. return nil
  337. }
  338. var inboundSettings map[string]any
  339. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  340. secretKey, _ := inboundSettings["secretKey"].(string)
  341. proxy := map[string]any{
  342. "name": subReq.endpointRemark(inbound, client.Email, ep, ""),
  343. "type": "wireguard",
  344. "server": inbound.Listen,
  345. "port": inbound.Port,
  346. "udp": true,
  347. "private-key": client.PrivateKey,
  348. }
  349. if secretKey != "" {
  350. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  351. proxy["public-key"] = pub
  352. }
  353. }
  354. if client.PreSharedKey != "" {
  355. proxy["pre-shared-key"] = client.PreSharedKey
  356. }
  357. if client.KeepAlive > 0 {
  358. proxy["persistent-keepalive"] = client.KeepAlive
  359. }
  360. for _, addr := range client.AllowedIPs {
  361. ip := stripCIDR(addr)
  362. if ip == "" {
  363. continue
  364. }
  365. if strings.Contains(ip, ":") {
  366. proxy["ipv6"] = ip
  367. } else {
  368. proxy["ip"] = ip
  369. }
  370. }
  371. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  372. proxy["mtu"] = int(mtu)
  373. }
  374. if dns, _ := inboundSettings["dns"].(string); dns != "" {
  375. servers := make([]string, 0)
  376. for _, server := range strings.Split(dns, ",") {
  377. if server = strings.TrimSpace(server); server != "" {
  378. servers = append(servers, server)
  379. }
  380. }
  381. if len(servers) > 0 {
  382. proxy["dns"] = servers
  383. }
  384. }
  385. return proxy
  386. }
  387. // buildXhttpClashOpts converts xhttpSettings from 3x-ui's camelCase JSON
  388. // storage into the kebab-case map that Mihomo expects under xhttp-opts.
  389. //
  390. // Only client-relevant fields are included (allowlist approach).
  391. // Server-only fields (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  392. // serverMaxHeaderBytes) are automatically excluded because they are not in
  393. // the mapping. This is intentional — when Mihomo adds new fields, the mapping
  394. // must be updated explicitly rather than leaking unverified fields to clients.
  395. //
  396. // Returns nil if no non-trivial fields are present.
  397. func buildXhttpClashOpts(xhttp map[string]any) map[string]any {
  398. if xhttp == nil {
  399. return nil
  400. }
  401. opts := map[string]any{}
  402. // Direct fields: path, mode
  403. if v, ok := xhttp["path"].(string); ok && v != "" {
  404. opts["path"] = v
  405. }
  406. if v, ok := xhttp["mode"].(string); ok && v != "" {
  407. opts["mode"] = v
  408. }
  409. // Host: explicit host field wins, then fall back to headers.Host
  410. host := ""
  411. if v, ok := xhttp["host"].(string); ok && v != "" {
  412. host = v
  413. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  414. host = searchHost(headers)
  415. }
  416. if host != "" {
  417. opts["host"] = host
  418. }
  419. type xhttpStringField struct{ src, dst, skipValue string }
  420. stringFields := []xhttpStringField{
  421. {"xPaddingBytes", "x-padding-bytes", ""},
  422. {"uplinkHTTPMethod", "uplink-http-method", ""},
  423. {"sessionIDPlacement", "session-id-placement", ""},
  424. {"sessionIDKey", "session-id-key", ""},
  425. {"sessionIDTable", "session-id-table", ""},
  426. {"sessionIDLength", "session-id-length", ""},
  427. {"seqPlacement", "seq-placement", ""},
  428. {"seqKey", "seq-key", ""},
  429. {"uplinkDataPlacement", "uplink-data-placement", ""},
  430. {"uplinkDataKey", "uplink-data-key", ""},
  431. {"scMaxEachPostBytes", "sc-max-each-post-bytes", "1000000"},
  432. {"scMinPostsIntervalMs", "sc-min-posts-interval-ms", "30"},
  433. }
  434. for _, f := range stringFields {
  435. if v, ok := xhttp[f.src].(string); ok && v != "" && (f.skipValue == "" || v != f.skipValue) {
  436. opts[f.dst] = v
  437. }
  438. }
  439. // Legacy inbounds (pre xray-core #6258) stored sessionPlacement/sessionKey.
  440. // Fall back to them so not-yet-resaved configs still map. Mirrors the
  441. // frontend migration.
  442. for _, f := range []xhttpStringField{
  443. {"sessionPlacement", "session-id-placement", ""},
  444. {"sessionKey", "session-id-key", ""},
  445. } {
  446. if _, exists := opts[f.dst]; exists {
  447. continue
  448. }
  449. if v, ok := xhttp[f.src].(string); ok && v != "" {
  450. opts[f.dst] = v
  451. }
  452. }
  453. // Bool fields (truthy only)
  454. if v, ok := xhttp["noGRPCHeader"].(bool); ok && v {
  455. opts["no-grpc-header"] = true
  456. }
  457. if v, ok := xhttp["xPaddingObfsMode"].(bool); ok && v {
  458. opts["x-padding-obfs-mode"] = true
  459. // Padding obfs gated fields
  460. for _, field := range []struct{ src, dst string }{
  461. {"xPaddingKey", "x-padding-key"},
  462. {"xPaddingHeader", "x-padding-header"},
  463. {"xPaddingPlacement", "x-padding-placement"},
  464. {"xPaddingMethod", "x-padding-method"},
  465. } {
  466. if v, ok := xhttp[field.src].(string); ok && v != "" {
  467. opts[field.dst] = v
  468. }
  469. }
  470. }
  471. // Non-zero value fields
  472. if v, ok := nonZeroShareValue(xhttp["uplinkChunkSize"]); ok {
  473. opts["uplink-chunk-size"] = v
  474. }
  475. // Nested object: xmux → reuse-settings
  476. if xmux, ok := xhttp["xmux"].(map[string]any); ok && len(xmux) > 0 {
  477. reuse := map[string]any{}
  478. for _, f := range []struct{ src, dst string }{
  479. {"maxConcurrency", "max-concurrency"},
  480. {"maxConnections", "max-connections"},
  481. {"cMaxReuseTimes", "c-max-reuse-times"},
  482. {"hMaxRequestTimes", "h-max-request-times"},
  483. {"hMaxReusableSecs", "h-max-reusable-secs"},
  484. } {
  485. if v, ok := xmux[f.src].(string); ok && v != "" {
  486. reuse[f.dst] = v
  487. }
  488. }
  489. if v, ok := nonZeroShareValue(xmux["hKeepAlivePeriod"]); ok {
  490. reuse["h-keep-alive-period"] = v
  491. }
  492. if len(reuse) > 0 {
  493. opts["reuse-settings"] = reuse
  494. }
  495. }
  496. // Headers (drop Host key)
  497. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  498. out := map[string]any{}
  499. for k, v := range rawHeaders {
  500. if strings.EqualFold(k, "host") {
  501. continue
  502. }
  503. out[k] = v
  504. }
  505. if len(out) > 0 {
  506. opts["headers"] = out
  507. }
  508. }
  509. if len(opts) == 0 {
  510. return nil
  511. }
  512. return opts
  513. }
  514. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  515. switch network {
  516. case "", "tcp":
  517. proxy["network"] = "tcp"
  518. tcp, _ := stream["tcpSettings"].(map[string]any)
  519. if tcp != nil {
  520. header, _ := tcp["header"].(map[string]any)
  521. if header != nil {
  522. typeStr, _ := header["type"].(string)
  523. if typeStr != "" && typeStr != "none" {
  524. return false
  525. }
  526. }
  527. }
  528. return true
  529. case "ws":
  530. proxy["network"] = "ws"
  531. ws, _ := stream["wsSettings"].(map[string]any)
  532. wsOpts := map[string]any{}
  533. if ws != nil {
  534. if path, ok := ws["path"].(string); ok && path != "" {
  535. wsOpts["path"] = path
  536. }
  537. host := ""
  538. if v, ok := ws["host"].(string); ok && v != "" {
  539. host = v
  540. } else if headers, ok := ws["headers"].(map[string]any); ok {
  541. host = searchHost(headers)
  542. }
  543. if host != "" {
  544. wsOpts["headers"] = map[string]any{"Host": host}
  545. }
  546. }
  547. if len(wsOpts) > 0 {
  548. proxy["ws-opts"] = wsOpts
  549. }
  550. return true
  551. case "grpc":
  552. proxy["network"] = "grpc"
  553. grpc, _ := stream["grpcSettings"].(map[string]any)
  554. grpcOpts := map[string]any{}
  555. if grpc != nil {
  556. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  557. grpcOpts["grpc-service-name"] = serviceName
  558. }
  559. }
  560. if len(grpcOpts) > 0 {
  561. proxy["grpc-opts"] = grpcOpts
  562. }
  563. return true
  564. case "httpupgrade":
  565. proxy["network"] = "httpupgrade"
  566. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  567. opts := map[string]any{}
  568. if hu != nil {
  569. if path, ok := hu["path"].(string); ok && path != "" {
  570. opts["path"] = path
  571. }
  572. host := ""
  573. if v, ok := hu["host"].(string); ok && v != "" {
  574. host = v
  575. } else if headers, ok := hu["headers"].(map[string]any); ok {
  576. host = searchHost(headers)
  577. }
  578. if host != "" {
  579. opts["headers"] = map[string]any{"Host": host}
  580. }
  581. }
  582. if len(opts) > 0 {
  583. proxy["http-upgrade-opts"] = opts
  584. }
  585. return true
  586. case "xhttp":
  587. proxy["network"] = "xhttp"
  588. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  589. opts := buildXhttpClashOpts(xhttp)
  590. if opts != nil {
  591. proxy["xhttp-opts"] = opts
  592. }
  593. return true
  594. default:
  595. return false
  596. }
  597. }
  598. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  599. switch security {
  600. case "", "none":
  601. proxy["tls"] = false
  602. return true
  603. case "tls":
  604. proxy["tls"] = true
  605. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  606. if tlsSettings != nil {
  607. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  608. proxy["servername"] = serverName
  609. switch proxy["type"] {
  610. case "trojan":
  611. proxy["sni"] = serverName
  612. }
  613. }
  614. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  615. proxy["client-fingerprint"] = fingerprint
  616. }
  617. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  618. out := make([]string, 0, len(alpn))
  619. for _, item := range alpn {
  620. if s, ok := item.(string); ok && s != "" {
  621. out = append(out, s)
  622. }
  623. }
  624. if len(out) > 0 {
  625. proxy["alpn"] = out
  626. }
  627. }
  628. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  629. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  630. proxy["skip-cert-verify"] = true
  631. }
  632. }
  633. }
  634. return true
  635. case "reality":
  636. proxy["tls"] = true
  637. realitySettings, _ := stream["realitySettings"].(map[string]any)
  638. if realitySettings == nil {
  639. return false
  640. }
  641. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  642. proxy["servername"] = serverName
  643. }
  644. realityOpts := map[string]any{}
  645. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  646. realityOpts["public-key"] = publicKey
  647. }
  648. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  649. realityOpts["short-id"] = shortID
  650. }
  651. if len(realityOpts) > 0 {
  652. proxy["reality-opts"] = realityOpts
  653. }
  654. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  655. proxy["client-fingerprint"] = fingerprint
  656. }
  657. return true
  658. default:
  659. return false
  660. }
  661. }
  662. func (s *SubClashService) streamData(stream string) map[string]any {
  663. var streamSettings map[string]any
  664. _ = json.Unmarshal([]byte(stream), &streamSettings)
  665. security, _ := streamSettings["security"].(string)
  666. switch security {
  667. case "tls":
  668. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  669. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  670. }
  671. case "reality":
  672. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  673. streamSettings["realitySettings"] = s.realityData(realitySettings)
  674. }
  675. }
  676. delete(streamSettings, "sockopt")
  677. return streamSettings
  678. }
  679. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  680. tlsData := make(map[string]any, 1)
  681. tlsClientSettings, _ := tData["settings"].(map[string]any)
  682. tlsData["serverName"] = tData["serverName"]
  683. tlsData["alpn"] = tData["alpn"]
  684. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  685. tlsData["fingerprint"] = fingerprint
  686. }
  687. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  688. tlsData["pin-sha256"] = pins
  689. }
  690. return tlsData
  691. }
  692. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  693. rDataOut := make(map[string]any, 1)
  694. realityClientSettings, _ := rData["settings"].(map[string]any)
  695. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  696. rDataOut["publicKey"] = publicKey
  697. }
  698. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  699. rDataOut["fingerprint"] = fingerprint
  700. }
  701. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  702. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  703. }
  704. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  705. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  706. }
  707. return rDataOut
  708. }
  709. func cloneMap(src map[string]any) map[string]any {
  710. if src == nil {
  711. return nil
  712. }
  713. dst := make(map[string]any, len(src))
  714. maps.Copy(dst, src)
  715. return dst
  716. }
  717. func mergeClashRulesYAML(base map[string]any, raw string) error {
  718. raw = strings.TrimSpace(raw)
  719. if raw == "" {
  720. return nil
  721. }
  722. var custom any
  723. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  724. mergeClashRules(base, linesToClashRules(raw))
  725. return nil
  726. }
  727. switch typed := custom.(type) {
  728. case []any:
  729. mergeClashRules(base, typed)
  730. case map[string]any:
  731. for key, value := range typed {
  732. if key == "rules" {
  733. if ruleList, ok := asAnySlice(value); ok {
  734. mergeClashRules(base, ruleList)
  735. }
  736. continue
  737. }
  738. base[key] = value
  739. }
  740. default:
  741. mergeClashRules(base, linesToClashRules(raw))
  742. }
  743. return nil
  744. }
  745. func mergeClashRules(base map[string]any, customRules []any) {
  746. if len(customRules) == 0 {
  747. return
  748. }
  749. baseRules, _ := asAnySlice(base["rules"])
  750. if hasClashMatchRule(customRules) {
  751. base["rules"] = customRules
  752. return
  753. }
  754. merged := make([]any, 0, len(customRules)+len(baseRules))
  755. merged = append(merged, customRules...)
  756. merged = append(merged, baseRules...)
  757. base["rules"] = merged
  758. }
  759. func asAnySlice(value any) ([]any, bool) {
  760. switch typed := value.(type) {
  761. case []any:
  762. return typed, true
  763. case []string:
  764. out := make([]any, 0, len(typed))
  765. for _, item := range typed {
  766. out = append(out, item)
  767. }
  768. return out, true
  769. case []map[string]any:
  770. out := make([]any, 0, len(typed))
  771. for _, item := range typed {
  772. out = append(out, item)
  773. }
  774. return out, true
  775. default:
  776. return nil, false
  777. }
  778. }
  779. func hasClashMatchRule(rules []any) bool {
  780. for _, rule := range rules {
  781. ruleText, ok := rule.(string)
  782. if !ok {
  783. continue
  784. }
  785. parts := strings.SplitN(ruleText, ",", 2)
  786. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  787. return true
  788. }
  789. }
  790. return false
  791. }
  792. func linesToClashRules(raw string) []any {
  793. lines := strings.Split(raw, "\n")
  794. rules := make([]any, 0, len(lines))
  795. for _, line := range lines {
  796. line = strings.TrimSpace(line)
  797. if line == "" || strings.HasPrefix(line, "#") {
  798. continue
  799. }
  800. rules = append(rules, line)
  801. }
  802. return rules
  803. }