probe_http.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. package outbound
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/fs"
  10. "net"
  11. "net/http"
  12. "net/http/httptrace"
  13. "net/url"
  14. "os"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  20. "github.com/mhsanaei/3x-ui/v3/internal/config"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  22. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  23. )
  24. // HTTP-mode probing works by spinning up ONE temporary xray instance per
  25. // batch: every outbound under test gets its own loopback SOCKS inbound plus
  26. // an inboundTag→outboundTag routing rule, and the panel then issues a real,
  27. // individually-timed HTTP request through each inbound. Measuring the request
  28. // client-side (instead of polling xray's observatory) returns the moment the
  29. // response lands, yields the actual HTTP status, and allows an httptrace
  30. // timing breakdown — while the shared process keeps "Test All" at one xray
  31. // spawn per batch instead of one per outbound. The reported delay comes from
  32. // a second request on the kept-alive connection, so it reflects the tunnel's
  33. // real per-request round-trip rather than the stacked SOCKS/proxy/TLS
  34. // handshakes of connection establishment. Mode "real" instead reports the
  35. // cold request's full elapsed time and skips the warm request.
  36. const (
  37. // httpProbeTimeout bounds each probe request end-to-end (a probe makes
  38. // two: a cold one for the breakdown, a warm one for the delay).
  39. httpProbeTimeout = 10 * time.Second
  40. // probeDrainLimit caps how much response body a probe reads back to keep
  41. // the connection reusable for the warm request.
  42. probeDrainLimit = 256 << 10
  43. // httpProbeConcurrency caps parallel probe requests within a batch —
  44. // enough to keep a batch fast, low enough not to spike CPU with TLS
  45. // handshakes on small VPSes.
  46. httpProbeConcurrency = 16
  47. // batchPortsReadyTimeout bounds the wait for the temp instance to open
  48. // its test inbounds.
  49. batchPortsReadyTimeout = 10 * time.Second
  50. // maxBatchItems caps one batch request; the frontend chunks below this.
  51. maxBatchItems = 50
  52. // tcpBatchConcurrency caps parallel TCP-mode items in a batch (each item
  53. // already dials its endpoints concurrently).
  54. tcpBatchConcurrency = 8
  55. // egressTraceTimeout keeps diagnostic trace metadata from extending a
  56. // successful HTTP probe by the full reachability timeout.
  57. egressTraceTimeout = 3 * time.Second
  58. defaultTestURL = "https://www.google.com/generate_204"
  59. egressTraceHost = "cloudflare.com"
  60. egressTracePath = "/cdn-cgi/trace"
  61. )
  62. // httpTestSemaphore serialises HTTP-mode batches (each spawns a temp xray
  63. // instance, which is too expensive to run in parallel). TCP-mode probes are
  64. // dial-only and don't need the semaphore.
  65. var httpTestSemaphore sync.Mutex
  66. // batchProcess is the slice of xray.Process the batch engine needs; a seam
  67. // so unit tests can stub the process without an xray binary.
  68. type batchProcess interface {
  69. Start() error
  70. Stop() error
  71. IsRunning() bool
  72. GetResult() string
  73. }
  74. var newBatchProcess = func(cfg *xray.Config, configPath string) batchProcess {
  75. return xray.NewTestProcess(cfg, configPath)
  76. }
  77. var egressTraceProbe = probeEgressTrace
  78. // httpBatchItem is one outbound inside an HTTP-mode batch. result is the
  79. // pre-allocated entry in the caller's result slice, filled in place.
  80. type httpBatchItem struct {
  81. index int
  82. tag string
  83. outbound map[string]any
  84. result *TestOutboundResult
  85. }
  86. func probeModeLabel(mode string) string {
  87. switch mode {
  88. case "tcp", "real":
  89. return mode
  90. default:
  91. return "http"
  92. }
  93. }
  94. // TestOutbound probes a single outbound; legacy single-test API kept for the
  95. // /testOutbound endpoint. Dispatch matches TestOutbounds: mode "tcp" dials
  96. // the outbound's endpoints directly, anything else routes a real HTTP request
  97. // through a temp xray instance (UDP-transport outbounds are always forced to
  98. // the HTTP probe — a raw dial can't measure them).
  99. func (s *OutboundService) TestOutbound(outboundJSON string, testURL string, allOutboundsJSON string, mode string) (*TestOutboundResult, error) {
  100. var ob map[string]any
  101. if err := json.Unmarshal([]byte(outboundJSON), &ob); err != nil {
  102. return &TestOutboundResult{Mode: probeModeLabel(mode), Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}, nil
  103. }
  104. results := s.testOutboundsParsed([]map[string]any{ob}, testURL, allOutboundsJSON, mode)
  105. return results[0], nil
  106. }
  107. // TestOutbounds probes a JSON array of outbounds and returns one result per
  108. // input, in input order, each carrying the outbound's tag. allOutboundsJSON
  109. // supplies the config context (sockopt.dialerProxy chains); testURL falls
  110. // back to the default probe URL when empty.
  111. func (s *OutboundService) TestOutbounds(outboundsJSON string, testURL string, allOutboundsJSON string, mode string) ([]*TestOutboundResult, error) {
  112. var raw []json.RawMessage
  113. if err := json.Unmarshal([]byte(outboundsJSON), &raw); err != nil {
  114. return nil, fmt.Errorf("invalid outbounds JSON: %w", err)
  115. }
  116. if len(raw) > maxBatchItems {
  117. return nil, fmt.Errorf("too many outbounds in one request (max %d)", maxBatchItems)
  118. }
  119. items := make([]map[string]any, len(raw))
  120. for i, r := range raw {
  121. var ob map[string]any
  122. if err := json.Unmarshal(r, &ob); err == nil {
  123. items[i] = ob
  124. }
  125. }
  126. return s.testOutboundsParsed(items, testURL, allOutboundsJSON, mode), nil
  127. }
  128. // testOutboundsParsed splits items into the TCP lane (direct dials, bounded
  129. // worker pool) and the HTTP lane (one shared temp xray instance), runs both,
  130. // and returns results aligned with items. A nil item marks unparseable input.
  131. func (s *OutboundService) testOutboundsParsed(items []map[string]any, testURL string, allOutboundsJSON string, mode string) []*TestOutboundResult {
  132. results := make([]*TestOutboundResult, len(items))
  133. modeLabel := probeModeLabel(mode)
  134. probeLabel := modeLabel
  135. if probeLabel == "tcp" {
  136. probeLabel = "http"
  137. }
  138. realDelay := mode == "real"
  139. type tcpEntry struct {
  140. idx int
  141. ob map[string]any
  142. }
  143. var tcpLane []tcpEntry
  144. var httpItems []*httpBatchItem
  145. seenTags := make(map[string]bool)
  146. for i, ob := range items {
  147. if ob == nil {
  148. results[i] = &TestOutboundResult{Mode: modeLabel, Success: false, Error: "Invalid outbound JSON"}
  149. continue
  150. }
  151. // A bare TCP dial only proves reachability for TCP-based proxies.
  152. // UDP protocols (wireguard, hysteria, kcp/quic transports) ignore
  153. // unauthenticated packets, so a raw dial can't tell "reachable" from
  154. // "dead" — route them through the real xray probe.
  155. if mode == "tcp" && !outboundTransportIsUDP(ob) {
  156. tcpLane = append(tcpLane, tcpEntry{idx: i, ob: ob})
  157. continue
  158. }
  159. tag, _ := ob["tag"].(string)
  160. r := &TestOutboundResult{Tag: tag, Mode: probeLabel}
  161. results[i] = r
  162. protocol, _ := ob["protocol"].(string)
  163. switch {
  164. case tag == "":
  165. r.Error = "Outbound has no tag"
  166. case protocol == "blackhole" || tag == "blocked":
  167. r.Error = "Blocked/blackhole outbound cannot be tested"
  168. case protocol == "loopback":
  169. r.Error = "Loopback outbound cannot be tested"
  170. case protocol == "freedom" || protocol == "dns":
  171. // Direct/DNS outbounds aren't proxies — an HTTP probe through them
  172. // would only measure the host's own reachability, not a tunnel.
  173. r.Error = "Direct/DNS outbound cannot be tested"
  174. case seenTags[tag]:
  175. r.Error = fmt.Sprintf("Duplicate outbound tag in batch: %s", tag)
  176. default:
  177. seenTags[tag] = true
  178. httpItems = append(httpItems, &httpBatchItem{index: i, tag: tag, outbound: ob, result: r})
  179. }
  180. }
  181. if len(tcpLane) > 0 {
  182. var wg sync.WaitGroup
  183. sem := make(chan struct{}, tcpBatchConcurrency)
  184. for _, e := range tcpLane {
  185. wg.Add(1)
  186. go func(e tcpEntry) {
  187. defer wg.Done()
  188. sem <- struct{}{}
  189. defer func() { <-sem }()
  190. obJSON, err := json.Marshal(e.ob)
  191. if err != nil {
  192. tag, _ := e.ob["tag"].(string)
  193. results[e.idx] = &TestOutboundResult{Tag: tag, Mode: "tcp", Success: false, Error: fmt.Sprintf("Invalid outbound JSON: %v", err)}
  194. return
  195. }
  196. r, _ := s.testOutboundTCP(string(obJSON))
  197. results[e.idx] = r
  198. }(e)
  199. }
  200. wg.Wait()
  201. }
  202. if len(httpItems) == 0 {
  203. return results
  204. }
  205. failAll := func(msg string) {
  206. for _, it := range httpItems {
  207. it.result.Success = false
  208. it.result.Error = msg
  209. }
  210. }
  211. var allOutbounds []any
  212. if allOutboundsJSON != "" {
  213. if err := json.Unmarshal([]byte(allOutboundsJSON), &allOutbounds); err != nil {
  214. failAll(fmt.Sprintf("Invalid allOutbounds JSON: %v", err))
  215. return results
  216. }
  217. }
  218. if testURL == "" {
  219. testURL = defaultTestURL
  220. }
  221. if !httpTestSemaphore.TryLock() {
  222. failAll("Another outbound test is already running, please wait")
  223. return results
  224. }
  225. defer httpTestSemaphore.Unlock()
  226. retryPerItem, err := runHTTPProbeBatch(httpItems, allOutbounds, testURL, realDelay)
  227. if err == nil {
  228. return results
  229. }
  230. if !retryPerItem || len(httpItems) == 1 {
  231. failAll(err.Error())
  232. return results
  233. }
  234. // The shared process never came up — one structurally-bad outbound can
  235. // poison the whole batch config. Retry each item in its own isolated
  236. // instance so the broken outbound reports xray's real error and the
  237. // rest still get tested. Serial: the poisoned case fails fast (~1s).
  238. for _, it := range httpItems {
  239. if _, ferr := runHTTPProbeBatch([]*httpBatchItem{it}, allOutbounds, testURL, realDelay); ferr != nil {
  240. it.result.Success = false
  241. it.result.Error = ferr.Error()
  242. }
  243. }
  244. return results
  245. }
  246. // runHTTPProbeBatch makes one shared-process attempt for the given items,
  247. // writing per-request outcomes into the items' results. It returns a non-nil
  248. // error only when the process never became usable; retryPerItem reports
  249. // whether splitting the batch into per-item instances could help (true for
  250. // start failures / early exits that a poisoned config would explain, false
  251. // for environmental failures like a missing binary or no free ports).
  252. func runHTTPProbeBatch(items []*httpBatchItem, allOutbounds []any, testURL string, realDelay bool) (retryPerItem bool, err error) {
  253. ports, release, err := reserveLoopbackPorts(len(items))
  254. if err != nil {
  255. return false, fmt.Errorf("Failed to reserve test ports: %w", err)
  256. }
  257. defer release()
  258. cfg := buildBatchTestConfig(items, allOutbounds, ports)
  259. configPath, err := createTestConfigPath()
  260. if err != nil {
  261. return false, fmt.Errorf("Failed to create test config path: %w", err)
  262. }
  263. defer os.Remove(configPath)
  264. proc := newBatchProcess(cfg, configPath)
  265. defer func() {
  266. if proc.IsRunning() {
  267. _ = proc.Stop()
  268. }
  269. }()
  270. // Free the reserved ports just before xray binds them; the window is
  271. // milliseconds, and a lost race makes xray exit fast, which surfaces
  272. // below and triggers the per-item retry with fresh ports.
  273. release()
  274. if err := proc.Start(); err != nil {
  275. if errors.Is(err, fs.ErrNotExist) {
  276. // Binary missing — per-item retries would all fail the same way.
  277. return false, fmt.Errorf("Failed to start test xray instance: %w", err)
  278. }
  279. return true, fmt.Errorf("Failed to start test xray instance: %w", err)
  280. }
  281. if err := waitForPortsReady(proc, ports, batchPortsReadyTimeout); err != nil {
  282. return err.exited, err
  283. }
  284. sem := make(chan struct{}, httpProbeConcurrency)
  285. var wg sync.WaitGroup
  286. for i := range items {
  287. wg.Add(1)
  288. go func(it *httpBatchItem, port int) {
  289. defer wg.Done()
  290. sem <- struct{}{}
  291. defer func() { <-sem }()
  292. probeThroughSocks(port, testURL, httpProbeTimeout, realDelay, it.result)
  293. }(items[i], ports[i])
  294. }
  295. wg.Wait()
  296. if !proc.IsRunning() {
  297. detail := proc.GetResult()
  298. for _, it := range items {
  299. if !it.result.Success {
  300. it.result.Error = "Xray process exited: " + detail
  301. }
  302. }
  303. }
  304. return false, nil
  305. }
  306. // portsReadyError distinguishes "process died" (a poisoned config — worth a
  307. // per-item retry) from "ports never opened while alive" (environmental).
  308. type portsReadyError struct {
  309. msg string
  310. exited bool
  311. }
  312. func (e *portsReadyError) Error() string { return e.msg }
  313. // waitForPortsReady polls until every test inbound accepts connections,
  314. // aborting as soon as the process exits.
  315. func waitForPortsReady(proc batchProcess, ports []int, timeout time.Duration) *portsReadyError {
  316. deadline := time.Now().Add(timeout)
  317. for _, port := range ports {
  318. for {
  319. if !proc.IsRunning() {
  320. return &portsReadyError{msg: "Xray process exited: " + proc.GetResult(), exited: true}
  321. }
  322. conn, err := (&net.Dialer{Timeout: 100 * time.Millisecond}).DialContext(context.Background(), "tcp", fmt.Sprintf("127.0.0.1:%d", port))
  323. if err == nil {
  324. conn.Close()
  325. break
  326. }
  327. if time.Now().After(deadline) {
  328. return &portsReadyError{msg: fmt.Sprintf("Xray failed to open test inbounds: port %d not ready after %v", port, timeout)}
  329. }
  330. time.Sleep(50 * time.Millisecond)
  331. }
  332. }
  333. return nil
  334. }
  335. // buildBatchTestConfig assembles the temp instance config: one loopback SOCKS
  336. // inbound per tested outbound, a routing rule binding each inbound to its
  337. // outbound tag, and the full outbound context so dialerProxy chains resolve.
  338. func buildBatchTestConfig(items []*httpBatchItem, allOutbounds []any, ports []int) *xray.Config {
  339. // allOutbounds is the template's outbound list; subscription outbounds
  340. // are injected at runtime and aren't part of it, so append any tested
  341. // outbound whose tag is missing. When a tested outbound's tag collides
  342. // with a template outbound, the template version wins — same semantics
  343. // as the pre-batch tester.
  344. outbounds := make([]any, 0, len(allOutbounds)+len(items))
  345. outbounds = append(outbounds, allOutbounds...)
  346. for _, it := range items {
  347. if !outboundsContainTag(outbounds, it.tag) {
  348. outbounds = append(outbounds, it.outbound)
  349. }
  350. }
  351. // Bridge amneziawg entries like GetXrayConfig does -- one raw entry fails
  352. // the whole temp config; drop unbridgeable ones, not unrelated items.
  353. bridged := make([]any, 0, len(outbounds))
  354. for _, ob := range outbounds {
  355. m, ok := ob.(map[string]any)
  356. if !ok {
  357. bridged = append(bridged, ob)
  358. continue
  359. }
  360. if p, _ := m["protocol"].(string); p != "amneziawg" {
  361. bridged = append(bridged, ob)
  362. continue
  363. }
  364. raw, err := json.Marshal(m)
  365. if err != nil {
  366. continue
  367. }
  368. repl, ok := amneziawgnet.BuildSocksBridge(raw)
  369. if !ok {
  370. continue
  371. }
  372. var replacement any
  373. if json.Unmarshal(repl, &replacement) == nil {
  374. bridged = append(bridged, replacement)
  375. }
  376. }
  377. outbounds = bridged
  378. for _, ob := range outbounds {
  379. outbound, ok := ob.(map[string]any)
  380. if !ok {
  381. continue
  382. }
  383. // The temp instance must not touch kernel WireGuard devices.
  384. if protocol, ok := outbound["protocol"].(string); ok && protocol == "wireguard" {
  385. if settings, ok := outbound["settings"].(map[string]any); ok {
  386. settings["noKernelTun"] = true
  387. } else {
  388. outbound["settings"] = map[string]any{"noKernelTun": true}
  389. }
  390. }
  391. }
  392. outboundsJSON, _ := json.Marshal(outbounds)
  393. inbounds := make([]xray.InboundConfig, len(items))
  394. rules := make([]any, len(items))
  395. for i, it := range items {
  396. inTag := fmt.Sprintf("test-in-%d", i)
  397. inbounds[i] = xray.InboundConfig{
  398. Listen: json_util.RawMessage(`"127.0.0.1"`),
  399. Port: ports[i],
  400. Protocol: "socks",
  401. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  402. Tag: inTag,
  403. }
  404. rules[i] = map[string]any{
  405. "type": "field",
  406. "inboundTag": []string{inTag},
  407. "outboundTag": it.tag,
  408. }
  409. }
  410. routingJSON, _ := json.Marshal(map[string]any{
  411. "domainStrategy": "AsIs",
  412. "rules": rules,
  413. })
  414. logJSON, _ := json.Marshal(map[string]any{
  415. "loglevel": "warning",
  416. "access": "none",
  417. "error": "",
  418. "dnsLog": false,
  419. })
  420. return &xray.Config{
  421. LogConfig: json_util.RawMessage(logJSON),
  422. InboundConfigs: inbounds,
  423. OutboundConfigs: json_util.RawMessage(outboundsJSON),
  424. RouterConfig: json_util.RawMessage(routingJSON),
  425. Policy: json_util.RawMessage(`{}`),
  426. Stats: json_util.RawMessage(`{}`),
  427. }
  428. }
  429. // outboundsContainTag reports whether any outbound in the slice has the given tag.
  430. func outboundsContainTag(outbounds []any, tag string) bool {
  431. for _, ob := range outbounds {
  432. if m, ok := ob.(map[string]any); ok {
  433. if t, _ := m["tag"].(string); t == tag {
  434. return true
  435. }
  436. }
  437. }
  438. return false
  439. }
  440. // probeThroughSocks probes the local SOCKS inbound at the given port and
  441. // fills result. A first, cold GET proves reachability and carries the
  442. // httptrace breakdown: any HTTP response — including 4xx/5xx and unfollowed
  443. // redirects — counts as reachable; only transport-level failures (refused,
  444. // reset, timeout, proxy errors) are failures. Delay is then re-measured on a
  445. // warm request over the kept-alive connection — the real round-trip through
  446. // the established tunnel — falling back to the cold total if the warm request
  447. // fails. The test URL's hostname is resolved by xray (Go's SOCKS5 client
  448. // sends the domain to the proxy), so DNS goes through the outbound too.
  449. func probeThroughSocks(port int, testURL string, timeout time.Duration, realDelay bool, result *TestOutboundResult) {
  450. proxyURL := &url.URL{Scheme: "socks5", Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(port))}
  451. tr := &http.Transport{
  452. Proxy: http.ProxyURL(proxyURL),
  453. MaxIdleConns: 1,
  454. MaxIdleConnsPerHost: 1,
  455. IdleConnTimeout: timeout,
  456. }
  457. defer tr.CloseIdleConnections()
  458. client := &http.Client{
  459. Transport: tr,
  460. Timeout: timeout,
  461. // A redirect would re-dial through the proxy and skew the timing;
  462. // the 3xx itself already proves the outbound works.
  463. CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
  464. }
  465. // Timing breakdown. ConnectStart/Done wrap the TCP dial to the local
  466. // inbound (the SOCKS handshake isn't traced, and xray ACKs CONNECT
  467. // before dialing upstream — so the real outbound establishment lands in
  468. // the TLS phase for https URLs, or inside TTFB for plain http).
  469. var (
  470. connStart, tlsStart time.Time
  471. connDur, tlsDur, ttfbDur time.Duration
  472. connDone, tlsDone, gotFirstRB bool
  473. )
  474. start := time.Now()
  475. trace := &httptrace.ClientTrace{
  476. ConnectStart: func(network, addr string) {
  477. if connStart.IsZero() {
  478. connStart = time.Now()
  479. }
  480. },
  481. ConnectDone: func(network, addr string, err error) {
  482. if err == nil && !connDone && !connStart.IsZero() {
  483. connDone = true
  484. connDur = time.Since(connStart)
  485. }
  486. },
  487. TLSHandshakeStart: func() {
  488. if tlsStart.IsZero() {
  489. tlsStart = time.Now()
  490. }
  491. },
  492. TLSHandshakeDone: func(_ tls.ConnectionState, err error) {
  493. if err == nil && !tlsDone && !tlsStart.IsZero() {
  494. tlsDone = true
  495. tlsDur = time.Since(tlsStart)
  496. }
  497. },
  498. GotFirstResponseByte: func() {
  499. if !gotFirstRB {
  500. gotFirstRB = true
  501. ttfbDur = time.Since(start)
  502. }
  503. },
  504. }
  505. req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, testURL, nil)
  506. if err != nil {
  507. result.Error = err.Error()
  508. return
  509. }
  510. resp, err := client.Do(req)
  511. coldDelay := time.Since(start).Milliseconds()
  512. if err != nil {
  513. result.Error = err.Error()
  514. return
  515. }
  516. drainAndClose(resp)
  517. result.Success = true
  518. result.HTTPStatus = resp.StatusCode
  519. if connDone {
  520. result.ConnectMs = max(connDur.Milliseconds(), 1)
  521. }
  522. if tlsDone {
  523. result.TLSMs = max(tlsDur.Milliseconds(), 1)
  524. }
  525. if gotFirstRB {
  526. result.TTFBMs = max(ttfbDur.Milliseconds(), 1)
  527. }
  528. delay := coldDelay
  529. if !realDelay {
  530. if warmDelay, ok := timedWarmGet(client, testURL); ok {
  531. delay = warmDelay
  532. }
  533. }
  534. result.Delay = max(delay, 1)
  535. if !realDelay {
  536. result.Egress = egressTraceProbe(proxyURL)
  537. }
  538. }
  539. // probeEgressTrace fetches Cloudflare's plain-text trace endpoint through the
  540. // same SOCKS route used by the HTTP probe. It asks one IPv4 and one IPv6
  541. // Cloudflare address directly, when available, while keeping the TLS SNI as
  542. // cloudflare.com. Failures are intentionally ignored by the caller: egress
  543. // metadata is diagnostic, not reachability.
  544. func probeEgressTrace(proxyURL *url.URL) *TestEgressResult {
  545. ipv4, ipv6 := cloudflareTraceTargets()
  546. if ipv4 == nil && ipv6 == nil {
  547. return nil
  548. }
  549. tr := &http.Transport{
  550. Proxy: http.ProxyURL(proxyURL),
  551. TLSClientConfig: &tls.Config{
  552. ServerName: egressTraceHost,
  553. },
  554. }
  555. defer tr.CloseIdleConnections()
  556. client := &http.Client{
  557. Transport: tr,
  558. Timeout: egressTraceTimeout,
  559. }
  560. egress := &TestEgressResult{}
  561. targets := make([]net.IP, 0, 2)
  562. if ipv4 != nil {
  563. targets = append(targets, ipv4)
  564. }
  565. if ipv6 != nil {
  566. targets = append(targets, ipv6)
  567. }
  568. results := make(chan map[string]string, len(targets))
  569. for _, target := range targets {
  570. go func(ip net.IP) {
  571. results <- fetchCloudflareTrace(client, ip)
  572. }(target)
  573. }
  574. for range targets {
  575. applyEgressTrace(egress, <-results)
  576. }
  577. if egress.IPv4 == "" && egress.IPv6 == "" && egress.Country == "" && egress.Warp == "" {
  578. return nil
  579. }
  580. return egress
  581. }
  582. func cloudflareTraceTargets() (net.IP, net.IP) {
  583. ctx, cancel := context.WithTimeout(context.Background(), egressTraceTimeout)
  584. defer cancel()
  585. addrs, err := net.DefaultResolver.LookupIPAddr(ctx, egressTraceHost)
  586. if err != nil {
  587. return nil, nil
  588. }
  589. var ipv4, ipv6 net.IP
  590. for _, addr := range addrs {
  591. ip := addr.IP
  592. if ipv4 == nil {
  593. if v4 := ip.To4(); v4 != nil {
  594. ipv4 = v4
  595. continue
  596. }
  597. }
  598. if ipv6 == nil && ip.To4() == nil && ip.To16() != nil {
  599. ipv6 = ip
  600. }
  601. if ipv4 != nil && ipv6 != nil {
  602. break
  603. }
  604. }
  605. return ipv4, ipv6
  606. }
  607. func fetchCloudflareTrace(client *http.Client, ip net.IP) map[string]string {
  608. if ip == nil {
  609. return nil
  610. }
  611. traceURL := (&url.URL{
  612. Scheme: "https",
  613. Host: net.JoinHostPort(ip.String(), "443"),
  614. Path: egressTracePath,
  615. }).String()
  616. req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, traceURL, nil)
  617. if err != nil {
  618. return nil
  619. }
  620. req.Host = egressTraceHost
  621. resp, err := client.Do(req)
  622. if err != nil {
  623. return nil
  624. }
  625. defer resp.Body.Close()
  626. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  627. return nil
  628. }
  629. body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<10))
  630. if err != nil {
  631. return nil
  632. }
  633. return parseCloudflareTrace(string(body))
  634. }
  635. func applyEgressTrace(egress *TestEgressResult, values map[string]string) {
  636. if len(values) == 0 {
  637. return
  638. }
  639. if ip := net.ParseIP(values["ip"]); ip != nil {
  640. if ip.To4() != nil {
  641. if egress.IPv4 == "" {
  642. egress.IPv4 = values["ip"]
  643. }
  644. } else if egress.IPv6 == "" {
  645. egress.IPv6 = values["ip"]
  646. }
  647. }
  648. if egress.Country == "" {
  649. egress.Country = values["loc"]
  650. }
  651. if values["warp"] == "on" || egress.Warp == "" {
  652. egress.Warp = values["warp"]
  653. }
  654. }
  655. func parseCloudflareTrace(body string) map[string]string {
  656. values := make(map[string]string)
  657. for line := range strings.SplitSeq(body, "\n") {
  658. line = strings.TrimSpace(line)
  659. if line == "" {
  660. continue
  661. }
  662. key, value, ok := strings.Cut(line, "=")
  663. if !ok {
  664. continue
  665. }
  666. values[strings.TrimSpace(key)] = strings.TrimSpace(value)
  667. }
  668. return values
  669. }
  670. // timedWarmGet re-issues the probe request over the transport's kept-alive
  671. // connection and returns its duration — the tunnel's per-request round-trip.
  672. func timedWarmGet(client *http.Client, testURL string) (int64, bool) {
  673. req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, testURL, nil)
  674. if err != nil {
  675. return 0, false
  676. }
  677. start := time.Now()
  678. resp, err := client.Do(req)
  679. delay := time.Since(start).Milliseconds()
  680. if err != nil {
  681. return 0, false
  682. }
  683. drainAndClose(resp)
  684. return delay, true
  685. }
  686. // drainAndClose consumes the body (bounded by probeDrainLimit) so the
  687. // connection returns to the keep-alive pool for the warm request.
  688. func drainAndClose(resp *http.Response) {
  689. _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, probeDrainLimit))
  690. resp.Body.Close()
  691. }
  692. // reserveLoopbackPorts grabs n free loopback ports and keeps the listeners
  693. // open so nothing else claims them; release() frees them (idempotent — the
  694. // caller releases right before starting xray and again via defer).
  695. func reserveLoopbackPorts(n int) ([]int, func(), error) {
  696. listeners := make([]net.Listener, 0, n)
  697. release := func() {
  698. for _, l := range listeners {
  699. l.Close()
  700. }
  701. }
  702. ports := make([]int, 0, n)
  703. for range n {
  704. l, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  705. if err != nil {
  706. release()
  707. return nil, nil, err
  708. }
  709. listeners = append(listeners, l)
  710. ports = append(ports, l.Addr().(*net.TCPAddr).Port)
  711. }
  712. return ports, release, nil
  713. }
  714. // createTestConfigPath returns a unique path for a temporary xray config file in the bin folder.
  715. // The temp file is created and closed so the path is reserved; Start() will overwrite it.
  716. func createTestConfigPath() (string, error) {
  717. tmpFile, err := os.CreateTemp(config.GetBinFolderPath(), "xray_test_*.json")
  718. if err != nil {
  719. return "", err
  720. }
  721. path := tmpFile.Name()
  722. if err := tmpFile.Close(); err != nil {
  723. os.Remove(path)
  724. return "", err
  725. }
  726. return path, nil
  727. }