跳到主要内容

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

浏览文件

helper_windows.go

325 行 · 8.5 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package hcs
5
6import (
7 "bytes"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "net"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "strings"
18 "syscall"
19
20 "github.com/Microsoft/hcsshim/hcn"
21 "github.com/lima-vm/go-qcow2reader/image/qcow2"
22 "github.com/lima-vm/go-qcow2reader/image/vhdx"
23 "github.com/sirupsen/logrus"
24
25 "github.com/lima-vm/lima/v2/pkg/imgutil/nativeimgutil"
26 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
27 "github.com/lima-vm/lima/v2/pkg/limayaml"
28)
29
30const (
31 // hcsTimeoutInfinite corresponds to Win32 INFINITE.
32 hcsTimeoutInfinite uint32 = 0xFFFFFFFF
33
34 // These flags are not exported by the hcn package.
35 netFlagEnableDNS hcn.NetworkFlags = 1
36 netFlagEnableDHCP hcn.NetworkFlags = 2
37 netFlagIsolateSwitch hcn.NetworkFlags = 32
38
39 networkAddressPrefix = "192.168.10.0/24"
40 networkGateway = "192.168.10.1"
41)
42
43type computeSystemProperties struct {
44 State string `json:"State"`
45}
46
47var errNotFound = errors.New("not found")
48
49// getComputeSystemState obtains compute system properties.
50func getComputeSystemState(ctx context.Context, id string) (string, error) {
51 system, err := hcsOpenComputeSystem(ctx, id, syscall.GENERIC_ALL)
52 if err != nil {
53 return "", errNotFound
54 }
55 defer hcsCloseComputeSystem(system)
56
57 op, err := hcsCreateOperation()
58 if err != nil {
59 return "", fmt.Errorf("failed to create an HCS operation: %w", err)
60 }
61 defer hcsCloseOperation(op)
62
63 if err := hcsGetComputeSystemProperties(ctx, system, op, "{}"); err != nil {
64 return "", fmt.Errorf("failed to get compute system properties: %w", err)
65 }
66
67 result, err := hcsWait(op, "hcsGetComputeSystemProperties", nil)
68 if err != nil {
69 return "", fmt.Errorf("failed to get compute system properties: %w (result=%s)", err, result)
70 }
71
72 var properties computeSystemProperties
73 if err := json.Unmarshal([]byte(result), &properties); err != nil {
74 return "", fmt.Errorf("failed to decode compute system properties: %w", err)
75 }
76
77 return properties.State, nil
78}
79
80// buildVMConfig returns the HCS compute system configuration document.
81func buildVMConfig(
82 diskPath, isoPath, endpointID, macAddress, serialPipe string,
83 cpus int, memoryMiB int64,
84) (string, error) {
85 config := map[string]any{
86 "SchemaVersion": map[string]any{
87 "Major": 2,
88 "Minor": 1,
89 },
90 "Owner": "Lima",
91 "ShouldTerminateOnLastHandleClosed": true,
92 "VirtualMachine": map[string]any{
93 "Chipset": map[string]any{
94 "Uefi": map[string]any{
95 "Console": "ComPort1",
96 "BootThis": map[string]any{
97 "DevicePath": "Primary disk",
98 "DiskNumber": 0,
99 "DeviceType": "ScsiDrive",
100 },
101 },
102 },
103 "ComputeTopology": map[string]any{
104 "Memory": map[string]any{
105 "Backing": "Virtual",
106 "SizeInMB": memoryMiB,
107 },
108 "Processor": map[string]any{
109 "Count": cpus,
110 },
111 },
112 "Devices": map[string]any{
113 "Scsi": map[string]any{
114 "Primary disk": map[string]any{
115 "Attachments": map[string]any{
116 "0": map[string]any{
117 "Type": "VirtualDisk",
118 "Path": diskPath,
119 },
120 },
121 },
122 "cidata": map[string]any{
123 "Attachments": map[string]any{
124 "0": map[string]any{
125 "Type": "Iso",
126 "Path": isoPath,
127 },
128 },
129 },
130 },
131 "ComPorts": map[string]any{
132 "0": map[string]any{
133 "NamedPipe": serialPipe,
134 },
135 },
136 "NetworkAdapters": map[string]any{
137 endpointID: map[string]any{
138 "EndpointId": endpointID,
139 "MacAddress": macAddress,
140 },
141 },
142 },
143 },
144 }
145
146 configBytes, err := json.Marshal(config)
147 if err != nil {
148 return "", err
149 }
150
151 return string(configBytes), nil
152}
153
154func ensureNetwork(name string) (*hcn.HostComputeNetwork, error) {
155 network, err := hcn.GetNetworkByName(name)
156 if err == nil {
157 return network, nil
158 }
159
160 if !hcn.IsNotFoundError(err) {
161 return nil, fmt.Errorf("failed to look up the HCN network %#q: %w", name, err)
162 }
163
164 network = &hcn.HostComputeNetwork{
165 Name: name,
166 SchemaVersion: hcn.V2SchemaVersion(),
167 Type: hcn.ICS,
168 Flags: netFlagEnableDNS | netFlagEnableDHCP | hcn.EnableNonPersistent | netFlagIsolateSwitch,
169 Ipams: []hcn.Ipam{{
170 Type: "Static",
171 Subnets: []hcn.Subnet{{
172 IpAddressPrefix: networkAddressPrefix,
173 Routes: []hcn.Route{{
174 NextHop: networkGateway,
175 DestinationPrefix: "0.0.0.0/0",
176 }},
177 }},
178 }},
179 }
180
181 return network.Create()
182}
183
184func ensureEndpoint(network *hcn.HostComputeNetwork, name, instDir string) (*hcn.HostComputeEndpoint, error) {
185 endpoint, err := hcn.GetEndpointByName(name)
186 if err == nil {
187 if endpoint.HostComputeNetwork != network.Id {
188 return nil, fmt.Errorf("endpoint %#q already exists on a different network", name)
189 }
190 return endpoint, nil
191 }
192 if !hcn.IsNotFoundError(err) {
193 return nil, err
194 }
195
196 endpoint = &hcn.HostComputeEndpoint{
197 Name: name,
198 SchemaVersion: hcn.V2SchemaVersion(),
199 HostComputeNetwork: network.Id,
200 MacAddress: hnsMACAddress(instDir),
201 }
202
203 return endpoint.Create()
204}
205
206func networkName(instName string) string {
207 return "lima-" + instName + "-net"
208}
209
210func endpointName(instName string) string {
211 return "lima-" + instName + "-ep"
212}
213
214// hnsMACAddress converts MAC address notation saved in limayaml struct to the one HNS expects.
215func hnsMACAddress(instDir string) string {
216 return strings.ToUpper(strings.ReplaceAll(limayaml.MACAddress(instDir), ":", "-"))
217}
218
219// createComputeSystem creates (but does not start) an HCS compute system.
220func createComputeSystem(_ context.Context, id, config string) (hcsSystem, error) {
221 system, err := hcsCreateComputeSystem(id, config)
222 if err != nil {
223 return 0, fmt.Errorf("create compute system error: %w", err)
224 }
225
226 return system, nil
227}
228
229func startComputeSystem(_ context.Context, system hcsSystem) error {
230 return hcsStartComputeSystem(system)
231}
232
233func terminateComputeSystem(_ context.Context, system hcsSystem) error {
234 return hcsTerminateComputeSystem(system)
235}
236
237// serveSerial accepts connections from the guest port.
238// It appends everything it reads to logPath and return when ln is closed.
239func serveSerial(ln net.Listener, logPath string) {
240 f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
241 if err != nil {
242 logrus.WithError(err).Errorf("failed to open the serial log %#q", logPath)
243 return
244 }
245 defer f.Close()
246
247 for {
248 conn, err := ln.Accept()
249 if err != nil {
250 if errors.Is(err, net.ErrClosed) {
251 return
252 }
253 logrus.WithError(err).Warn("failed to accept a serial connection")
254 return
255 }
256 logrus.Debugf("serial: the guest connected to %s", ln.Addr())
257 if _, err := io.Copy(f, conn); err != nil {
258 logrus.WithError(err).Debug("serial: copy finished with an error")
259 }
260 conn.Close()
261 }
262}
263
264// mayConvertQcow2ToVHDX checks `disk` and converts it to .vhdx if it is qcow2.
265func mayConvertQcow2ToVHDX(ctx context.Context, instDir string) error {
266 disk := filepath.Join(instDir, filenames.Disk)
267 _, err := os.Stat(disk)
268 if err == nil {
269 return nil
270 }
271 if !os.IsNotExist(err) {
272 return err
273 }
274
275 imagePath := filepath.Join(instDir, filenames.Image)
276 format, err := nativeimgutil.DetectFormat(imagePath)
277 if err != nil {
278 return err
279 }
280
281 switch format {
282 case string(vhdx.Type):
283 logrus.Debug("disk is already .vhdx")
284 if err = os.Rename(imagePath, disk); err != nil {
285 return fmt.Errorf("failed to rename %#q to %#q: %w", imagePath, disk, err)
286 }
287 if err := os.Chmod(disk, 0o644); err != nil {
288 return fmt.Errorf("failed to chmod %#q: %w", disk, err)
289 }
290 return nil
291 case qcow2.Type, "raw":
292 if err := execQemuImgConvert(ctx, imagePath, disk); err != nil {
293 return fmt.Errorf("failed to convert to vhdx: %w", err)
294 }
295 if err := execFsutil(ctx, disk); err != nil {
296 return fmt.Errorf("failed to set disk flag: %w", err)
297 }
298 return nil
299 default:
300 return fmt.Errorf("disk type %s is not supported", format)
301 }
302}
303
304func execQemuImgConvert(ctx context.Context, source, dist string) error {
305 var stdout, stderr bytes.Buffer
306 cmd := exec.CommandContext(ctx, "qemu-img", "convert", "-O", "vhdx", source, dist)
307 cmd.Stdout = &stdout
308 cmd.Stderr = &stderr
309 if err := cmd.Run(); err != nil {
310 return fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w",
311 cmd.Args, stdout.String(), stderr.String(), err)
312 }
313 return nil
314}
315
316func execFsutil(ctx context.Context, disk string) error {
317 var stdout, stderr bytes.Buffer
318 cmd := exec.CommandContext(ctx, "fsutil", "sparse", "setflag", disk, "0")
319 cmd.Stdout = &stdout
320 cmd.Stderr = &stderr
321 if err := cmd.Run(); err != nil {
322 return fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w", cmd.Args, stdout.String(), stderr.String(), err)
323 }
324 return nil
325}