subClashService.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/logger"
  10. "github.com/mhsanaei/3x-ui/v3/web/service"
  11. )
  12. type SubClashService struct {
  13. inboundService service.InboundService
  14. SubService *SubService
  15. }
  16. type ClashConfig struct {
  17. Proxies []map[string]any `yaml:"proxies"`
  18. ProxyGroups []map[string]any `yaml:"proxy-groups"`
  19. Rules []string `yaml:"rules"`
  20. }
  21. func NewSubClashService(subService *SubService) *SubClashService {
  22. return &SubClashService{SubService: subService}
  23. }
  24. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  25. // Set per-request state so resolveInboundAddress sees the node map.
  26. s.SubService.PrepareForRequest(host)
  27. inbounds, err := s.SubService.getInboundsBySubId(subId)
  28. if err != nil || len(inbounds) == 0 {
  29. return "", "", err
  30. }
  31. var proxies []map[string]any
  32. seenEmails := make(map[string]struct{})
  33. for _, inbound := range inbounds {
  34. clients, err := s.inboundService.GetClients(inbound)
  35. if err != nil {
  36. logger.Error("SubClashService - GetClients: Unable to get clients from inbound")
  37. }
  38. if clients == nil {
  39. continue
  40. }
  41. s.SubService.projectThroughFallbackMaster(inbound)
  42. for _, client := range clients {
  43. if client.SubID == subId {
  44. seenEmails[client.Email] = struct{}{}
  45. proxies = append(proxies, s.getProxies(inbound, client, host)...)
  46. }
  47. }
  48. }
  49. if len(proxies) == 0 {
  50. return "", "", nil
  51. }
  52. emails := make([]string, 0, len(seenEmails))
  53. for e := range seenEmails {
  54. emails = append(emails, e)
  55. }
  56. traffic, _ := s.SubService.AggregateTrafficByEmails(emails)
  57. proxyNames := make([]string, 0, len(proxies)+1)
  58. for _, proxy := range proxies {
  59. if name, ok := proxy["name"].(string); ok && name != "" {
  60. proxyNames = append(proxyNames, name)
  61. }
  62. }
  63. proxyNames = append(proxyNames, "DIRECT")
  64. config := ClashConfig{
  65. Proxies: proxies,
  66. ProxyGroups: []map[string]any{{
  67. "name": "PROXY",
  68. "type": "select",
  69. "proxies": proxyNames,
  70. }},
  71. Rules: []string{"MATCH,PROXY"},
  72. }
  73. finalYAML, err := yaml.Marshal(config)
  74. if err != nil {
  75. return "", "", err
  76. }
  77. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  78. return string(finalYAML), header, nil
  79. }
  80. func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client, host string) []map[string]any {
  81. stream := s.streamData(inbound.StreamSettings)
  82. // For node-managed inbounds the Clash proxy "server" must be the
  83. // node's address, not the request host. resolveInboundAddress handles
  84. // the node→listen→request-host fallback chain.
  85. defaultDest := s.SubService.resolveInboundAddress(inbound)
  86. if defaultDest == "" {
  87. defaultDest = host
  88. }
  89. externalProxies, ok := stream["externalProxy"].([]any)
  90. hasExternalProxy := ok && len(externalProxies) > 0
  91. if !hasExternalProxy {
  92. externalProxies = []any{map[string]any{
  93. "forceTls": "same",
  94. "dest": defaultDest,
  95. "port": float64(inbound.Port),
  96. "remark": "",
  97. }}
  98. }
  99. delete(stream, "externalProxy")
  100. proxies := make([]map[string]any, 0, len(externalProxies))
  101. for _, ep := range externalProxies {
  102. extPrxy := ep.(map[string]any)
  103. workingInbound := *inbound
  104. workingInbound.Listen = extPrxy["dest"].(string)
  105. workingInbound.Port = int(extPrxy["port"].(float64))
  106. workingStream := cloneStreamForExternalProxy(stream)
  107. switch extPrxy["forceTls"].(string) {
  108. case "tls":
  109. if workingStream["security"] != "tls" {
  110. workingStream["security"] = "tls"
  111. workingStream["tlsSettings"] = map[string]any{}
  112. }
  113. case "none":
  114. if workingStream["security"] != "none" {
  115. workingStream["security"] = "none"
  116. delete(workingStream, "tlsSettings")
  117. delete(workingStream, "realitySettings")
  118. }
  119. }
  120. security, _ := workingStream["security"].(string)
  121. if hasExternalProxy {
  122. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  123. }
  124. proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
  125. if len(proxy) > 0 {
  126. proxies = append(proxies, proxy)
  127. }
  128. }
  129. return proxies
  130. }
  131. func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
  132. // Hysteria has its own transport + TLS model, applyTransport /
  133. // applySecurity don't fit.
  134. if inbound.Protocol == model.Hysteria {
  135. return s.buildHysteriaProxy(inbound, client, extraRemark)
  136. }
  137. proxy := map[string]any{
  138. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  139. "server": inbound.Listen,
  140. "port": inbound.Port,
  141. "udp": true,
  142. }
  143. network, _ := stream["network"].(string)
  144. if !s.applyTransport(proxy, network, stream) {
  145. return nil
  146. }
  147. switch inbound.Protocol {
  148. case model.VMESS:
  149. proxy["type"] = "vmess"
  150. proxy["uuid"] = client.ID
  151. proxy["alterId"] = 0
  152. cipher := client.Security
  153. if cipher == "" {
  154. cipher = "auto"
  155. }
  156. proxy["cipher"] = cipher
  157. case model.VLESS:
  158. proxy["type"] = "vless"
  159. proxy["uuid"] = client.ID
  160. if client.Flow != "" && network == "tcp" {
  161. proxy["flow"] = client.Flow
  162. }
  163. var inboundSettings map[string]any
  164. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  165. if encryption, ok := inboundSettings["encryption"].(string); ok && encryption != "" {
  166. proxy["packet-encoding"] = encryption
  167. }
  168. case model.Trojan:
  169. proxy["type"] = "trojan"
  170. proxy["password"] = client.Password
  171. case model.Shadowsocks:
  172. proxy["type"] = "ss"
  173. proxy["password"] = client.Password
  174. var inboundSettings map[string]any
  175. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  176. method, _ := inboundSettings["method"].(string)
  177. if method == "" {
  178. return nil
  179. }
  180. proxy["cipher"] = method
  181. if strings.HasPrefix(method, "2022") {
  182. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  183. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  184. }
  185. }
  186. default:
  187. return nil
  188. }
  189. security, _ := stream["security"].(string)
  190. if !s.applySecurity(proxy, security, stream) {
  191. return nil
  192. }
  193. return proxy
  194. }
  195. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  196. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  197. // directly instead of going through streamData/tlsData, because those
  198. // helpers prune fields (like `allowInsecure` / the salamander obfs
  199. // block) that the hysteria proxy wants preserved.
  200. func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
  201. var inboundSettings map[string]any
  202. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  203. proxyType := "hysteria2"
  204. authKey := "password"
  205. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  206. proxyType = "hysteria"
  207. authKey = "auth-str"
  208. }
  209. proxy := map[string]any{
  210. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  211. "type": proxyType,
  212. "server": inbound.Listen,
  213. "port": inbound.Port,
  214. "udp": true,
  215. authKey: client.Auth,
  216. }
  217. var rawStream map[string]any
  218. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  219. // TLS details — hysteria always uses TLS.
  220. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  221. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  222. proxy["sni"] = serverName
  223. }
  224. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  225. out := make([]string, 0, len(alpnList))
  226. for _, a := range alpnList {
  227. if s, ok := a.(string); ok && s != "" {
  228. out = append(out, s)
  229. }
  230. }
  231. if len(out) > 0 {
  232. proxy["alpn"] = out
  233. }
  234. }
  235. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  236. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  237. proxy["skip-cert-verify"] = true
  238. }
  239. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  240. proxy["client-fingerprint"] = fp
  241. }
  242. }
  243. }
  244. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  245. // block the subscription link generator uses.
  246. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  247. if udpMasks, ok := finalmask["udp"].([]any); ok {
  248. for _, m := range udpMasks {
  249. mask, _ := m.(map[string]any)
  250. if mask == nil || mask["type"] != "salamander" {
  251. continue
  252. }
  253. settings, _ := mask["settings"].(map[string]any)
  254. if pw, ok := settings["password"].(string); ok && pw != "" {
  255. proxy["obfs"] = "salamander"
  256. proxy["obfs-password"] = pw
  257. break
  258. }
  259. }
  260. }
  261. }
  262. return proxy
  263. }
  264. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  265. switch network {
  266. case "", "tcp":
  267. proxy["network"] = "tcp"
  268. tcp, _ := stream["tcpSettings"].(map[string]any)
  269. if tcp != nil {
  270. header, _ := tcp["header"].(map[string]any)
  271. if header != nil {
  272. typeStr, _ := header["type"].(string)
  273. if typeStr != "" && typeStr != "none" {
  274. return false
  275. }
  276. }
  277. }
  278. return true
  279. case "ws":
  280. proxy["network"] = "ws"
  281. ws, _ := stream["wsSettings"].(map[string]any)
  282. wsOpts := map[string]any{}
  283. if ws != nil {
  284. if path, ok := ws["path"].(string); ok && path != "" {
  285. wsOpts["path"] = path
  286. }
  287. host := ""
  288. if v, ok := ws["host"].(string); ok && v != "" {
  289. host = v
  290. } else if headers, ok := ws["headers"].(map[string]any); ok {
  291. host = searchHost(headers)
  292. }
  293. if host != "" {
  294. wsOpts["headers"] = map[string]any{"Host": host}
  295. }
  296. }
  297. if len(wsOpts) > 0 {
  298. proxy["ws-opts"] = wsOpts
  299. }
  300. return true
  301. case "grpc":
  302. proxy["network"] = "grpc"
  303. grpc, _ := stream["grpcSettings"].(map[string]any)
  304. grpcOpts := map[string]any{}
  305. if grpc != nil {
  306. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  307. grpcOpts["grpc-service-name"] = serviceName
  308. }
  309. }
  310. if len(grpcOpts) > 0 {
  311. proxy["grpc-opts"] = grpcOpts
  312. }
  313. return true
  314. case "httpupgrade":
  315. proxy["network"] = "httpupgrade"
  316. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  317. opts := map[string]any{}
  318. if hu != nil {
  319. if path, ok := hu["path"].(string); ok && path != "" {
  320. opts["path"] = path
  321. }
  322. host := ""
  323. if v, ok := hu["host"].(string); ok && v != "" {
  324. host = v
  325. } else if headers, ok := hu["headers"].(map[string]any); ok {
  326. host = searchHost(headers)
  327. }
  328. if host != "" {
  329. opts["headers"] = map[string]any{"Host": host}
  330. }
  331. }
  332. if len(opts) > 0 {
  333. proxy["http-upgrade-opts"] = opts
  334. }
  335. return true
  336. case "xhttp":
  337. proxy["network"] = "xhttp"
  338. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  339. opts := map[string]any{}
  340. if xhttp != nil {
  341. if path, ok := xhttp["path"].(string); ok && path != "" {
  342. opts["path"] = path
  343. }
  344. host := ""
  345. if v, ok := xhttp["host"].(string); ok && v != "" {
  346. host = v
  347. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  348. host = searchHost(headers)
  349. }
  350. if host != "" {
  351. opts["host"] = host
  352. }
  353. if mode, ok := xhttp["mode"].(string); ok && mode != "" {
  354. opts["mode"] = mode
  355. }
  356. }
  357. if len(opts) > 0 {
  358. proxy["xhttp-opts"] = opts
  359. }
  360. return true
  361. default:
  362. return false
  363. }
  364. }
  365. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  366. switch security {
  367. case "", "none":
  368. proxy["tls"] = false
  369. return true
  370. case "tls":
  371. proxy["tls"] = true
  372. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  373. if tlsSettings != nil {
  374. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  375. proxy["servername"] = serverName
  376. switch proxy["type"] {
  377. case "trojan":
  378. proxy["sni"] = serverName
  379. }
  380. }
  381. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  382. proxy["client-fingerprint"] = fingerprint
  383. }
  384. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  385. out := make([]string, 0, len(alpn))
  386. for _, item := range alpn {
  387. if s, ok := item.(string); ok && s != "" {
  388. out = append(out, s)
  389. }
  390. }
  391. if len(out) > 0 {
  392. proxy["alpn"] = out
  393. }
  394. }
  395. }
  396. return true
  397. case "reality":
  398. proxy["tls"] = true
  399. realitySettings, _ := stream["realitySettings"].(map[string]any)
  400. if realitySettings == nil {
  401. return false
  402. }
  403. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  404. proxy["servername"] = serverName
  405. }
  406. realityOpts := map[string]any{}
  407. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  408. realityOpts["public-key"] = publicKey
  409. }
  410. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  411. realityOpts["short-id"] = shortID
  412. }
  413. if len(realityOpts) > 0 {
  414. proxy["reality-opts"] = realityOpts
  415. }
  416. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  417. proxy["client-fingerprint"] = fingerprint
  418. }
  419. return true
  420. default:
  421. return false
  422. }
  423. }
  424. func (s *SubClashService) streamData(stream string) map[string]any {
  425. var streamSettings map[string]any
  426. json.Unmarshal([]byte(stream), &streamSettings)
  427. security, _ := streamSettings["security"].(string)
  428. switch security {
  429. case "tls":
  430. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  431. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  432. }
  433. case "reality":
  434. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  435. streamSettings["realitySettings"] = s.realityData(realitySettings)
  436. }
  437. }
  438. delete(streamSettings, "sockopt")
  439. return streamSettings
  440. }
  441. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  442. tlsData := make(map[string]any, 1)
  443. tlsClientSettings, _ := tData["settings"].(map[string]any)
  444. tlsData["serverName"] = tData["serverName"]
  445. tlsData["alpn"] = tData["alpn"]
  446. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  447. tlsData["fingerprint"] = fingerprint
  448. }
  449. return tlsData
  450. }
  451. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  452. rDataOut := make(map[string]any, 1)
  453. realityClientSettings, _ := rData["settings"].(map[string]any)
  454. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  455. rDataOut["publicKey"] = publicKey
  456. }
  457. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  458. rDataOut["fingerprint"] = fingerprint
  459. }
  460. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  461. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  462. }
  463. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  464. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  465. }
  466. return rDataOut
  467. }
  468. func cloneMap(src map[string]any) map[string]any {
  469. if src == nil {
  470. return nil
  471. }
  472. dst := make(map[string]any, len(src))
  473. maps.Copy(dst, src)
  474. return dst
  475. }