Files
Reims-Go/internal/macos/installer/accelerated.go
T
NwflowerandClaude Opus 5.5 b203bde650 refactor: merge duplicated helpers and the window event contract
Events to the frontend go through App.emit, and a test keeps their names
in step with wails.ts. QEMU argument splitting, hidden console processes,
the macOS release record, the running check and a few smaller helpers
now exist once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 21:09:19 -07:00

559 lines
17 KiB
Go

package installer
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/downloader"
"github.com/Nwflower/reims-go/internal/host"
)
func resolveOfflineRelease(releases []Release, version string) (Release, bool) {
if len(releases) == 0 {
return Release{}, false
}
v := strings.TrimSpace(version)
low := strings.ToLower(v)
if low == "" || low == "latest" {
return releases[0], true
}
for _, r := range releases {
if strings.EqualFold(r.Version, v) || strings.EqualFold(r.Build, v) || strings.EqualFold(r.Product, v) {
return r, true
}
}
// Major version (e.g. "26" -> newest 26.x) or codename (e.g. "tahoe", "sequoia").
for _, r := range releases {
if strings.HasPrefix(strings.ToLower(r.Version), low+".") {
return r, true
}
name := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(r.Title)), "macos ")
if name == low || strings.ReplaceAll(name, " ", "-") == low {
return r, true
}
}
return Release{}, false
}
func offlineImageFilename(r Release) string {
title := strings.TrimSpace(r.Title)
title = strings.TrimPrefix(title, "macOS ")
title = strings.TrimPrefix(title, "MacOS ")
title = strings.ReplaceAll(strings.TrimSpace(title), " ", "-")
if title == "" {
title = "Release"
}
return fmt.Sprintf("macOS-%s-%s-%s-offline-installer.img", title, r.Version, r.Build)
}
func findOfflinePkgRegion(partPath string) (offset, size int64, ok bool) {
f, err := os.Open(partPath)
if err != nil {
return 0, 0, false
}
defer f.Close()
off, sz, err := FindFileInHFSPlusImage(f, "InstallAssistant.pkg")
if err != nil || off <= 0 || sz <= 0 {
return 0, 0, false
}
return off, sz, true
}
// prepareOfflinePartWithUtil lets reims-util initialize the 2-partition GPT
// .img.part (Recovery FAT32 + HFS+ Installer header) and stops it right when it
// reaches the large InstallAssistant.pkg download stage so the active
// downloader plugin can take over the multi-GB transfer at full speed.
func (c *Client) prepareOfflinePartWithUtil(ctx context.Context, version, partPath string, onUpdate func(Update)) (alreadyDone *Result, err error) {
prepCtx, cancel := context.WithCancel(ctx)
defer cancel()
cmd := exec.CommandContext(prepCtx, c.Util, "--json", "offline-installer", version, "-o", c.InstallersDir)
host.HideConsole(cmd)
cmd.Env = c.Env
cmd.Stdin = nil
var stderr bytes.Buffer
cmd.Stderr = &stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, err
}
var (
step string
handedOff bool
doneResult json.RawMessage
failedMsg string
)
sc := bufio.NewScanner(stdout)
sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
for sc.Scan() {
var ev event
if json.Unmarshal(sc.Bytes(), &ev) != nil {
continue
}
switch ev.Event {
case "step":
step = lowerFirst(ev.Message)
lowStep := strings.ToLower(step)
// Once reims-util enters either the recovery image download or the main
// macOS package download, .img.part has both GPT partitions formatted
// with BaseSystem.dmg (and its chunklist) + InstallAssistant.pkg mapped.
if strings.HasPrefix(lowStep, "downloading the macos") || strings.HasPrefix(lowStep, "downloading macos") {
if _, _, ok := findOfflinePkgRegion(partPath); ok {
if rec, rok := inspectRecoveryPartition(partPath, false); rok && rec.contiguous && len(rec.chunklist) > 0 {
handedOff = true
cancel()
continue
}
if strings.HasPrefix(lowStep, "downloading macos") {
handedOff = true
cancel()
continue
}
}
}
onUpdate(Update{Kind: KindStep, Message: step, Step: step, Percent: -1})
case "note":
onUpdate(Update{Kind: KindNote, Message: ev.Message, Step: step, Percent: -1})
case "progress":
if handedOff {
continue
}
lowStep := strings.ToLower(step)
if strings.HasPrefix(lowStep, "downloading the macos") || strings.HasPrefix(lowStep, "downloading macos") {
if _, _, ok := findOfflinePkgRegion(partPath); ok {
if rec, rok := inspectRecoveryPartition(partPath, false); rok && rec.contiguous && len(rec.chunklist) > 0 {
handedOff = true
cancel()
continue
}
if strings.HasPrefix(lowStep, "downloading macos") {
handedOff = true
cancel()
continue
}
}
}
var total int64
if ev.Total != nil {
total = *ev.Total
}
onUpdate(Update{Kind: KindProgress, Step: step, Done: ev.Done, Total: total, Percent: percentOf(ev.Done, total)})
case "done":
doneResult = ev.Result
case "error":
failedMsg = ev.Message
}
}
waitErr := cmd.Wait()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if handedOff {
return nil, nil
}
if doneResult != nil && waitErr == nil {
var r offlineResult
if json.Unmarshal(doneResult, &r) == nil {
return &Result{Image: r.Image, Version: r.Installer.Version, Build: r.Installer.Build}, nil
}
}
if failedMsg != "" {
return nil, fmt.Errorf("%s", failedMsg)
}
if waitErr != nil {
return nil, fmt.Errorf("prepare offline image: %w (%s)", waitErr, strings.TrimSpace(stderr.String()))
}
return nil, nil
}
// downloadOfflineAccelerated accelerates the large InstallAssistant.pkg transfer
// using prov while preserving 100% compatibility with reims-util's .img.part
// container and finalization. Returns handled=false to fall back to reims-util.
func (c *Client) downloadOfflineAccelerated(ctx context.Context, version string, prov downloader.Provider, onUpdate func(Update)) (*Result, bool, error) {
releases, err := c.ListOffline(ctx, onUpdate)
if err != nil {
if ctx.Err() != nil {
return nil, true, ctx.Err()
}
return nil, false, nil
}
rel, ok := resolveOfflineRelease(releases, version)
if !ok || rel.URL == "" || rel.Size <= 0 {
return nil, false, nil
}
finalPath := filepath.Join(c.InstallersDir, offlineImageFilename(rel))
if st, err := os.Stat(finalPath); err == nil && st.Size() > rel.Size {
// Already downloaded completely; let reims-util verify and return immediately.
return nil, false, nil
}
partPath := finalPath + ".part"
pkgOff, pkgSize, ready := findOfflinePkgRegion(partPath)
if !ready || pkgSize != rel.Size {
alreadyDone, prepErr := c.prepareOfflinePartWithUtil(ctx, version, partPath, onUpdate)
if prepErr != nil {
if ctx.Err() != nil {
return nil, true, ctx.Err()
}
onUpdate(Update{Kind: KindNote, Message: "Parallel downloader setup skipped; falling back to reims-util: " + prepErr.Error(), Percent: -1})
return nil, false, nil
}
if alreadyDone != nil {
return alreadyDone, true, nil
}
pkgOff, pkgSize, ready = findOfflinePkgRegion(partPath)
if !ready || pkgSize != rel.Size {
return nil, false, nil
}
}
// Step 1: If the Recovery partition's BaseSystem.dmg is not yet verified,
// accelerate it via the active multi-connection downloader plugin too.
if rec, rok := inspectRecoveryPartition(partPath, true); rok && !rec.verified && rec.contiguous && len(rec.chunklist) > 0 {
onlineList := c.listOnlineReleases(ctx)
if onRel, found := resolveOnlineRelease(onlineList, rel.Title); found && onRel.BoardID != "" {
httpClient := newDirectRecoveryHTTPClient()
asset, osType, aerr := fetchMatchingRecoveryAsset(ctx, httpClient, osRecoveryBaseURL, onRel.BoardID, onRel.Slug, rec.chunklist)
if aerr == nil && asset != nil {
recStep := fmt.Sprintf("downloading %s recovery (%s)", onRel.Name, prov.ID())
onUpdate(Update{Kind: KindStep, Message: recStep, Step: recStep, Percent: -1})
rErr := prov.Download(ctx, downloader.Request{
URL: asset.AssetURL,
DestPath: partPath,
DestOffset: rec.dmgOffset,
ExpectedSize: rec.dmgSize,
IntegrityBytes: rec.chunklist,
Headers: recoveryHeaders(asset.AssetToken),
Resume: true,
DirectHint: true,
SameOriginRedirects: true,
RefreshHeaders: func(rctx context.Context) (map[string]string, error) {
fresh, ferr := fetchRecoveryAsset(rctx, httpClient, osRecoveryBaseURL, onRel.BoardID, osType)
if ferr != nil {
return nil, ferr
}
return recoveryHeaders(fresh.AssetToken), nil
},
}, func(p downloader.Progress) {
onUpdate(Update{
Kind: KindProgress,
Step: recStep,
Done: p.Done,
Total: p.Total,
Percent: percentOf(p.Done, p.Total),
})
})
if rErr != nil {
if ctx.Err() != nil {
return nil, true, ctx.Err()
}
onUpdate(Update{Kind: KindNote, Message: fmt.Sprintf("Recovery parallel download skipped (%v); will finalize via reims-util", rErr), Percent: -1})
}
}
}
}
step := fmt.Sprintf("downloading %s %s (%s)", rel.Title, rel.Version, prov.ID())
onUpdate(Update{Kind: KindStep, Message: step, Step: step, Percent: -1})
dlErr := prov.Download(ctx, downloader.Request{
URL: rel.URL,
IntegrityURL: rel.IntegrityURL,
DestPath: partPath,
DestOffset: pkgOff,
ExpectedSize: rel.Size,
Resume: true,
DirectHint: true,
}, func(p downloader.Progress) {
onUpdate(Update{
Kind: KindProgress,
Step: step,
Done: p.Done,
Total: p.Total,
Percent: percentOf(p.Done, p.Total),
})
})
if dlErr != nil {
if ctx.Err() != nil {
return nil, true, ctx.Err()
}
onUpdate(Update{Kind: KindNote, Message: fmt.Sprintf("Downloader plugin %s failed (%v); falling back to reims-util", prov.ID(), dlErr), Percent: -1})
return nil, false, nil
}
// If the FAT32 Recovery partition (part[1]) already holds a complete
// BaseSystem.dmg verified against its BaseSystem.chunklist (CNKL), and
// InstallAssistant.pkg just passed Apple CNKL verification above, finalize
// directly with an atomic rename — avoiding a redundant reims-util pass and
// extra osrecovery.apple.com network round-trip.
finalStep := fmt.Sprintf("finalizing %s %s offline installer", rel.Title, rel.Version)
onUpdate(Update{Kind: KindStep, Message: finalStep, Step: finalStep, Percent: -1})
if verifyRecoveryPartition(partPath) {
if err := os.Rename(partPath, finalPath); err == nil {
return &Result{Image: finalPath, Version: rel.Version, Build: rel.Build}, true, nil
}
}
// Fallback finalization via reims-util when Recovery wasn't already complete.
raw, err := c.run(ctx, onUpdate, "offline-installer", version, "-o", c.InstallersDir)
if err != nil {
return nil, true, err
}
var r offlineResult
if err := json.Unmarshal(raw, &r); err != nil {
return nil, true, fmt.Errorf("read reims-util's result: %w", err)
}
return &Result{Image: r.Image, Version: r.Installer.Version, Build: r.Installer.Build}, true, nil
}
type recoveryPartitionInfo struct {
dmgOffset int64
dmgSize int64
contiguous bool
chunklist []byte
verified bool
}
// verifyRecoveryPartition checks GPT partition 2 (FAT32 RECOVERY) inside a
// reims-util .img.part file and verifies that BaseSystem.dmg exists and matches
// every SHA-256 chunk in BaseSystem.chunklist (CNKL).
func verifyRecoveryPartition(imagePath string) bool {
info, ok := inspectRecoveryPartition(imagePath, true)
return ok && info.verified
}
// inspectRecoveryPartition locates BaseSystem.dmg and BaseSystem.chunklist inside
// GPT partition 2 (FAT32 RECOVERY). When verifyData is true, it also streams
// BaseSystem.dmg and verifies every CNKL SHA-256 chunk.
func inspectRecoveryPartition(imagePath string, verifyData bool) (*recoveryPartitionInfo, bool) {
f, err := os.Open(imagePath)
if err != nil {
return nil, false
}
defer f.Close()
// Validate GPT signature at LBA 1.
var hdr [512]byte
if _, err := f.ReadAt(hdr[:], 512); err != nil || string(hdr[:8]) != "EFI PART" {
return nil, false
}
entrySize := binary.LittleEndian.Uint32(hdr[84:88])
if entrySize < 128 || entrySize > 512 {
return nil, false
}
// Partition 2 (index 1) is the FAT32 Recovery partition.
ent := make([]byte, entrySize)
if _, err := f.ReadAt(ent, 1024+int64(entrySize)); err != nil {
return nil, false
}
firstLBA := binary.LittleEndian.Uint64(ent[32:40])
lastLBA := binary.LittleEndian.Uint64(ent[40:48])
if firstLBA == 0 || lastLBA <= firstLBA {
return nil, false
}
partOff := int64(firstLBA) * 512
var boot [512]byte
if _, err := f.ReadAt(boot[:], partOff); err != nil || boot[510] != 0x55 || boot[511] != 0xAA {
return nil, false
}
bps := int64(binary.LittleEndian.Uint16(boot[11:13]))
spc := int64(boot[13])
rsvd := int64(binary.LittleEndian.Uint16(boot[14:16]))
numFATs := int64(boot[16])
fatSz := int64(binary.LittleEndian.Uint32(boot[36:40]))
rootClus := uint32(binary.LittleEndian.Uint32(boot[44:48]))
if bps != 512 || spc == 0 || fatSz == 0 || rootClus < 2 {
return nil, false
}
fatOff := partOff + rsvd*bps
dataOff := partOff + (rsvd+numFATs*fatSz)*bps
clusSize := spc * bps
nextCluster := func(c uint32) uint32 {
var b [4]byte
if _, err := f.ReadAt(b[:], fatOff+int64(c)*4); err != nil {
return 0x0FFFFFFF
}
return binary.LittleEndian.Uint32(b[:]) & 0x0FFFFFFF
}
readChain := func(start uint32, maxBytes int64) ([]byte, bool) {
var out bytes.Buffer
c := start
for hops := 0; c >= 2 && c < 0x0FFFFFF8 && hops < 1<<20; hops++ {
buf := make([]byte, clusSize)
if _, err := f.ReadAt(buf, dataOff+int64(c-2)*clusSize); err != nil {
return nil, false
}
out.Write(buf)
if maxBytes > 0 && int64(out.Len()) >= maxBytes {
return out.Bytes()[:maxBytes], true
}
c = nextCluster(c)
}
if maxBytes > 0 && int64(out.Len()) < maxBytes {
return nil, false
}
return out.Bytes(), true
}
type fatEntry struct {
name string
attr byte
clus uint32
size uint32
}
parseDir := func(dirBytes []byte) []fatEntry {
var out []fatEntry
for i := 0; i+32 <= len(dirBytes); i += 32 {
e := dirBytes[i : i+32]
if e[0] == 0x00 {
break
}
if e[0] == 0xE5 || e[11] == 0x0F {
continue
}
name := strings.TrimSpace(string(e[0:8]))
ext := strings.TrimSpace(string(e[8:11]))
if ext != "" {
name += "." + ext
}
hi := uint32(binary.LittleEndian.Uint16(e[20:22]))
lo := uint32(binary.LittleEndian.Uint16(e[26:28]))
out = append(out, fatEntry{
name: strings.ToUpper(name),
attr: e[11],
clus: (hi << 16) | lo,
size: binary.LittleEndian.Uint32(e[28:32]),
})
}
return out
}
rootBytes, ok := readChain(rootClus, 0)
if !ok {
return nil, false
}
var bootDirClus uint32
for _, e := range parseDir(rootBytes) {
if (e.attr&0x10) != 0 && (strings.HasPrefix(e.name, "COM") || strings.Contains(e.name, "BOO")) {
bootDirClus = e.clus
break
}
}
if bootDirClus < 2 {
return nil, false
}
subBytes, ok := readChain(bootDirClus, 0)
if !ok {
return nil, false
}
var dmgEnt, chuEnt fatEntry
for _, e := range parseDir(subBytes) {
if (e.attr & 0x10) != 0 {
continue
}
if strings.HasSuffix(e.name, ".DMG") {
dmgEnt = e
} else if strings.HasSuffix(e.name, ".CHU") {
chuEnt = e
}
}
if dmgEnt.clus < 2 || dmgEnt.size < 1<<20 || chuEnt.clus < 2 || chuEnt.size < 36 || chuEnt.size > 16<<20 {
return nil, false
}
chuBytes, ok := readChain(chuEnt.clus, int64(chuEnt.size))
if !ok {
return nil, false
}
cl, err := parseSignedRecoveryChunklist(chuBytes)
if err != nil || cl.TotalSize != int64(dmgEnt.size) {
return nil, false
}
// Verify whether BaseSystem.dmg occupies a single contiguous cluster run.
needClusters := (int64(dmgEnt.size) + clusSize - 1) / clusSize
contiguous := true
cur := dmgEnt.clus
for i := int64(0); i < needClusters; i++ {
if cur != dmgEnt.clus+uint32(i) {
contiguous = false
break
}
next := nextCluster(cur)
if i+1 < needClusters && (next < 2 || next >= 0x0FFFFFF8) {
contiguous = false
break
}
cur = next
}
info := &recoveryPartitionInfo{
dmgOffset: dataOff + int64(dmgEnt.clus-2)*clusSize,
dmgSize: int64(dmgEnt.size),
contiguous: contiguous,
chunklist: chuBytes,
}
if !verifyData {
return info, true
}
// Stream BaseSystem.dmg clusters sequentially and verify every CNKL chunk SHA-256.
c := dmgEnt.clus
var remInClus int64
clusBuf := make([]byte, clusSize)
var clusPos int64
readDmg := func(p []byte) error {
off := 0
for off < len(p) {
if remInClus == 0 {
if c < 2 || c >= 0x0FFFFFF8 {
return io.ErrUnexpectedEOF
}
if _, err := f.ReadAt(clusBuf, dataOff+int64(c-2)*clusSize); err != nil {
return err
}
c = nextCluster(c)
clusPos = 0
remInClus = clusSize
}
n := copy(p[off:], clusBuf[clusPos:clusPos+remInClus])
off += n
clusPos += int64(n)
remInClus -= int64(n)
}
return nil
}
var chunkBuf []byte
for _, ch := range cl.Chunks {
if int64(cap(chunkBuf)) < ch.Size {
chunkBuf = make([]byte, ch.Size)
} else {
chunkBuf = chunkBuf[:ch.Size]
}
if err := readDmg(chunkBuf); err != nil {
return info, true
}
if sha256.Sum256(chunkBuf) != ch.SHA256 {
return info, true
}
}
info.verified = true
return info, true
}