| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "net/netip" |
| 14 | "net/url" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/miekg/dns" |
| 19 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 20 | "github.com/sylvinus/agent-vm/internal/usererror" |
| 21 | ) |
| 22 | |
| 23 | |
| 24 | |
| 25 | func ProbeExitIP(ctx context.Context, cfg Config) (string, error) { |
| 26 | e, err := NewEgress(cfg) |
| 27 | if err != nil { |
| 28 | return "", err |
| 29 | } |
| 30 | return probeExitIP(ctx, e) |
| 31 | } |
| 32 | |
| 33 | func probeExitIP(ctx context.Context, e *Egress) (string, error) { |
| 34 | transport := &http.Transport{Proxy: nil, DialContext: e.DialContext, DisableKeepAlives: true} |
| 35 | defer transport.CloseIdleConnections() |
| 36 | client := &http.Client{Transport: transport, Timeout: 5 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("probe redirect refused") }} |
| 37 | |
| 38 | |
| 39 | allTimedOut := true |
| 40 | var failures []string |
| 41 | for _, service := range []struct{ id, name, endpoint string }{ |
| 42 | {"icanhazip", "主检测服务", "https://ipv4.icanhazip.com/"}, |
| 43 | {"ipify", "备用检测服务", "https://api.ipify.org/"}, |
| 44 | } { |
| 45 | started := time.Now() |
| 46 | ip, err := queryExitIP(ctx, client, service.endpoint) |
| 47 | if err == nil { |
| 48 | return ip, nil |
| 49 | } |
| 50 | |
| 51 | diagnostics.Log("warn", "exit-probe", fmt.Sprintf("service=%s duration_ms=%d error=%v cause=%v", service.id, time.Since(started).Milliseconds(), err, errors.Unwrap(err))) |
| 52 | failures = append(failures, service.name+":"+err.Error()) |
| 53 | var networkError net.Error |
| 54 | if !errors.Is(err, context.DeadlineExceeded) && !(errors.As(err, &networkError) && networkError.Timeout()) { |
| 55 | allTimedOut = false |
| 56 | } |
| 57 | if ctx.Err() != nil { |
| 58 | break |
| 59 | } |
| 60 | } |
| 61 | if errors.Is(ctx.Err(), context.Canceled) { |
| 62 | return "", usererror.Wrap("通过所选代理查询出口 IP", ctx.Err(), "外网保持关闭。") |
| 63 | } |
| 64 | if allTimedOut { |
| 65 | return "", usererror.New("通过所选代理查询出口 IP", strings.Join(failures, ";"), "出口检测超时,请稍后重试。", context.DeadlineExceeded) |
| 66 | } |
| 67 | return "", errors.New("通过所选代理查询出口 IP 失败:" + strings.Join(failures, ";") + "。未能确认出口时,外网保持关闭。") |
| 68 | } |
| 69 | |
| 70 | func queryExitIP(ctx context.Context, client *http.Client, endpoint string) (string, error) { |
| 71 | req, _ := http.NewRequestWithContext(ctx, "GET", endpoint, nil) |
| 72 | req.Header.Set("User-Agent", "Cage-network-check/1") |
| 73 | resp, err := client.Do(req) |
| 74 | if err != nil { |
| 75 | var requestError *url.Error |
| 76 | if errors.As(err, &requestError) { |
| 77 | err = requestError.Err |
| 78 | } |
| 79 | return "", usererror.Display("通过所选代理查询出口 IP", err, "请检查网络与代理,再重新检测。") |
| 80 | } |
| 81 | defer resp.Body.Close() |
| 82 | if resp.StatusCode != 200 { |
| 83 | return "", fmt.Errorf("查询出口 IP 失败:检测服务返回 HTTP %d。请检查所选代理,稍后重新检测;外网保持关闭。", resp.StatusCode) |
| 84 | } |
| 85 | body, err := io.ReadAll(io.LimitReader(resp.Body, 4097)) |
| 86 | if err != nil { |
| 87 | return "", usererror.Wrap("读取出口检测响应", err, "请稍后重新检测。") |
| 88 | } |
| 89 | if len(body) > 4096 { |
| 90 | return "", errors.New("查询出口 IP 失败:检测服务没有返回有效的 IP 记录。请更换可用节点或稍后重新检测;外网保持关闭。") |
| 91 | } |
| 92 | ip, err := netip.ParseAddr(strings.TrimSpace(string(body))) |
| 93 | if err != nil || !ip.Is4() || !ip.IsGlobalUnicast() || ip.IsPrivate() { |
| 94 | return "", errors.New("出口检测结果不是有效公网 IPv4 地址") |
| 95 | } |
| 96 | return ip.String(), nil |
| 97 | } |
| 98 | |
| 99 | func probeDNS(ctx context.Context, e *Egress) error { |
| 100 | q := new(dns.Msg) |
| 101 | q.SetQuestion("example.com.", dns.TypeA) |
| 102 | r, err := e.ExchangeDNS(ctx, q) |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | if r.Rcode != dns.RcodeSuccess { |
| 107 | return errors.New("DNS probe did not resolve its fixed target") |
| 108 | } |
| 109 | for _, answer := range r.Answer { |
| 110 | if a, ok := answer.(*dns.A); ok && a.A.IsGlobalUnicast() && !a.A.IsPrivate() { |
| 111 | return nil |
| 112 | } |
| 113 | } |
| 114 | return errors.New("DNS probe returned no usable answer") |
| 115 | } |
| 116 | |
| 117 | func (g *EgressGate) dialDiagnostic(ctx context.Context) (net.Conn, error) { |
| 118 | _, done, epoch, err := g.operation(ctx, true) |
| 119 | if err != nil { |
| 120 | return nil, err |
| 121 | } |
| 122 | defer done() |
| 123 | client, server := net.Pipe() |
| 124 | tracked, err := g.track(client, epoch) |
| 125 | if err != nil { |
| 126 | server.Close() |
| 127 | return nil, err |
| 128 | } |
| 129 | g.mu.Lock() |
| 130 | if !g.validLocked(epoch) { |
| 131 | g.mu.Unlock() |
| 132 | _ = tracked.Close() |
| 133 | _ = server.Close() |
| 134 | return nil, ErrGateClosed |
| 135 | } |
| 136 | parent, fault := g.epochContext, g.state.Fault |
| 137 | g.mu.Unlock() |
| 138 | go g.serveDiagnostic(parent, server, fault) |
| 139 | return tracked, nil |
| 140 | } |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | func (g *EgressGate) serveDiagnostic(parent context.Context, conn net.Conn, fault bool) { |
| 146 | defer conn.Close() |
| 147 | _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) |
| 148 | ctx, cancel := context.WithTimeout(parent, 14*time.Second) |
| 149 | defer cancel() |
| 150 | stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) |
| 151 | defer stop() |
| 152 | req, err := http.ReadRequest(bufio.NewReader(io.LimitReader(conn, 8192))) |
| 153 | if err != nil { |
| 154 | return |
| 155 | } |
| 156 | defer req.Body.Close() |
| 157 | host := strings.TrimSuffix(strings.ToLower(req.Host), ":80") |
| 158 | if req.Method != "GET" || host != DiagnosticHost || req.URL.IsAbs() || req.URL.RawQuery != "" || req.ContentLength > 0 || len(req.TransferEncoding) != 0 || |
| 159 | (req.URL.Path != "/" && req.URL.Path != "/egress" && req.URL.Path != "/dns") { |
| 160 | writeDiagnostic(conn, 400, map[string]string{"error": "fixed_probe_only"}) |
| 161 | return |
| 162 | } |
| 163 | if req.URL.Path == "/" { |
| 164 | writeDiagnostic(conn, 200, map[string]string{"service": "cage-diagnostic"}) |
| 165 | return |
| 166 | } |
| 167 | g.mu.Lock() |
| 168 | if g.probeRequests >= 32 { |
| 169 | g.mu.Unlock() |
| 170 | writeDiagnostic(conn, 429, map[string]string{"error": "probe_limit"}) |
| 171 | return |
| 172 | } |
| 173 | g.probeRequests++ |
| 174 | g.mu.Unlock() |
| 175 | e := g.diagnostic |
| 176 | if fault { |
| 177 | e = g.failedDiagnostic |
| 178 | } |
| 179 | if req.URL.Path == "/dns" { |
| 180 | err = probeDNS(ctx, e) |
| 181 | g.mu.Lock() |
| 182 | g.state.Counters.ProbeDNS++ |
| 183 | if fault && err != nil { |
| 184 | g.state.Counters.FaultDNS++ |
| 185 | } |
| 186 | g.mu.Unlock() |
| 187 | if err != nil { |
| 188 | writeDiagnostic(conn, 503, map[string]string{"error": "dns_unavailable"}) |
| 189 | return |
| 190 | } |
| 191 | writeDiagnostic(conn, 200, map[string]bool{"ok": true}) |
| 192 | return |
| 193 | } |
| 194 | ip, err := probeExitIP(ctx, e) |
| 195 | g.mu.Lock() |
| 196 | g.state.Counters.ProbeTCP++ |
| 197 | if fault && err != nil { |
| 198 | g.state.Counters.FaultTCP++ |
| 199 | } |
| 200 | g.mu.Unlock() |
| 201 | if err != nil { |
| 202 | writeDiagnostic(conn, 503, map[string]string{"error": "proxy_unavailable"}) |
| 203 | return |
| 204 | } |
| 205 | writeDiagnostic(conn, 200, map[string]string{"ip": ip}) |
| 206 | } |
| 207 | |
| 208 | func writeDiagnostic(conn net.Conn, status int, value any) { |
| 209 | body, _ := json.Marshal(value) |
| 210 | resp := http.Response{StatusCode: status, Status: fmt.Sprintf("%d %s", status, http.StatusText(status)), ProtoMajor: 1, ProtoMinor: 1, |
| 211 | Header: http.Header{"Content-Type": {"application/json"}, "Cache-Control": {"no-store"}, "Access-Control-Allow-Origin": {"*"}, "Connection": {"close"}}, |
| 212 | Body: io.NopCloser(bytes.NewReader(body)), ContentLength: int64(len(body)), Close: true} |
| 213 | _ = resp.Write(conn) |
| 214 | } |