Files
Reims-Go/internal/macos/installer/hfs_image.go
T
ShroapandShroap 7f4cbbe911 feat(guesttools): support Windows-to-macOS window drag-and-drop (zero-copy WebDAV + stealth paste) (#82)
* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image

* feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13)

---------

Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
2026-12-02 21:35:59 +08:00

951 lines
28 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package installer
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
"unicode/utf16"
)
// HFSFile describes one root-level file placed into a minimal GPT + HFS Plus
// disk image (compatible with macOS Recovery 11–26 auto-mount).
type HFSFile struct {
Name string
Mode uint16 // POSIX mode, e.g. 0o100644 or 0o100755
Size int64
Open func() (io.ReadCloser, error)
}
const (
hfsSector = 512
hfsBlock = 4096
hfsNode = 4096
hfsCatalogNode = 2 * hfsNode
hfsCatalogNodes = 64
hfsExtentsNodes = 128
hfsAttributesNodes = 64
hfsFirstLBA = 2048
hfsEpoch1904 = 2082844800
)
// BuildHFSPlusDiskImage creates a single-partition GPT + HFS Plus disk image
// containing files in its root directory (Apple TN1150 layout, matching
// reims-util's src/image/hfsplus.rs & gpt.rs).
func BuildHFSPlusDiskImage(destPath, label string, files []HFSFile) error {
if len(files) == 0 {
return fmt.Errorf("HFS+ image requires at least one file")
}
if err := os.MkdirAll(filepath.Dir(destPath), 0o755); err != nil {
return err
}
// Calculate required HFS+ blocks:
// block 0 (header), allocation bitmap, extents, attributes, catalog, files, last block (alt header).
var fileBlocks uint64
for _, f := range files {
if f.Size > 0 {
fileBlocks += uint64((f.Size + hfsBlock - 1) / hfsBlock)
}
}
metaBlocks := uint64(1 + 4 + hfsExtentsNodes + 2*hfsAttributesNodes + 2*hfsCatalogNodes + 1)
// Add 16 MiB headroom and align partition size to 1 MiB.
partBytes := (metaBlocks + fileBlocks) * hfsBlock
partBytes += 16 << 20
const oneMiB = 1 << 20
partBytes = ((partBytes + oneMiB - 1) / oneMiB) * oneMiB
if partBytes < 8<<20 {
partBytes = 8 << 20
}
totalBlocks := uint32(partBytes / hfsBlock)
partSectors := partBytes / hfsSector
// GPT needs backup entries (32 sectors) + backup header (1 sector) at disk end; align to 1 MiB.
totalSectors := hfsFirstLBA + partSectors + 33
totalSectors = ((totalSectors + 2047) / 2048) * 2048
diskBytes := int64(totalSectors * hfsSector)
tmpPath := destPath + ".tmp"
out, err := os.Create(tmpPath)
if err != nil {
return err
}
cleanup := func() {
_ = out.Close()
_ = os.Remove(tmpPath)
}
if err := out.Truncate(diskBytes); err != nil {
cleanup()
return err
}
// Deterministic GUIDs derived from label + file names/sizes.
h := sha256.New()
_, _ = h.Write([]byte(label))
for _, f := range files {
_, _ = fmt.Fprintf(h, "|%s:%d", f.Name, f.Size)
}
seed := h.Sum(nil)
var diskGUID, partGUID [16]byte
copy(diskGUID[:], seed[0:16])
copy(partGUID[:], seed[16:32])
diskGUID[7] = (diskGUID[7] & 0x0f) | 0x40
diskGUID[8] = (diskGUID[8] & 0x3f) | 0x80
partGUID[7] = (partGUID[7] & 0x0f) | 0x40
partGUID[8] = (partGUID[8] & 0x3f) | 0x80
if err := writeGPT(out, totalSectors, diskGUID, partGUID, hfsFirstLBA, hfsFirstLBA+partSectors-1, label); err != nil {
cleanup()
return err
}
partOffset := int64(hfsFirstLBA * hfsSector)
var volID [8]byte
copy(volID[:], seed[0:8])
if err := writeHFSPlusVolume(out, partOffset, totalBlocks, label, volID, files); err != nil {
cleanup()
return err
}
if err := out.Sync(); err != nil {
cleanup()
return err
}
if err := out.Close(); err != nil {
_ = os.Remove(tmpPath)
return err
}
_ = os.Remove(destPath)
if err := os.Rename(tmpPath, destPath); err != nil {
_ = os.Remove(tmpPath)
return err
}
return nil
}
func writeGPT(out *os.File, sectors uint64, diskGUID, partGUID [16]byte, firstLBA, lastLBA uint64, name string) error {
last := sectors - 1
const entrySectors = 32
lastUsable := sectors - 1 - entrySectors - 1
var mbr [hfsSector]byte
e := mbr[446:462]
copy(e[1:4], []byte{0x00, 0x02, 0x00})
e[4] = 0xee
copy(e[5:8], []byte{0xff, 0xff, 0xff})
binary.LittleEndian.PutUint32(e[8:12], 1)
mbrSize := sectors - 1
if mbrSize > 0xffffffff {
mbrSize = 0xffffffff
}
binary.LittleEndian.PutUint32(e[12:16], uint32(mbrSize))
mbr[510], mbr[511] = 0x55, 0xaa
if _, err := out.WriteAt(mbr[:], 0); err != nil {
return err
}
entries := make([]byte, 128*128)
copy(entries[0:16], appleHFSPlusGUID[:])
copy(entries[16:32], partGUID[:])
binary.LittleEndian.PutUint64(entries[32:40], firstLBA)
binary.LittleEndian.PutUint64(entries[40:48], lastLBA)
u16 := utf16.Encode([]rune(name))
if len(u16) > 36 {
u16 = u16[:36]
}
for i, c := range u16 {
binary.LittleEndian.PutUint16(entries[56+2*i:58+2*i], c)
}
entriesCRC := crc32.ChecksumIEEE(entries)
makeHdr := func(myLBA, altLBA, entriesLBA uint64) [hfsSector]byte {
var hdr [hfsSector]byte
copy(hdr[0:8], "EFI PART")
binary.LittleEndian.PutUint32(hdr[8:12], 0x00010000)
binary.LittleEndian.PutUint32(hdr[12:16], 92)
binary.LittleEndian.PutUint64(hdr[24:32], myLBA)
binary.LittleEndian.PutUint64(hdr[32:40], altLBA)
binary.LittleEndian.PutUint64(hdr[40:48], 2+entrySectors)
binary.LittleEndian.PutUint64(hdr[48:56], lastUsable)
copy(hdr[56:72], diskGUID[:])
binary.LittleEndian.PutUint64(hdr[72:80], entriesLBA)
binary.LittleEndian.PutUint32(hdr[80:84], 128)
binary.LittleEndian.PutUint32(hdr[84:88], 128)
binary.LittleEndian.PutUint32(hdr[88:92], entriesCRC)
crc := crc32.ChecksumIEEE(hdr[:92])
binary.LittleEndian.PutUint32(hdr[16:20], crc)
return hdr
}
priHdr := makeHdr(1, last, 2)
backupEntriesLBA := last - entrySectors
bakHdr := makeHdr(last, 1, backupEntriesLBA)
if _, err := out.WriteAt(priHdr[:], hfsSector); err != nil {
return err
}
if _, err := out.WriteAt(entries, 2*hfsSector); err != nil {
return err
}
if _, err := out.WriteAt(entries, int64(backupEntriesLBA*hfsSector)); err != nil {
return err
}
if _, err := out.WriteAt(bakHdr[:], int64(last*hfsSector)); err != nil {
return err
}
return nil
}
type hfsFork struct {
length uint64
first uint32
blocks uint32
}
func encodeHFSFork(f hfsFork, clump uint32) [80]byte {
var d [80]byte
binary.BigEndian.PutUint64(d[0:8], f.length)
binary.BigEndian.PutUint32(d[8:12], clump)
binary.BigEndian.PutUint32(d[12:16], f.blocks)
if f.blocks > 0 {
binary.BigEndian.PutUint32(d[16:20], f.first)
binary.BigEndian.PutUint32(d[20:24], f.blocks)
}
return d
}
func writeHFSPlusVolume(out *os.File, partOff int64, totalBlocks uint32, label string, volID [8]byte, files []HFSFile) error {
date := uint32(time.Now().Unix() + hfsEpoch1904)
nextBlock := uint32(1)
alloc := func(bytesLen uint64) (hfsFork, error) {
n := uint32((bytesLen + hfsBlock - 1) / hfsBlock)
first := nextBlock
if uint64(first)+uint64(n) >= uint64(totalBlocks) {
return hfsFork{}, fmt.Errorf("HFS+ volume out of space")
}
nextBlock += n
return hfsFork{length: bytesLen, first: first, blocks: n}, nil
}
bitmapBytes := ((uint64(totalBlocks)+7)/8 + hfsBlock - 1) / hfsBlock * hfsBlock
allocFork, err := alloc(bitmapBytes)
if err != nil {
return err
}
extentsFork, err := alloc(uint64(hfsExtentsNodes) * hfsNode)
if err != nil {
return err
}
attrsFork, err := alloc(uint64(hfsAttributesNodes) * 2 * hfsNode)
if err != nil {
return err
}
catalogFork, err := alloc(uint64(hfsCatalogNodes) * hfsCatalogNode)
if err != nil {
return err
}
type fileEntry struct {
id uint32
name []uint16
fold string
mode uint16
fork hfsFork
}
entries := make([]fileEntry, 0, len(files))
for i, f := range files {
var fk hfsFork
if f.Size > 0 {
fk, err = alloc(uint64(f.Size))
if err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
writeOff := partOff + int64(fk.first)*hfsBlock
buf := make([]byte, 256*1024)
var written int64
for {
n, rerr := rc.Read(buf)
if n > 0 {
if _, werr := out.WriteAt(buf[:n], writeOff+written); werr != nil {
_ = rc.Close()
return werr
}
written += int64(n)
}
if rerr == io.EOF {
break
}
if rerr != nil {
_ = rc.Close()
return rerr
}
}
_ = rc.Close()
if written != f.Size {
return fmt.Errorf("HFS+ file %s size mismatch: wrote %d, expected %d", f.Name, written, f.Size)
}
}
mode := f.Mode
if mode == 0 {
mode = 0o100644
}
entries = append(entries, fileEntry{
id: uint32(16 + i),
name: utf16.Encode([]rune(f.Name)),
fold: strings.ToLower(f.Name),
mode: mode,
fork: fk,
})
}
usedBlocks := nextBlock + 1
labelU16 := utf16.Encode([]rune(label))
var recs [][]byte
recs = append(recs, append(hfsKey(1, labelU16), hfsFolderRecord(uint32(len(files)), date)...))
recs = append(recs, append(hfsKey(2, nil), hfsThreadRecord(3, 1, labelU16)...))
byName := append([]fileEntry(nil), entries...)
sort.Slice(byName, func(i, j int) bool { return byName[i].fold < byName[j].fold })
for _, e := range byName {
recs = append(recs, append(hfsKey(2, e.name), hfsFileRecord(e.id, date, e.mode, e.fork)...))
}
for _, e := range entries {
recs = append(recs, append(hfsKey(e.id, nil), hfsThreadRecord(4, 2, e.name)...))
}
leaf, err := hfsLeafNode(hfsCatalogNode, recs)
if err != nil {
return err
}
catHdr := hfsHeaderNode(hfsCatalogNode, hfsCatalogNodes, 516, 2|4, 0xcf, uint32(len(recs)))
if _, err := out.WriteAt(catHdr, partOff+int64(catalogFork.first)*hfsBlock); err != nil {
return err
}
if _, err := out.WriteAt(leaf, partOff+int64(catalogFork.first)*hfsBlock+hfsCatalogNode); err != nil {
return err
}
extHdr := hfsHeaderNode(hfsNode, hfsExtentsNodes, 10, 2, 0, 0)
if _, err := out.WriteAt(extHdr, partOff+int64(extentsFork.first)*hfsBlock); err != nil {
return err
}
attrHdr := hfsHeaderNode(2*hfsNode, hfsAttributesNodes, 266, 2|4, 0, 0)
if _, err := out.WriteAt(attrHdr, partOff+int64(attrsFork.first)*hfsBlock); err != nil {
return err
}
bitmap := make([]byte, bitmapBytes)
for b := uint32(0); b < nextBlock; b++ {
bitmap[b/8] |= 0x80 >> (b % 8)
}
lastBlk := totalBlocks - 1
bitmap[lastBlk/8] |= 0x80 >> (lastBlk % 8)
if _, err := out.WriteAt(bitmap, partOff+int64(allocFork.first)*hfsBlock); err != nil {
return err
}
var vh [512]byte
copy(vh[0:2], "H+")
binary.BigEndian.PutUint16(vh[2:4], 4)
binary.BigEndian.PutUint32(vh[4:8], (1<<8)|(1<<31))
copy(vh[8:12], "10.0")
binary.BigEndian.PutUint32(vh[16:20], date)
binary.BigEndian.PutUint32(vh[20:24], date)
binary.BigEndian.PutUint32(vh[28:32], date)
binary.BigEndian.PutUint32(vh[32:36], uint32(len(files)))
binary.BigEndian.PutUint32(vh[40:44], hfsBlock)
binary.BigEndian.PutUint32(vh[44:48], totalBlocks)
binary.BigEndian.PutUint32(vh[48:52], totalBlocks-usedBlocks)
binary.BigEndian.PutUint32(vh[52:56], nextBlock)
binary.BigEndian.PutUint32(vh[56:60], 65536)
binary.BigEndian.PutUint32(vh[60:64], 65536)
binary.BigEndian.PutUint32(vh[64:68], uint32(16+len(files)))
binary.BigEndian.PutUint32(vh[68:72], 1)
binary.BigEndian.PutUint64(vh[72:80], 1)
copy(vh[104:112], volID[:])
af := encodeHFSFork(allocFork, hfsBlock)
ef := encodeHFSFork(extentsFork, uint32(extentsFork.length))
cf := encodeHFSFork(catalogFork, uint32(catalogFork.length))
atf := encodeHFSFork(attrsFork, uint32(attrsFork.length))
copy(vh[112:192], af[:])
copy(vh[192:272], ef[:])
copy(vh[272:352], cf[:])
copy(vh[352:432], atf[:])
if _, err := out.WriteAt(vh[:], partOff+1024); err != nil {
return err
}
partEnd := partOff + int64(totalBlocks)*hfsBlock
if _, err := out.WriteAt(vh[:], partEnd-1024); err != nil {
return err
}
return nil
}
func hfsHeaderNode(nodeSize int, nodes uint32, maxKey uint16, attrs uint32, compare byte, leafRecs uint32) []byte {
n := make([]byte, nodeSize)
n[8] = 1 // kBTHeaderNode
binary.BigEndian.PutUint16(n[10:12], 3)
used := uint32(1)
if leafRecs > 0 {
used = 2
binary.BigEndian.PutUint16(n[14:16], 1)
binary.BigEndian.PutUint32(n[16:20], 1)
binary.BigEndian.PutUint32(n[20:24], leafRecs)
binary.BigEndian.PutUint32(n[24:28], 1)
binary.BigEndian.PutUint32(n[28:32], 1)
n[248] = 0xc0
} else {
n[248] = 0x80
}
binary.BigEndian.PutUint16(n[32:34], uint16(nodeSize))
binary.BigEndian.PutUint16(n[34:36], maxKey)
binary.BigEndian.PutUint32(n[36:40], nodes)
binary.BigEndian.PutUint32(n[40:44], nodes-used)
binary.BigEndian.PutUint32(n[46:50], nodes*uint32(nodeSize))
n[51] = compare
binary.BigEndian.PutUint32(n[52:56], attrs)
for i, off := range []uint16{14, 120, 248, uint16(nodeSize - 8)} {
binary.BigEndian.PutUint16(n[nodeSize-2-2*i:nodeSize-2*i], off)
}
return n
}
func hfsLeafNode(nodeSize int, recs [][]byte) ([]byte, error) {
n := make([]byte, nodeSize)
n[8] = 0xff // kBTLeafNode
n[9] = 1
binary.BigEndian.PutUint16(n[10:12], uint16(len(recs)))
offsets := make([]uint16, 0, len(recs)+1)
at := 14
for _, r := range recs {
if at+len(r)+2*(len(recs)+1) > nodeSize {
return nil, fmt.Errorf("HFS+ catalog records exceed one leaf node")
}
offsets = append(offsets, uint16(at))
copy(n[at:], r)
at += len(r)
}
offsets = append(offsets, uint16(at))
for i, off := range offsets {
binary.BigEndian.PutUint16(n[nodeSize-2-2*i:nodeSize-2*i], off)
}
return n, nil
}
func hfsKey(parent uint32, name []uint16) []byte {
k := make([]byte, 8+2*len(name))
binary.BigEndian.PutUint16(k[0:2], uint16(6+2*len(name)))
binary.BigEndian.PutUint32(k[2:6], parent)
binary.BigEndian.PutUint16(k[6:8], uint16(len(name)))
for i, c := range name {
binary.BigEndian.PutUint16(k[8+2*i:10+2*i], c)
}
return k
}
func hfsFolderRecord(valence, date uint32) []byte {
r := make([]byte, 88)
binary.BigEndian.PutUint16(r[0:2], 1)
binary.BigEndian.PutUint32(r[4:8], valence)
binary.BigEndian.PutUint32(r[8:12], 2)
for i := 0; i < 4; i++ {
binary.BigEndian.PutUint32(r[12+4*i:16+4*i], date)
}
binary.BigEndian.PutUint32(r[32:36], 99)
binary.BigEndian.PutUint32(r[36:40], 99)
binary.BigEndian.PutUint16(r[42:44], 0o40755)
binary.BigEndian.PutUint32(r[44:48], 1)
return r
}
func hfsFileRecord(id, date uint32, mode uint16, fork hfsFork) []byte {
r := make([]byte, 248)
binary.BigEndian.PutUint16(r[0:2], 2)
binary.BigEndian.PutUint16(r[2:4], 2) // kHFSThreadExistsMask
binary.BigEndian.PutUint32(r[8:12], id)
for i := 0; i < 4; i++ {
binary.BigEndian.PutUint32(r[12+4*i:16+4*i], date)
}
binary.BigEndian.PutUint32(r[32:36], 99)
binary.BigEndian.PutUint32(r[36:40], 99)
binary.BigEndian.PutUint16(r[42:44], mode)
binary.BigEndian.PutUint32(r[44:48], 1)
fd := encodeHFSFork(fork, 0)
copy(r[88:168], fd[:])
return r
}
func hfsThreadRecord(kind uint16, parent uint32, name []uint16) []byte {
r := make([]byte, 10+2*len(name))
binary.BigEndian.PutUint16(r[0:2], kind)
binary.BigEndian.PutUint32(r[4:8], parent)
binary.BigEndian.PutUint16(r[8:10], uint16(len(name)))
for i, c := range name {
binary.BigEndian.PutUint16(r[10+2*i:12+2*i], c)
}
return r
}
// HelperInstallScript returns the Recovery shell script placed on the REIMSHELP
// volume. It auto-detects a writable target volume (skipping read-only system,
// recovery, and installer volumes), automatically formats a single blank VM
// physical disk (>= 30 GB) as APFS ("Macintosh HD") when no writable volume
// exists yet (and prompts/requires --erase before touching any non-blank disk),
// unpacks InstallApp.tar directly with BSD tar (no `installer` or `pkgutil`
// required in macOS Recovery), copies InstallAssistant.pkg as SharedSupport.dmg,
// and launches startosinstall.
func HelperInstallScript() []byte {
return []byte(`#!/bin/sh
# Installs macOS offline without relying on Recovery's installer or pkgutil.
# Auto-formats a single blank VM disk (>= 30 GB) as APFS ("Macintosh HD")
# when no writable target volume is mounted yet.
set -e
MIN_DISK_MB=30000
TAB=$(printf '\t')
trim_ws() {
v=$1
while :; do
case "$v" in
" "*|"$TAB"*) v=${v#?} ;;
*) break ;;
esac
done
printf '%s' "$v"
}
can_write() {
[ -d "$1" ] || return 1
probe="$1/.reims-write-test-$$"
if mkdir "$probe" 2>/dev/null; then
rmdir "$probe" 2>/dev/null || true
return 0
fi
return 1
}
is_reserved_vol() {
case "$1" in
Installer|REIMSHELP|RECOVERY|OPENCORE|"macOS Base System"|"Image Volume"|Recovery|Preboot|VM|Update)
return 0 ;;
*)
return 1 ;;
esac
}
find_writable_target() {
for v in "/Volumes/Macintosh HD" "/Volumes/Untitled"; do
if can_write "$v"; then
printf '%s\n' "$v"
return 0
fi
done
for v in /Volumes/*; do
[ -d "$v" ] || continue
name=${v##*/}
if is_reserved_vol "$name"; then
continue
fi
if can_write "$v"; then
printf '%s\n' "$v"
return 0
fi
done
return 1
}
bytes_to_mb() {
b=$1
case "$b" in
''|*[!0-9]*) printf '0\n'; return ;;
esac
if [ "${#b}" -le 6 ]; then
printf '0\n'
else
printf '%s\n' "${b%??????}"
fi
}
disk_prop() {
printf '%s\n' "$1" | while IFS= read -r line; do
case "$line" in
*"$2"*)
val=${line#*"$2"}
trim_ws "$val"
printf '\n'
break
;;
esac
done
}
disk_has_reserved() {
printf '%s\n' "$1" | while IFS= read -r line; do
case "$line" in
*" Installer "*|*" REIMSHELP "*|*" OPENCORE "*|*" RECOVERY "*|*" macOS Base System "*|*" Image Volume "*)
printf 'yes\n'
break
;;
esac
done
}
disk_has_partitions() {
printf '%s\n' "$1" | while IFS= read -r line; do
t=$(trim_ws "$line")
case "$t" in
[1-9]*:*)
printf 'yes\n'
break
;;
esac
done
}
list_physical_disks() {
diskutil list physical 2>/dev/null | while IFS= read -r line; do
case "$line" in
/dev/disk*synthesized*|/dev/disk*"disk image"*)
;;
/dev/disk*)
printf '%s\n' "${line%% *}"
;;
esac
done
}
inspect_candidate_disk() {
d=$1
cand_ok=0
cand_blank=0
cand_size_human=""
cand_media=""
cand_content=""
cand_reason=""
info=$(diskutil info "$d" 2>/dev/null) || { cand_reason="diskutil info failed"; return; }
whole=$(disk_prop "$info" "Whole:")
if [ "$whole" != "Yes" ]; then
cand_reason="not a whole disk"
return
fi
virtual=$(disk_prop "$info" "Virtual:")
if [ "$virtual" = "Yes" ]; then
cand_reason="virtual disk image"
return
fi
proto=$(disk_prop "$info" "Protocol:")
case "$proto" in
*"Disk Image"*)
cand_reason="disk image"
return ;;
esac
ro=$(disk_prop "$info" "Read-Only Media:")
if [ "$ro" = "Yes" ]; then
cand_reason="read-only media"
return
fi
size_str=$(disk_prop "$info" "Disk Size:")
[ -n "$size_str" ] || size_str=$(disk_prop "$info" "Total Size:")
cand_size_human=${size_str%% (*}
bytes_part=${size_str#*(}
bytes=${bytes_part%% *}
mb=$(bytes_to_mb "$bytes")
if [ "$mb" -lt "$MIN_DISK_MB" ]; then
cand_reason="too small (${cand_size_human:-unknown} < 30 GB)"
return
fi
dlist=$(diskutil list "$d" 2>/dev/null || true)
if [ -n "$(disk_has_reserved "$dlist")" ]; then
cand_reason="contains reserved/installer volume"
return
fi
cand_media=$(disk_prop "$info" "Device / Media Name:")
cand_content=$(disk_prop "$info" "Content (IOContent):")
cand_ok=1
if [ -z "$(disk_has_partitions "$dlist")" ] && { [ -z "$cand_content" ] || [ "$cand_content" = "None" ]; }; then
cand_blank=1
fi
}
erase_and_mount() {
disk=$1
echo "Formatting $disk as APFS (Macintosh HD, GPT)..."
diskutil eraseDisk APFS "Macintosh HD" GPT "$disk"
target=""
for _ in 1 2 3 4 5; do
if target=$(find_writable_target); then
break
fi
sleep 1
done
if [ -z "$target" ]; then
echo "Formatted $disk, but no writable target volume appeared under /Volumes." >&2
diskutil list "$disk" >&2 || true
ls /Volumes >&2 || true
exit 1
fi
}
erase_mode=0
erase_disk=""
target=""
case "${1:-}" in
--erase)
erase_mode=1
erase_disk=${2:-}
case "$erase_disk" in
disk*) erase_disk="/dev/$erase_disk" ;;
esac
;;
-h|--help)
echo "Usage: sh /Volumes/REIMSHELP/install.sh [TARGET_VOLUME | --erase [/dev/diskN]]"
exit 0
;;
"")
;;
*)
target=${1%/}
;;
esac
if [ "$erase_mode" -eq 1 ]; then
if ! command -v diskutil >/dev/null 2>&1; then
echo "diskutil is not available in this environment." >&2
exit 1
fi
if [ -n "$erase_disk" ]; then
inspect_candidate_disk "$erase_disk"
if [ "$cand_ok" -ne 1 ]; then
echo "Refusing to erase $erase_disk: $cand_reason" >&2
exit 1
fi
erase_and_mount "$erase_disk"
else
cand_count=0
cand_disk=""
cand_summary=""
for d in $(list_physical_disks); do
inspect_candidate_disk "$d"
if [ "$cand_ok" -eq 1 ]; then
cand_count=$((cand_count + 1))
cand_disk=$d
status="has partitions"
[ "$cand_blank" -eq 1 ] && status="blank"
cand_summary="${cand_summary} $d ${cand_size_human} (${cand_media:-disk}, $status)
"
fi
done
if [ "$cand_count" -eq 1 ]; then
erase_and_mount "$cand_disk"
elif [ "$cand_count" -eq 0 ]; then
echo "No eligible physical disk (>= 30 GB) found to erase." >&2
diskutil list physical >&2 || true
exit 1
else
echo "Multiple eligible disks found; specify one explicitly:" >&2
printf '%s' "$cand_summary" >&2
echo "Run: sh /Volumes/REIMSHELP/install.sh --erase /dev/diskN" >&2
exit 1
fi
fi
elif [ -n "$target" ]; then
if ! can_write "$target"; then
echo "Target volume is missing or read-only: $target" >&2
mount | grep /Volumes >&2 || ls /Volumes >&2
exit 1
fi
else
if target=$(find_writable_target); then
:
elif command -v diskutil >/dev/null 2>&1; then
blank_count=0
blank_disk=""
blank_desc=""
nonblank_count=0
nonblank_disk=""
nonblank_desc=""
all_summary=""
for d in $(list_physical_disks); do
inspect_candidate_disk "$d"
if [ "$cand_ok" -eq 1 ]; then
if [ "$cand_blank" -eq 1 ]; then
blank_count=$((blank_count + 1))
blank_disk=$d
blank_desc="$d (${cand_size_human}, ${cand_media:-blank disk})"
all_summary="${all_summary} $d ${cand_size_human} (${cand_media:-disk}, blank)
"
else
nonblank_count=$((nonblank_count + 1))
nonblank_disk=$d
nonblank_desc="$d (${cand_size_human}, ${cand_media:-disk}, ${cand_content:-partitioned})"
all_summary="${all_summary} $d ${cand_size_human} (${cand_media:-disk}, ${cand_content:-partitioned})
"
fi
fi
done
if [ "$blank_count" -eq 1 ] && [ "$nonblank_count" -eq 0 ]; then
echo "No writable volume found; detected blank VM disk: $blank_desc"
erase_and_mount "$blank_disk"
elif [ "$blank_count" -eq 0 ] && [ "$nonblank_count" -eq 1 ]; then
echo "No writable target volume found under /Volumes."
echo "Found 1 disk >= 30 GB that already has partitions: $nonblank_desc"
if [ -t 0 ]; then
printf 'Erase %s as APFS ("Macintosh HD")? All data on it will be lost! [y/N]: ' "$nonblank_disk"
IFS= read -r ans || ans=""
case "$ans" in
y|Y|yes|YES)
erase_and_mount "$nonblank_disk"
;;
*)
echo "Aborted. You can erase it in Disk Utility, or re-run with --erase $nonblank_disk" >&2
exit 1
;;
esac
else
echo "Refusing to erase a non-blank disk non-interactively." >&2
echo "Re-run with: sh /Volumes/REIMSHELP/install.sh --erase $nonblank_disk" >&2
exit 1
fi
elif [ $((blank_count + nonblank_count)) -gt 1 ]; then
echo "No writable target volume found under /Volumes, and multiple candidate disks exist:" >&2
printf '%s' "$all_summary" >&2
echo "Re-run with: sh /Volumes/REIMSHELP/install.sh --erase /dev/diskN" >&2
echo "Or erase your target disk in Disk Utility first." >&2
exit 1
fi
fi
fi
if [ -z "$target" ]; then
echo "No writable target volume found under /Volumes." >&2
echo "Open Disk Utility -> View -> Show All Devices -> select the largest QEMU HARDDISK Media" >&2
echo "-> Erase as APFS (GUID Partition Map, name e.g. Macintosh HD), then re-run." >&2
mount | grep /Volumes >&2 || ls /Volumes >&2
exit 1
fi
echo "Using target volume: $target"
pkg="/Volumes/Installer/InstallAssistant.pkg"
if [ ! -f "$pkg" ]; then
echo "Offline installer package not found at $pkg" >&2
ls /Volumes >&2
exit 1
fi
echo "Extracting Install macOS app onto $target..."
tar -xf /Volumes/REIMSHELP/InstallApp.tar -C "$target"
app=""
for a in "$target"/Applications/Install\ macOS*.app; do
if [ -d "$a" ]; then app=$a; fi
done
if [ -z "$app" ] || [ ! -f "$app/Contents/Resources/startosinstall" ]; then
echo "Install macOS app not found in $target/Applications after extract" >&2
exit 1
fi
shared="$app/Contents/SharedSupport"
if [ ! -f "$shared/SharedSupport.dmg" ]; then
echo "Copying InstallAssistant.pkg as SharedSupport.dmg (this takes a few minutes)..."
mkdir -p "$shared"
chmod 0755 "$shared"
cp "$pkg" "$shared/SharedSupport.dmg"
chflags -h norestricted "$shared/SharedSupport.dmg" 2>/dev/null || true
fi
chmod -R 755 "$app"
echo "Starting $app; the VM will restart automatically when ready..."
exec "$app/Contents/Resources/startosinstall" --agreetolicense --volume "$target"
`)
}
// EnsureOfflineHelperImage prepares (or reuses from cache) a small HFS Plus
// helper disk image containing InstallApp.tar + install.sh extracted from an
// offline installer image's InstallAssistant.pkg Payload.
func EnsureOfflineHelperImage(xdgCacheDir, offlineImgPath string) (string, error) {
info, err := os.Stat(offlineImgPath)
if err != nil {
return "", fmt.Errorf("stat offline installer: %w", err)
}
sum := sha256.Sum256([]byte(fmt.Sprintf("%s|%d|%d|v3", filepath.Base(offlineImgPath), info.Size(), info.ModTime().UnixNano())))
key := hex.EncodeToString(sum[:8])
helperDir := filepath.Join(xdgCacheDir, "reims-go", "offline-helpers")
helperPath := filepath.Join(helperDir, fmt.Sprintf("reims-helper-%s.img", key))
if st, err := os.Stat(helperPath); err == nil && st.Size() > 0 {
return helperPath, nil
}
f, err := os.Open(offlineImgPath)
if err != nil {
return "", fmt.Errorf("open offline installer: %w", err)
}
defer f.Close()
pkgOff, pkgSize, err := FindFileInHFSPlusImage(f, "InstallAssistant.pkg")
if err != nil {
return "", fmt.Errorf("locate InstallAssistant.pkg: %w", err)
}
if err := os.MkdirAll(helperDir, 0o755); err != nil {
return "", err
}
tarFile, err := os.CreateTemp(helperDir, "installapp-*.tar")
if err != nil {
return "", err
}
tarPath := tarFile.Name()
defer os.Remove(tarPath)
if err := ExtractPkgPayloadToTar(f, pkgOff, pkgSize, tarFile); err != nil {
_ = tarFile.Close()
return "", fmt.Errorf("extract InstallAssistant.pkg payload: %w", err)
}
if err := tarFile.Close(); err != nil {
return "", err
}
tarInfo, err := os.Stat(tarPath)
if err != nil {
return "", err
}
script := HelperInstallScript()
files := []HFSFile{
{
Name: "InstallApp.tar",
Mode: 0o100644,
Size: tarInfo.Size(),
Open: func() (io.ReadCloser, error) { return os.Open(tarPath) },
},
{
Name: "install.sh",
Mode: 0o100755,
Size: int64(len(script)),
Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(string(script))), nil },
},
}
if err := BuildHFSPlusDiskImage(helperPath, "REIMSHELP", files); err != nil {
return "", fmt.Errorf("build helper disk image: %w", err)
}
return helperPath, nil
}