outbound.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. 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 = outbound.Up + traffic.Up
  51. outbound.Down = outbound.Down + traffic.Down
  52. outbound.Total = 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. }
  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. func (s *OutboundService) testOutboundTCP(outboundJSON string) (*TestOutboundResult, error) {
  119. var ob map[string]any
  120. if err := json.Unmarshal([]byte(outboundJSON), &ob); err != nil {
  121. return &TestOutboundResult{Mode: "tcp", Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}, nil
  122. }
  123. tag, _ := ob["tag"].(string)
  124. protocol, _ := ob["protocol"].(string)
  125. if protocol == "blackhole" || protocol == "freedom" || tag == "blocked" {
  126. return &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: "Outbound has no testable endpoint"}, nil
  127. }
  128. endpoints := extractOutboundEndpoints(ob)
  129. if len(endpoints) == 0 {
  130. return &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: "No testable endpoint"}, nil
  131. }
  132. results := make([]TestEndpointResult, len(endpoints))
  133. var wg sync.WaitGroup
  134. for i := range endpoints {
  135. wg.Add(1)
  136. go func(i int) {
  137. defer wg.Done()
  138. results[i] = probeTCPEndpoint(endpoints[i], 5*time.Second)
  139. }(i)
  140. }
  141. wg.Wait()
  142. var bestDelay int64 = -1
  143. var firstErr string
  144. for _, r := range results {
  145. if r.Success {
  146. if bestDelay < 0 || r.Delay < bestDelay {
  147. bestDelay = r.Delay
  148. }
  149. } else if firstErr == "" {
  150. firstErr = r.Error
  151. }
  152. }
  153. out := &TestOutboundResult{Tag: tag, Mode: "tcp", Endpoints: results}
  154. if bestDelay >= 0 {
  155. out.Success = true
  156. out.Delay = bestDelay
  157. } else {
  158. out.Error = firstErr
  159. if out.Error == "" {
  160. out.Error = "All endpoints unreachable"
  161. }
  162. }
  163. return out, nil
  164. }
  165. func probeTCPEndpoint(endpoint string, timeout time.Duration) TestEndpointResult {
  166. r := TestEndpointResult{Address: endpoint}
  167. start := time.Now()
  168. conn, err := (&net.Dialer{Timeout: timeout}).DialContext(context.Background(), "tcp", endpoint)
  169. r.Delay = time.Since(start).Milliseconds()
  170. if err != nil {
  171. r.Error = err.Error()
  172. return r
  173. }
  174. conn.Close()
  175. r.Success = true
  176. return r
  177. }
  178. // outboundTransportIsUDP reports whether the outbound's proxy speaks UDP
  179. // (wireguard, hysteria, or a kcp/quic/hysteria stream transport). A bare
  180. // UDP dial can't probe these — they ignore unauthenticated packets, so a
  181. // dial neither proves reachability nor measures latency. Such outbounds
  182. // must go through the real xray handshake probe instead.
  183. func outboundTransportIsUDP(ob map[string]any) bool {
  184. if protocol, _ := ob["protocol"].(string); protocol == "hysteria" || protocol == "wireguard" {
  185. return true
  186. }
  187. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  188. if n, _ := stream["network"].(string); n == "hysteria" || n == "kcp" || n == "quic" {
  189. return true
  190. }
  191. }
  192. return false
  193. }
  194. func extractOutboundEndpoints(ob map[string]any) []string {
  195. protocol, _ := ob["protocol"].(string)
  196. settings, _ := ob["settings"].(map[string]any)
  197. if settings == nil {
  198. return nil
  199. }
  200. var out []string
  201. addServer := func(addr any, port any) {
  202. host, _ := addr.(string)
  203. p := numAsInt(port)
  204. if host != "" && p > 0 {
  205. out = append(out, fmt.Sprintf("%s:%d", host, p))
  206. }
  207. }
  208. switch protocol {
  209. case "vmess":
  210. if vnext, ok := settings["vnext"].([]any); ok {
  211. for _, v := range vnext {
  212. if vm, ok := v.(map[string]any); ok {
  213. addServer(vm["address"], vm["port"])
  214. }
  215. }
  216. }
  217. case "vless":
  218. addServer(settings["address"], settings["port"])
  219. case "hysteria":
  220. addServer(settings["address"], settings["port"])
  221. case "trojan", "shadowsocks", "http", "socks":
  222. if servers, ok := settings["servers"].([]any); ok {
  223. for _, sv := range servers {
  224. if sm, ok := sv.(map[string]any); ok {
  225. addServer(sm["address"], sm["port"])
  226. }
  227. }
  228. }
  229. case "wireguard":
  230. if peers, ok := settings["peers"].([]any); ok {
  231. for _, p := range peers {
  232. if pm, ok := p.(map[string]any); ok {
  233. if ep, _ := pm["endpoint"].(string); ep != "" {
  234. out = append(out, ep)
  235. }
  236. }
  237. }
  238. }
  239. }
  240. return out
  241. }
  242. func numAsInt(v any) int {
  243. switch n := v.(type) {
  244. case float64:
  245. return int(n)
  246. case int:
  247. return n
  248. case int64:
  249. return int(n)
  250. case string:
  251. if i, err := strconv.Atoi(n); err == nil {
  252. return i
  253. }
  254. }
  255. return 0
  256. }