跳到主要内容

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

浏览文件

qemuimgutil.go

295 行 · 10.2 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package qemuimgutil
5
6import (
7 "bytes"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io/fs"
13 "os"
14 "os/exec"
15 "strconv"
16
17 "github.com/lima-vm/go-qcow2reader/image"
18 "github.com/lima-vm/go-qcow2reader/image/raw"
19 "github.com/sirupsen/logrus"
20)
21
22const QemuImgFormat = "qcow2"
23
24// QemuImageUtil is the QEMU implementation of the imgutil Interface.
25type QemuImageUtil struct {
26 DefaultFormat string // Default disk format, e.g., "qcow2"
27}
28
29// Info corresponds to the output of `qemu-img info --output=json FILE`.
30type Info struct {
31 Filename string `json:"filename,omitempty"` // since QEMU 1.3
32 Format string `json:"format,omitempty"` // since QEMU 1.3
33 VSize int64 `json:"virtual-size,omitempty"` // since QEMU 1.3
34 ActualSize int64 `json:"actual-size,omitempty"` // since QEMU 1.3
35 DirtyFlag bool `json:"dirty-flag,omitempty"` // since QEMU 5.2
36 ClusterSize int `json:"cluster-size,omitempty"` // since QEMU 1.3
37 BackingFilename string `json:"backing-filename,omitempty"` // since QEMU 1.3
38 FullBackingFilename string `json:"full-backing-filename,omitempty"` // since QEMU 1.3
39 BackingFilenameFormat string `json:"backing-filename-format,omitempty"` // since QEMU 1.3
40 FormatSpecific *InfoFormatSpecific `json:"format-specific,omitempty"` // since QEMU 1.7
41 Children []InfoChild `json:"children,omitempty"` // since QEMU 8.0
42}
43
44type InfoChild struct {
45 Name string `json:"name,omitempty"` // since QEMU 8.0
46 Info Info `json:"info,omitempty"` // since QEMU 8.0
47}
48
49type InfoFormatSpecific struct {
50 Type string `json:"type,omitempty"` // since QEMU 1.7
51 Data json.RawMessage `json:"data,omitempty"` // since QEMU 1.7
52}
53
54func resizeDisk(ctx context.Context, disk, format string, size int64) error {
55 args := []string{"resize", "-f", format, disk, strconv.FormatInt(size, 10)}
56 cmd := exec.CommandContext(ctx, "qemu-img", args...)
57 if out, err := cmd.CombinedOutput(); err != nil {
58 return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
59 }
60 return nil
61}
62
63func (sp *InfoFormatSpecific) Qcow2() *InfoFormatSpecificDataQcow2 {
64 if sp.Type != "qcow2" {
65 return nil
66 }
67 var x InfoFormatSpecificDataQcow2
68 if err := json.Unmarshal(sp.Data, &x); err != nil {
69 panic(err)
70 }
71 return &x
72}
73
74func (sp *InfoFormatSpecific) Vmdk() *InfoFormatSpecificDataVmdk {
75 if sp.Type != "vmdk" {
76 return nil
77 }
78 var x InfoFormatSpecificDataVmdk
79 if err := json.Unmarshal(sp.Data, &x); err != nil {
80 panic(err)
81 }
82 return &x
83}
84
85type InfoFormatSpecificDataQcow2 struct {
86 Compat string `json:"compat,omitempty"` // since QEMU 1.7
87 DataFile string `json:"data-file,omitempty"` // since QEMU 3.0
88 LazyRefcounts bool `json:"lazy-refcounts,omitempty"` // since QEMU 1.7
89 Corrupt bool `json:"corrupt,omitempty"` // since QEMU 2.2
90 RefcountBits int `json:"refcount-bits,omitempty"` // since QEMU 2.3
91 CompressionType string `json:"compression-type,omitempty"` // since QEMU 5.1
92 ExtendedL2 bool `json:"extended-l2,omitempty"` // since QEMU 5.2
93}
94
95type InfoFormatSpecificDataVmdk struct {
96 CreateType string `json:"create-type,omitempty"` // since QEMU 1.7
97 CID int `json:"cid,omitempty"` // since QEMU 1.7
98 ParentCID int `json:"parent-cid,omitempty"` // since QEMU 1.7
99 Extents []InfoFormatSpecificDataVmdkExtent `json:"extents,omitempty"` // since QEMU 1.7
100}
101
102type InfoFormatSpecificDataVmdkExtent struct {
103 Filename string `json:"filename,omitempty"` // since QEMU 1.7
104 Format string `json:"format,omitempty"` // since QEMU 1.7
105 VSize int64 `json:"virtual-size,omitempty"` // since QEMU 1.7
106 ClusterSize int `json:"cluster-size,omitempty"` // since QEMU 1.7
107}
108
109func convertToRaw(ctx context.Context, source, dest string) error {
110 if source != dest {
111 return execQemuImgConvert(ctx, source, dest)
112 }
113
114 // If source == dest, we need to use a temporary file to avoid file locking issues
115
116 info, err := getInfo(ctx, source)
117 if err != nil {
118 return fmt.Errorf("failed to get info for source disk %#q: %w", source, err)
119 }
120 if info.Format == "raw" {
121 return nil
122 }
123
124 tempFile := dest + ".lima-qemu-convert.tmp"
125 defer os.Remove(tempFile)
126
127 if err := execQemuImgConvert(ctx, source, tempFile); err != nil {
128 return err
129 }
130
131 return os.Rename(tempFile, dest)
132}
133
134func execQemuImgConvert(ctx context.Context, source, dest string) error {
135 var stdout, stderr bytes.Buffer
136 cmd := exec.CommandContext(ctx, "qemu-img", "convert", "-O", "raw", source, dest)
137 cmd.Stdout = &stdout
138 cmd.Stderr = &stderr
139 if err := cmd.Run(); err != nil {
140 return fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w",
141 cmd.Args, stdout.String(), stderr.String(), err)
142 }
143 return nil
144}
145
146func parseInfo(b []byte) (*Info, error) {
147 var imgInfo Info
148 if err := json.Unmarshal(b, &imgInfo); err != nil {
149 return nil, err
150 }
151 return &imgInfo, nil
152}
153
154func getInfo(ctx context.Context, f string) (*Info, error) {
155 var stdout, stderr bytes.Buffer
156 cmd := exec.CommandContext(ctx, "qemu-img", "info", "--output=json", "--force-share", f)
157 cmd.Stdout = &stdout
158 cmd.Stderr = &stderr
159 if err := cmd.Run(); err != nil {
160 return nil, fmt.Errorf("failed to run %v: stdout=%#q, stderr=%#q: %w",
161 cmd.Args, stdout.String(), stderr.String(), err)
162 }
163 return parseInfo(stdout.Bytes())
164}
165
166// CreateDisk creates a new disk image with the specified size.
167func (q *QemuImageUtil) CreateDisk(ctx context.Context, disk string, size int64) error {
168 if _, err := os.Stat(disk); err == nil || !errors.Is(err, fs.ErrNotExist) {
169 // disk already exists
170 return err
171 }
172
173 args := []string{"create", "-f", q.DefaultFormat, disk, strconv.FormatInt(size, 10)}
174 cmd := exec.CommandContext(ctx, "qemu-img", args...)
175 if out, err := cmd.CombinedOutput(); err != nil {
176 return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
177 }
178 return nil
179}
180
181// ResizeDisk resizes an existing disk image to the specified size.
182func (q *QemuImageUtil) ResizeDisk(ctx context.Context, disk string, size int64) error {
183 info, err := getInfo(ctx, disk)
184 if err != nil {
185 return fmt.Errorf("failed to get info for disk %#q: %w", disk, err)
186 }
187 return resizeDisk(ctx, disk, info.Format, size)
188}
189
190// MakeSparse is a stub implementation as the qemu package doesn't provide this functionality.
191func (q *QemuImageUtil) MakeSparse(_ context.Context, _ *os.File, _ int64) error {
192 return nil
193}
194
195// GetInfo retrieves the information of a disk image.
196func GetInfo(ctx context.Context, path string) (*Info, error) {
197 qemuInfo, err := getInfo(ctx, path)
198 if err != nil {
199 return nil, err
200 }
201
202 return qemuInfo, nil
203}
204
205// Convert converts a disk image to raw format.
206// Currently only raw.Type is supported.
207func (q *QemuImageUtil) Convert(ctx context.Context, imageType image.Type, source, dest string, size *int64, allowSourceWithBackingFile bool) error {
208 if imageType != raw.Type {
209 return fmt.Errorf("QemuImageUtil.Convert only supports raw.Type, got %#q", imageType)
210 }
211 if !allowSourceWithBackingFile {
212 info, err := getInfo(ctx, source)
213 if err != nil {
214 return fmt.Errorf("failed to get info for source disk %#q: %w", source, err)
215 }
216 if err := rejectExternalFileReferences(info); err != nil {
217 return err
218 }
219 }
220
221 if err := convertToRaw(ctx, source, dest); err != nil {
222 return err
223 }
224
225 if size != nil {
226 destInfo, err := getInfo(ctx, dest)
227 if err != nil {
228 return fmt.Errorf("failed to get info for converted disk %#q: %w", dest, err)
229 }
230
231 if *size > destInfo.VSize {
232 return resizeDisk(ctx, dest, "raw", *size)
233 }
234 }
235
236 return nil
237}
238
239// rejectExternalFileReferences returns an error if info references any file
240// other than itself: a backing file, a qcow2 external data-file, or a VMDK
241// extent. qemu-img reads those files from the host when it opens the image, so
242// an untrusted image that points them at an arbitrary host path (e.g.
243// /etc/passwd) would have that path's contents copied into the guest disk. The
244// native converter already refuses such images via go-qcow2reader's Readable();
245// this keeps the qemu path and the base-disk gate consistent with it.
246func rejectExternalFileReferences(info *Info) error {
247 if info.BackingFilename != "" {
248 return fmt.Errorf("image (%#q) must not have a backing file (%#q)", info.Filename, info.BackingFilename)
249 }
250 if info.FullBackingFilename != "" {
251 return fmt.Errorf("image (%#q) must not have a backing file (%#q)", info.Filename, info.FullBackingFilename)
252 }
253 if info.FormatSpecific != nil {
254 if qcow2 := info.FormatSpecific.Qcow2(); qcow2 != nil && qcow2.DataFile != "" {
255 return fmt.Errorf("image (%#q) must not have an external data file (%#q)", info.Filename, qcow2.DataFile)
256 }
257 if vmdk := info.FormatSpecific.Vmdk(); vmdk != nil {
258 for _, e := range vmdk.Extents {
259 if e.Filename != info.Filename {
260 return fmt.Errorf("image (%#q) must not have an extent file (%#q)", info.Filename, e.Filename)
261 }
262 }
263 }
264 }
265 return nil
266}
267
268// AcceptableAsBaseDisk checks if a disk image is acceptable as a base disk.
269func AcceptableAsBaseDisk(info *Info) error {
270 switch info.Format {
271 case "qcow2", "raw":
272 // NOP
273 default:
274 logrus.WithField("filename", info.Filename).
275 Warnf("Unsupported image format %#q. The image may not boot, or may have an extra privilege to access the host filesystem. Use with caution.", info.Format)
276 }
277 if err := rejectExternalFileReferences(info); err != nil {
278 return err
279 }
280 // info.Children is set since QEMU 8.0
281 switch len(info.Children) {
282 case 0:
283 // NOP
284 case 1:
285 if info.Filename != info.Children[0].Info.Filename {
286 return fmt.Errorf("base disk (%#q) child must not have a different filename (%#q)", info.Filename, info.Children[0].Info.Filename)
287 }
288 if len(info.Children[0].Info.Children) > 0 {
289 return fmt.Errorf("base disk (%#q) child must not have children of its own", info.Filename)
290 }
291 default:
292 return fmt.Errorf("base disk (%#q) must not have multiple children: %+v", info.Filename, info.Children)
293 }
294 return nil
295}