outbound.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. package outbound
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "slices"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "gorm.io/gorm"
  17. )
  18. // OutboundService provides business logic for managing Xray outbound configurations.
  19. // It handles outbound traffic monitoring and statistics.
  20. type OutboundService struct{}
  21. func (s *OutboundService) AddTraffic(traffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  22. err := database.GetDB().Transaction(func(tx *gorm.DB) error {
  23. return s.addOutboundTraffic(tx, traffics)
  24. })
  25. return err, false
  26. }
  27. // saturatingAdd caps counters at database.TrafficMax: unlike the SQL paths,
  28. // this read-modify-write add happens in Go, where an int64 overflow silently
  29. // wraps negative instead of erroring (#5762).
  30. func saturatingAdd(a, b int64) int64 {
  31. if b > database.TrafficMax-a {
  32. return database.TrafficMax
  33. }
  34. return a + b
  35. }
  36. func (s *OutboundService) addOutboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  37. if len(traffics) == 0 {
  38. return nil
  39. }
  40. var err error
  41. for _, traffic := range traffics {
  42. if traffic.IsOutbound {
  43. var outbound model.OutboundTraffics
  44. err = tx.Model(&model.OutboundTraffics{}).Where("tag = ?", traffic.Tag).
  45. FirstOrCreate(&outbound).Error
  46. if err != nil {
  47. return err
  48. }
  49. outbound.Tag = traffic.Tag
  50. outbound.Up = saturatingAdd(outbound.Up, traffic.Up)
  51. outbound.Down = saturatingAdd(outbound.Down, traffic.Down)
  52. outbound.Total = saturatingAdd(outbound.Up, outbound.Down)
  53. err = tx.Save(&outbound).Error
  54. if err != nil {
  55. return err
  56. }
  57. }
  58. }
  59. return nil
  60. }
  61. func (s *OutboundService) GetOutboundsTraffic() ([]*model.OutboundTraffics, error) {
  62. db := database.GetDB()
  63. var traffics []*model.OutboundTraffics
  64. err := db.Model(model.OutboundTraffics{}).Find(&traffics).Error
  65. if err != nil {
  66. logger.Warning("Error retrieving OutboundTraffics: ", err)
  67. return nil, err
  68. }
  69. return traffics, nil
  70. }
  71. func (s *OutboundService) ResetOutboundTraffic(tag string) error {
  72. db := database.GetDB()
  73. whereText := "tag "
  74. if tag == "-alltags-" {
  75. whereText += " <> ?"
  76. } else {
  77. whereText += " = ?"
  78. }
  79. result := db.Model(model.OutboundTraffics{}).
  80. Where(whereText, tag).
  81. Updates(map[string]any{"up": 0, "down": 0, "total": 0})
  82. err := result.Error
  83. if err != nil {
  84. return err
  85. }
  86. return nil
  87. }
  88. // TestOutboundResult represents the result of testing an outbound.
  89. // Delay is in milliseconds. Endpoints is only populated for TCP-mode
  90. // probes; HTTP mode reports the round-trip of a real HTTP request on an
  91. // established connection through the outbound (the cold first request
  92. // supplies the timing breakdown).
  93. type TestOutboundResult struct {
  94. Tag string `json:"tag,omitempty"`
  95. Success bool `json:"success"`
  96. Delay int64 `json:"delay"`
  97. Error string `json:"error,omitempty"`
  98. Mode string `json:"mode,omitempty"`
  99. // HTTP-mode extras. Any HTTP response counts as reachable; HTTPStatus
  100. // records what the test URL answered. ConnectMs is the dial to the local
  101. // test inbound; TLSMs covers outbound-chain establishment + target TLS
  102. // (https URLs only, since xray ACKs the SOCKS CONNECT before dialing
  103. // upstream); TTFBMs is request start → first response byte.
  104. HTTPStatus int `json:"httpStatus,omitempty"`
  105. ConnectMs int64 `json:"connectMs,omitempty"`
  106. TLSMs int64 `json:"tlsMs,omitempty"`
  107. TTFBMs int64 `json:"ttfbMs,omitempty"`
  108. Endpoints []TestEndpointResult `json:"endpoints,omitempty"`
  109. Egress *TestEgressResult `json:"egress,omitempty"`
  110. }
  111. // TestEndpointResult is one entry in a TCP-mode probe — the per-endpoint
  112. // dial outcome for outbounds that expose multiple servers/peers.
  113. type TestEndpointResult struct {
  114. Address string `json:"address"`
  115. Success bool `json:"success"`
  116. Delay int64 `json:"delay"`
  117. Error string `json:"error,omitempty"`
  118. }
  119. // TestEgressResult is populated by HTTP-mode probes from Cloudflare's trace
  120. // endpoint. It reports what an external service sees after the outbound chain.
  121. type TestEgressResult struct {
  122. IPv4 string `json:"ipv4,omitempty"`
  123. IPv6 string `json:"ipv6,omitempty"`
  124. Country string `json:"country,omitempty"`
  125. Warp string `json:"warp,omitempty"`
  126. }
  127. func (s *OutboundService) testOutboundTCP(outboundJSON string) (*TestOutboundResult, error) {
  128. var ob map[string]any
  129. if err := json.Unmarshal([]byte(outboundJSON), &ob); err != nil {
  130. return &TestOutboundResult{Mode: "tcp", Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}, nil
  131. }
  132. tag, _ := ob["tag"].(string)
  133. protocol, _ := ob["protocol"].(string)
  134. if equalsAnyFold(protocol, "blackhole", "freedom") || tag == "blocked" {
  135. return &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: "Outbound has no testable endpoint"}, nil
  136. }
  137. endpoints := extractOutboundEndpoints(ob)
  138. if len(endpoints) == 0 {
  139. return &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: "No testable endpoint"}, nil
  140. }
  141. results := make([]TestEndpointResult, len(endpoints))
  142. var wg sync.WaitGroup
  143. for i := range endpoints {
  144. wg.Add(1)
  145. go func(i int) {
  146. defer wg.Done()
  147. results[i] = probeTCPEndpoint(endpoints[i], 5*time.Second)
  148. }(i)
  149. }
  150. wg.Wait()
  151. var bestDelay int64 = -1
  152. var firstErr string
  153. for _, r := range results {
  154. if r.Success {
  155. if bestDelay < 0 || r.Delay < bestDelay {
  156. bestDelay = r.Delay
  157. }
  158. } else if firstErr == "" {
  159. firstErr = r.Error
  160. }
  161. }
  162. out := &TestOutboundResult{Tag: tag, Mode: "tcp", Endpoints: results}
  163. if bestDelay >= 0 {
  164. out.Success = true
  165. out.Delay = bestDelay
  166. } else {
  167. out.Error = firstErr
  168. if out.Error == "" {
  169. out.Error = "All endpoints unreachable"
  170. }
  171. }
  172. return out, nil
  173. }
  174. func probeTCPEndpoint(endpoint string, timeout time.Duration) TestEndpointResult {
  175. r := TestEndpointResult{Address: endpoint}
  176. start := time.Now()
  177. conn, err := (&net.Dialer{Timeout: timeout}).DialContext(context.Background(), "tcp", endpoint)
  178. r.Delay = time.Since(start).Milliseconds()
  179. if err != nil {
  180. r.Error = err.Error()
  181. return r
  182. }
  183. conn.Close()
  184. r.Success = true
  185. return r
  186. }
  187. // outboundTransportIsUDP reports whether the outbound's proxy speaks UDP
  188. // (wireguard, hysteria, or a kcp/quic/hysteria stream transport). A bare
  189. // UDP dial can't probe these — they ignore unauthenticated packets, so a
  190. // dial neither proves reachability nor measures latency. Such outbounds
  191. // must go through the real xray handshake probe instead.
  192. func outboundTransportIsUDP(ob map[string]any) bool {
  193. if protocol, _ := ob["protocol"].(string); equalsAnyFold(protocol, "hysteria", "wireguard", "amneziawg") {
  194. return true
  195. }
  196. if protocol, _ := ob["protocol"].(string); equalsAnyFold(protocol, "masque") {
  197. return masqueDialsHTTP3(ob)
  198. }
  199. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  200. // The core resolves "kcp" and "mkcp" to the same mKCP transport.
  201. if n, _ := stream["network"].(string); equalsAnyFold(n, "hysteria", "kcp", "mkcp", "quic") {
  202. return true
  203. }
  204. }
  205. return false
  206. }
  207. // masqueDialsHTTP3 mirrors the core's MASQUE client, which falls back to HTTP/2 over
  208. // TCP only when the TLS ALPN offers h2 and not h3.
  209. func masqueDialsHTTP3(ob map[string]any) bool {
  210. stream, _ := ob["streamSettings"].(map[string]any)
  211. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  212. alpn, _ := tlsSettings["alpn"].([]any)
  213. return !slices.Contains(alpn, any("h2")) || slices.Contains(alpn, any("h3"))
  214. }
  215. // equalsAnyFold mirrors the core, which lowercases a protocol id and a
  216. // transport name before it resolves either of them.
  217. func equalsAnyFold(value string, want ...string) bool {
  218. for _, w := range want {
  219. if strings.EqualFold(value, w) {
  220. return true
  221. }
  222. }
  223. return false
  224. }
  225. func extractOutboundEndpoints(ob map[string]any) []string {
  226. protocol, _ := ob["protocol"].(string)
  227. protocol = strings.ToLower(protocol)
  228. settings, _ := ob["settings"].(map[string]any)
  229. if settings == nil {
  230. return nil
  231. }
  232. var out []string
  233. addServer := func(addr any, port any) {
  234. host, _ := addr.(string)
  235. p := numAsInt(port)
  236. if host != "" && p > 0 {
  237. out = append(out, fmt.Sprintf("%s:%d", host, p))
  238. }
  239. }
  240. switch protocol {
  241. case "vmess":
  242. if vnext, ok := settings["vnext"].([]any); ok {
  243. for _, v := range vnext {
  244. if vm, ok := v.(map[string]any); ok {
  245. addServer(vm["address"], vm["port"])
  246. }
  247. }
  248. }
  249. case "vless":
  250. if vnext, ok := settings["vnext"].([]any); ok {
  251. for _, v := range vnext {
  252. if vm, ok := v.(map[string]any); ok {
  253. addServer(vm["address"], vm["port"])
  254. }
  255. }
  256. }
  257. if len(out) == 0 {
  258. addServer(settings["address"], settings["port"])
  259. }
  260. case "hysteria", "masque":
  261. addServer(settings["address"], settings["port"])
  262. case "trojan", "shadowsocks", "http", "socks":
  263. if servers, ok := settings["servers"].([]any); ok {
  264. for _, sv := range servers {
  265. if sm, ok := sv.(map[string]any); ok {
  266. addServer(sm["address"], sm["port"])
  267. }
  268. }
  269. }
  270. case "wireguard":
  271. if peers, ok := settings["peers"].([]any); ok {
  272. for _, p := range peers {
  273. if pm, ok := p.(map[string]any); ok {
  274. if ep, _ := pm["endpoint"].(string); ep != "" {
  275. out = append(out, ep)
  276. }
  277. }
  278. }
  279. }
  280. }
  281. return out
  282. }
  283. func numAsInt(v any) int {
  284. switch n := v.(type) {
  285. case float64:
  286. return int(n)
  287. case int:
  288. return n
  289. case int64:
  290. return int(n)
  291. case string:
  292. if i, err := strconv.Atoi(n); err == nil {
  293. return i
  294. }
  295. }
  296. return 0
  297. }