| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "go.yaml.in/yaml/v3" |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | |
| 23 | func TestCoreLatencyExcludesProxyHandshake(t *testing.T) { |
| 24 | if os.Getenv("CAGE_PROXY_INTEGRATION") != "1" { |
| 25 | t.Skip("requires a test binary beside the bundled Mihomo") |
| 26 | } |
| 27 | var requests, connections atomic.Int32 |
| 28 | target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 29 | if r.Method != http.MethodHead { |
| 30 | t.Error("latency probe must use HEAD") |
| 31 | } |
| 32 | requests.Add(1) |
| 33 | w.WriteHeader(http.StatusNoContent) |
| 34 | })) |
| 35 | t.Cleanup(target.Close) |
| 36 | const handshake = 500 * time.Millisecond |
| 37 | upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 38 | if r.Method != http.MethodConnect { |
| 39 | t.Error("expected proxy CONNECT") |
| 40 | w.WriteHeader(http.StatusMethodNotAllowed) |
| 41 | return |
| 42 | } |
| 43 | remote, err := net.Dial("tcp", strings.TrimPrefix(target.URL, "http://")) |
| 44 | if err != nil { |
| 45 | t.Error(err) |
| 46 | return |
| 47 | } |
| 48 | defer remote.Close() |
| 49 | client, buffered, err := w.(http.Hijacker).Hijack() |
| 50 | if err != nil { |
| 51 | t.Error(err) |
| 52 | return |
| 53 | } |
| 54 | defer client.Close() |
| 55 | connections.Add(1) |
| 56 | time.Sleep(handshake) |
| 57 | if _, err := io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { |
| 58 | return |
| 59 | } |
| 60 | go func() { _, _ = io.Copy(remote, buffered) }() |
| 61 | _, _ = io.Copy(client, remote) |
| 62 | })) |
| 63 | t.Cleanup(upstream.Close) |
| 64 | |
| 65 | profile := t.TempDir() |
| 66 | s, err := Load(profile) |
| 67 | if err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | address := strings.TrimPrefix(upstream.URL, "http://") |
| 71 | _, port, _ := net.SplitHostPort(address) |
| 72 | if err := s.Import("local", "", []byte("proxies: [{name: local, type: http, server: 127.0.0.1, port: "+port+"}]"), "local", 0, ""); err != nil { |
| 73 | t.Fatal(err) |
| 74 | } |
| 75 | s.Selected, s.Port = s.Sources[0].Nodes[0].ID, 0 |
| 76 | data, err := s.Runtime(profile) |
| 77 | if err != nil { |
| 78 | t.Fatal(err) |
| 79 | } |
| 80 | interfaces, err := net.Interfaces() |
| 81 | if err != nil { |
| 82 | t.Fatal(err) |
| 83 | } |
| 84 | loopback := "" |
| 85 | for _, iface := range interfaces { |
| 86 | if iface.Flags&net.FlagLoopback != 0 { |
| 87 | loopback = iface.Name |
| 88 | break |
| 89 | } |
| 90 | } |
| 91 | data, err = BindInterface(data, loopback) |
| 92 | if err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | config := filepath.Join(Dir(profile), "config.yaml") |
| 96 | if err := Write(config, data); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | if err := os.MkdirAll(filepath.Dir(Socket(profile)), 0700); err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(Socket(profile))) }) |
| 103 | core, err := CorePath() |
| 104 | if err != nil { |
| 105 | t.Fatal(err) |
| 106 | } |
| 107 | log, err := os.Create(filepath.Join(profile, "core.log")) |
| 108 | if err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | cmd := exec.Command(core, "-d", Dir(profile), "-f", config) |
| 112 | cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log |
| 113 | if err := cmd.Start(); err != nil { |
| 114 | log.Close() |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); _ = log.Close() }) |
| 118 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 119 | defer cancel() |
| 120 | ticker := time.NewTicker(20 * time.Millisecond) |
| 121 | defer ticker.Stop() |
| 122 | for !Running(ctx, profile, s) { |
| 123 | select { |
| 124 | case <-ctx.Done(): |
| 125 | t.Fatal("generated configuration did not become ready") |
| 126 | case <-ticker.C: |
| 127 | } |
| 128 | } |
| 129 | var result struct { |
| 130 | Delay int `json:"delay"` |
| 131 | } |
| 132 | start := time.Now() |
| 133 | if err := API(ctx, profile, "GET", "/proxies/"+s.Selected+"/delay?timeout=5000&url="+url.QueryEscape(target.URL), nil, &result); err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | elapsed := time.Since(start) |
| 137 | if result.Delay <= 0 || elapsed-time.Duration(result.Delay)*time.Millisecond < handshake-100*time.Millisecond || requests.Load() != 2 || connections.Load() != 1 { |
| 138 | t.Fatalf("delay=%dms elapsed=%s HEADs=%d connections=%d; expected two requests on one connection with handshake excluded", result.Delay, elapsed, requests.Load(), connections.Load()) |
| 139 | } |
| 140 | t.Logf("reported=%dms elapsed=%s HEADs=%d CONNECTs=%d", result.Delay, elapsed, requests.Load(), connections.Load()) |
| 141 | var legacy map[string]any |
| 142 | if err := yaml.Unmarshal(data, &legacy); err != nil { |
| 143 | t.Fatal(err) |
| 144 | } |
| 145 | legacy["unified-delay"] = false |
| 146 | legacyData, err := yaml.Marshal(legacy) |
| 147 | if err != nil { |
| 148 | t.Fatal(err) |
| 149 | } |
| 150 | if err := API(ctx, profile, "PUT", "/configs", map[string]string{"payload": string(legacyData)}, nil); err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | if Running(ctx, profile, s) { |
| 154 | t.Fatal("core using the old latency metric was accepted for reuse") |
| 155 | } |
| 156 | } |