subClashService.go 15 KB

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