1
0

outbound.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. package outbound
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "strconv"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. "gorm.io/gorm"
  15. )
  16. // OutboundService provides business logic for managing Xray outbound configurations.
  17. // It handles outbound traffic monitoring and statistics.
  18. type OutboundService struct{}
  19. func (s *OutboundService) AddTraffic(traffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  20. var err error
  21. db := database.GetDB()
  22. tx := db.Begin()
  23. defer func() {
  24. if err != nil {
  25. tx.Rollback()
  26. } else {
  27. tx.Commit()
  28. }
  29. }()
  30. err = s.addOutboundTraffic(tx, traffics)
  31. if err != nil {
  32. return err, false
  33. }
  34. return nil, false
  35. }
  36. // saturatingAdd caps counters at database.TrafficMax: unlike the SQL paths,
  37. // this read-modify-write add happens in Go, where an int64 overflow silently
  38. // wraps negative instead of erroring (#5762).
  39. func saturatingAdd(a, b int64) int64 {
  40. if b > database.TrafficMax-a {
  41. return database.TrafficMax
  42. }
  43. return a + b
  44. }
  45. func (s *OutboundService) addOutboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  46. if len(traffics) == 0 {
  47. return nil
  48. }
  49. var err error
  50. for _, traffic := range traffics {
  51. if traffic.IsOutbound {
  52. var outbound model.OutboundTraffics
  53. err = tx.Model(&model.OutboundTraffics{}).Where("tag = ?", traffic.Tag).
  54. FirstOrCreate(&outbound).Error
  55. if err != nil {
  56. return err
  57. }
  58. outbound.Tag = traffic.Tag
  59. outbound.Up = saturatingAdd(outbound.Up, traffic.Up)
  60. outbound.Down = saturatingAdd(outbound.Down, traffic.Down)
  61. outbound.Total = saturatingAdd(outbound.Up, outbound.Down)
  62. err = tx.Save(&outbound).Error
  63. if err != nil {
  64. return err
  65. }
  66. }
  67. }
  68. return nil
  69. }
  70. func (s *OutboundService) GetOutboundsTraffic() ([]*model.OutboundTraffics, error) {
  71. db := database.GetDB()
  72. var traffics []*model.OutboundTraffics
  73. err := db.Model(model.OutboundTraffics{}).Find(&traffics).Error
  74. if err != nil {
  75. logger.Warning("Error retrieving OutboundTraffics: ", err)
  76. return nil, err
  77. }
  78. return traffics, nil
  79. }
  80. func (s *OutboundService) ResetOutboundTraffic(tag string) error {
  81. db := database.GetDB()
  82. whereText := "tag "
  83. if tag == "-alltags-" {
  84. whereText += " <> ?"
  85. } else {
  86. whereText += " = ?"
  87. }
  88. result := db.Model(model.OutboundTraffics{}).
  89. Where(whereText, tag).
  90. Updates(map[string]any{"up": 0, "down": 0, "total": 0})
  91. err := result.Error
  92. if err != nil {
  93. return err
  94. }
  95. return nil
  96. }
  97. // TestOutboundResult represents the result of testing an outbound.
  98. // Delay is in milliseconds. Endpoints is only populated for TCP-mode
  99. // probes; HTTP mode reports the round-trip of a real HTTP request on an
  100. // established connection through the outbound (the cold first request
  101. // supplies the timing breakdown).
  102. type TestOutboundResult struct {
  103. Tag string `json:"tag,omitempty"`
  104. Success bool `json:"success"`
  105. Delay int64 `json:"delay"`
  106. Error string `json:"error,omitempty"`
  107. Mode string `json:"mode,omitempty"`
  108. // HTTP-mode extras. Any HTTP response counts as reachable; HTTPStatus
  109. // records what the test URL answered. ConnectMs is the dial to the local
  110. // test inbound; TLSMs covers outbound-chain establishment + target TLS
  111. // (https URLs only, since xray ACKs the SOCKS CONNECT before dialing
  112. // upstream); TTFBMs is request start → first response byte.
  113. HTTPStatus int `json:"httpStatus,omitempty"`
  114. ConnectMs int64 `json:"connectMs,omitempty"`
  115. TLSMs int64 `json:"tlsMs,omitempty"`
  116. TTFBMs int64 `json:"ttfbMs,omitempty"`
  117. Endpoints []TestEndpointResult `json:"endpoints,omitempty"`
  118. }
  119. // TestEndpointResult is one entry in a TCP-mode probe — the per-endpoint
  120. // dial outcome for outbounds that expose multiple servers/peers.
  121. type TestEndpointResult struct {
  122. Address string `json:"address"`
  123. Success bool `json:"success"`
  124. Delay int64 `json:"delay"`
  125. Error string `json:"error,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 protocol == "blackhole" || protocol == "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); protocol == "hysteria" || protocol == "wireguard" {
  194. return true
  195. }
  196. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  197. if n, _ := stream["network"].(string); n == "hysteria" || n == "kcp" || n == "quic" {
  198. return true
  199. }
  200. }
  201. return false
  202. }
  203. func extractOutboundEndpoints(ob map[string]any) []string {
  204. protocol, _ := ob["protocol"].(string)
  205. settings, _ := ob["settings"].(map[string]any)
  206. if settings == nil {
  207. return nil
  208. }
  209. var out []string
  210. addServer := func(addr any, port any) {
  211. host, _ := addr.(string)
  212. p := numAsInt(port)
  213. if host != "" && p > 0 {
  214. out = append(out, fmt.Sprintf("%s:%d", host, p))
  215. }
  216. }
  217. switch protocol {
  218. case "vmess":
  219. if vnext, ok := settings["vnext"].([]any); ok {
  220. for _, v := range vnext {
  221. if vm, ok := v.(map[string]any); ok {
  222. addServer(vm["address"], vm["port"])
  223. }
  224. }
  225. }
  226. case "vless":
  227. addServer(settings["address"], settings["port"])
  228. case "hysteria":
  229. addServer(settings["address"], settings["port"])
  230. case "trojan", "shadowsocks", "http", "socks":
  231. if servers, ok := settings["servers"].([]any); ok {
  232. for _, sv := range servers {
  233. if sm, ok := sv.(map[string]any); ok {
  234. addServer(sm["address"], sm["port"])
  235. }
  236. }
  237. }
  238. case "wireguard":
  239. if peers, ok := settings["peers"].([]any); ok {
  240. for _, p := range peers {
  241. if pm, ok := p.(map[string]any); ok {
  242. if ep, _ := pm["endpoint"].(string); ep != "" {
  243. out = append(out, ep)
  244. }
  245. }
  246. }
  247. }
  248. }
  249. return out
  250. }
  251. func numAsInt(v any) int {
  252. switch n := v.(type) {
  253. case float64:
  254. return int(n)
  255. case int:
  256. return n
  257. case int64:
  258. return int(n)
  259. case string:
  260. if i, err := strconv.Atoi(n); err == nil {
  261. return i
  262. }
  263. }
  264. return 0
  265. }