跳到主要内容

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

浏览文件

config.go

446 行 · 14.1 KB历史下载
1package main
2
3import (
4 "errors"
5 "flag"
6 "fmt"
7 "net"
8 "net/netip"
9 "net/url"
10 "os"
11 "runtime"
12 "slices"
13 "strings"
14
15 "github.com/containers/gvisor-tap-vsock/pkg/types"
16 log "github.com/sirupsen/logrus"
17 yaml "gopkg.in/yaml.v3"
18)
19
20const (
21 // gatewayIP = "192.168.127.1"
22 sshHostPort = "192.168.127.2:22"
23 hostIP = "192.168.127.254"
24 host = "host"
25 gateway = "gateway"
26)
27
28type GvproxyArgs struct {
29 config string
30 endpoints arrayFlags
31 debug bool
32 mtu int
33 sshPort int
34 vpnkitSocket string
35 qemuSocket string
36 bessSocket string
37 stdioSocket string
38 vfkitSocket string
39 notificationSocket string
40 forwardSocket arrayFlags
41 forwardDest arrayFlags
42 forwardUser arrayFlags
43 forwardIdentify arrayFlags
44 pidFile string
45 pcapFile string
46 logFile string
47 servicesEndpoint string
48 ec2MetadataAccess bool
49}
50
51type GvproxyConfig struct {
52 Listen []string `yaml:"listen,omitempty"`
53 LogLevel string `yaml:"log-level,omitempty"`
54 Stack types.Configuration `yaml:"stack,omitempty"`
55 Interfaces struct {
56 VPNKit string `yaml:"vpnkit,omitempty"`
57 Qemu string `yaml:"qemu,omitempty"`
58 Bess string `yaml:"bess,omitempty"`
59 Stdio string `yaml:"stdio,omitempty"`
60 Vfkit string `yaml:"vfkit,omitempty"`
61 } `yaml:"interfaces,omitempty"`
62 Forwards []GvproxyConfigForward `yaml:"forwards,omitempty"`
63 PIDFile string `yaml:"pid-file,omitempty"`
64 LogFile string `yaml:"log-file,omitempty"`
65 Services string `yaml:"services,omitempty"`
66 Ec2MetadataAccess bool `yaml:"ec2-metadata-access,omitempty"`
67 NotificationSocket string `yaml:"notification,omitempty"`
68}
69
70type GvproxyConfigForward struct {
71 Socket string `yaml:"socket,omitempty"`
72 Dest string `yaml:"dest,omitempty"`
73 User string `yaml:"user,omitempty"`
74 Identity string `yaml:"identity,omitempty"`
75}
76
77func GvproxyVersion() string {
78 return types.NewVersion("gvproxy").String()
79}
80
81func GvproxyInit() (*GvproxyConfig, error) {
82 var args GvproxyArgs
83 var config GvproxyConfig
84
85 version := types.NewVersion("gvproxy")
86 version.AddFlag()
87
88 // Pass it to the testable function
89 _, err := GvproxyArgParse(flag.CommandLine, &args, os.Args[1:])
90 if err != nil {
91 return nil, fmt.Errorf("failed to parse command line arguments: %w", err)
92 }
93
94 if version.ShowVersion() {
95 fmt.Println(version.String())
96 os.Exit(0)
97 }
98
99 // Init config if provided
100 if args.config != "" {
101 content, err := os.ReadFile(args.config)
102 if err != nil {
103 return nil, fmt.Errorf("failed to read config file: %w", err)
104 }
105
106 if err := yaml.Unmarshal(content, &config); err != nil {
107 return nil, fmt.Errorf("failed to parse configuration: %w", err)
108 }
109 }
110
111 // Pass it to the testable function
112 return GvproxyConfigure(&config, &args, version.String())
113}
114
115func GvproxyArgParse(flagSet *flag.FlagSet, args *GvproxyArgs, argv []string) (*GvproxyArgs, error) {
116 flagSet.StringVar(&args.config, "config", "", "Use configuration file with command line override")
117 flagSet.Var(&args.endpoints, "listen", "control endpoint")
118 flagSet.BoolVar(&args.debug, "debug", false, "Print debug info")
119 flagSet.StringVar(&args.pcapFile, "pcap", "", "Capture network traffic to a pcap file")
120 flagSet.IntVar(&args.mtu, "mtu", 0, "Set the MTU (default: 1500)")
121 flagSet.IntVar(&args.sshPort, "ssh-port", 2222, "Port to access the guest virtual machine. Must be between 1024 and 65535")
122 flagSet.StringVar(&args.vpnkitSocket, "listen-vpnkit", "", "VPNKit socket to be used by Hyperkit")
123 flagSet.StringVar(&args.qemuSocket, "listen-qemu", "", "Socket to be used by Qemu")
124 flagSet.StringVar(&args.bessSocket, "listen-bess", "", "unixpacket socket to be used by Bess-compatible applications")
125 flagSet.StringVar(&args.stdioSocket, "listen-stdio", "", "accept stdio pipe")
126 flagSet.StringVar(&args.vfkitSocket, "listen-vfkit", "", "unixgram socket to be used by vfkit-compatible applications")
127 flagSet.Var(&args.forwardSocket, "forward-sock", "Forwards a unix socket to the guest virtual machine over SSH")
128 flagSet.Var(&args.forwardDest, "forward-dest", "Forwards a unix socket to the guest virtual machine over SSH")
129 flagSet.Var(&args.forwardUser, "forward-user", "SSH user to use for unix socket forward")
130 flagSet.Var(&args.forwardIdentify, "forward-identity", "Path to SSH identity key for forwarding")
131 flagSet.StringVar(&args.pidFile, "pid-file", "", "Generate a file with the PID in it")
132 flagSet.StringVar(&args.logFile, "log-file", "", "Output log messages (logrus) to a given file path")
133 flagSet.StringVar(&args.servicesEndpoint, "services", "", "Exposes the same HTTP API as the --listen flag, without the /connect endpoint")
134 flagSet.BoolVar(&args.ec2MetadataAccess, "ec2-metadata-access", false, "Permits access to EC2 Metadata Service and Amazon Time Sync Service")
135 flagSet.StringVar(&args.notificationSocket, "notification", "", "Socket to be used to send network-ready notifications")
136 if err := flagSet.Parse(argv); err != nil {
137 return nil, err
138 }
139
140 return args, nil
141}
142
143func GvproxyConfigure(config *GvproxyConfig, args *GvproxyArgs, version string) (*GvproxyConfig, error) {
144 if args.debug {
145 config.LogLevel = "debug"
146 }
147 if args.logFile != "" {
148 config.LogFile = args.logFile
149 }
150
151 if config.LogLevel == "" {
152 config.LogLevel = "info"
153 }
154
155 // Set log level
156 if logLevel, err := log.ParseLevel(strings.ToLower(config.LogLevel)); err != nil {
157 log.Warningf("bad log level \"%s\", falling back to \"info\"", config.LogLevel)
158 log.SetLevel(log.InfoLevel)
159 } else {
160 log.SetLevel(logLevel)
161 }
162
163 // Set log file
164 if config.LogFile != "" {
165 lf, err := os.Create(config.LogFile)
166 if err != nil {
167 return config, fmt.Errorf("unable to open log file %s", config.LogFile)
168 }
169 log.DeferExitHandler(func() {
170 if err := lf.Close(); err != nil {
171 fmt.Printf("unable to close log-file: %q\n", err)
172 }
173 })
174 log.SetOutput(lf)
175
176 // If debug is set, lets seed the log file with some basic information
177 // about the environment and how it was called
178 log.Debugf("gvproxy version: %q", version)
179 log.Debugf("os: %q arch: %q", runtime.GOOS, runtime.GOARCH)
180 log.Debugf("command line: %q", os.Args)
181 }
182
183 // Set defaults
184 if config.Stack.MTU == 0 {
185 config.Stack.MTU = 1500
186 }
187 if config.Stack.Subnet == "" {
188 config.Stack.Subnet = "192.168.127.0/24"
189 }
190
191 // Parse subnet address for further use
192 naddr, err := netip.ParsePrefix(config.Stack.Subnet)
193 if err != nil {
194 return config, fmt.Errorf("failed to parse subnet: %w", err)
195 }
196 fuaddr, err := getFirstUsableIPFromSubnet(naddr)
197 if err != nil {
198 return config, fmt.Errorf("failed to identify first usable address in subnet: %w", err)
199 }
200 luaddr, err := getLastUsableIPFromSubnet(naddr)
201 if err != nil {
202 return config, fmt.Errorf("failed to identify last usable address in subnet: %w", err)
203 }
204
205 if config.Stack.GatewayIP == "" {
206 config.Stack.GatewayIP = fuaddr.String()
207 }
208 if config.Stack.GatewayMacAddress == "" {
209 config.Stack.GatewayMacAddress = "5a:94:ef:e4:0c:dd"
210 }
211 if len(config.Stack.NAT) == 0 {
212 config.Stack.NAT = map[string]string{
213 luaddr.String(): "127.0.0.1",
214 }
215 }
216 if len(config.Stack.GatewayVirtualIPs) == 0 {
217 config.Stack.GatewayVirtualIPs = []string{
218 luaddr.String(),
219 }
220 }
221
222 // Default DNS zone enabled only for the default mode
223 // Default DNS search domains enabled only for the default mode
224 // Default forwards enabled only for the default mode
225 // Default static leases enabled only for the default mode
226 // Default vpnkit mac addresses enabled only for the default mode
227
228 // Patch config with CLI args
229 if args.qemuSocket != "" {
230 config.Interfaces.Qemu = args.qemuSocket
231 }
232 if args.bessSocket != "" {
233 config.Interfaces.Bess = args.bessSocket
234 }
235 if args.vfkitSocket != "" {
236 config.Interfaces.Vfkit = args.vfkitSocket
237 }
238 if args.vpnkitSocket != "" {
239 config.Interfaces.VPNKit = args.vpnkitSocket
240 }
241 if args.stdioSocket != "" {
242 config.Interfaces.Stdio = args.stdioSocket
243 }
244 if args.pidFile != "" {
245 config.PIDFile = args.pidFile
246 }
247 if args.notificationSocket != "" {
248 log.Debugf("notification socket: %s", args.notificationSocket)
249 uri, err := url.Parse(args.notificationSocket)
250 if err != nil {
251 return config, fmt.Errorf("invalid value for notification listen address: %w", err)
252 }
253 if uri.Scheme != "unix" {
254 return config, errors.New("notification listen address must be unix:// address")
255 }
256 config.NotificationSocket = uri.Path
257 }
258 if len(args.endpoints) > 0 {
259 config.Listen = args.endpoints
260 }
261 if args.servicesEndpoint != "" {
262 config.Services = args.servicesEndpoint
263 }
264 if args.ec2MetadataAccess {
265 config.Ec2MetadataAccess = true
266 }
267 if args.mtu != 0 {
268 config.Stack.MTU = args.mtu
269 }
270
271 // Make sure the qemu socket provided is valid syntax
272 if config.Interfaces.Qemu != "" {
273 uri, err := url.Parse(config.Interfaces.Qemu)
274 if err != nil || uri == nil {
275 return config, fmt.Errorf("invalid value for qemu listen address: %w", err)
276 }
277 if _, err := os.Stat(uri.Path); err == nil && uri.Scheme == "unix" {
278 return config, fmt.Errorf("%q already exists", uri.Path)
279 }
280 }
281 if config.Interfaces.Bess != "" {
282 uri, err := url.Parse(config.Interfaces.Bess)
283 if err != nil || uri == nil {
284 return config, fmt.Errorf("invalid value for bess listen address: %w", err)
285 }
286 if uri.Scheme != "unixpacket" {
287 return config, errors.New("bess listen address must be unixpacket:// address")
288 }
289 if _, err := os.Stat(uri.Path); err == nil {
290 return config, fmt.Errorf("%q already exists", uri.Path)
291 }
292 }
293 if config.Interfaces.Vfkit != "" {
294 uri, err := url.Parse(config.Interfaces.Vfkit)
295 if err != nil || uri == nil {
296 return config, fmt.Errorf("invalid value for vfkit listen address: %w", err)
297 }
298 if uri.Scheme != "unixgram" {
299 return config, errors.New("vfkit listen address must be unixgram:// address")
300 }
301 if _, err := os.Stat(uri.Path); err == nil {
302 return config, fmt.Errorf("%q already exists", uri.Path)
303 }
304 }
305
306 if config.Interfaces.VPNKit != "" && config.Interfaces.Qemu != "" {
307 return config, errors.New("cannot use qemu and vpnkit protocol at the same time")
308 }
309 if config.Interfaces.VPNKit != "" && config.Interfaces.Bess != "" {
310 return config, errors.New("cannot use bess and vpnkit protocol at the same time")
311 }
312 if config.Interfaces.Qemu != "" && config.Interfaces.Bess != "" {
313 return config, errors.New("cannot use qemu and bess protocol at the same time")
314 }
315
316 if args.config != "" {
317 if slices.Contains(os.Args, "-ssh-port") || slices.Contains(os.Args, "--ssh-port") {
318 log.Warningf("CLI argument \"-ssh-port\" is unavailable with config file. You need to add \"127.0.0.1:%d: 192.168.127.2:22\" entry into .stack.forwards in \"\" instead", args.sshPort)
319 }
320 }
321
322 config.Stack.Protocol = types.HyperKitProtocol
323 if config.Interfaces.Qemu != "" {
324 config.Stack.Protocol = types.QemuProtocol
325 }
326 if config.Interfaces.Bess != "" {
327 config.Stack.Protocol = types.BessProtocol
328 }
329 if config.Interfaces.Vfkit != "" {
330 config.Stack.Protocol = types.VfkitProtocol
331 }
332
333 if InDebugMode() {
334 config.Stack.Debug = true
335 }
336
337 // Handle the default behavior without config
338 if args.config == "" {
339 if args.sshPort != -1 && args.sshPort < 1024 || args.sshPort > 65535 {
340 return config, errors.New("ssh-port value must be between 1024 and 65535")
341 }
342
343 config.Stack.CaptureFile = args.pcapFile
344
345 config.Stack.DNS = []types.Zone{
346 {
347 Name: "containers.internal.",
348 Records: []types.Record{
349 {
350 Name: gateway,
351 IP: net.ParseIP(config.Stack.GatewayIP),
352 },
353 {
354 Name: host,
355 IP: net.ParseIP(hostIP),
356 },
357 },
358 },
359 {
360 Name: "docker.internal.",
361 Records: []types.Record{
362 {
363 Name: gateway,
364 IP: net.ParseIP(config.Stack.GatewayIP),
365 },
366 {
367 Name: host,
368 IP: net.ParseIP(hostIP),
369 },
370 },
371 },
372 }
373 config.Stack.DNSSearchDomains = searchDomains()
374 config.Stack.Forwards = getForwardsMap(args.sshPort, sshHostPort)
375 config.Stack.DHCPStaticLeases = map[string]string{
376 "192.168.127.2": "5a:94:ef:e4:0c:ee",
377 }
378 config.Stack.VpnKitUUIDMacAddresses = map[string]string{
379 "c3d68012-0208-11ea-9fd7-f2189899ab08": "5a:94:ef:e4:0c:ee",
380 }
381 }
382
383 // Add SSH forwards from CLI args
384 if c := len(args.forwardSocket); c != len(args.forwardDest) || c != len(args.forwardUser) || c != len(args.forwardIdentify) {
385 return config, errors.New("--forward-sock, --forward-dest, --forward-user, and --forward-identity must all be specified together, " +
386 "the same number of times, or not at all")
387 }
388
389 for i := range args.forwardSocket {
390 config.Forwards = append(config.Forwards, GvproxyConfigForward{
391 Socket: args.forwardSocket[i],
392 Dest: args.forwardDest[i],
393 User: args.forwardUser[i],
394 Identity: args.forwardIdentify[i],
395 })
396 }
397
398 // Validate SSH forward rules
399 for _, v := range config.Forwards {
400 _, err := os.Stat(v.Identity)
401 if err != nil {
402 return config, fmt.Errorf("identity file %q can't be loaded: %w", v.Identity, err)
403 }
404 }
405
406 return config, nil
407}
408
409func getFirstUsableIPFromSubnet(network netip.Prefix) (netip.Addr, error) {
410 // The network must have at least 5 IP addresses: network, broadcast, gateway, guest, and preferably host
411 // v4/30 has only 2 devices, thus prefer at least v4/29 CIDR. This code works also for IPv6, just in case
412 if (network.Bits() + 3) > network.Addr().BitLen() {
413 return netip.Addr{}, errors.New("too small network")
414 }
415
416 b := network.Masked().Addr().AsSlice()
417 b[len(b)-1] += 1
418
419 addr, ok := netip.AddrFromSlice(b)
420 if !ok {
421 return netip.Addr{}, errors.New("bad ip address")
422 }
423
424 return addr, nil
425}
426
427func getLastUsableIPFromSubnet(network netip.Prefix) (netip.Addr, error) {
428 // The network must have at least 5 IP addresses: network, broadcast, gateway, guest, and preferably host
429 // v4/30 has only 2 devices, thus prefer at least v4/29 CIDR. This code works also for IPv6, just in case
430 if (network.Bits() + 3) > network.Addr().BitLen() {
431 return netip.Addr{}, errors.New("too small network")
432 }
433
434 var b = network.Masked().Addr().AsSlice()
435 for i, v := range net.CIDRMask(network.Bits(), network.Addr().BitLen()) {
436 b[i] += ^v
437 }
438 b[len(b)-1] -= 1
439
440 addr, ok := netip.AddrFromSlice(b)
441 if !ok {
442 return netip.Addr{}, errors.New("bad ip address")
443 }
444
445 return addr, nil
446}