outbound.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package outbound
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. "sync"
  8. "time"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  12. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  13. "gorm.io/gorm"
  14. )
  15. // OutboundService provides business logic for managing Xray outbound configurations.
  16. // It handles outbound traffic monitoring and statistics.
  17. type OutboundService struct{}
  18. func (s *OutboundService) AddTraffic(traffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  19. var err error
  20. db := database.GetDB()
  21. tx := db.Begin()
  22. defer func() {
  23. if err != nil {
  24. tx.Rollback()
  25. } else {
  26. tx.Commit()
  27. }
  28. }()
  29. err = s.addOutboundTraffic(tx, traffics)
  30. if err != nil {
  31. return err, false
  32. }
  33. return nil, false
  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 = outbound.Up + traffic.Up
  50. outbound.Down = outbound.Down + traffic.Down
  51. outbound.Total = 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 time of a real HTTP request routed
  90. // through the outbound, with an optional timing breakdown.
  91. type TestOutboundResult struct {
  92. Tag string `json:"tag,omitempty"`
  93. Success bool `json:"success"`
  94. Delay int64 `json:"delay"`
  95. Error string `json:"error,omitempty"`
  96. Mode string `json:"mode,omitempty"`
  97. // HTTP-mode extras. Any HTTP response counts as reachable; HTTPStatus
  98. // records what the test URL answered. ConnectMs is the dial to the local
  99. // test inbound; TLSMs covers outbound-chain establishment + target TLS
  100. // (https URLs only, since xray ACKs the SOCKS CONNECT before dialing
  101. // upstream); TTFBMs is request start → first response byte.
  102. HTTPStatus int `json:"httpStatus,omitempty"`
  103. ConnectMs int64 `json:"connectMs,omitempty"`
  104. TLSMs int64 `json:"tlsMs,omitempty"`
  105. TTFBMs int64 `json:"ttfbMs,omitempty"`
  106. Endpoints []TestEndpointResult `json:"endpoints,omitempty"`
  107. }
  108. // TestEndpointResult is one entry in a TCP-mode probe — the per-endpoint
  109. // dial outcome for outbounds that expose multiple servers/peers.
  110. type TestEndpointResult struct {
  111. Address string `json:"address"`
  112. Success bool `json:"success"`
  113. Delay int64 `json:"delay"`
  114. Error string `json:"error,omitempty"`
  115. }
  116. func (s *OutboundService) testOutboundTCP(outboundJSON string) (*TestOutboundResult, error) {
  117. var ob map[string]any
  118. if err := json.Unmarshal([]byte(outboundJSON), &ob); err != nil {
  119. return &TestOutboundResult{Mode: "tcp", Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}, nil
  120. }
  121. tag, _ := ob["tag"].(string)
  122. protocol, _ := ob["protocol"].(string)
  123. if protocol == "blackhole" || protocol == "freedom" || tag == "blocked" {
  124. return &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: "Outbound has no testable endpoint"}, nil
  125. }
  126. endpoints := extractOutboundEndpoints(ob)
  127. if len(endpoints) == 0 {
  128. return &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: "No testable endpoint"}, nil
  129. }
  130. results := make([]TestEndpointResult, len(endpoints))
  131. var wg sync.WaitGroup
  132. for i := range endpoints {
  133. wg.Add(1)
  134. go func(i int) {
  135. defer wg.Done()
  136. results[i] = probeTCPEndpoint(endpoints[i], 5*time.Second)
  137. }(i)
  138. }
  139. wg.Wait()
  140. var bestDelay int64 = -1
  141. var firstErr string
  142. for _, r := range results {
  143. if r.Success {
  144. if bestDelay < 0 || r.Delay < bestDelay {
  145. bestDelay = r.Delay
  146. }
  147. } else if firstErr == "" {
  148. firstErr = r.Error
  149. }
  150. }
  151. out := &TestOutboundResult{Tag: tag, Mode: "tcp", Endpoints: results}
  152. if bestDelay >= 0 {
  153. out.Success = true
  154. out.Delay = bestDelay
  155. } else {
  156. out.Error = firstErr
  157. if out.Error == "" {
  158. out.Error = "All endpoints unreachable"
  159. }
  160. }
  161. return out, nil
  162. }
  163. func probeTCPEndpoint(endpoint string, timeout time.Duration) TestEndpointResult {
  164. r := TestEndpointResult{Address: endpoint}
  165. start := time.Now()
  166. conn, err := net.DialTimeout("tcp", endpoint, timeout)
  167. r.Delay = time.Since(start).Milliseconds()
  168. if err != nil {
  169. r.Error = err.Error()
  170. return r
  171. }
  172. conn.Close()
  173. r.Success = true
  174. return r
  175. }
  176. // outboundTransportIsUDP reports whether the outbound's proxy speaks UDP
  177. // (wireguard, hysteria, or a kcp/quic/hysteria stream transport). A bare
  178. // UDP dial can't probe these — they ignore unauthenticated packets, so a
  179. // dial neither proves reachability nor measures latency. Such outbounds
  180. // must go through the real xray handshake probe instead.
  181. func outboundTransportIsUDP(ob map[string]any) bool {
  182. if protocol, _ := ob["protocol"].(string); protocol == "hysteria" || protocol == "wireguard" {
  183. return true
  184. }
  185. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  186. if n, _ := stream["network"].(string); n == "hysteria" || n == "kcp" || n == "quic" {
  187. return true
  188. }
  189. }
  190. return false
  191. }
  192. func extractOutboundEndpoints(ob map[string]any) []string {
  193. protocol, _ := ob["protocol"].(string)
  194. settings, _ := ob["settings"].(map[string]any)
  195. if settings == nil {
  196. return nil
  197. }
  198. var out []string
  199. addServer := func(addr any, port any) {
  200. host, _ := addr.(string)
  201. p := numAsInt(port)
  202. if host != "" && p > 0 {
  203. out = append(out, fmt.Sprintf("%s:%d", host, p))
  204. }
  205. }
  206. switch protocol {
  207. case "vmess":
  208. if vnext, ok := settings["vnext"].([]any); ok {
  209. for _, v := range vnext {
  210. if vm, ok := v.(map[string]any); ok {
  211. addServer(vm["address"], vm["port"])
  212. }
  213. }
  214. }
  215. case "vless":
  216. addServer(settings["address"], settings["port"])
  217. case "hysteria":
  218. addServer(settings["address"], settings["port"])
  219. case "trojan", "shadowsocks", "http", "socks":
  220. if servers, ok := settings["servers"].([]any); ok {
  221. for _, sv := range servers {
  222. if sm, ok := sv.(map[string]any); ok {
  223. addServer(sm["address"], sm["port"])
  224. }
  225. }
  226. }
  227. case "wireguard":
  228. if peers, ok := settings["peers"].([]any); ok {
  229. for _, p := range peers {
  230. if pm, ok := p.(map[string]any); ok {
  231. if ep, _ := pm["endpoint"].(string); ep != "" {
  232. out = append(out, ep)
  233. }
  234. }
  235. }
  236. }
  237. }
  238. return out
  239. }
  240. func numAsInt(v any) int {
  241. switch n := v.(type) {
  242. case float64:
  243. return int(n)
  244. case int:
  245. return n
  246. case int64:
  247. return int(n)
  248. case string:
  249. if i, err := strconv.Atoi(n); err == nil {
  250. return i
  251. }
  252. }
  253. return 0
  254. }