跳到主要内容

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

浏览文件

gvproxy.go

413 行 · 9.8 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package usernet
5
6import (
7 "bufio"
8 "context"
9 "errors"
10 "fmt"
11 "net"
12 "net/http"
13 "net/netip"
14 "os"
15 "runtime"
16 "strconv"
17 "strings"
18 "sync"
19 "time"
20
21 "github.com/balajiv113/fd"
22 "github.com/containers/gvisor-tap-vsock/pkg/types"
23 "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork"
24 "github.com/miekg/dns"
25 "github.com/sirupsen/logrus"
26 "golang.org/x/sync/errgroup"
27)
28
29type GVisorNetstackOpts struct {
30 MTU int
31
32 QemuSocket string
33 FdSocket string
34 Endpoint string
35
36 // DgramConn is one end of a datagram socketpair, whose other end is
37 // QEMU's dgram netdev: one raw Ethernet frame per datagram. The netstack
38 // closes it when its context ends.
39 DgramConn net.Conn
40
41 Subnet string
42
43 Async bool
44
45 DefaultLeases map[string]string
46}
47
48var opts *GVisorNetstackOpts
49
50const gatewayMacAddr = "5a:94:ef:e4:0c:dd"
51
52// Outbound, when set by the program running the hostagent, decides what the
53// guests of the per-instance netstacks may reach (types.Configuration.Outbound).
54// The host services the guest needs (AllowHostService) are reached past it.
55var Outbound types.Outbound
56
57// DroppedIPv6 is an optional observer for the instance-owned IPv4-only guest link.
58var DroppedIPv6 func([]byte)
59
60// GuestDial and DNSExchange are host-owned transport hooks.
61var GuestDial types.DialContext
62var DNSExchange func(context.Context, *dns.Msg) (*dns.Msg, error)
63
64func dialGuest(ctx context.Context, network, addr string) (net.Conn, error) {
65 if GuestDial == nil {
66 return (&net.Dialer{}).DialContext(ctx, network, addr)
67 }
68 dst, err := netip.ParseAddrPort(addr)
69 if err == nil && dst.Addr().Unmap() == netip.MustParseAddr("127.0.0.1") {
70 if _, ok := hostServices.Load(hostService{network, dst.Port()}); ok {
71 return (&net.Dialer{}).DialContext(ctx, network, addr)
72 }
73 }
74 return GuestDial(ctx, network, addr)
75}
76
77// Names and Answered, when set by the program running the hostagent, are
78// applied by the gateway's DNS server of the per-instance netstacks to every
79// query it gets (types.Configuration.DNSNames and DNSAnswered).
80var (
81 Names func(name string) bool
82 Answered func(name string, ips []net.IP)
83)
84
85type hostService struct {
86 network string
87 port uint16
88}
89
90// hostServices are the ports of 127.0.0.1 the guest may always reach.
91var hostServices sync.Map
92
93// AllowHostService lets the guest reach port of 127.0.0.1 over network ("tcp"
94// or "udp") past Outbound: the hostagent's DNS server.
95func AllowHostService(network string, port int) {
96 hostServices.Store(hostService{network, uint16(port)}, true)
97}
98
99func outbound(network string, dst netip.AddrPort) bool {
100 if dst.Addr().Unmap() == netip.AddrFrom4([4]byte{127, 0, 0, 1}) {
101 if _, ok := hostServices.Load(hostService{network, dst.Port()}); ok {
102 return true
103 }
104 }
105 return Outbound.Allows(network, dst)
106}
107
108func StartGVisorNetstack(ctx context.Context, gVisorOpts *GVisorNetstackOpts) error {
109 opts = gVisorOpts
110
111 ip, ipNet, err := net.ParseCIDR(opts.Subnet)
112 if err != nil {
113 return err
114 }
115 gatewayIP := GatewayIP(ip)
116
117 leases := map[string]string{}
118 if opts.DefaultLeases != nil {
119 for k, v := range opts.DefaultLeases {
120 if ipNet.Contains(net.ParseIP(k)) {
121 leases[k] = v
122 }
123 }
124 }
125 leases[gatewayIP] = gatewayMacAddr
126
127 // The way gvisor-tap-vsock implemented slirp is different from tradition SLIRP,
128 // - GatewayIP handling all request, also answers DNS queries
129 // - based on NAT configuration, gateway forwards and translates calls to host
130 // Comparing this with QEMU SLIRP,
131 // - DNS is equivalent to GatewayIP
132 // - GatewayIP is equivalent to NAT configuration
133 config := types.Configuration{
134 Debug: false,
135 MTU: opts.MTU,
136 Subnet: opts.Subnet,
137 GatewayIP: gatewayIP,
138 GatewayMacAddress: gatewayMacAddr,
139 DHCPStaticLeases: leases,
140 Forwards: map[string]string{},
141 DNS: []types.Zone{},
142 DNSSearchDomains: searchDomains(),
143 NAT: map[string]string{
144 gatewayIP: "127.0.0.1",
145 },
146 GatewayVirtualIPs: []string{gatewayIP},
147 Outbound: outbound,
148 DroppedIPv6: DroppedIPv6,
149 DialContext: dialGuest,
150 DNSExchange: DNSExchange,
151 DNSNames: Names,
152 DNSAnswered: Answered,
153 }
154
155 groupErrs, ctx := errgroup.WithContext(ctx)
156 err = run(ctx, groupErrs, &config)
157 if err != nil {
158 return err
159 }
160 if opts.Async {
161 return err
162 }
163 return groupErrs.Wait()
164}
165
166func run(ctx context.Context, g *errgroup.Group, configuration *types.Configuration) error {
167 vn, err := virtualnetwork.New(configuration)
168 if err != nil {
169 return err
170 }
171
172 ln, err := net.Listen("unix", opts.Endpoint)
173 if err != nil {
174 return err
175 }
176
177 httpServe(ctx, g, ln, muxWithExtension(vn))
178
179 if opts.QemuSocket != "" {
180 err = listenQEMU(ctx, vn)
181 if err != nil {
182 return err
183 }
184 }
185 if opts.FdSocket != "" {
186 err = listenFD(ctx, vn)
187 if err != nil {
188 return err
189 }
190 }
191 if opts.DgramConn != nil {
192 serveDgram(ctx, vn, opts.DgramConn)
193 }
194 return nil
195}
196
197// serveDgram serves the netstack on conn, until ctx ends. Frames are the
198// datagrams: there is no length prefix to lose track of, as with QEMU's
199// socket and stream netdevs.
200func serveDgram(ctx context.Context, vn *virtualnetwork.VirtualNetwork, conn net.Conn) {
201 ctx, cancel := context.WithCancel(ctx)
202 go func() {
203 <-ctx.Done()
204 conn.Close()
205 }()
206 go func() {
207 defer cancel()
208 if err := vn.AcceptBess(ctx, &UDPFileConn{Conn: conn}); err != nil && ctx.Err() == nil {
209 logrus.Error("QEMU datagram connection closed with error: ", err)
210 }
211 }()
212}
213
214func listenQEMU(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error {
215 var lc net.ListenConfig
216 listener, err := lc.Listen(ctx, "unix", opts.QemuSocket)
217 if err != nil {
218 return err
219 }
220
221 go func() {
222 defer listener.Close()
223 <-ctx.Done()
224 }()
225
226 go func() {
227 for {
228 conn, err := listener.Accept()
229 if err != nil {
230 if errors.Is(err, net.ErrClosed) {
231 return
232 }
233 logrus.Error("QEMU accept failed", err)
234 }
235
236 go func() {
237 err = vn.AcceptQemu(ctx, conn)
238 if err != nil {
239 logrus.Error("QEMU connection closed with error", err)
240 }
241 conn.Close()
242 }()
243 select {
244 case <-ctx.Done():
245 return
246 default:
247 continue
248 }
249 }
250 }()
251
252 return nil
253}
254
255func listenFD(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error {
256 var lc net.ListenConfig
257 listener, err := lc.Listen(ctx, "unix", opts.FdSocket)
258 if err != nil {
259 return err
260 }
261
262 go func() {
263 defer listener.Close()
264 <-ctx.Done()
265 }()
266
267 go func() {
268 for {
269 conn, err := listener.Accept()
270 if err != nil {
271 if errors.Is(err, net.ErrClosed) {
272 return
273 }
274 logrus.Error("FD accept failed", err)
275 continue // since conn is nil
276 }
277
278 files, err := fd.Get(conn.(*net.UnixConn), 1, []string{"client"})
279 if err != nil {
280 logrus.Error("Failed to get FD via socket", err)
281 }
282
283 if len(files) != 1 {
284 logrus.Error("Invalid number of fd in response", err)
285 }
286 fileConn, err := net.FileConn(files[0])
287 if err != nil {
288 logrus.Error("Error in FD Socket", err)
289 }
290 files[0].Close()
291
292 go func() {
293 err = vn.AcceptBess(ctx, &UDPFileConn{Conn: fileConn})
294 if err != nil {
295 logrus.Error("FD connection closed with error", err)
296 }
297 fileConn.Close()
298 }()
299 select {
300 case <-ctx.Done():
301 return
302 default:
303 continue
304 }
305 }
306 }()
307
308 return nil
309}
310
311func httpServe(ctx context.Context, g *errgroup.Group, ln net.Listener, mux http.Handler) {
312 s := &http.Server{
313 Handler: mux,
314 ReadTimeout: 10 * time.Second,
315 WriteTimeout: 10 * time.Second,
316 }
317 g.Go(func() error {
318 <-ctx.Done()
319 return s.Close()
320 })
321 g.Go(func() error {
322 err := s.Serve(ln)
323 if err != nil {
324 if err == http.ErrServerClosed {
325 return nil
326 }
327 return err
328 }
329 return nil
330 })
331}
332
333func muxWithExtension(n *virtualnetwork.VirtualNetwork) *http.ServeMux {
334 m := n.Mux()
335 m.HandleFunc("/extension/wait_port", func(w http.ResponseWriter, r *http.Request) {
336 ip := r.URL.Query().Get("ip")
337 if net.ParseIP(ip) == nil {
338 msg := fmt.Sprintf("invalid ip address: %s", ip)
339 http.Error(w, msg, http.StatusBadRequest)
340 return
341 }
342 port16, err := strconv.ParseUint(r.URL.Query().Get("port"), 10, 16)
343 if err != nil {
344 http.Error(w, err.Error(), http.StatusBadRequest)
345 return
346 }
347 port := uint16(port16)
348 addr := fmt.Sprintf("%s:%d", ip, port)
349
350 timeoutSeconds := 10
351 if timeoutString := r.URL.Query().Get("timeout"); timeoutString != "" {
352 timeout16, err := strconv.ParseUint(timeoutString, 10, 16)
353 if err != nil {
354 http.Error(w, err.Error(), http.StatusBadRequest)
355 return
356 }
357 timeoutSeconds = int(timeout16)
358 }
359 ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds)*time.Second)
360 defer cancel()
361 // Wait until the port is available.
362 for {
363 conn, err := n.DialContextTCP(ctx, addr)
364 if err == nil {
365 conn.Close()
366 logrus.Debugf("Port is available on %s", addr)
367 w.WriteHeader(http.StatusOK)
368 break
369 }
370 select {
371 case <-ctx.Done():
372 msg := fmt.Sprintf("timed out waiting for port to become available on %s", addr)
373 logrus.Warn(msg)
374 http.Error(w, msg, http.StatusRequestTimeout)
375 return
376 default:
377 }
378 logrus.Debugf("Waiting for port to become available on %s", addr)
379 time.Sleep(1 * time.Second)
380 }
381 })
382 return m
383}
384
385func searchDomains() []string {
386 if runtime.GOOS != "windows" {
387 return resolveSearchDomain("/etc/resolv.conf")
388 }
389 return nil
390}
391
392func resolveSearchDomain(file string) []string {
393 f, err := os.Open(file)
394 if err != nil {
395 logrus.Errorf("open file error: %v", err)
396 return nil
397 }
398 defer f.Close()
399 sc := bufio.NewScanner(f)
400 searchPrefix := "search "
401 for sc.Scan() {
402 if after, ok := strings.CutPrefix(sc.Text(), searchPrefix); ok {
403 searchDomains := strings.Split(after, " ")
404 logrus.Debugf("Using search domains: %v", searchDomains)
405 return searchDomains
406 }
407 }
408 if err := sc.Err(); err != nil {
409 logrus.Errorf("scan file error: %v", err)
410 return nil
411 }
412 return nil
413}