subClashService.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. if !ok || len(externalProxies) == 0 {
  110. externalProxies = []any{map[string]any{
  111. "forceTls": "same",
  112. "dest": defaultDest,
  113. "port": float64(inbound.Port),
  114. "remark": "",
  115. }}
  116. }
  117. delete(stream, "externalProxy")
  118. proxies := make([]map[string]any, 0, len(externalProxies))
  119. for _, ep := range externalProxies {
  120. extPrxy := ep.(map[string]any)
  121. workingInbound := *inbound
  122. workingInbound.Listen = extPrxy["dest"].(string)
  123. workingInbound.Port = int(extPrxy["port"].(float64))
  124. workingStream := cloneMap(stream)
  125. switch extPrxy["forceTls"].(string) {
  126. case "tls":
  127. if workingStream["security"] != "tls" {
  128. workingStream["security"] = "tls"
  129. workingStream["tlsSettings"] = map[string]any{}
  130. }
  131. case "none":
  132. if workingStream["security"] != "none" {
  133. workingStream["security"] = "none"
  134. delete(workingStream, "tlsSettings")
  135. delete(workingStream, "realitySettings")
  136. }
  137. }
  138. proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
  139. if len(proxy) > 0 {
  140. proxies = append(proxies, proxy)
  141. }
  142. }
  143. return proxies
  144. }
  145. func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
  146. // Hysteria has its own transport + TLS model, applyTransport /
  147. // applySecurity don't fit. IsHysteria also covers the literal
  148. // "hysteria2" protocol string (#4081).
  149. if model.IsHysteria(inbound.Protocol) {
  150. return s.buildHysteriaProxy(inbound, client, extraRemark)
  151. }
  152. proxy := map[string]any{
  153. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  154. "server": inbound.Listen,
  155. "port": inbound.Port,
  156. "udp": true,
  157. }
  158. network, _ := stream["network"].(string)
  159. if !s.applyTransport(proxy, network, stream) {
  160. return nil
  161. }
  162. switch inbound.Protocol {
  163. case model.VMESS:
  164. proxy["type"] = "vmess"
  165. proxy["uuid"] = client.ID
  166. proxy["alterId"] = 0
  167. cipher := client.Security
  168. if cipher == "" {
  169. cipher = "auto"
  170. }
  171. proxy["cipher"] = cipher
  172. case model.VLESS:
  173. proxy["type"] = "vless"
  174. proxy["uuid"] = client.ID
  175. if client.Flow != "" && network == "tcp" {
  176. proxy["flow"] = client.Flow
  177. }
  178. var inboundSettings map[string]any
  179. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  180. if encryption, ok := inboundSettings["encryption"].(string); ok && encryption != "" {
  181. proxy["packet-encoding"] = encryption
  182. }
  183. case model.Trojan:
  184. proxy["type"] = "trojan"
  185. proxy["password"] = client.Password
  186. case model.Shadowsocks:
  187. proxy["type"] = "ss"
  188. proxy["password"] = client.Password
  189. var inboundSettings map[string]any
  190. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  191. method, _ := inboundSettings["method"].(string)
  192. if method == "" {
  193. return nil
  194. }
  195. proxy["cipher"] = method
  196. if strings.HasPrefix(method, "2022") {
  197. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  198. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  199. }
  200. }
  201. default:
  202. return nil
  203. }
  204. security, _ := stream["security"].(string)
  205. if !s.applySecurity(proxy, security, stream) {
  206. return nil
  207. }
  208. return proxy
  209. }
  210. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  211. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  212. // directly instead of going through streamData/tlsData, because those
  213. // helpers prune fields (like `allowInsecure` / the salamander obfs
  214. // block) that the hysteria proxy wants preserved.
  215. func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
  216. var inboundSettings map[string]any
  217. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  218. proxyType := "hysteria2"
  219. authKey := "password"
  220. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  221. proxyType = "hysteria"
  222. authKey = "auth-str"
  223. }
  224. proxy := map[string]any{
  225. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  226. "type": proxyType,
  227. "server": inbound.Listen,
  228. "port": inbound.Port,
  229. "udp": true,
  230. authKey: client.Auth,
  231. }
  232. var rawStream map[string]any
  233. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  234. // TLS details — hysteria always uses TLS.
  235. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  236. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  237. proxy["sni"] = serverName
  238. }
  239. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  240. out := make([]string, 0, len(alpnList))
  241. for _, a := range alpnList {
  242. if s, ok := a.(string); ok && s != "" {
  243. out = append(out, s)
  244. }
  245. }
  246. if len(out) > 0 {
  247. proxy["alpn"] = out
  248. }
  249. }
  250. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  251. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  252. proxy["skip-cert-verify"] = true
  253. }
  254. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  255. proxy["client-fingerprint"] = fp
  256. }
  257. }
  258. }
  259. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  260. // block the subscription link generator uses.
  261. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  262. if udpMasks, ok := finalmask["udp"].([]any); ok {
  263. for _, m := range udpMasks {
  264. mask, _ := m.(map[string]any)
  265. if mask == nil || mask["type"] != "salamander" {
  266. continue
  267. }
  268. settings, _ := mask["settings"].(map[string]any)
  269. if pw, ok := settings["password"].(string); ok && pw != "" {
  270. proxy["obfs"] = "salamander"
  271. proxy["obfs-password"] = pw
  272. break
  273. }
  274. }
  275. }
  276. }
  277. return proxy
  278. }
  279. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  280. switch network {
  281. case "", "tcp":
  282. proxy["network"] = "tcp"
  283. tcp, _ := stream["tcpSettings"].(map[string]any)
  284. if tcp != nil {
  285. header, _ := tcp["header"].(map[string]any)
  286. if header != nil {
  287. typeStr, _ := header["type"].(string)
  288. if typeStr != "" && typeStr != "none" {
  289. return false
  290. }
  291. }
  292. }
  293. return true
  294. case "ws":
  295. proxy["network"] = "ws"
  296. ws, _ := stream["wsSettings"].(map[string]any)
  297. wsOpts := map[string]any{}
  298. if ws != nil {
  299. if path, ok := ws["path"].(string); ok && path != "" {
  300. wsOpts["path"] = path
  301. }
  302. host := ""
  303. if v, ok := ws["host"].(string); ok && v != "" {
  304. host = v
  305. } else if headers, ok := ws["headers"].(map[string]any); ok {
  306. host = searchHost(headers)
  307. }
  308. if host != "" {
  309. wsOpts["headers"] = map[string]any{"Host": host}
  310. }
  311. }
  312. if len(wsOpts) > 0 {
  313. proxy["ws-opts"] = wsOpts
  314. }
  315. return true
  316. case "grpc":
  317. proxy["network"] = "grpc"
  318. grpc, _ := stream["grpcSettings"].(map[string]any)
  319. grpcOpts := map[string]any{}
  320. if grpc != nil {
  321. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  322. grpcOpts["grpc-service-name"] = serviceName
  323. }
  324. }
  325. if len(grpcOpts) > 0 {
  326. proxy["grpc-opts"] = grpcOpts
  327. }
  328. return true
  329. default:
  330. return false
  331. }
  332. }
  333. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  334. switch security {
  335. case "", "none":
  336. proxy["tls"] = false
  337. return true
  338. case "tls":
  339. proxy["tls"] = true
  340. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  341. if tlsSettings != nil {
  342. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  343. proxy["servername"] = serverName
  344. switch proxy["type"] {
  345. case "trojan":
  346. proxy["sni"] = serverName
  347. }
  348. }
  349. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  350. proxy["client-fingerprint"] = fingerprint
  351. }
  352. }
  353. return true
  354. case "reality":
  355. proxy["tls"] = true
  356. realitySettings, _ := stream["realitySettings"].(map[string]any)
  357. if realitySettings == nil {
  358. return false
  359. }
  360. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  361. proxy["servername"] = serverName
  362. }
  363. realityOpts := map[string]any{}
  364. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  365. realityOpts["public-key"] = publicKey
  366. }
  367. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  368. realityOpts["short-id"] = shortID
  369. }
  370. if len(realityOpts) > 0 {
  371. proxy["reality-opts"] = realityOpts
  372. }
  373. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  374. proxy["client-fingerprint"] = fingerprint
  375. }
  376. return true
  377. default:
  378. return false
  379. }
  380. }
  381. func (s *SubClashService) streamData(stream string) map[string]any {
  382. var streamSettings map[string]any
  383. json.Unmarshal([]byte(stream), &streamSettings)
  384. security, _ := streamSettings["security"].(string)
  385. switch security {
  386. case "tls":
  387. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  388. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  389. }
  390. case "reality":
  391. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  392. streamSettings["realitySettings"] = s.realityData(realitySettings)
  393. }
  394. }
  395. delete(streamSettings, "sockopt")
  396. return streamSettings
  397. }
  398. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  399. tlsData := make(map[string]any, 1)
  400. tlsClientSettings, _ := tData["settings"].(map[string]any)
  401. tlsData["serverName"] = tData["serverName"]
  402. tlsData["alpn"] = tData["alpn"]
  403. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  404. tlsData["fingerprint"] = fingerprint
  405. }
  406. return tlsData
  407. }
  408. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  409. rDataOut := make(map[string]any, 1)
  410. realityClientSettings, _ := rData["settings"].(map[string]any)
  411. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  412. rDataOut["publicKey"] = publicKey
  413. }
  414. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  415. rDataOut["fingerprint"] = fingerprint
  416. }
  417. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  418. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  419. }
  420. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  421. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  422. }
  423. return rDataOut
  424. }
  425. func cloneMap(src map[string]any) map[string]any {
  426. if src == nil {
  427. return nil
  428. }
  429. dst := make(map[string]any, len(src))
  430. maps.Copy(dst, src)
  431. return dst
  432. }