subClashService.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. IsHysteria also covers the literal
  154. // "hysteria2" protocol string (#4081).
  155. if model.IsHysteria(inbound.Protocol) {
  156. return s.buildHysteriaProxy(inbound, client, extraRemark)
  157. }
  158. proxy := map[string]any{
  159. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  160. "server": inbound.Listen,
  161. "port": inbound.Port,
  162. "udp": true,
  163. }
  164. network, _ := stream["network"].(string)
  165. if !s.applyTransport(proxy, network, stream) {
  166. return nil
  167. }
  168. switch inbound.Protocol {
  169. case model.VMESS:
  170. proxy["type"] = "vmess"
  171. proxy["uuid"] = client.ID
  172. proxy["alterId"] = 0
  173. cipher := client.Security
  174. if cipher == "" {
  175. cipher = "auto"
  176. }
  177. proxy["cipher"] = cipher
  178. case model.VLESS:
  179. proxy["type"] = "vless"
  180. proxy["uuid"] = client.ID
  181. if client.Flow != "" && network == "tcp" {
  182. proxy["flow"] = client.Flow
  183. }
  184. var inboundSettings map[string]any
  185. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  186. if encryption, ok := inboundSettings["encryption"].(string); ok && encryption != "" {
  187. proxy["packet-encoding"] = encryption
  188. }
  189. case model.Trojan:
  190. proxy["type"] = "trojan"
  191. proxy["password"] = client.Password
  192. case model.Shadowsocks:
  193. proxy["type"] = "ss"
  194. proxy["password"] = client.Password
  195. var inboundSettings map[string]any
  196. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  197. method, _ := inboundSettings["method"].(string)
  198. if method == "" {
  199. return nil
  200. }
  201. proxy["cipher"] = method
  202. if strings.HasPrefix(method, "2022") {
  203. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  204. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  205. }
  206. }
  207. default:
  208. return nil
  209. }
  210. security, _ := stream["security"].(string)
  211. if !s.applySecurity(proxy, security, stream) {
  212. return nil
  213. }
  214. return proxy
  215. }
  216. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  217. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  218. // directly instead of going through streamData/tlsData, because those
  219. // helpers prune fields (like `allowInsecure` / the salamander obfs
  220. // block) that the hysteria proxy wants preserved.
  221. func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
  222. var inboundSettings map[string]any
  223. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  224. proxyType := "hysteria2"
  225. authKey := "password"
  226. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  227. proxyType = "hysteria"
  228. authKey = "auth-str"
  229. }
  230. proxy := map[string]any{
  231. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  232. "type": proxyType,
  233. "server": inbound.Listen,
  234. "port": inbound.Port,
  235. "udp": true,
  236. authKey: client.Auth,
  237. }
  238. var rawStream map[string]any
  239. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  240. // TLS details — hysteria always uses TLS.
  241. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  242. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  243. proxy["sni"] = serverName
  244. }
  245. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  246. out := make([]string, 0, len(alpnList))
  247. for _, a := range alpnList {
  248. if s, ok := a.(string); ok && s != "" {
  249. out = append(out, s)
  250. }
  251. }
  252. if len(out) > 0 {
  253. proxy["alpn"] = out
  254. }
  255. }
  256. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  257. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  258. proxy["skip-cert-verify"] = true
  259. }
  260. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  261. proxy["client-fingerprint"] = fp
  262. }
  263. }
  264. }
  265. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  266. // block the subscription link generator uses.
  267. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  268. if udpMasks, ok := finalmask["udp"].([]any); ok {
  269. for _, m := range udpMasks {
  270. mask, _ := m.(map[string]any)
  271. if mask == nil || mask["type"] != "salamander" {
  272. continue
  273. }
  274. settings, _ := mask["settings"].(map[string]any)
  275. if pw, ok := settings["password"].(string); ok && pw != "" {
  276. proxy["obfs"] = "salamander"
  277. proxy["obfs-password"] = pw
  278. break
  279. }
  280. }
  281. }
  282. }
  283. return proxy
  284. }
  285. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  286. switch network {
  287. case "", "tcp":
  288. proxy["network"] = "tcp"
  289. tcp, _ := stream["tcpSettings"].(map[string]any)
  290. if tcp != nil {
  291. header, _ := tcp["header"].(map[string]any)
  292. if header != nil {
  293. typeStr, _ := header["type"].(string)
  294. if typeStr != "" && typeStr != "none" {
  295. return false
  296. }
  297. }
  298. }
  299. return true
  300. case "ws":
  301. proxy["network"] = "ws"
  302. ws, _ := stream["wsSettings"].(map[string]any)
  303. wsOpts := map[string]any{}
  304. if ws != nil {
  305. if path, ok := ws["path"].(string); ok && path != "" {
  306. wsOpts["path"] = path
  307. }
  308. host := ""
  309. if v, ok := ws["host"].(string); ok && v != "" {
  310. host = v
  311. } else if headers, ok := ws["headers"].(map[string]any); ok {
  312. host = searchHost(headers)
  313. }
  314. if host != "" {
  315. wsOpts["headers"] = map[string]any{"Host": host}
  316. }
  317. }
  318. if len(wsOpts) > 0 {
  319. proxy["ws-opts"] = wsOpts
  320. }
  321. return true
  322. case "grpc":
  323. proxy["network"] = "grpc"
  324. grpc, _ := stream["grpcSettings"].(map[string]any)
  325. grpcOpts := map[string]any{}
  326. if grpc != nil {
  327. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  328. grpcOpts["grpc-service-name"] = serviceName
  329. }
  330. }
  331. if len(grpcOpts) > 0 {
  332. proxy["grpc-opts"] = grpcOpts
  333. }
  334. return true
  335. case "httpupgrade":
  336. proxy["network"] = "httpupgrade"
  337. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  338. opts := map[string]any{}
  339. if hu != nil {
  340. if path, ok := hu["path"].(string); ok && path != "" {
  341. opts["path"] = path
  342. }
  343. host := ""
  344. if v, ok := hu["host"].(string); ok && v != "" {
  345. host = v
  346. } else if headers, ok := hu["headers"].(map[string]any); ok {
  347. host = searchHost(headers)
  348. }
  349. if host != "" {
  350. opts["headers"] = map[string]any{"Host": host}
  351. }
  352. }
  353. if len(opts) > 0 {
  354. proxy["http-upgrade-opts"] = opts
  355. }
  356. return true
  357. case "xhttp":
  358. proxy["network"] = "xhttp"
  359. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  360. opts := map[string]any{}
  361. if xhttp != nil {
  362. if path, ok := xhttp["path"].(string); ok && path != "" {
  363. opts["path"] = path
  364. }
  365. host := ""
  366. if v, ok := xhttp["host"].(string); ok && v != "" {
  367. host = v
  368. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  369. host = searchHost(headers)
  370. }
  371. if host != "" {
  372. opts["host"] = host
  373. }
  374. if mode, ok := xhttp["mode"].(string); ok && mode != "" {
  375. opts["mode"] = mode
  376. }
  377. }
  378. if len(opts) > 0 {
  379. proxy["xhttp-opts"] = opts
  380. }
  381. return true
  382. default:
  383. return false
  384. }
  385. }
  386. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  387. switch security {
  388. case "", "none":
  389. proxy["tls"] = false
  390. return true
  391. case "tls":
  392. proxy["tls"] = true
  393. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  394. if tlsSettings != nil {
  395. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  396. proxy["servername"] = serverName
  397. switch proxy["type"] {
  398. case "trojan":
  399. proxy["sni"] = serverName
  400. }
  401. }
  402. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  403. proxy["client-fingerprint"] = fingerprint
  404. }
  405. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  406. out := make([]string, 0, len(alpn))
  407. for _, item := range alpn {
  408. if s, ok := item.(string); ok && s != "" {
  409. out = append(out, s)
  410. }
  411. }
  412. if len(out) > 0 {
  413. proxy["alpn"] = out
  414. }
  415. }
  416. }
  417. return true
  418. case "reality":
  419. proxy["tls"] = true
  420. realitySettings, _ := stream["realitySettings"].(map[string]any)
  421. if realitySettings == nil {
  422. return false
  423. }
  424. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  425. proxy["servername"] = serverName
  426. }
  427. realityOpts := map[string]any{}
  428. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  429. realityOpts["public-key"] = publicKey
  430. }
  431. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  432. realityOpts["short-id"] = shortID
  433. }
  434. if len(realityOpts) > 0 {
  435. proxy["reality-opts"] = realityOpts
  436. }
  437. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  438. proxy["client-fingerprint"] = fingerprint
  439. }
  440. return true
  441. default:
  442. return false
  443. }
  444. }
  445. func (s *SubClashService) streamData(stream string) map[string]any {
  446. var streamSettings map[string]any
  447. json.Unmarshal([]byte(stream), &streamSettings)
  448. security, _ := streamSettings["security"].(string)
  449. switch security {
  450. case "tls":
  451. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  452. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  453. }
  454. case "reality":
  455. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  456. streamSettings["realitySettings"] = s.realityData(realitySettings)
  457. }
  458. }
  459. delete(streamSettings, "sockopt")
  460. return streamSettings
  461. }
  462. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  463. tlsData := make(map[string]any, 1)
  464. tlsClientSettings, _ := tData["settings"].(map[string]any)
  465. tlsData["serverName"] = tData["serverName"]
  466. tlsData["alpn"] = tData["alpn"]
  467. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  468. tlsData["fingerprint"] = fingerprint
  469. }
  470. return tlsData
  471. }
  472. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  473. rDataOut := make(map[string]any, 1)
  474. realityClientSettings, _ := rData["settings"].(map[string]any)
  475. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  476. rDataOut["publicKey"] = publicKey
  477. }
  478. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  479. rDataOut["fingerprint"] = fingerprint
  480. }
  481. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  482. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  483. }
  484. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  485. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  486. }
  487. return rDataOut
  488. }
  489. func cloneMap(src map[string]any) map[string]any {
  490. if src == nil {
  491. return nil
  492. }
  493. dst := make(map[string]any, len(src))
  494. maps.Copy(dst, src)
  495. return dst
  496. }