1
0

probe_http.go 20 KB

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