1
0

outbound.go 8.8 KB

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