probe_http.go 24 KB

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