| 1 | |
| 2 | |
| 3 | package hostimage |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "encoding/xml" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "net/http" |
| 15 | "net/url" |
| 16 | "os" |
| 17 | "path/filepath" |
| 18 | "regexp" |
| 19 | "strings" |
| 20 | "time" |
| 21 | |
| 22 | "go.yaml.in/yaml/v3" |
| 23 | "golang.org/x/mod/semver" |
| 24 | ) |
| 25 | |
| 26 | type Identity struct { |
| 27 | System string `json:"system"` |
| 28 | Version string `json:"version"` |
| 29 | Build string `json:"build,omitempty"` |
| 30 | Edition string `json:"edition,omitempty"` |
| 31 | Language string `json:"language,omitempty"` |
| 32 | Arch string `json:"arch"` |
| 33 | } |
| 34 | |
| 35 | func IsLinux(system string) bool { |
| 36 | return system == "debian-12" || system == "debian-13" || system == "ubuntu-22.04" || system == "ubuntu-24.04" |
| 37 | } |
| 38 | |
| 39 | |
| 40 | |
| 41 | type Plan struct { |
| 42 | Host Identity `json:"host"` |
| 43 | Version string `json:"version"` |
| 44 | Build string `json:"build,omitempty"` |
| 45 | Format string `json:"format"` |
| 46 | URL string `json:"url,omitempty"` |
| 47 | Digest string `json:"digest,omitempty"` |
| 48 | Bytes int64 `json:"bytes"` |
| 49 | Path string `json:"path,omitempty"` |
| 50 | Modified int64 `json:"modified,omitempty"` |
| 51 | } |
| 52 | |
| 53 | func (p Plan) Key() string { |
| 54 | if p.URL != "" && p.Digest != "" { |
| 55 | p.Path, p.Modified = "", 0 |
| 56 | } |
| 57 | data, _ := json.Marshal(p) |
| 58 | digest := sha256.Sum256(data) |
| 59 | return hex.EncodeToString(digest[:]) |
| 60 | } |
| 61 | |
| 62 | func (p Plan) Validate() error { |
| 63 | if p.Host.Arch != "arm64" && p.Host.Arch != "amd64" { |
| 64 | return errors.New("本机系统架构暂不支持创建客机") |
| 65 | } |
| 66 | if p.Version == "" || p.Version != p.Host.Version || p.Bytes < 0 || p.Bytes > 64<<30 { |
| 67 | return errors.New("系统镜像与本机版本不匹配") |
| 68 | } |
| 69 | switch p.Host.System { |
| 70 | case "macos": |
| 71 | if p.Format != "ipsw" || p.Build != p.Host.Build || p.Host.Arch != "arm64" { |
| 72 | return errors.New("macOS 恢复镜像与本机版本不匹配") |
| 73 | } |
| 74 | if !semver.IsValid("v"+p.Version) || semver.Compare("v"+p.Version, "v26.4") < 0 { |
| 75 | return errors.New("自动匹配 macOS 镜像需要本机运行 macOS 26.4 或更新版本,以支持当前工作台使用的 FSKit 只读挂载") |
| 76 | } |
| 77 | case "windows-11": |
| 78 | if p.Format != "esd" || p.Host.Arch != "amd64" || p.Host.Edition == "" || p.Host.Language == "" || p.Build == "" { |
| 79 | return errors.New("Windows 安装镜像信息不完整") |
| 80 | } |
| 81 | case "debian-12", "debian-13", "ubuntu-22.04", "ubuntu-24.04": |
| 82 | if p.Format != "qcow2" { |
| 83 | return errors.New("Linux 安装镜像与本机不匹配") |
| 84 | } |
| 85 | default: |
| 86 | return errors.New("当前支持的本机系统为 macOS、Windows 11、Debian 12/13 和 Ubuntu 22.04/24.04") |
| 87 | } |
| 88 | if p.Path != "" && (!filepath.IsAbs(p.Path) || filepath.Clean(p.Path) != p.Path || strings.ContainsAny(p.Path, "\r\n\x00")) { |
| 89 | return errors.New("本机系统镜像路径无效") |
| 90 | } |
| 91 | if p.URL != "" { |
| 92 | if err := trustedURL(p.URL, p.Host.System); err != nil { |
| 93 | return err |
| 94 | } |
| 95 | if _, err := digestHash(p.Digest); err != nil { |
| 96 | return err |
| 97 | } |
| 98 | } |
| 99 | if p.Path == "" && p.URL == "" { |
| 100 | return errors.New("缺少系统安装材料") |
| 101 | } |
| 102 | return nil |
| 103 | } |
| 104 | |
| 105 | func trustedURL(raw, system string) error { |
| 106 | u, err := url.Parse(raw) |
| 107 | if err != nil || u.User != nil || u.Port() != "" || u.Fragment != "" { |
| 108 | return errors.New("系统材料下载地址无效") |
| 109 | } |
| 110 | |
| 111 | |
| 112 | microsoftESD := system == "windows-11" && u.Scheme == "http" && u.Hostname() == "dl.delivery.mp.microsoft.com" |
| 113 | if u.Scheme != "https" && !microsoftESD { |
| 114 | return errors.New("系统材料下载协议无效") |
| 115 | } |
| 116 | allowed := map[string][]string{ |
| 117 | "macos": {"updates.cdn-apple.com", "appldnld.apple.com"}, |
| 118 | "windows-11": {"dl.delivery.mp.microsoft.com", "download.microsoft.com", "software.download.prss.microsoft.com"}, |
| 119 | "debian-12": {"cloud.debian.org"}, "debian-13": {"cloud.debian.org"}, |
| 120 | "ubuntu-22.04": {"cloud-images.ubuntu.com"}, |
| 121 | "ubuntu-24.04": {"cloud-images.ubuntu.com"}, |
| 122 | } |
| 123 | for _, domain := range allowed[system] { |
| 124 | if u.Hostname() == domain { |
| 125 | return nil |
| 126 | } |
| 127 | } |
| 128 | return errors.New("系统材料下载地址不属于受支持的系统厂商") |
| 129 | } |
| 130 | |
| 131 | func metadata(ctx context.Context, client *http.Client, address string, out any) error { |
| 132 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) |
| 133 | if err != nil { |
| 134 | return err |
| 135 | } |
| 136 | req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Cage-SystemInstaller/1.0)") |
| 137 | response, err := client.Do(req) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | defer response.Body.Close() |
| 142 | if response.StatusCode != http.StatusOK { |
| 143 | return fmt.Errorf("系统目录返回 HTTP %d", response.StatusCode) |
| 144 | } |
| 145 | data, err := io.ReadAll(io.LimitReader(response.Body, (8<<20)+1)) |
| 146 | if err != nil { |
| 147 | return err |
| 148 | } |
| 149 | if len(data) > 8<<20 { |
| 150 | return errors.New("系统目录超过大小限制") |
| 151 | } |
| 152 | if strings.HasSuffix(address, ".xml") { |
| 153 | return xml.Unmarshal(data, out) |
| 154 | } |
| 155 | return json.Unmarshal(data, out) |
| 156 | } |
| 157 | |
| 158 | |
| 159 | |
| 160 | func Resolve(ctx context.Context, identity Identity, cache, downloads string, template []byte, transport http.RoundTripper) (Plan, error) { |
| 161 | client := &http.Client{Transport: transport, Timeout: 30 * time.Second} |
| 162 | if plan, err := Load(cache); err == nil && plan.Host == identity { |
| 163 | if plan.Path != "" && usableFile(plan.Path, plan.Bytes) { |
| 164 | info, _ := os.Stat(plan.Path) |
| 165 | if info.ModTime().UnixNano() == plan.Modified { |
| 166 | return plan, nil |
| 167 | } |
| 168 | } |
| 169 | if path := plan.CachedPath(cache); usableFile(path, plan.Bytes) { |
| 170 | plan.Path = path |
| 171 | info, _ := os.Stat(path) |
| 172 | plan.Modified = info.ModTime().UnixNano() |
| 173 | return plan, plan.Validate() |
| 174 | } |
| 175 | } |
| 176 | var plan Plan |
| 177 | var err error |
| 178 | switch identity.System { |
| 179 | case "macos": |
| 180 | if plan, ok := localMacImage(identity, cache, downloads); ok { |
| 181 | return plan, plan.Validate() |
| 182 | } |
| 183 | plan, err = macCatalog(ctx, client, identity) |
| 184 | case "windows-11": |
| 185 | plan, err = windowsCatalog(ctx, client, identity) |
| 186 | default: |
| 187 | plan, err = linuxCatalog(identity, template) |
| 188 | } |
| 189 | if err != nil { |
| 190 | return Plan{}, err |
| 191 | } |
| 192 | for _, candidate := range []string{plan.CachedPath(cache), filepath.Join(downloads, filepath.Base(plan.URL))} { |
| 193 | if usableFile(candidate, plan.Bytes) { |
| 194 | info, _ := os.Stat(candidate) |
| 195 | plan.Path, plan.Modified = candidate, info.ModTime().UnixNano() |
| 196 | if plan.Bytes == 0 { |
| 197 | plan.Bytes = info.Size() |
| 198 | } |
| 199 | break |
| 200 | } |
| 201 | } |
| 202 | return plan, plan.Validate() |
| 203 | } |
| 204 | |
| 205 | func usableFile(path string, size int64) bool { |
| 206 | info, err := os.Lstat(path) |
| 207 | return err == nil && info.Mode().IsRegular() && info.Size() > 0 && (size == 0 || info.Size() == size) |
| 208 | } |
| 209 | |
| 210 | func macCatalog(ctx context.Context, client *http.Client, host Identity) (Plan, error) { |
| 211 | |
| 212 | |
| 213 | var catalog struct { |
| 214 | Firmware []struct { |
| 215 | Version string `json:"version"` |
| 216 | Build string `json:"buildid"` |
| 217 | URL string `json:"url"` |
| 218 | Bytes int64 `json:"filesize"` |
| 219 | SHA256 string `json:"sha256sum"` |
| 220 | } `json:"firmwares"` |
| 221 | } |
| 222 | if err := metadata(ctx, client, "https://api.ipsw.me/v4/device/VirtualMac2,1?type=ipsw", &catalog); err != nil { |
| 223 | return Plan{}, fmt.Errorf("查找与本机一致的 Apple 恢复镜像失败,可选择已有 IPSW:%w", err) |
| 224 | } |
| 225 | for _, media := range catalog.Firmware { |
| 226 | if media.Version == host.Version && media.Build == host.Build { |
| 227 | return Plan{Host: host, Version: media.Version, Build: media.Build, Format: "ipsw", URL: media.URL, Digest: "sha256:" + media.SHA256, Bytes: media.Bytes}, nil |
| 228 | } |
| 229 | } |
| 230 | return Plan{}, fmt.Errorf("未找到 macOS %s(%s)的恢复镜像,请选择已有的对应 IPSW", host.Version, host.Build) |
| 231 | } |
| 232 | |
| 233 | const windowsCatalogURL = "https://download.microsoft.com/download/eb1cc454-1c9a-4c94-adf8-b30c7f3d03d1/products.xml" |
| 234 | |
| 235 | type windowsMediaCatalog struct { |
| 236 | Files []struct { |
| 237 | Name string `xml:"FileName"` |
| 238 | Language string `xml:"LanguageCode"` |
| 239 | Edition string `xml:"Edition"` |
| 240 | Arch string `xml:"Architecture"` |
| 241 | Bytes int64 `xml:"Size"` |
| 242 | SHA256 string `xml:"Sha256"` |
| 243 | URL string `xml:"FilePath"` |
| 244 | } `xml:"Files>File"` |
| 245 | } |
| 246 | |
| 247 | func windowsCatalog(ctx context.Context, client *http.Client, host Identity) (Plan, error) { |
| 248 | current, currentErr := currentWindowsCatalog(ctx, client, host) |
| 249 | if currentErr == nil { |
| 250 | if plan, ok := selectWindowsMedia(current, host); ok { |
| 251 | return plan, nil |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | |
| 256 | var catalog windowsMediaCatalog |
| 257 | if err := metadata(ctx, client, windowsCatalogURL, &catalog); err != nil { |
| 258 | return Plan{}, fmt.Errorf("读取微软安装目录失败,可选择已有 ISO:%w", err) |
| 259 | } |
| 260 | if plan, ok := selectWindowsMedia(catalog, host); ok { |
| 261 | return plan, nil |
| 262 | } |
| 263 | if currentErr != nil { |
| 264 | return Plan{}, fmt.Errorf("无法读取匹配本机版本的微软目录,请检查所选代理后重试:%w", currentErr) |
| 265 | } |
| 266 | return Plan{}, fmt.Errorf("微软当前目录没有 Windows 11 %s %s %s 的对应介质,请选择已有 ISO", host.Version, host.Edition, host.Language) |
| 267 | } |
| 268 | |
| 269 | func selectWindowsMedia(catalog windowsMediaCatalog, host Identity) (Plan, bool) { |
| 270 | major := strings.SplitN(host.Build, ".", 2)[0] |
| 271 | for _, file := range catalog.Files { |
| 272 | if file.Arch != "x64" || file.Edition != host.Edition || !strings.EqualFold(file.Language, host.Language) || |
| 273 | major == "" || !strings.HasPrefix(file.Name, major+".") { |
| 274 | continue |
| 275 | } |
| 276 | build := regexp.MustCompile(`^\d+\.\d+`).FindString(file.Name) |
| 277 | return Plan{Host: host, Version: host.Version, Build: build, Format: "esd", Bytes: file.Bytes, |
| 278 | Digest: "sha256:" + strings.ToLower(file.SHA256), URL: file.URL}, true |
| 279 | } |
| 280 | return Plan{}, false |
| 281 | } |
| 282 | |
| 283 | func linuxCatalog(host Identity, template []byte) (Plan, error) { |
| 284 | var config struct { |
| 285 | Images []struct { |
| 286 | Location string `yaml:"location"` |
| 287 | Arch string `yaml:"arch"` |
| 288 | Digest string `yaml:"digest"` |
| 289 | Bytes int64 `yaml:"bytes"` |
| 290 | } `yaml:"images"` |
| 291 | } |
| 292 | if err := yaml.Unmarshal(template, &config); err != nil { |
| 293 | return Plan{}, err |
| 294 | } |
| 295 | arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64"}[host.Arch] |
| 296 | for _, image := range config.Images { |
| 297 | if arch != "" && image.Arch == arch && image.Digest != "" { |
| 298 | return Plan{Host: host, Version: host.Version, Format: "qcow2", URL: image.Location, Digest: image.Digest, Bytes: image.Bytes}, nil |
| 299 | } |
| 300 | } |
| 301 | return Plan{}, errors.New("此安装包缺少与本机发行版一致的已校验 Linux 镜像") |
| 302 | } |
| 303 | |
| 304 | func (p Plan) CachedPath(cache string) string { |
| 305 | key := strings.ReplaceAll(p.Digest, ":", "-") |
| 306 | if key == "" { |
| 307 | key = p.Key() |
| 308 | } |
| 309 | return filepath.Join(cache, key+"."+p.Format) |
| 310 | } |
| 311 | |
| 312 | func (p Plan) RemainingBytes(cache string) int64 { |
| 313 | if p.Path != "" { |
| 314 | return 0 |
| 315 | } |
| 316 | if usableFile(p.CachedPath(cache), p.Bytes) { |
| 317 | return 0 |
| 318 | } |
| 319 | info, err := os.Lstat(p.CachedPath(cache) + ".partial") |
| 320 | if err == nil && info.Mode().IsRegular() && info.Size() <= p.Bytes { |
| 321 | return p.Bytes - info.Size() |
| 322 | } |
| 323 | return p.Bytes |
| 324 | } |
| 325 | |
| 326 | const sourceRecord = "host-system-source.json" |
| 327 | |
| 328 | func Save(cache string, plan Plan) error { |
| 329 | if err := plan.Validate(); err != nil { |
| 330 | return err |
| 331 | } |
| 332 | if err := os.MkdirAll(cache, 0700); err != nil { |
| 333 | return err |
| 334 | } |
| 335 | file, err := os.CreateTemp(cache, ".host-system-source-*") |
| 336 | if err != nil { |
| 337 | return err |
| 338 | } |
| 339 | defer os.Remove(file.Name()) |
| 340 | err = json.NewEncoder(file).Encode(plan) |
| 341 | closeErr := file.Close() |
| 342 | if err = errors.Join(err, closeErr); err != nil { |
| 343 | return err |
| 344 | } |
| 345 | return os.Rename(file.Name(), filepath.Join(cache, sourceRecord)) |
| 346 | } |
| 347 | |
| 348 | func Load(cache string) (Plan, error) { |
| 349 | var plan Plan |
| 350 | file, err := os.Open(filepath.Join(cache, sourceRecord)) |
| 351 | if err != nil { |
| 352 | return plan, err |
| 353 | } |
| 354 | defer file.Close() |
| 355 | decoder := json.NewDecoder(io.LimitReader(file, 32<<10)) |
| 356 | decoder.DisallowUnknownFields() |
| 357 | if err = decoder.Decode(&plan); err != nil { |
| 358 | return plan, err |
| 359 | } |
| 360 | return plan, plan.Validate() |
| 361 | } |