1
0

subClashService.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. "github.com/mhsanaei/3x-ui/v3/xray"
  12. )
  13. type SubClashService struct {
  14. inboundService service.InboundService
  15. SubService *SubService
  16. }
  17. type ClashConfig struct {
  18. Proxies []map[string]any `yaml:"proxies"`
  19. ProxyGroups []map[string]any `yaml:"proxy-groups"`
  20. Rules []string `yaml:"rules"`
  21. }
  22. func NewSubClashService(subService *SubService) *SubClashService {
  23. return &SubClashService{SubService: subService}
  24. }
  25. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  26. // Set per-request state so resolveInboundAddress sees the node map.
  27. s.SubService.PrepareForRequest(host)
  28. inbounds, err := s.SubService.getInboundsBySubId(subId)
  29. if err != nil || len(inbounds) == 0 {
  30. return "", "", err
  31. }
  32. var traffic xray.ClientTraffic
  33. var clientTraffics []xray.ClientTraffic
  34. var proxies []map[string]any
  35. seenEmails := make(map[string]struct{})
  36. for _, inbound := range inbounds {
  37. clients, err := s.inboundService.GetClients(inbound)
  38. if err != nil {
  39. logger.Error("SubClashService - GetClients: Unable to get clients from inbound")
  40. }
  41. if clients == nil {
  42. continue
  43. }
  44. s.SubService.projectThroughFallbackMaster(inbound)
  45. for _, client := range clients {
  46. if client.SubID == subId {
  47. _, clientTraffics = s.SubService.appendUniqueTraffic(seenEmails, clientTraffics, inbound.ClientStats, client.Email)
  48. proxies = append(proxies, s.getProxies(inbound, client, host)...)
  49. }
  50. }
  51. }
  52. if len(proxies) == 0 {
  53. return "", "", nil
  54. }
  55. for index, clientTraffic := range clientTraffics {
  56. if index == 0 {
  57. traffic.Up = clientTraffic.Up
  58. traffic.Down = clientTraffic.Down
  59. traffic.Total = clientTraffic.Total
  60. if clientTraffic.ExpiryTime > 0 {
  61. traffic.ExpiryTime = clientTraffic.ExpiryTime
  62. }
  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. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  72. traffic.ExpiryTime = 0
  73. }
  74. }
  75. }
  76. proxyNames := make([]string, 0, len(proxies)+1)
  77. for _, proxy := range proxies {
  78. if name, ok := proxy["name"].(string); ok && name != "" {
  79. proxyNames = append(proxyNames, name)
  80. }
  81. }
  82. proxyNames = append(proxyNames, "DIRECT")
  83. config := ClashConfig{
  84. Proxies: proxies,
  85. ProxyGroups: []map[string]any{{
  86. "name": "PROXY",
  87. "type": "select",
  88. "proxies": proxyNames,
  89. }},
  90. Rules: []string{"MATCH,PROXY"},
  91. }
  92. finalYAML, err := yaml.Marshal(config)
  93. if err != nil {
  94. return "", "", err
  95. }
  96. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  97. return string(finalYAML), header, nil
  98. }
  99. func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client, host string) []map[string]any {
  100. stream := s.streamData(inbound.StreamSettings)
  101. // For node-managed inbounds the Clash proxy "server" must be the
  102. // node's address, not the request host. resolveInboundAddress handles
  103. // the node→listen→request-host fallback chain.
  104. defaultDest := s.SubService.resolveInboundAddress(inbound)
  105. if defaultDest == "" {
  106. defaultDest = host
  107. }
  108. externalProxies, ok := stream["externalProxy"].([]any)
  109. hasExternalProxy := ok && len(externalProxies) > 0
  110. if !hasExternalProxy {
  111. externalProxies = []any{map[string]any{
  112. "forceTls": "same",
  113. "dest": defaultDest,
  114. "port": float64(inbound.Port),
  115. "remark": "",
  116. }}
  117. }
  118. delete(stream, "externalProxy")
  119. proxies := make([]map[string]any, 0, len(externalProxies))
  120. for _, ep := range externalProxies {
  121. extPrxy := ep.(map[string]any)
  122. workingInbound := *inbound
  123. workingInbound.Listen = extPrxy["dest"].(string)
  124. workingInbound.Port = int(extPrxy["port"].(float64))
  125. workingStream := cloneStreamForExternalProxy(stream)
  126. switch extPrxy["forceTls"].(string) {
  127. case "tls":
  128. if workingStream["security"] != "tls" {
  129. workingStream["security"] = "tls"
  130. workingStream["tlsSettings"] = map[string]any{}
  131. }
  132. case "none":
  133. if workingStream["security"] != "none" {
  134. workingStream["security"] = "none"
  135. delete(workingStream, "tlsSettings")
  136. delete(workingStream, "realitySettings")
  137. }
  138. }
  139. security, _ := workingStream["security"].(string)
  140. if hasExternalProxy {
  141. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  142. }
  143. proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
  144. if len(proxy) > 0 {
  145. proxies = append(proxies, proxy)
  146. }
  147. }
  148. return proxies
  149. }
  150. func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
  151. // Hysteria has its own transport + TLS model, applyTransport /
  152. // applySecurity don't fit. IsHysteria also covers the literal
  153. // "hysteria2" protocol string (#4081).
  154. if model.IsHysteria(inbound.Protocol) {
  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. default:
  335. return false
  336. }
  337. }
  338. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  339. switch security {
  340. case "", "none":
  341. proxy["tls"] = false
  342. return true
  343. case "tls":
  344. proxy["tls"] = true
  345. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  346. if tlsSettings != nil {
  347. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  348. proxy["servername"] = serverName
  349. switch proxy["type"] {
  350. case "trojan":
  351. proxy["sni"] = serverName
  352. }
  353. }
  354. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  355. proxy["client-fingerprint"] = fingerprint
  356. }
  357. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  358. out := make([]string, 0, len(alpn))
  359. for _, item := range alpn {
  360. if s, ok := item.(string); ok && s != "" {
  361. out = append(out, s)
  362. }
  363. }
  364. if len(out) > 0 {
  365. proxy["alpn"] = out
  366. }
  367. }
  368. }
  369. return true
  370. case "reality":
  371. proxy["tls"] = true
  372. realitySettings, _ := stream["realitySettings"].(map[string]any)
  373. if realitySettings == nil {
  374. return false
  375. }
  376. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  377. proxy["servername"] = serverName
  378. }
  379. realityOpts := map[string]any{}
  380. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  381. realityOpts["public-key"] = publicKey
  382. }
  383. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  384. realityOpts["short-id"] = shortID
  385. }
  386. if len(realityOpts) > 0 {
  387. proxy["reality-opts"] = realityOpts
  388. }
  389. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  390. proxy["client-fingerprint"] = fingerprint
  391. }
  392. return true
  393. default:
  394. return false
  395. }
  396. }
  397. func (s *SubClashService) streamData(stream string) map[string]any {
  398. var streamSettings map[string]any
  399. json.Unmarshal([]byte(stream), &streamSettings)
  400. security, _ := streamSettings["security"].(string)
  401. switch security {
  402. case "tls":
  403. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  404. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  405. }
  406. case "reality":
  407. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  408. streamSettings["realitySettings"] = s.realityData(realitySettings)
  409. }
  410. }
  411. delete(streamSettings, "sockopt")
  412. return streamSettings
  413. }
  414. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  415. tlsData := make(map[string]any, 1)
  416. tlsClientSettings, _ := tData["settings"].(map[string]any)
  417. tlsData["serverName"] = tData["serverName"]
  418. tlsData["alpn"] = tData["alpn"]
  419. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  420. tlsData["fingerprint"] = fingerprint
  421. }
  422. return tlsData
  423. }
  424. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  425. rDataOut := make(map[string]any, 1)
  426. realityClientSettings, _ := rData["settings"].(map[string]any)
  427. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  428. rDataOut["publicKey"] = publicKey
  429. }
  430. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  431. rDataOut["fingerprint"] = fingerprint
  432. }
  433. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  434. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  435. }
  436. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  437. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  438. }
  439. return rDataOut
  440. }
  441. func cloneMap(src map[string]any) map[string]any {
  442. if src == nil {
  443. return nil
  444. }
  445. dst := make(map[string]any, len(src))
  446. maps.Copy(dst, src)
  447. return dst
  448. }