跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

egress.go

224 行 · 7.6 KB历史下载
1package cage
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/tls"
8 "encoding/base64"
9 "errors"
10 "fmt"
11 "io"
12 "net"
13 "net/http"
14 "net/netip"
15 "net/url"
16 "strings"
17 "time"
18
19 "github.com/miekg/dns"
20 "github.com/sylvinus/agent-vm/internal/netguard"
21 "github.com/sylvinus/agent-vm/internal/usererror"
22 "golang.org/x/net/proxy"
23)
24
25// Egress has one upstream and no direct fallback. It lives in the hostagent,
26// outside the VM. The guest never receives the upstream credentials.
27type Egress struct {
28 upstream *url.URL
29 dnsURL string
30 client *http.Client
31 public netguard.Policy
32 connect proxyConnector
33}
34
35type proxyConnector interface {
36 Dial(string, string) (net.Conn, error)
37 DialContext(context.Context, string, string) (net.Conn, error)
38}
39
40func NewEgress(c Config) (*Egress, error) {
41 if err := c.Validate(); err != nil {
42 return nil, err
43 }
44 u, _ := url.Parse(c.ProxyURL)
45 e := &Egress{upstream: u, dnsURL: c.DNSURL, connect: &net.Dialer{Timeout: 20 * time.Second, KeepAlive: 30 * time.Second}}
46 e.client = &http.Client{Timeout: 20 * time.Second, Transport: &http.Transport{Proxy: nil, DialContext: e.DialContext, ForceAttemptHTTP2: true}, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("DNS redirect refused") }}
47 return e, nil
48}
49
50func (e *Egress) Allows(network string, dst netip.AddrPort) bool {
51 // UDP and ICMP have no fallback. Guest DNS uses the dedicated DoH path.
52 return network == "tcp" && dst.Addr().Unmap().Is4() && e.public.Allows(network, dst)
53}
54
55type bufferedConn struct {
56 net.Conn
57 reader *bufio.Reader
58}
59
60func (c *bufferedConn) Read(p []byte) (int, error) { return c.reader.Read(p) }
61
62func proxyConnectionError(ctx context.Context, action string, err error) error {
63 // Closing a stalled handshake on cancellation can report net.ErrClosed.
64 // Preserve the operation deadline so exit monitoring can classify a timeout.
65 if ctx.Err() != nil {
66 err = ctx.Err()
67 } else if deadline, ok := ctx.Deadline(); ok && !time.Now().Before(deadline) {
68 // The socket deadline can fire before the context timer publishes Err.
69 var timeout net.Error
70 if errors.As(err, &timeout) && timeout.Timeout() {
71 err = errors.Join(context.DeadlineExceeded, err)
72 }
73 }
74 return usererror.Wrap(action, err, "请检查代理;请求不会改为直连。")
75}
76
77// DialContext is used for all guest TCP connections and DoH. DNS names are
78// passed to the proxy without resolving them on the host.
79func (e *Egress) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
80 if network != "tcp" && network != "tcp4" && network != "tcp6" {
81 return nil, errors.New("cage permits TCP only")
82 }
83 ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
84 defer cancel()
85 if strings.HasPrefix(e.upstream.Scheme, "socks5") {
86 var auth *proxy.Auth
87 if e.upstream.User != nil {
88 p, _ := e.upstream.User.Password()
89 auth = &proxy.Auth{User: e.upstream.User.Username(), Password: p}
90 }
91 d, err := proxy.SOCKS5("tcp", e.upstream.Host, auth, e.connect)
92 if err != nil {
93 return nil, errors.New("invalid SOCKS5 configuration")
94 }
95 c, err := d.(proxy.ContextDialer).DialContext(ctx, "tcp", addr)
96 if err != nil {
97 return nil, proxyConnectionError(ctx, "连接指定 SOCKS5 代理", err)
98 }
99 return c, nil
100 }
101 conn, err := e.connect.DialContext(ctx, "tcp", e.upstream.Host)
102 if err != nil {
103 return nil, proxyConnectionError(ctx, "连接指定代理", err)
104 }
105 // Cancellation must interrupt a stalled CONNECT response, not only the
106 // initial TCP connect. Stop the callback before returning a live tunnel.
107 upstreamConn := conn
108 stopCancel := context.AfterFunc(ctx, func() { _ = upstreamConn.Close() })
109 defer stopCancel()
110 ok := false
111 defer func() {
112 if !ok {
113 conn.Close()
114 }
115 }()
116 if deadline, yes := ctx.Deadline(); yes {
117 conn.SetDeadline(deadline)
118 }
119 if e.upstream.Scheme == "https" {
120 t := tls.Client(conn, &tls.Config{ServerName: e.upstream.Hostname(), MinVersion: tls.VersionTLS12})
121 if err = t.HandshakeContext(ctx); err != nil {
122 return nil, proxyConnectionError(ctx, "验证 HTTPS 代理的加密连接", err)
123 }
124 conn = t
125 }
126 req := &http.Request{Method: http.MethodConnect, URL: &url.URL{Opaque: addr}, Host: addr, Header: make(http.Header)}
127 if e.upstream.User != nil {
128 p, _ := e.upstream.User.Password()
129 req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(e.upstream.User.Username()+":"+p)))
130 }
131 if err = req.Write(conn); err != nil {
132 return nil, proxyConnectionError(ctx, "发送代理 CONNECT 请求", err)
133 }
134 r := bufio.NewReader(conn)
135 resp, err := http.ReadResponse(r, req)
136 if err != nil {
137 return nil, proxyConnectionError(ctx, "读取代理 CONNECT 响应", err)
138 }
139 if resp.StatusCode != http.StatusOK {
140 return nil, fmt.Errorf("代理拒绝 CONNECT 请求(HTTP %d);请求不会改为直连", resp.StatusCode)
141 }
142 conn.SetDeadline(time.Time{})
143 ok = true
144 return &bufferedConn{Conn: conn, reader: r}, nil
145}
146
147// ExchangeDNS forwards DNS wire messages over HTTPS via the same upstream.
148// It never calls the host resolver, even when the upstream fails.
149func (e *Egress) ExchangeDNS(ctx context.Context, q *dns.Msg) (*dns.Msg, error) {
150 for _, question := range q.Question {
151 // The initial exit policy monitors IPv4. Do not offer an unmeasured
152 // guest IPv6 route; literal IPv6 destinations are denied by Allows too.
153 if question.Qtype == dns.TypeAAAA {
154 r := new(dns.Msg)
155 r.SetReply(q)
156 return r, nil
157 }
158 n := strings.ToLower(strings.TrimSuffix(question.Name, "."))
159 if n == "localhost" || strings.HasSuffix(n, ".localhost") || strings.HasSuffix(n, ".internal") || strings.HasSuffix(n, ".local") {
160 r := new(dns.Msg)
161 r.SetRcode(q, dns.RcodeNameError)
162 return r, nil
163 }
164 }
165 wire, err := q.Pack()
166 if err != nil {
167 return nil, err
168 }
169 // Keep the original total deadline, but allow a fresh connection after an
170 // intermittent EOF or overloaded DoH server. Every attempt uses this same
171 // proxy-only transport and the configured endpoint.
172 ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
173 defer cancel()
174 for attempt := 0; attempt < 3; attempt++ {
175 if ctx.Err() != nil {
176 return nil, ctx.Err()
177 }
178 attemptCtx, done := context.WithTimeout(ctx, 6*time.Second)
179 var answer *dns.Msg
180 var retry bool
181 answer, retry, err = e.exchangeDNSOnce(attemptCtx, q, wire)
182 done()
183 if err == nil || !retry {
184 return answer, err
185 }
186 if attempt < 2 {
187 select {
188 case <-ctx.Done():
189 return nil, ctx.Err()
190 case <-time.After(time.Duration(attempt+1) * 150 * time.Millisecond):
191 }
192 }
193 }
194 return nil, err
195}
196
197func (e *Egress) exchangeDNSOnce(ctx context.Context, q *dns.Msg, wire []byte) (*dns.Msg, bool, error) {
198 req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.dnsURL, bytes.NewReader(wire))
199 if err != nil {
200 return nil, false, errors.New("invalid DNS request")
201 }
202 req.Header.Set("Content-Type", "application/dns-message")
203 req.Header.Set("Accept", "application/dns-message")
204 resp, err := e.client.Do(req)
205 if err != nil {
206 return nil, true, errors.New("cage DNS upstream unavailable; check the configured DoH endpoint through the selected proxy")
207 }
208 defer resp.Body.Close()
209 if resp.StatusCode != 200 {
210 return nil, resp.StatusCode == 429 || resp.StatusCode >= 500, fmt.Errorf("cage DNS upstream returned HTTP %d", resp.StatusCode)
211 }
212 body, err := io.ReadAll(io.LimitReader(resp.Body, 65536))
213 if err != nil {
214 return nil, true, errors.New("incomplete DNS upstream response")
215 }
216 r := new(dns.Msg)
217 if err = r.Unpack(body); err != nil {
218 return nil, false, errors.New("invalid DNS upstream response")
219 }
220 if !r.Response || r.Id != q.Id {
221 return nil, false, errors.New("mismatched DNS upstream response")
222 }
223 return r, false, nil
224}