outbound.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "os"
  8. "strconv"
  9. "sync"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v3/config"
  12. "github.com/mhsanaei/3x-ui/v3/database"
  13. "github.com/mhsanaei/3x-ui/v3/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/logger"
  15. "github.com/mhsanaei/3x-ui/v3/util/json_util"
  16. "github.com/mhsanaei/3x-ui/v3/xray"
  17. "gorm.io/gorm"
  18. )
  19. // OutboundService provides business logic for managing Xray outbound configurations.
  20. // It handles outbound traffic monitoring and statistics.
  21. type OutboundService struct{}
  22. // httpTestSemaphore serialises HTTP-mode probes (each one spawns a temp xray
  23. // instance, which is too expensive to run in parallel). TCP-mode probes are
  24. // dial-only and don't need the semaphore.
  25. var httpTestSemaphore sync.Mutex
  26. func (s *OutboundService) AddTraffic(traffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  27. var err error
  28. db := database.GetDB()
  29. tx := db.Begin()
  30. defer func() {
  31. if err != nil {
  32. tx.Rollback()
  33. } else {
  34. tx.Commit()
  35. }
  36. }()
  37. err = s.addOutboundTraffic(tx, traffics)
  38. if err != nil {
  39. return err, false
  40. }
  41. return nil, false
  42. }
  43. func (s *OutboundService) addOutboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  44. if len(traffics) == 0 {
  45. return nil
  46. }
  47. var err error
  48. for _, traffic := range traffics {
  49. if traffic.IsOutbound {
  50. var outbound model.OutboundTraffics
  51. err = tx.Model(&model.OutboundTraffics{}).Where("tag = ?", traffic.Tag).
  52. FirstOrCreate(&outbound).Error
  53. if err != nil {
  54. return err
  55. }
  56. outbound.Tag = traffic.Tag
  57. outbound.Up = outbound.Up + traffic.Up
  58. outbound.Down = outbound.Down + traffic.Down
  59. outbound.Total = outbound.Up + outbound.Down
  60. err = tx.Save(&outbound).Error
  61. if err != nil {
  62. return err
  63. }
  64. }
  65. }
  66. return nil
  67. }
  68. func (s *OutboundService) GetOutboundsTraffic() ([]*model.OutboundTraffics, error) {
  69. db := database.GetDB()
  70. var traffics []*model.OutboundTraffics
  71. err := db.Model(model.OutboundTraffics{}).Find(&traffics).Error
  72. if err != nil {
  73. logger.Warning("Error retrieving OutboundTraffics: ", err)
  74. return nil, err
  75. }
  76. return traffics, nil
  77. }
  78. func (s *OutboundService) ResetOutboundTraffic(tag string) error {
  79. db := database.GetDB()
  80. whereText := "tag "
  81. if tag == "-alltags-" {
  82. whereText += " <> ?"
  83. } else {
  84. whereText += " = ?"
  85. }
  86. result := db.Model(model.OutboundTraffics{}).
  87. Where(whereText, tag).
  88. Updates(map[string]any{"up": 0, "down": 0, "total": 0})
  89. err := result.Error
  90. if err != nil {
  91. return err
  92. }
  93. return nil
  94. }
  95. // TestOutboundResult represents the result of testing an outbound.
  96. // Delay is in milliseconds. Endpoints is only populated for TCP-mode
  97. // probes; HTTP mode reports the round-trip delay measured by xray's
  98. // burstObservatory probe.
  99. type TestOutboundResult struct {
  100. Success bool `json:"success"`
  101. Delay int64 `json:"delay"`
  102. Error string `json:"error,omitempty"`
  103. Mode string `json:"mode,omitempty"`
  104. Endpoints []TestEndpointResult `json:"endpoints,omitempty"`
  105. }
  106. // TestEndpointResult is one entry in a TCP-mode probe — the per-endpoint
  107. // dial outcome for outbounds that expose multiple servers/peers.
  108. type TestEndpointResult struct {
  109. Address string `json:"address"`
  110. Success bool `json:"success"`
  111. Delay int64 `json:"delay"`
  112. Error string `json:"error,omitempty"`
  113. }
  114. // TestOutbound dispatches to the chosen probe mode:
  115. // - mode="tcp": dial the outbound's host:port directly. No xray spin-up,
  116. // parallel-safe, ~100ms per endpoint. Doesn't validate the proxy
  117. // protocol — only that the remote is reachable on TCP.
  118. // - mode="" or "http": spin a temp xray instance, route a real HTTP
  119. // request through it, return delay + a DNS/Connect/TLS/TTFB breakdown.
  120. // Authoritative but expensive and serialised by httpTestSemaphore.
  121. //
  122. // allOutboundsJSON is only consulted in HTTP mode (it backs
  123. // sockopt.dialerProxy chains during test).
  124. func (s *OutboundService) TestOutbound(outboundJSON string, testURL string, allOutboundsJSON string, mode string) (*TestOutboundResult, error) {
  125. if mode == "tcp" {
  126. // A bare TCP dial only proves reachability for TCP-based proxies.
  127. // UDP protocols (wireguard, hysteria, kcp/quic transports) ignore
  128. // unauthenticated packets, so a raw dial can't tell "reachable" from
  129. // "dead" — route them through the authoritative xray handshake probe.
  130. var ob map[string]any
  131. if json.Unmarshal([]byte(outboundJSON), &ob) == nil && outboundTransportIsUDP(ob) {
  132. return s.testOutboundHTTP(outboundJSON, testURL, allOutboundsJSON)
  133. }
  134. return s.testOutboundTCP(outboundJSON)
  135. }
  136. return s.testOutboundHTTP(outboundJSON, testURL, allOutboundsJSON)
  137. }
  138. func (s *OutboundService) testOutboundTCP(outboundJSON string) (*TestOutboundResult, error) {
  139. var ob map[string]any
  140. if err := json.Unmarshal([]byte(outboundJSON), &ob); err != nil {
  141. return &TestOutboundResult{Mode: "tcp", Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}, nil
  142. }
  143. tag, _ := ob["tag"].(string)
  144. protocol, _ := ob["protocol"].(string)
  145. if protocol == "blackhole" || protocol == "freedom" || tag == "blocked" {
  146. return &TestOutboundResult{Mode: "tcp", Success: false, Error: "Outbound has no testable endpoint"}, nil
  147. }
  148. endpoints := extractOutboundEndpoints(ob)
  149. if len(endpoints) == 0 {
  150. return &TestOutboundResult{Mode: "tcp", Success: false, Error: "No testable endpoint"}, nil
  151. }
  152. results := make([]TestEndpointResult, len(endpoints))
  153. var wg sync.WaitGroup
  154. for i := range endpoints {
  155. wg.Add(1)
  156. go func(i int) {
  157. defer wg.Done()
  158. results[i] = probeTCPEndpoint(endpoints[i], 5*time.Second)
  159. }(i)
  160. }
  161. wg.Wait()
  162. var bestDelay int64 = -1
  163. var firstErr string
  164. for _, r := range results {
  165. if r.Success {
  166. if bestDelay < 0 || r.Delay < bestDelay {
  167. bestDelay = r.Delay
  168. }
  169. } else if firstErr == "" {
  170. firstErr = r.Error
  171. }
  172. }
  173. out := &TestOutboundResult{Mode: "tcp", Endpoints: results}
  174. if bestDelay >= 0 {
  175. out.Success = true
  176. out.Delay = bestDelay
  177. } else {
  178. out.Error = firstErr
  179. if out.Error == "" {
  180. out.Error = "All endpoints unreachable"
  181. }
  182. }
  183. return out, nil
  184. }
  185. func probeTCPEndpoint(endpoint string, timeout time.Duration) TestEndpointResult {
  186. r := TestEndpointResult{Address: endpoint}
  187. start := time.Now()
  188. conn, err := net.DialTimeout("tcp", endpoint, timeout)
  189. r.Delay = time.Since(start).Milliseconds()
  190. if err != nil {
  191. r.Error = err.Error()
  192. return r
  193. }
  194. conn.Close()
  195. r.Success = true
  196. return r
  197. }
  198. // outboundTransportIsUDP reports whether the outbound's proxy speaks UDP
  199. // (wireguard, hysteria, or a kcp/quic/hysteria stream transport). A bare
  200. // UDP dial can't probe these — they ignore unauthenticated packets, so a
  201. // dial neither proves reachability nor measures latency. Such outbounds
  202. // must go through the real xray handshake probe instead.
  203. func outboundTransportIsUDP(ob map[string]any) bool {
  204. if protocol, _ := ob["protocol"].(string); protocol == "hysteria" || protocol == "wireguard" {
  205. return true
  206. }
  207. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  208. if n, _ := stream["network"].(string); n == "hysteria" || n == "kcp" || n == "quic" {
  209. return true
  210. }
  211. }
  212. return false
  213. }
  214. func extractOutboundEndpoints(ob map[string]any) []string {
  215. protocol, _ := ob["protocol"].(string)
  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. addServer(settings["address"], settings["port"])
  239. case "hysteria":
  240. addServer(settings["address"], settings["port"])
  241. case "trojan", "shadowsocks", "http", "socks":
  242. if servers, ok := settings["servers"].([]any); ok {
  243. for _, sv := range servers {
  244. if sm, ok := sv.(map[string]any); ok {
  245. addServer(sm["address"], sm["port"])
  246. }
  247. }
  248. }
  249. case "wireguard":
  250. if peers, ok := settings["peers"].([]any); ok {
  251. for _, p := range peers {
  252. if pm, ok := p.(map[string]any); ok {
  253. if ep, _ := pm["endpoint"].(string); ep != "" {
  254. out = append(out, ep)
  255. }
  256. }
  257. }
  258. }
  259. }
  260. return out
  261. }
  262. func numAsInt(v any) int {
  263. switch n := v.(type) {
  264. case float64:
  265. return int(n)
  266. case int:
  267. return n
  268. case int64:
  269. return int(n)
  270. case string:
  271. if i, err := strconv.Atoi(n); err == nil {
  272. return i
  273. }
  274. }
  275. return 0
  276. }
  277. // testOutboundHTTP spins up a temporary xray instance whose only job is
  278. // to run a burstObservatory probe against the target outbound, then polls
  279. // xray's metrics /debug/vars endpoint until that outbound is reported
  280. // alive (success) or the deadline expires (failure). The probe lives
  281. // inside xray, so the measured delay and any failure reason reflect what
  282. // xray itself sees over the real proxy chain — no SOCKS round-trip on
  283. // the client side.
  284. func (s *OutboundService) testOutboundHTTP(outboundJSON string, testURL string, allOutboundsJSON string) (*TestOutboundResult, error) {
  285. if testURL == "" {
  286. testURL = "https://www.google.com/generate_204"
  287. }
  288. if !httpTestSemaphore.TryLock() {
  289. return &TestOutboundResult{
  290. Mode: "http",
  291. Success: false,
  292. Error: "Another outbound test is already running, please wait",
  293. }, nil
  294. }
  295. defer httpTestSemaphore.Unlock()
  296. var testOutbound map[string]any
  297. if err := json.Unmarshal([]byte(outboundJSON), &testOutbound); err != nil {
  298. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}, nil
  299. }
  300. outboundTag, _ := testOutbound["tag"].(string)
  301. if outboundTag == "" {
  302. return &TestOutboundResult{Mode: "http", Success: false, Error: "Outbound has no tag"}, nil
  303. }
  304. if protocol, _ := testOutbound["protocol"].(string); protocol == "blackhole" || outboundTag == "blocked" {
  305. return &TestOutboundResult{Mode: "http", Success: false, Error: "Blocked/blackhole outbound cannot be tested"}, nil
  306. }
  307. var allOutbounds []any
  308. if allOutboundsJSON != "" {
  309. if err := json.Unmarshal([]byte(allOutboundsJSON), &allOutbounds); err != nil {
  310. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Invalid allOutbounds JSON: %v", err)}, nil
  311. }
  312. }
  313. // The outbound under test must be present in the config so burstObservatory
  314. // has something with outboundTag to probe. allOutbounds is the template's
  315. // outbounds (for dialerProxy chains); subscription outbounds are injected at
  316. // runtime and aren't part of it, so without this the probe targets a tag that
  317. // doesn't exist in the config and every test times out. Append (don't replace)
  318. // so manual outbounds' dialerProxy chains keep resolving.
  319. if !outboundsContainTag(allOutbounds, outboundTag) {
  320. allOutbounds = append(allOutbounds, testOutbound)
  321. }
  322. metricsPort, err := findAvailablePort()
  323. if err != nil {
  324. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Failed to find available port: %v", err)}, nil
  325. }
  326. testConfig := s.createTestConfig(outboundTag, allOutbounds, metricsPort, testURL)
  327. testConfigPath, err := createTestConfigPath()
  328. if err != nil {
  329. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Failed to create test config path: %v", err)}, nil
  330. }
  331. defer os.Remove(testConfigPath)
  332. testProcess := xray.NewTestProcess(testConfig, testConfigPath)
  333. defer func() {
  334. if testProcess.IsRunning() {
  335. testProcess.Stop()
  336. }
  337. }()
  338. if err := testProcess.Start(); err != nil {
  339. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Failed to start test xray instance: %v", err)}, nil
  340. }
  341. if err := waitForPort(metricsPort, 5*time.Second); err != nil {
  342. if !testProcess.IsRunning() {
  343. result := testProcess.GetResult()
  344. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Xray process exited: %s", result)}, nil
  345. }
  346. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Xray failed to start metrics listener: %v", err)}, nil
  347. }
  348. if !testProcess.IsRunning() {
  349. result := testProcess.GetResult()
  350. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Xray process exited: %s", result)}, nil
  351. }
  352. return pollObservatoryResult(testProcess, metricsPort, outboundTag, 12*time.Second), nil
  353. }
  354. // outboundsContainTag reports whether any outbound in the slice has the given tag.
  355. func outboundsContainTag(outbounds []any, tag string) bool {
  356. for _, ob := range outbounds {
  357. if m, ok := ob.(map[string]any); ok {
  358. if t, _ := m["tag"].(string); t == tag {
  359. return true
  360. }
  361. }
  362. }
  363. return false
  364. }
  365. // createTestConfig builds a probe-only xray config: the original outbounds
  366. // are kept as-is so dialerProxy chains still resolve, a burstObservatory
  367. // is wired to probe the target tag, and a metrics listener exposes the
  368. // observatory snapshot via /debug/vars. No inbound or routing rules are
  369. // needed — burstObservatory issues the probe traffic itself.
  370. func (s *OutboundService) createTestConfig(outboundTag string, allOutbounds []any, metricsPort int, probeURL string) *xray.Config {
  371. processedOutbounds := make([]any, len(allOutbounds))
  372. for i, ob := range allOutbounds {
  373. outbound, ok := ob.(map[string]any)
  374. if !ok {
  375. processedOutbounds[i] = ob
  376. continue
  377. }
  378. if protocol, ok := outbound["protocol"].(string); ok && protocol == "wireguard" {
  379. if settings, ok := outbound["settings"].(map[string]any); ok {
  380. settings["noKernelTun"] = true
  381. } else {
  382. outbound["settings"] = map[string]any{"noKernelTun": true}
  383. }
  384. }
  385. processedOutbounds[i] = outbound
  386. }
  387. outboundsJSON, _ := json.Marshal(processedOutbounds)
  388. routingJSON, _ := json.Marshal(map[string]any{
  389. "domainStrategy": "AsIs",
  390. "rules": []any{},
  391. })
  392. burstObservatoryJSON, _ := json.Marshal(map[string]any{
  393. "subjectSelector": []string{outboundTag},
  394. "pingConfig": map[string]any{
  395. "destination": probeURL,
  396. "interval": "1s",
  397. "connectivity": "",
  398. "timeout": "5s",
  399. "samplingCount": 1,
  400. },
  401. })
  402. metricsJSON, _ := json.Marshal(map[string]any{
  403. "tag": "test-metrics",
  404. "listen": fmt.Sprintf("127.0.0.1:%d", metricsPort),
  405. })
  406. logConfig := map[string]any{
  407. "loglevel": "warning",
  408. "access": "none",
  409. "error": "none",
  410. "dnsLog": false,
  411. }
  412. logJSON, _ := json.Marshal(logConfig)
  413. cfg := &xray.Config{
  414. LogConfig: json_util.RawMessage(logJSON),
  415. InboundConfigs: []xray.InboundConfig{},
  416. OutboundConfigs: json_util.RawMessage(string(outboundsJSON)),
  417. RouterConfig: json_util.RawMessage(string(routingJSON)),
  418. Policy: json_util.RawMessage(`{}`),
  419. Stats: json_util.RawMessage(`{}`),
  420. BurstObservatory: json_util.RawMessage(string(burstObservatoryJSON)),
  421. Metrics: json_util.RawMessage(string(metricsJSON)),
  422. }
  423. return cfg
  424. }
  425. // observatoryEntry mirrors the per-outbound shape published by xray's
  426. // observatory under /debug/vars.
  427. type observatoryEntry struct {
  428. Alive bool `json:"alive"`
  429. Delay int64 `json:"delay"`
  430. LastSeenTime int64 `json:"last_seen_time"`
  431. LastTryTime int64 `json:"last_try_time"`
  432. OutboundTag string `json:"outbound_tag"`
  433. }
  434. // pollObservatoryResult repeatedly reads /debug/vars and returns as soon
  435. // as the target outbound reports alive=true. burstObservatory updates the
  436. // snapshot after each ping (interval=1s, timeout=5s), so a healthy
  437. // outbound usually surfaces within ~2s and the timeout caps the wait for
  438. // truly dead ones.
  439. func pollObservatoryResult(testProcess *xray.Process, metricsPort int, tag string, timeout time.Duration) *TestOutboundResult {
  440. url := fmt.Sprintf("http://127.0.0.1:%d/debug/vars", metricsPort)
  441. client := &http.Client{Timeout: 2 * time.Second}
  442. deadline := time.Now().Add(timeout)
  443. var lastEntry observatoryEntry
  444. var sawEntry bool
  445. for time.Now().Before(deadline) {
  446. if !testProcess.IsRunning() {
  447. result := testProcess.GetResult()
  448. return &TestOutboundResult{Mode: "http", Success: false, Error: fmt.Sprintf("Xray process exited: %s", result)}
  449. }
  450. entry, ok := fetchObservatoryEntry(client, url, tag)
  451. if ok {
  452. if entry.Alive {
  453. delay := entry.Delay
  454. if delay <= 0 {
  455. delay = 1
  456. }
  457. return &TestOutboundResult{Mode: "http", Success: true, Delay: delay}
  458. }
  459. lastEntry = entry
  460. sawEntry = true
  461. }
  462. time.Sleep(400 * time.Millisecond)
  463. }
  464. msg := "Probe timed out — outbound did not become reachable"
  465. if sawEntry && lastEntry.LastTryTime > 0 {
  466. msg = fmt.Sprintf("All probes failed (last attempt %ds ago)", time.Now().Unix()-lastEntry.LastTryTime)
  467. }
  468. return &TestOutboundResult{Mode: "http", Success: false, Error: msg}
  469. }
  470. func fetchObservatoryEntry(client *http.Client, url, tag string) (observatoryEntry, bool) {
  471. resp, err := client.Get(url)
  472. if err != nil {
  473. return observatoryEntry{}, false
  474. }
  475. defer resp.Body.Close()
  476. if resp.StatusCode != http.StatusOK {
  477. return observatoryEntry{}, false
  478. }
  479. var payload struct {
  480. Observatory map[string]observatoryEntry `json:"observatory"`
  481. }
  482. if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
  483. return observatoryEntry{}, false
  484. }
  485. if entry, ok := payload.Observatory[tag]; ok {
  486. return entry, true
  487. }
  488. for _, entry := range payload.Observatory {
  489. if entry.OutboundTag == tag {
  490. return entry, true
  491. }
  492. }
  493. return observatoryEntry{}, false
  494. }
  495. // waitForPort polls until the given TCP port is accepting connections or the timeout expires.
  496. func waitForPort(port int, timeout time.Duration) error {
  497. deadline := time.Now().Add(timeout)
  498. for time.Now().Before(deadline) {
  499. conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", port), 100*time.Millisecond)
  500. if err == nil {
  501. conn.Close()
  502. return nil
  503. }
  504. time.Sleep(50 * time.Millisecond)
  505. }
  506. return fmt.Errorf("port %d not ready after %v", port, timeout)
  507. }
  508. // findAvailablePort finds an available port for testing
  509. func findAvailablePort() (int, error) {
  510. listener, err := net.Listen("tcp", ":0")
  511. if err != nil {
  512. return 0, err
  513. }
  514. defer listener.Close()
  515. addr := listener.Addr().(*net.TCPAddr)
  516. return addr.Port, nil
  517. }
  518. // createTestConfigPath returns a unique path for a temporary xray config file in the bin folder.
  519. // The temp file is created and closed so the path is reserved; Start() will overwrite it.
  520. func createTestConfigPath() (string, error) {
  521. tmpFile, err := os.CreateTemp(config.GetBinFolderPath(), "xray_test_*.json")
  522. if err != nil {
  523. return "", err
  524. }
  525. path := tmpFile.Name()
  526. if err := tmpFile.Close(); err != nil {
  527. os.Remove(path)
  528. return "", err
  529. }
  530. return path, nil
  531. }