Compare commits

...
10 Commits
60 changed files with 3962 additions and 395 deletions

No files matched your search

+12 -4
View File
@@ -22,6 +22,7 @@ import (
"github.com/majd/go-apfs/pkg/disk"
"github.com/majd/go-apfs/pkg/disk/dmg"
"github.com/majd/go-apfs/types"
"github.com/majd/ipatool/v2/internal/sap/machimage"
)
const (
@@ -74,7 +75,7 @@ func extractAPFSFiles(ctx context.Context, source io.ReaderAt, size int64, paths
if err := ctx.Err(); err != nil {
return fmt.Errorf("extract Apple filesystem files: %w", err)
}
if err := extractor.extractFile(ctx, path, destination); err != nil {
if err := extractor.extractImageFile(ctx, path, destination, filepath.Ext(path) != ".icxs"); err != nil {
return fmt.Errorf("extract %s from Apple filesystem: %w", path, err)
}
}
@@ -129,7 +130,7 @@ func newAPFSExtractor(source io.ReaderAt, size int64) (*apfsExtractor, func() er
return extractor, closeExtractor, nil
}
func (e *apfsExtractor) extractFile(ctx context.Context, path, destination string) (err error) {
func (e *apfsExtractor) extractImageFile(ctx context.Context, path, destination string, thin bool) (err error) {
file, err := e.openFile(ctx, path)
if err != nil {
return err
@@ -150,8 +151,15 @@ func (e *apfsExtractor) extractFile(ctx context.Context, path, destination strin
}
}()
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, 0, file.size)}
if _, err := io.CopyN(output, reader, file.size); err != nil {
offset, size := int64(0), file.size
if thin {
offset, size, err = machimage.ARM64Range(file, file.size)
if err != nil {
return fmt.Errorf("select runtime image architecture: %w", err)
}
}
reader := &contextReader{ctx: ctx, reader: io.NewSectionReader(file, offset, size)}
if _, err := io.CopyN(output, reader, size); err != nil {
return fmt.Errorf("copy file data: %w", err)
}
+173 -25
View File
@@ -1,22 +1,27 @@
package assets
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/majd/ipatool/v2/internal/sap/machimage"
)
const (
macOSVersion = "27.0.1"
macOSBuild = "26A434"
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
macOSVersion = "27.0.1"
macOSBuild = "26A434"
macOSRestoreURL = "https://updates.cdn-apple.com/2026FallFCS/59241290-5d51-4ca8-9df4-31624b9a4eac/UniversalMac_27.0.1_26A434_Restore.ipsw"
assetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v5"
legacyAssetCacheDirectory = "apple-assets-macos-27-26A434-arm64-v4"
)
type Bundle struct {
@@ -36,6 +41,16 @@ type fileSpec struct {
}
var requiredFiles = []fileSpec{
{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
}
var legacyFiles = []fileSpec{
{
name: "AppleMediaServices",
size: 14813888,
@@ -73,9 +88,21 @@ var requiredFiles = []fileSpec{
},
}
// Load resolves and caches the pinned macOS framework profile used by SAP,
// kbsync generation, and package decryption.
type bundleLoader struct {
gate chan struct{}
installed *Bundle
resolve func(context.Context) (Bundle, error)
}
var defaultLoader = bundleLoader{gate: make(chan struct{}, 1), resolve: loadBundle}
// Load resolves and verifies the pinned macOS framework profile once per process.
// The returned slices are shared and must not be modified by callers.
func Load(ctx context.Context) (Bundle, error) {
return defaultLoader.load(ctx)
}
func (l *bundleLoader) load(ctx context.Context) (Bundle, error) {
if ctx == nil {
return Bundle{}, errors.New("apple asset context is nil")
}
@@ -84,12 +111,43 @@ func Load(ctx context.Context) (Bundle, error) {
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
}
select {
case l.gate <- struct{}{}:
case <-ctx.Done():
return Bundle{}, fmt.Errorf("load Apple assets: %w", ctx.Err())
}
defer func() { <-l.gate }()
if err := ctx.Err(); err != nil {
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
}
if l.installed != nil {
return *l.installed, nil
}
bundle, err := l.resolve(ctx)
if err != nil {
return Bundle{}, err
}
if err := ctx.Err(); err != nil {
return Bundle{}, fmt.Errorf("load Apple assets: %w", err)
}
l.installed = &bundle
return bundle, nil
}
func loadBundle(ctx context.Context) (Bundle, error) {
directory, err := cacheDirectory()
if err != nil {
return Bundle{}, err
}
if bundle, err := readCache(directory); err == nil {
if bundle, found := loadCachedBundle(directory); found {
return bundle, nil
}
@@ -105,6 +163,44 @@ func Load(ctx context.Context) (Bundle, error) {
return bundle, nil
}
// Keep only the architecture used by the emulator after verifying and caching
// the original files. Cloning releases the unused slices of universal binaries.
func compactBundle(bundle Bundle) (Bundle, error) {
for _, image := range []struct {
name string
data *[]byte
}{
{"AppleMediaServices", &bundle.AppleMediaServices},
{"commerce", &bundle.Commerce},
{"adid", &bundle.ADID},
{"CoreFP", &bundle.CoreFP},
{"fairplayd", &bundle.FairPlayD},
{"FairPlayIOKit", &bundle.FairPlayKext},
} {
data, err := compactImage(image.name, *image.data)
if err != nil {
return Bundle{}, err
}
*image.data = data
}
return bundle, nil
}
func compactImage(name string, input []byte) ([]byte, error) {
data, err := machimage.ARM64Slice(input)
if err != nil {
return nil, fmt.Errorf("select %s architecture: %w", name, err)
}
if len(data) != len(input) {
return bytes.Clone(data), nil
}
return data, nil
}
func cacheDirectory() (string, error) {
root, err := os.UserCacheDir()
if err != nil {
@@ -114,11 +210,38 @@ func cacheDirectory() (string, error) {
return filepath.Join(root, "ipatool", "sap", assetCacheDirectory), nil
}
func readCache(directory string) (Bundle, error) {
files := make(map[string][]byte, len(requiredFiles))
func loadCachedBundle(directory string) (Bundle, bool) {
if bundle, err := readCache(directory); err == nil {
return bundle, true
}
for _, spec := range requiredFiles {
data, err := readCacheFile(filepath.Join(directory, spec.name), spec.size)
legacyDirectory := filepath.Join(filepath.Dir(directory), legacyAssetCacheDirectory)
bundle, err := readCacheSpecs(legacyDirectory, legacyFiles)
if err != nil {
return Bundle{}, false
}
if err := validate(bundle); err != nil {
return Bundle{}, false
}
// A verified legacy cache remains usable on read-only mounts. Persist the
// smaller representation when possible without requiring a new download.
_ = writeCache(directory, bundle)
return bundle, true
}
func readCache(directory string) (Bundle, error) {
return readCacheSpecs(directory, requiredFiles)
}
func readCacheSpecs(directory string, specs []fileSpec) (Bundle, error) {
files := make(map[string][]byte, len(specs))
for _, spec := range specs {
data, err := readCacheData(filepath.Join(directory, spec.name), spec.size, &spec)
if err != nil {
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
}
@@ -126,15 +249,14 @@ func readCache(directory string) (Bundle, error) {
files[spec.name] = data
}
bundle := bundleFrom(files)
if err := validate(bundle); err != nil {
return Bundle{}, err
}
return bundle, nil
return bundleFrom(files), nil
}
func readCacheFile(path string, expectedSize int) ([]byte, error) {
return readCacheData(path, expectedSize, nil)
}
func readCacheData(path string, expectedSize int, spec *fileSpec) ([]byte, error) {
if expectedSize < 0 {
return nil, errors.New("invalid expected size")
}
@@ -155,8 +277,23 @@ func readCacheFile(path string, expectedSize int) ([]byte, error) {
return nil, fmt.Errorf("has size %d, expected %d", info.Size(), expectedSize)
}
data := make([]byte, expectedSize)
if _, err := io.ReadFull(file, data); err != nil {
var reader io.Reader = file
var digest hash.Hash
if spec != nil {
digest = sha256.New()
reader = io.TeeReader(file, digest)
}
var data []byte
if spec != nil && spec.name != "CoreFP.icxs" {
data, err = machimage.ReadARM64(reader, expectedSize)
} else {
data = make([]byte, expectedSize)
_, err = io.ReadFull(reader, data)
}
if err != nil {
return nil, fmt.Errorf("read cached asset: %w", err)
}
@@ -167,6 +304,10 @@ func readCacheFile(path string, expectedSize int) ([]byte, error) {
return nil, fmt.Errorf("verify cached asset length: %w", err)
}
if spec != nil && !bytes.Equal(digest.Sum(nil), spec.digest[:]) {
return nil, fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
}
return data, nil
}
@@ -232,14 +373,21 @@ func replaceFile(path string, data []byte) error {
func validate(bundle Bundle) error {
files := bundleFiles(bundle)
for _, spec := range requiredFiles {
data := files[spec.name]
if len(data) != spec.size {
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
if err := validateFile(spec, files[spec.name]); err != nil {
return err
}
}
if sha256.Sum256(data) != spec.digest {
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
}
return nil
}
func validateFile(spec fileSpec, data []byte) error {
if len(data) != spec.size {
return fmt.Errorf("apple SAP asset %s has size %d, expected %d", spec.name, len(data), spec.size)
}
if sha256.Sum256(data) != spec.digest {
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
}
return nil
+122
View File
@@ -0,0 +1,122 @@
package assets
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Verified bundle cache", func() {
It("shares one successful load across concurrent callers", func() {
var calls atomic.Int32
entered, release := make(chan struct{}), make(chan struct{})
data := []byte("verified bundle")
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls.Add(1)
close(entered)
<-release
return Bundle{CoreFP: data}, nil
}}
var workers sync.WaitGroup
results := make(chan Bundle, 8)
failures := make(chan error, 8)
for range 8 {
workers.Go(func() {
bundle, err := loader.load(context.Background())
results <- bundle
failures <- err
})
}
Eventually(entered).Should(BeClosed())
close(release)
workers.Wait()
Expect(calls.Load()).To(Equal(int32(1)))
for range 8 {
Expect(<-failures).NotTo(HaveOccurred())
Expect(&(<-results).CoreFP[0]).To(BeIdenticalTo(&data[0]))
}
})
It("lets a waiting caller cancel without interrupting the load", func() {
entered, release := make(chan struct{}), make(chan struct{})
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
close(entered)
<-release
return Bundle{CoreFP: []byte("ready")}, nil
}}
done := make(chan error, 1)
go func() { _, err := loader.load(context.Background()); done <- err }()
Eventually(entered).Should(BeClosed())
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
_, err := loader.load(ctx)
Expect(errors.Is(err, context.DeadlineExceeded)).To(BeTrue())
close(release)
Eventually(done).Should(Receive(BeNil()))
bundle, err := loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(string(bundle.CoreFP)).To(Equal("ready"))
})
It("retries failed loads", func() {
calls := 0
failed := errors.New("temporary failure")
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls++
if calls == 1 {
return Bundle{}, failed
}
return Bundle{CoreFP: []byte("ready")}, nil
}}
_, err := loader.load(context.Background())
Expect(err).To(MatchError(failed))
bundle, err := loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(string(bundle.CoreFP)).To(Equal("ready"))
Expect(calls).To(Equal(2))
})
It("does not publish a load canceled before completion", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := 0
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls++
cancel()
return Bundle{CoreFP: []byte("ready")}, nil
}}
_, err := loader.load(ctx)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(loader.installed).To(BeNil())
_, err = loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
Expect(calls).To(Equal(2))
})
It("rejects nil and canceled contexts even after a successful load", func() {
calls := 0
loader := bundleLoader{gate: make(chan struct{}, 1), resolve: func(context.Context) (Bundle, error) {
calls++
return Bundle{}, nil
}}
_, err := loader.load(nil) //nolint:staticcheck // Verify invalid caller input.
Expect(err).To(MatchError(ContainSubstring("context is nil")))
_, err = loader.load(context.Background())
Expect(err).NotTo(HaveOccurred())
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = loader.load(ctx)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(calls).To(Equal(1))
})
})
+68
View File
@@ -0,0 +1,68 @@
package assets
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"os"
"path/filepath"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Runtime bundle compaction", func() {
It("retains independent arm64e images and preserves thin images and ICXS", func() {
fat := make([]byte, 32)
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
binary.BigEndian.PutUint32(fat[i*4:], value)
}
copy(fat[28:], "arm!")
thin, icxs := []byte("thin"), []byte("ICXS")
bundle := Bundle{CoreFP: fat, Commerce: fat, ADID: fat, FairPlayD: fat, AppleMediaServices: thin, FairPlayKext: thin, CoreFPICXS: icxs}
original := bytes.Clone(fat)
compact, err := compactBundle(bundle)
Expect(err).NotTo(HaveOccurred())
for _, data := range [][]byte{compact.CoreFP, compact.Commerce, compact.ADID, compact.FairPlayD} {
Expect(string(data)).To(Equal("arm!"))
Expect(&data[0]).NotTo(BeIdenticalTo(&fat[28]))
Expect(cap(data)).To(BeNumerically("<", len(fat)))
}
Expect(&compact.AppleMediaServices[0]).To(BeIdenticalTo(&thin[0]))
Expect(&compact.FairPlayKext[0]).To(BeIdenticalTo(&thin[0]))
Expect(&compact.CoreFPICXS[0]).To(BeIdenticalTo(&icxs[0]))
Expect(fat).To(Equal(original))
Expect(bundle.CoreFP).To(HaveLen(32))
})
It("verifies the entire cached file before discarding unused architectures", func() {
fat := make([]byte, 40)
for i, value := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
binary.BigEndian.PutUint32(fat[i*4:], value)
}
copy(fat[28:], "arm!unused!!")
originalSpecs := requiredFiles
DeferCleanup(func() { requiredFiles = originalSpecs })
requiredFiles = []fileSpec{{name: "CoreFP", size: len(fat), digest: sha256.Sum256(fat)}}
directory := GinkgoT().TempDir()
path := filepath.Join(directory, "CoreFP")
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
bundle, err := readCache(directory)
Expect(err).NotTo(HaveOccurred())
Expect(string(bundle.CoreFP)).To(Equal("arm!"))
cached, err := os.ReadFile(path)
Expect(err).NotTo(HaveOccurred())
Expect(cached).To(Equal(fat))
fat[len(fat)-1] ^= 0xff
Expect(os.WriteFile(path, fat, 0o600)).To(Succeed())
_, err = readCache(directory)
Expect(err).To(MatchError(ContainSubstring("failed integrity verification")))
})
It("rejects invalid universal images", func() {
fat := make([]byte, 4)
binary.BigEndian.PutUint32(fat, types.MagicFat.Int())
_, err := compactBundle(Bundle{CoreFP: fat})
Expect(err).To(MatchError(ContainSubstring("select CoreFP architecture")))
})
})
+172
View File
@@ -0,0 +1,172 @@
package assets
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Buffered remote ranges", func() {
var source []byte
var remote *remoteFile
var requests []string
var mu sync.Mutex
BeforeEach(func() {
source = make([]byte, 1<<20)
for n := range source {
source[n] = byte(n % 251)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
requests = append(requests, r.Header.Get("Range"))
mu.Unlock()
http.ServeContent(w, r, "image", time.Time{}, bytes.NewReader(source))
}))
DeferCleanup(server.Close)
requests = nil
remote = &remoteFile{ctx: context.Background(), client: server.Client(), url: server.URL, size: int64(len(source))}
})
It("serves a small sequential stream in bounded larger transfers", func() {
output := make([]byte, len(source))
for offset := 0; offset < len(output); offset += 4096 {
count, err := remote.ReadAt(output[offset:offset+4096], int64(offset))
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(4096))
}
Expect(output).To(Equal(source))
mu.Lock()
count := len(requests)
mu.Unlock()
Expect(count).To(Equal(5))
Expect(len(remote.cache)).To(BeNumerically("<=", remoteReadAheadSize))
})
It("keeps sparse metadata requests exact", func() {
for _, offset := range []int64{0, 500000, 900000} {
output := make([]byte, 8)
_, err := remote.ReadAt(output, offset)
Expect(err).NotTo(HaveOccurred())
Expect(output).To(Equal(source[offset : offset+8]))
}
mu.Lock()
defer mu.Unlock()
Expect(requests).To(Equal([]string{"bytes=0-7", "bytes=500000-500007", "bytes=900000-900007"}))
})
It("isolates cached bytes from caller mutation and reports EOF correctly", func() {
data := make([]byte, 4096)
_, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
clear(data)
_, err = remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
Expect(data).To(Equal(source[:4096]))
tail := make([]byte, 32)
count, err := remote.ReadAt(tail, int64(len(source)-16))
Expect(err).To(MatchError(io.EOF))
Expect(count).To(Equal(16))
Expect(tail[:count]).To(Equal(source[len(source)-16:]))
})
It("honors cancellation even when data is buffered", func() {
ctx, cancel := context.WithCancel(context.Background())
remote.ctx = ctx
data := make([]byte, 32)
_, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
cancel()
_, err = remote.ReadAt(data, 0)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
})
It("supports concurrent independent reads", func() {
finished := make(chan error, 8)
for n := range 8 {
go func() {
offset := int64(n * 40000)
output := make([]byte, 4096)
_, err := remote.ReadAt(output, offset)
if err == nil && !bytes.Equal(output, source[offset:offset+4096]) {
err = errors.New("incorrect concurrent range")
}
finished <- err
}()
}
for range 8 {
Eventually(finished).Should(Receive(BeNil()))
}
})
})
var _ = Describe("Interrupted remote responses", func() {
It("resumes a short response at the first unread byte", func() {
var ranges []string
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
ranges = append(ranges, r.Header.Get("Range"))
if len(ranges) == 1 {
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-7/8"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
}
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 4-7/8"}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
})}}
data := make([]byte, 8)
count, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(8))
Expect(string(data)).To(Equal("abcdefgh"))
Expect(ranges).To(Equal([]string{"bytes=0-7", "bytes=4-7"}))
})
It("rejects incorrect response ranges without caching them", func() {
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 8, client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 1-7/8"}}, Body: io.NopCloser(strings.NewReader("1234567"))}, nil
})}}
_, err := remote.ReadAt(make([]byte, 8), 0)
Expect(err).To(MatchError(ContainSubstring("server returned bytes")))
Expect(remote.cache).To(BeEmpty())
})
It("does not fail a completed requested prefix when speculative tail reads fail", func() {
remote := &remoteFile{ctx: context.Background(), url: "https://example.test/image", size: 1 << 20}
calls := 0
remote.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
calls++
switch calls {
case 1:
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-3/1048576"}}, Body: io.NopCloser(strings.NewReader("abcd"))}, nil
case 2:
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{fmt.Sprintf("bytes 4-%d/1048576", 4+remoteReadAheadSize-1)}}, Body: io.NopCloser(strings.NewReader("efgh"))}, nil
default:
return nil, errors.New("connection interrupted")
}
})}
data := make([]byte, 4)
_, err := remote.ReadAt(data, 0)
Expect(err).NotTo(HaveOccurred())
count, err := remote.ReadAt(data, 4)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(4))
Expect(string(data)).To(Equal("efgh"))
Expect(remote.cacheOffset).To(BeZero())
Expect(remote.cache).To(HaveLen(4))
})
})
var _ = Describe("Remote image size probes", func() {
DescribeTable("requires exactly the requested byte", func(body string, valid bool) {
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusPartialContent, Header: http.Header{"Content-Range": []string{"bytes 0-0/123"}}, Body: io.NopCloser(strings.NewReader(body))}, nil
})}
remote, err := openRemoteFile(context.Background(), client)
if valid {
Expect(err).NotTo(HaveOccurred())
Expect(remote.size).To(Equal(int64(123)))
} else {
Expect(err).To(MatchError(ContainSubstring("probe has an invalid length")))
}
}, Entry("one byte", "x", true), Entry("empty body", "", false), Entry("too much data", "xx", false))
})
+84 -9
View File
@@ -1,6 +1,7 @@
package assets
import (
"bytes"
"context"
"errors"
"fmt"
@@ -8,15 +9,26 @@ import (
"net/http"
"strconv"
"strings"
"sync"
)
const remoteReadAttempts = 3
const (
remoteReadAttempts = 3
restoreImageUserAgent = "Mozilla/5.0"
remoteSmallReadSize = 32 << 10
remoteReadAheadSize = 256 << 10
)
type remoteFile struct {
ctx context.Context
client *http.Client
url string
size int64
ctx context.Context
client *http.Client
url string
size int64
mu sync.Mutex
cache []byte
cacheOffset int64
previous bool
lastEnd int64
}
//nolint:wsl // Request construction and validation are clearer in protocol order.
@@ -26,6 +38,7 @@ func openRemoteFile(ctx context.Context, client *http.Client) (*remoteFile, erro
return nil, fmt.Errorf("create remote image request: %w", err)
}
request.Header.Set("User-Agent", restoreImageUserAgent)
request.Header.Set("Range", "bytes=0-0")
response, err := client.Do(request)
@@ -47,6 +60,14 @@ func openRemoteFile(ctx context.Context, client *http.Client) (*remoteFile, erro
return nil, fmt.Errorf("open remote image: server returned unexpected byte range %d-%d", start, end)
}
probe, err := io.ReadAll(io.LimitReader(response.Body, 2))
if err != nil {
return nil, fmt.Errorf("read remote image probe: %w", err)
}
if len(probe) != 1 {
return nil, errors.New("remote image probe has an invalid length")
}
return &remoteFile{ctx: ctx, client: client, url: macOSRestoreURL, size: size}, nil
}
@@ -97,6 +118,60 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
wanted = int(remaining)
}
if err := r.ctx.Err(); err != nil {
return 0, fmt.Errorf("read remote image: %w", err)
}
r.mu.Lock()
if offset >= r.cacheOffset && offset+int64(wanted) <= r.cacheOffset+int64(len(r.cache)) {
copy(data[:wanted], r.cache[offset-r.cacheOffset:offset-r.cacheOffset+int64(wanted)])
r.previous, r.lastEnd = true, offset+int64(wanted)
r.mu.Unlock()
if wanted != len(data) {
return wanted, io.EOF
}
return wanted, nil
}
// Sparse metadata reads stay exact; only a sequential small-read stream
// earns read-ahead. This avoids fetching large unused image regions.
ahead := r.previous && offset == r.lastEnd && wanted <= remoteSmallReadSize
r.previous, r.lastEnd = true, offset+int64(wanted)
r.mu.Unlock()
fetchSize := wanted
if ahead {
fetchSize = int(min(int64(remoteReadAheadSize), r.size-offset))
}
buffer := data[:wanted]
if fetchSize > wanted {
buffer = make([]byte, fetchSize)
}
count, err := r.readRange(buffer, offset)
if count == fetchSize && err == nil && fetchSize <= remoteReadAheadSize {
cached := buffer
if fetchSize == wanted {
cached = bytes.Clone(buffer)
}
r.mu.Lock()
r.cacheOffset, r.cache = offset, cached
r.mu.Unlock()
}
if fetchSize > wanted {
copy(data[:wanted], buffer[:min(count, wanted)])
}
if count < wanted {
return count, err
}
if wanted != len(data) {
return wanted, io.EOF
}
return wanted, nil
}
// Read and validate one wire range, resuming interrupted bodies as needed.
func (r *remoteFile) readRange(data []byte, offset int64) (int, error) {
wanted := len(data)
total := 0
var lastErr error
@@ -110,7 +185,9 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
return total, fmt.Errorf("create remote range request: %w", err)
}
request.Header.Set("User-Agent", restoreImageUserAgent)
request.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
response, err := r.client.Do(request)
if err != nil {
lastErr = err
@@ -123,10 +200,12 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
return total, fmt.Errorf("read remote image range: server returned %s", response.Status)
}
actualStart, actualEnd, actualSize, err := parseContentRange(response.Header.Get("Content-Range"))
if err != nil || actualStart != start || actualEnd != end || actualSize != r.size {
response.Body.Close()
if err != nil {
return total, fmt.Errorf("read remote image range: %w", err)
}
@@ -155,9 +234,5 @@ func (r *remoteFile) ReadAt(data []byte, offset int64) (int, error) {
return total, fmt.Errorf("read remote image at offset %d: %w", offset+int64(total), lastErr)
}
if wanted != len(data) {
return total, io.EOF
}
return total, nil
}
+56
View File
@@ -0,0 +1,56 @@
package assets
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return function(request)
}
var _ = Describe("remote image HTTP requests", func() {
It("reads image ranges from a server requiring a browser-compatible user agent", func() {
const content = "restore image"
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if request.UserAgent() != "Mozilla/5.0" {
http.Error(response, "unsupported user agent", http.StatusForbidden)
return
}
http.ServeContent(response, request, "restore.ipsw", time.Time{}, strings.NewReader(content))
}))
DeferCleanup(server.Close)
transport := &http.Transport{}
DeferCleanup(transport.CloseIdleConnections)
client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
request = request.Clone(request.Context())
request.URL.Scheme = "http"
request.URL.Host = server.Listener.Addr().String()
return transport.RoundTrip(request)
})}
remote, err := openRemoteFile(context.Background(), client)
Expect(err).NotTo(HaveOccurred())
Expect(remote.size).To(Equal(int64(len(content))))
data := make([]byte, len(content)-1)
count, err := remote.ReadAt(data, 1)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(len(data)))
Expect(string(data)).To(Equal(content[1:]))
})
})
+79
View File
@@ -0,0 +1,79 @@
package assets
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"os"
"path/filepath"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Compact asset cache migration", func() {
var directory, legacyDirectory string
var source, selected []byte
BeforeEach(func() {
root := GinkgoT().TempDir()
directory = filepath.Join(root, assetCacheDirectory)
legacyDirectory = filepath.Join(root, legacyAssetCacheDirectory)
source = make([]byte, 40)
for n, v := range []uint32{types.MagicFat.Int(), 1, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 28, 4, 0} {
binary.BigEndian.PutUint32(source[n*4:], v)
}
copy(source[28:], "arm!unused!")
selected = []byte("arm!")
originalRequired, originalLegacy := requiredFiles, legacyFiles
DeferCleanup(func() { requiredFiles, legacyFiles = originalRequired, originalLegacy })
requiredFiles = []fileSpec{{name: "CoreFP", size: len(selected), digest: sha256.Sum256(selected)}}
legacyFiles = []fileSpec{{name: "CoreFP", size: len(source), digest: sha256.Sum256(source)}}
Expect(os.MkdirAll(legacyDirectory, 0o700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), source, 0o600)).To(Succeed())
})
It("verifies legacy files and writes only the selected architecture", func() {
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
migrated, err := os.ReadFile(filepath.Join(directory, "CoreFP"))
Expect(err).NotTo(HaveOccurred())
Expect(migrated).To(Equal(selected))
old, err := os.ReadFile(filepath.Join(legacyDirectory, "CoreFP"))
Expect(err).NotTo(HaveOccurred())
Expect(old).To(Equal(source))
})
It("uses a compact cache without requiring the old files", func() {
Expect(writeCache(directory, Bundle{CoreFP: selected})).To(Succeed())
Expect(os.RemoveAll(legacyDirectory)).To(Succeed())
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
})
It("rejects corrupt discarded legacy bytes", func() {
corrupt := bytes.Clone(source)
corrupt[len(corrupt)-1] ^= 0xff
Expect(os.WriteFile(filepath.Join(legacyDirectory, "CoreFP"), corrupt, 0o600)).To(Succeed())
_, found := loadCachedBundle(directory)
Expect(found).To(BeFalse())
})
It("repairs corrupt compact data from a valid old cache", func() {
Expect(os.MkdirAll(directory, 0o700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(directory, "CoreFP"), []byte("bad!"), 0o600)).To(Succeed())
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
})
It("keeps valid legacy data usable when the compact cache cannot be written", func() {
Expect(os.WriteFile(directory, []byte("not a directory"), 0o600)).To(Succeed())
bundle, found := loadCachedBundle(directory)
Expect(found).To(BeTrue())
Expect(bundle.CoreFP).To(Equal(selected))
})
It("rejects a legacy slice that does not match the new pin", func() {
requiredFiles[0].digest = sha256.Sum256([]byte("bad!"))
_, found := loadCachedBundle(directory)
Expect(found).To(BeFalse())
})
})
+4 -1
View File
@@ -82,7 +82,10 @@ func resolveRemoteImage(ctx context.Context) (Bundle, error) {
files[spec.name] = data
}
bundle := bundleFrom(files)
bundle, err := compactBundle(bundleFrom(files))
if err != nil {
return Bundle{}, err
}
if err := validate(bundle); err != nil {
return Bundle{}, err
}
+14 -2
View File
@@ -15,8 +15,8 @@ var _ = Describe("macOS 27 asset profile", func() {
Expect(assetCacheDirectory).To(ContainSubstring("macos-27-26A434"))
})
It("pins every runtime artifact by size and digest", func() {
Expect(requiredFiles).To(ConsistOf(
It("preserves the pinned legacy artifacts for migration", func() {
Expect(legacyFiles).To(ConsistOf(
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
fileSpec{name: "commerce", size: 8092640, digest: mustDigest("76de40a4a32f691947cb926ce3b128d2fc446f7cac9755f831c406cf5a316ac9")},
fileSpec{name: "adid", size: 9797952, digest: mustDigest("1fec225b6917206e3d9b00fe636c04878f82bfd06a87a4b6941711de60efab5b")},
@@ -27,6 +27,18 @@ var _ = Describe("macOS 27 asset profile", func() {
))
})
It("pins compact runtime artifacts by size and digest", func() {
Expect(requiredFiles).To(ConsistOf(
fileSpec{name: "AppleMediaServices", size: 14813888, digest: mustDigest("95f4558aa2c0ccd9f96ed479e336b630b46bf4b4e0baabc1c1ac8c7d55e21ab4")},
fileSpec{name: "commerce", size: 2735088, digest: mustDigest("c4b2088dd39aeb353f59cb57597902e8317aec66ae7da0414b03c5f932771343")},
fileSpec{name: "adid", size: 3047808, digest: mustDigest("43419a206c28bc93ecb8884256088d18306a0a462350f83adbced8e60a94e390")},
fileSpec{name: "CoreFP", size: 30764976, digest: mustDigest("afbc123e688a822d980d5816cc2b52f69fde669d1dca92cf85627e1cbee587f6")},
fileSpec{name: "CoreFP.icxs", size: 7365344, digest: mustDigest("cb8f55330ec567da3e692dab5f5388bed0312dd9093340477c5759078cc2aa7b")},
fileSpec{name: "fairplayd", size: 17389744, digest: mustDigest("1e58d37e9602dd0ca5e24b14762063b6c310248b4d3a94272771d815e4ea1784")},
fileSpec{name: "FairPlayIOKit", size: 2132320, digest: mustDigest("47452960ec010d3a80b02cceec73a65f8a9758850fd0fb7b2fdac7a5d1b81025")},
))
})
It("pins the CoreADI path and deflated kernel entry", func() {
Expect(frameworkImagePaths).To(ContainElement("/System/Library/PrivateFrameworks/CoreADI.framework/Versions/A/adid"))
archive := &zip.Reader{File: []*zip.File{{FileHeader: zip.FileHeader{
+200 -61
View File
@@ -2,9 +2,11 @@ package machimage
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"sort"
@@ -33,16 +35,19 @@ type segment struct {
}
type Image struct {
name string
data []byte
file *macho.File
base uint64
segments []segment
binds []types.Bind
rebases []types.Rebase
chained *fixupchains.DyldChainedFixups
relocated bool
loadedBase uint64
name string
data []byte
modified map[uint64][]byte
instructions map[uint64][]instructionPatch
file *macho.File
base uint64
segments []segment
binds []types.Bind
rebases []types.Rebase
chained *fixupchains.DyldChainedFixups
fixups []chainedRelocation
relocated bool
loadedBase uint64
}
func (i *Image) Base() uint64 {
@@ -56,7 +61,41 @@ func Open(name string, input []byte) (*Image, error) {
return nil, fmt.Errorf("open %s: %w", name, err)
}
file, err := macho.NewFile(bytes.NewReader(data))
return openImage(name, data, nil)
}
func openImage(name string, data []byte, modified map[uint64][]byte) (*Image, error) {
image := &Image{name: name, data: data, modified: modified}
var reader io.ReaderAt = bytes.NewReader(data)
if modified != nil {
reader = imageInput{image}
}
var key [sha256.Size]byte
var preparation imagePreparation
var cached bool
if modified != nil {
key = sha256.Sum256(data)
preparation, cached = imagePreparations.get(key)
}
var file *macho.File
var err error
if cached {
file, err = macho.NewFile(reader, macho.FileConfig{LoadExcluding: []types.LoadCmd{types.LC_SYMTAB, types.LC_DYSYMTAB, types.LC_CODE_SIGNATURE}})
if err == nil {
file.Symtab, file.Dysymtab = preparation.symtab, preparation.dysymtab
}
} else {
file, err = macho.NewFile(reader)
}
if err != nil {
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
}
@@ -65,12 +104,9 @@ func Open(name string, input []byte) (*Image, error) {
return nil, fmt.Errorf("open %s: expected arm64 Mach-O, found %s", name, file.CPU)
}
image := &Image{
name: name,
data: data,
file: file,
base: file.GetBaseAddress(),
}
image.file = file
image.base = file.GetBaseAddress()
for _, item := range file.Segments() {
image.segments = append(image.segments, segment{
name: item.Name,
@@ -84,6 +120,14 @@ func Open(name string, input []byte) (*Image, error) {
if err := image.validateSegments(); err != nil {
return nil, err
}
if cached {
image.instructions, image.fixups = preparation.instructions, preparation.fixups
image.binds, image.rebases = preparation.binds, preparation.rebases
return image, nil
}
if err := image.removePointerAuthentication(); err != nil {
return nil, err
}
@@ -109,26 +153,50 @@ func Open(name string, input []byte) (*Image, error) {
}
}
if modified != nil {
if image.chained != nil {
image.fixups, err = image.decodeChainedRelocations()
if err != nil {
return nil, err
}
image.chained = nil
}
imagePreparations.put(key, imagePreparation{instructions: image.instructions, fixups: image.fixups, binds: image.binds, rebases: image.rebases, symtab: file.Symtab, dysymtab: file.Dysymtab})
}
return image, nil
}
//nolint:wsl // Instruction decoding is clearer when related operations stay together.
func (i *Image) removePointerAuthentication() error {
var ranges [][2]uint64
for _, section := range i.file.Sections {
if !section.Flags.IsPureInstructions() && !section.Flags.IsSomeInstructions() {
continue
}
start := uint64(section.Offset)
end, overflow := add(start, section.Size)
if overflow || end > uint64(len(i.data)) {
return fmt.Errorf("instruction section %s exceeds %s", section.Name, i.name)
}
for offset := start; offset+4 <= end; offset += 4 {
ranges = append(ranges, [2]uint64{start, end})
}
for _, region := range ranges {
for offset := region[0]; offset+4 <= region[1]; offset += 4 {
instruction := binary.LittleEndian.Uint32(i.data[offset:])
replacement := WithoutPointerAuthentication(instruction)
if replacement != instruction {
binary.LittleEndian.PutUint32(i.data[offset:], replacement)
if replacement == instruction {
continue
}
i.writeInstruction(offset, replacement)
}
}
@@ -177,28 +245,55 @@ func WithoutPointerAuthentication(instruction uint32) uint32 {
return replacement
}
func arm64Slice(input []byte) ([]byte, error) {
fat, err := macho.NewFatFile(bytes.NewReader(input))
if err != nil {
return bytes.Clone(input), nil
// ARM64Slice selects the arm64e image without parsing the other architectures.
// The returned view aliases input and must not be modified by the caller.
func ARM64Slice(input []byte) ([]byte, error) {
if len(input) < 4 || binary.BigEndian.Uint32(input) != types.MagicFat.Int() {
return input, nil
}
for _, architecture := range fat.Arches {
if architecture.CPU != types.CPUArm64 || architecture.SubCPU&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
const headerSize, architectureSize = 8, 20
if len(input) < headerSize {
return nil, errors.New("truncated universal binary header")
}
count := uint64(binary.BigEndian.Uint32(input[4:]))
if count == 0 || count > uint64(len(input)-headerSize)/architectureSize {
return nil, errors.New("invalid universal binary architecture count")
}
for index := uint64(0); index < count; index++ {
header := input[headerSize+index*architectureSize:]
cpu := types.CPU(binary.BigEndian.Uint32(header))
subtype := types.CPUSubtype(binary.BigEndian.Uint32(header[4:]))
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
continue
}
end, overflow := add(uint64(architecture.Offset), uint64(architecture.Size))
if overflow || end > uint64(len(input)) {
return nil, errors.New("arm64e slice exceeds input size")
offset := uint64(binary.BigEndian.Uint32(header[8:]))
size := uint64(binary.BigEndian.Uint32(header[12:]))
end, overflow := add(offset, size)
if size == 0 || offset < headerSize+count*architectureSize || overflow || end > uint64(len(input)) {
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
}
return bytes.Clone(input[architecture.Offset:end]), nil
return input[offset:end], nil
}
return nil, errors.New("universal binary has no arm64e slice")
}
func arm64Slice(input []byte) ([]byte, error) {
data, err := ARM64Slice(input)
if err != nil {
return nil, err
}
return bytes.Clone(data), nil
}
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
address, err := i.file.FindSymbolAddress(name)
if err != nil {
@@ -313,7 +408,7 @@ func (i *Image) RelocateKernelCachePointers(loadBase, kernelBase uint64, resolve
end := item.fileOff + item.fileSize
for offset := start; offset <= end-pointerSize; offset += kernelFixupStride {
raw := binary.LittleEndian.Uint64(i.data[offset : offset+pointerSize])
raw := i.pointerAt(offset)
pointer := fixupchains.DyldChainedPtr64KernelCacheRebase{Pointer: raw}
if pointer.CacheLevel() != 0 || pointer.Target() == 0 {
@@ -362,19 +457,20 @@ func (i *Image) containsAddress(address uint64) bool {
}
//nolint:wsl // Chained-fixup decoding is clearer when related operations stay together.
func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
func (i *Image) decodeChainedRelocations() ([]chainedRelocation, error) {
if i.chained == nil {
return nil
return nil, nil
}
var relocations []chainedRelocation
for _, start := range i.chained.Starts {
for _, fixup := range start.Fixups {
offset := fixup.Offset()
if offset > uint64(len(i.data)) || pointerSize > uint64(len(i.data))-offset {
return fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
return nil, fmt.Errorf("chained fixup at %#x exceeds %s", offset, i.name)
}
var address uint64
relocation := chainedRelocation{offset: offset}
switch {
case fixup.IsRebase():
@@ -391,7 +487,7 @@ func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, e
if i.chained.PointerFormat == fixupchains.DYLD_CHAINED_PTR_ARM64E {
absolute := rebase.UnpackTarget() & 0x00ffffffffffffff
if absolute < i.base {
return fmt.Errorf("chained rebase at %#x precedes the base of %s", offset, i.name)
return nil, fmt.Errorf("chained rebase at %#x precedes the base of %s", offset, i.name)
}
target = absolute - i.base
}
@@ -402,28 +498,19 @@ func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, e
target, err = i.chained.Rebase(offset, i.base)
if err != nil {
return fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
return nil, fmt.Errorf("decode chained rebase at %#x in %s: %w", offset, i.name, err)
}
}
var overflow bool
address, overflow = add(loadBase, target)
if overflow {
return fmt.Errorf("chained rebase at %#x with target %#x, image base %#x, load base %#x, format %s, and type %T overflows in %s", offset, target, i.base, loadBase, i.chained.PointerFormat, fixup, i.name)
}
relocation.target = target
case fixup.IsBind():
binding, ok := fixup.(fixupchains.Bind)
if !ok {
return fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
return nil, fmt.Errorf("invalid chained bind at %#x in %s", offset, i.name)
}
var err error
address, err = resolve(binding.Name())
if err != nil {
return fmt.Errorf("resolve %s for %s: %w", binding.Name(), i.name, err)
}
relocation.isBind = true
relocation.symbol = binding.Name()
addend := int64(binding.Addend())
switch arm64e := fixup.(type) {
@@ -436,17 +523,54 @@ func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, e
addend += int64(i.chained.Imports[ordinal].Addend())
}
address, err = addSigned(address, addend)
if err != nil {
return fmt.Errorf("apply chained addend for %s in %s: %w", binding.Name(), i.name, err)
}
relocation.addend = addend
default:
return fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
return nil, fmt.Errorf("unknown chained fixup at %#x in %s", offset, i.name)
}
if err := i.putPointer(offset, address); err != nil {
return err
relocations = append(relocations, relocation)
}
}
return relocations, nil
}
func (i *Image) relocateChained(loadBase uint64, resolve func(string) (uint64, error)) error {
relocations := i.fixups
if i.chained != nil {
var err error
relocations, err = i.decodeChainedRelocations()
if err != nil {
return err
}
}
for _, relocation := range relocations {
var address uint64
if relocation.isBind {
value, err := resolve(relocation.symbol)
if err != nil {
return fmt.Errorf("resolve %s for %s: %w", relocation.symbol, i.name, err)
}
address, err = addSigned(value, relocation.addend)
if err != nil {
return fmt.Errorf("apply chained addend for %s in %s: %w", relocation.symbol, i.name, err)
}
} else {
var overflow bool
address, overflow = add(loadBase, relocation.target)
if overflow {
return fmt.Errorf("chained rebase at %#x with target %#x overflows in %s", relocation.offset, relocation.target, i.name)
}
}
if err := i.putPointer(relocation.offset, address); err != nil {
return err
}
}
@@ -473,6 +597,13 @@ func (i *Image) PreparePrelinked(external map[uint64]string, resolve func(string
patched[address] = value
}
if len(patched) == 0 {
i.relocated = true
i.loadedBase = i.base
return nil
}
for _, item := range i.segments {
if item.name == "__TEXT" || item.name == "__LINKEDIT" || item.fileSize < pointerSize {
continue
@@ -485,7 +616,7 @@ func (i *Image) PreparePrelinked(external map[uint64]string, resolve func(string
end := item.fileOff + item.fileSize
for offset := start; offset <= end-pointerSize; offset += pointerSize {
current := binary.LittleEndian.Uint64(i.data[offset : offset+pointerSize])
current := i.pointerAt(offset)
value, ok := patched[current]
if !ok {
@@ -571,6 +702,11 @@ func (i *Image) Load(memory Memory) error {
}
}
var buffer []byte
if len(i.modified) > 0 || len(i.instructions) > 0 {
buffer = make([]byte, min(128<<10, len(i.data)))
}
for _, item := range i.segments {
if item.name == "__PAGEZERO" || item.fileSize == 0 {
continue
@@ -586,7 +722,7 @@ func (i *Image) Load(memory Memory) error {
return fmt.Errorf("segment %s address overflows in %s", item.name, i.name)
}
if err := memory.MemWrite(address, i.data[item.fileOff:end]); err != nil {
if err := i.writeSegment(memory, address, item.fileOff, end, buffer); err != nil {
return fmt.Errorf("write segment %s from %s: %w", item.name, i.name, err)
}
}
@@ -650,7 +786,10 @@ func (i *Image) putPointer(offset, value uint64) error {
return fmt.Errorf("fixup at %#x exceeds %s", offset, i.name)
}
binary.LittleEndian.PutUint64(i.data[offset:end], value)
var data [8]byte
binary.LittleEndian.PutUint64(data[:], value)
i.writeAt(offset, data[:])
return nil
}
+26
View File
@@ -0,0 +1,26 @@
package machimage
import "github.com/blacktop/go-macho"
// Symbols returns the immutable symbol table used for guest exports and ivars.
// Callers must not modify the returned slice.
func (i *Image) Symbols() []macho.Symbol {
if i.file.Symtab == nil {
return nil
}
return i.file.Symtab.Syms
}
// InstructionRanges returns the guest's executable section address ranges.
func (i *Image) InstructionRanges() [][2]uint64 {
var ranges [][2]uint64
for _, section := range i.file.Sections {
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
ranges = append(ranges, [2]uint64{section.Addr, section.Addr + section.Size})
}
}
return ranges
}
+112
View File
@@ -0,0 +1,112 @@
package machimage
import (
"crypto/sha256"
"sync"
"unsafe"
"github.com/blacktop/go-macho"
"github.com/blacktop/go-macho/types"
)
const (
maxImagePreparations = 8
maxPreparationBytes = 64 << 20
)
type chainedRelocation struct {
offset, target uint64
addend int64
symbol string
isBind bool
}
type instructionPatch struct {
offset uint64
value uint32
}
type imagePreparation struct {
instructions map[uint64][]instructionPatch
fixups []chainedRelocation
binds []types.Bind
rebases []types.Rebase
symtab *macho.Symtab
dysymtab *macho.Dysymtab
}
func (p imagePreparation) size() int {
size := cap(p.fixups)*int(unsafe.Sizeof(chainedRelocation{})) + cap(p.binds)*int(unsafe.Sizeof(types.Bind{})) + cap(p.rebases)*int(unsafe.Sizeof(types.Rebase{}))
for _, patches := range p.instructions {
size += cap(patches) * int(unsafe.Sizeof(instructionPatch{}))
}
for _, fixup := range p.fixups {
size += len(fixup.symbol)
}
for _, bind := range p.binds {
size += len(bind.Name)
}
if p.symtab != nil {
size += cap(p.symtab.Syms)*int(unsafe.Sizeof(macho.Symbol{})) + cap(p.symtab.LoadBytes)
for _, symbol := range p.symtab.Syms {
size += len(symbol.Name) + len(symbol.IndirectName)
}
}
if p.dysymtab != nil {
size += cap(p.dysymtab.IndirectSyms)*4 + cap(p.dysymtab.LoadBytes)
}
return size
}
type imagePreparationCache struct {
mu sync.Mutex
entries map[[sha256.Size]byte]imagePreparation
order [][sha256.Size]byte
bytes int
}
// Cache only immutable instruction patches, symbol tables and decoded relocations. Every guest
// supplies its own load bases, import addresses and mutable memory.
var imagePreparations imagePreparationCache
func (c *imagePreparationCache) get(key [sha256.Size]byte) (imagePreparation, bool) {
c.mu.Lock()
defer c.mu.Unlock()
prepared, ok := c.entries[key]
return prepared, ok
}
func (c *imagePreparationCache) put(key [sha256.Size]byte, prepared imagePreparation) {
size := prepared.size()
if size > maxPreparationBytes {
return
}
c.mu.Lock()
defer c.mu.Unlock()
if _, exists := c.entries[key]; exists {
return
}
if c.entries == nil {
c.entries = make(map[[sha256.Size]byte]imagePreparation)
}
for len(c.order) >= maxImagePreparations || c.bytes+size > maxPreparationBytes {
oldest := c.order[0]
c.bytes -= c.entries[oldest].size()
delete(c.entries, oldest)
c.order = c.order[1:]
}
c.order = append(c.order, key)
c.entries[key] = prepared
c.bytes += size
}
+68
View File
@@ -0,0 +1,68 @@
package machimage
import (
"encoding/binary"
"errors"
"fmt"
"io"
"github.com/blacktop/go-macho/types"
)
// ARM64Range locates a thin image or the arm64e slice using only its headers.
// It leaves unselected architectures unread for range-backed remote sources.
func ARM64Range(source io.ReaderAt, size int64) (int64, int64, error) {
if size < 0 {
return 0, 0, errors.New("invalid image size")
}
var header [8]byte
if size < 4 {
return 0, size, nil
}
if _, err := source.ReadAt(header[:4], 0); err != nil {
return 0, 0, fmt.Errorf("read image magic: %w", err)
}
if binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
return 0, size, nil
}
if size < 8 {
return 0, 0, errors.New("truncated universal binary header")
}
if _, err := source.ReadAt(header[4:], 4); err != nil {
return 0, 0, fmt.Errorf("read universal binary header: %w", err)
}
count := int64(binary.BigEndian.Uint32(header[4:]))
if count == 0 || count > (size-8)/20 {
return 0, 0, errors.New("invalid universal binary architecture count")
}
var architecture [20]byte
for index := int64(0); index < count; index++ {
if _, err := source.ReadAt(architecture[:], 8+index*20); err != nil {
return 0, 0, fmt.Errorf("read universal binary architecture: %w", err)
}
cpu := types.CPU(binary.BigEndian.Uint32(architecture[:]))
subtype := types.CPUSubtype(binary.BigEndian.Uint32(architecture[4:]))
if cpu != types.CPUArm64 || subtype&types.CpuSubtypeMask != types.CPUSubtypeArm64E {
continue
}
offset, length := int64(binary.BigEndian.Uint32(architecture[8:])), int64(binary.BigEndian.Uint32(architecture[12:]))
if length == 0 || offset < 8+count*20 || offset > size || length > size-offset {
return 0, 0, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
}
return offset, length, nil
}
return 0, 0, errors.New("universal binary has no arm64e slice")
}
+70
View File
@@ -0,0 +1,70 @@
package machimage
import (
"bytes"
"encoding/binary"
"io"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type headerReader struct {
input []byte
read int
end int64
}
func (r *headerReader) ReadAt(data []byte, offset int64) (int, error) {
r.read += len(data)
r.end = max(r.end, offset+int64(len(data)))
return bytes.NewReader(r.input).ReadAt(data, offset) //nolint:wrapcheck // ReaderAt adapters preserve io.EOF.
}
var _ = Describe("Remote architecture selection", func() {
It("reads only the architecture headers", func() {
input := universalImage()
reader := &headerReader{input: input}
offset, size, err := ARM64Range(reader, int64(len(input)))
Expect(err).NotTo(HaveOccurred())
Expect(offset).To(Equal(int64(52)))
Expect(size).To(Equal(int64(4)))
Expect(reader.end).To(BeNumerically("<=", 48))
Expect(reader.read).To(BeNumerically("<=", 48))
})
It("keeps thin images whole", func() {
data := []byte("thin image")
reader := &headerReader{input: data}
offset, size, err := ARM64Range(reader, int64(len(data)))
Expect(err).NotTo(HaveOccurred())
Expect(offset).To(BeZero())
Expect(size).To(Equal(int64(len(data))))
Expect(reader.read).To(Equal(4))
})
It("rejects invalid counts and out-of-bounds slices", func() {
for _, index := range []int{4, 36, 40} {
data := universalImage()
binary.BigEndian.PutUint32(data[index:], ^uint32(0))
_, _, err := ARM64Range(bytes.NewReader(data), int64(len(data)))
Expect(err).To(HaveOccurred())
}
})
It("reports truncated headers and missing arm64e slices", func() {
data := universalImage()
_, _, err := ARM64Range(bytes.NewReader(data[:10]), int64(len(data)))
Expect(err).To(HaveOccurred())
binary.BigEndian.PutUint32(data[32:], 0)
_, _, err = ARM64Range(bytes.NewReader(data), int64(len(data)))
Expect(err).To(MatchError(ContainSubstring("no arm64e slice")))
})
It("handles tiny files and rejects a negative declared size", func() {
_, size, err := ARM64Range(bytes.NewReader([]byte{1}), 1)
Expect(err).NotTo(HaveOccurred())
Expect(size).To(Equal(int64(1)))
_, _, err = ARM64Range(bytes.NewReader(nil), -1)
Expect(err).To(HaveOccurred())
_, _, err = ARM64Range(io.NewSectionReader(bytes.NewReader(nil), 0, 4), 4)
Expect(err).To(HaveOccurred())
})
})
+103
View File
@@ -0,0 +1,103 @@
package machimage
import (
"encoding/binary"
"errors"
"fmt"
"io"
"github.com/blacktop/go-macho/types"
)
// ReadARM64 consumes exactly size bytes, retaining only the arm64e image of a
// universal binary. A caller can hash the entire input with an io.TeeReader.
func ReadARM64(input io.Reader, size int) ([]byte, error) {
if size < 0 {
return nil, errors.New("invalid image size")
}
var header [8]byte
prefix := min(size, 4)
if _, err := io.ReadFull(input, header[:prefix]); err != nil {
return nil, fmt.Errorf("read image magic: %w", err)
}
if prefix < 4 || binary.BigEndian.Uint32(header[:]) != types.MagicFat.Int() {
data := make([]byte, size)
copy(data, header[:prefix])
if _, err := io.ReadFull(input, data[prefix:]); err != nil {
return nil, fmt.Errorf("read thin image: %w", err)
}
return data, nil
}
if size < 8 {
return nil, errors.New("truncated universal binary header")
}
if _, err := io.ReadFull(input, header[4:]); err != nil {
return nil, fmt.Errorf("read universal binary header: %w", err)
}
count := uint64(binary.BigEndian.Uint32(header[4:]))
if count == 0 || count > uint64(size-8)/20 {
return nil, errors.New("invalid universal binary architecture count")
}
var offset, length uint64
var arch [20]byte
for range count {
if _, err := io.ReadFull(input, arch[:]); err != nil {
return nil, fmt.Errorf("read universal binary architecture: %w", err)
}
cpu := types.CPU(binary.BigEndian.Uint32(arch[:]))
subtype := types.CPUSubtype(binary.BigEndian.Uint32(arch[4:]))
if length == 0 && cpu == types.CPUArm64 && subtype&types.CpuSubtypeMask == types.CPUSubtypeArm64E {
offset = uint64(binary.BigEndian.Uint32(arch[8:]))
length = uint64(binary.BigEndian.Uint32(arch[12:]))
if length == 0 || offset < 8+count*20 || offset+length > uint64(size) {
return nil, errors.New("arm64e slice exceeds input size or overlaps universal binary header")
}
}
}
if length == 0 {
return nil, errors.New("universal binary has no arm64e slice")
}
buffer := make([]byte, 256<<10)
if err := discardImageBytes(input, offset-(8+count*20), buffer); err != nil {
return nil, fmt.Errorf("read universal binary prefix: %w", err)
}
data := make([]byte, int(length))
if _, err := io.ReadFull(input, data); err != nil {
return nil, fmt.Errorf("read arm64e image: %w", err)
}
if err := discardImageBytes(input, uint64(size)-offset-length, buffer); err != nil {
return nil, fmt.Errorf("read universal binary suffix: %w", err)
}
return data, nil
}
func discardImageBytes(input io.Reader, count uint64, buffer []byte) error {
for count > 0 {
size := min(count, uint64(len(buffer)))
if _, err := io.ReadFull(input, buffer[:size]); err != nil {
return fmt.Errorf("consume image bytes: %w", err)
}
count -= size
}
return nil
}
+52
View File
@@ -0,0 +1,52 @@
package machimage
import (
"bytes"
"crypto/sha256"
"errors"
"io"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Streaming ARM64 extraction", func() {
It("hashes discarded bytes and stops at the declared size", func() {
fat := append(universalImage(), []byte("unused suffix")...)
reader := bytes.NewReader(append(bytes.Clone(fat), []byte("trailer")...))
digest := sha256.New()
data, err := ReadARM64(io.TeeReader(reader, digest), len(fat))
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(Equal("arm!"))
expected := sha256.Sum256(fat)
Expect(digest.Sum(nil)).To(Equal(expected[:]))
trailing, err := io.ReadAll(reader)
Expect(err).NotTo(HaveOccurred())
Expect(string(trailing)).To(Equal("trailer"))
})
It("preserves thin and short input", func() {
for _, input := range [][]byte{nil, {1}, {1, 2, 3}, []byte("thin image")} {
data, err := ReadARM64(bytes.NewReader(input), len(input))
Expect(err).NotTo(HaveOccurred())
Expect(bytes.Equal(data, input)).To(BeTrue())
}
})
It("rejects a negative size", func() {
_, err := ReadARM64(bytes.NewReader(nil), -1)
Expect(err).To(MatchError(ContainSubstring("invalid image size")))
})
It("rejects truncation before, inside, and after the selected slice", func() {
input := append(universalImage(), []byte("suffix")...)
for _, length := range []int{0, 4, 7, 20, 48, 53, 55, 59} {
_, err := ReadARM64(bytes.NewReader(input[:length]), len(input))
Expect(err).To(HaveOccurred())
Expect(errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)).To(BeTrue())
}
})
It("rejects invalid architecture ranges before allocating their data", func() {
input := universalImage()
input[40] = 0xff
_, err := ReadARM64(bytes.NewReader(input), len(input))
Expect(err).To(MatchError(ContainSubstring("exceeds input size")))
})
})
+159
View File
@@ -0,0 +1,159 @@
package machimage
import (
"bytes"
"encoding/binary"
"fmt"
"io"
)
// OpenShared borrows immutable image bytes and copies only pages changed by
// relocation. Instruction patches are applied while loading into guest memory.
// Input must remain unchanged while the Image is used.
func OpenShared(name string, input []byte) (*Image, error) {
data, err := ARM64Slice(input)
if err != nil {
return nil, fmt.Errorf("open %s: %w", name, err)
}
return openImage(name, data, make(map[uint64][]byte))
}
func (i *Image) writeAt(offset uint64, data []byte) {
if i.modified == nil {
copy(i.data[offset:], data)
return
}
for len(data) > 0 {
page := offset &^ (pageSize - 1)
buffer := i.modified[page]
if buffer == nil {
buffer = bytes.Clone(i.data[page:min(page+pageSize, uint64(len(i.data)))])
i.overlay(buffer, page)
i.modified[page] = buffer
}
count := copy(buffer[offset-page:], data)
offset += uint64(count)
data = data[count:]
}
}
func (i *Image) pointerAt(offset uint64) uint64 {
pageStart := offset &^ (pageSize - 1)
if offset+pointerSize <= pageStart+pageSize {
if page := i.modified[pageStart]; page != nil {
return binary.LittleEndian.Uint64(page[offset-pageStart:])
}
if len(i.instructions[pageStart]) == 0 {
return binary.LittleEndian.Uint64(i.data[offset:])
}
}
var value [8]byte
copy(value[:], i.data[offset:offset+8])
i.overlay(value[:], offset)
return binary.LittleEndian.Uint64(value[:])
}
func (i *Image) writeInstruction(offset uint64, value uint32) {
if i.modified != nil {
if i.instructions == nil {
i.instructions = make(map[uint64][]instructionPatch)
}
for page := offset &^ (pageSize - 1); page < offset+4; page += pageSize {
i.instructions[page] = append(i.instructions[page], instructionPatch{offset, value})
}
return
}
var data [4]byte
binary.LittleEndian.PutUint32(data[:], value)
i.writeAt(offset, data[:])
}
// Overlay private relocations and immutable instruction patches. Clip each page
// and patch to the destination, including unaligned segment and chunk boundaries.
func (i *Image) overlay(data []byte, offset uint64) {
end := offset + uint64(len(data))
for page := offset &^ (pageSize - 1); page < end; page += pageSize {
first, last := max(page, offset), min(page+pageSize, end)
if modified := i.modified[page]; modified != nil {
copy(data[first-offset:last-offset], modified[first-page:last-page])
continue
}
for _, patch := range i.instructions[page] {
start, stop := max(first, patch.offset), min(last, patch.offset+4)
if start >= stop {
continue
}
var encoded [4]byte
binary.LittleEndian.PutUint32(encoded[:], patch.value)
copy(data[start-offset:stop-offset], encoded[start-patch.offset:stop-patch.offset])
}
}
}
// Keep staging memory bounded regardless of image size and guest count.
func (i *Image) writeSegment(memory Memory, address, start, end uint64, buffer []byte) error {
if len(i.modified) == 0 && len(i.instructions) == 0 {
if err := memory.MemWrite(address, i.data[start:end]); err != nil {
return fmt.Errorf("write image data: %w", err)
}
return nil
}
for position := start; position < end; {
stop := min(position+uint64(len(buffer)), end)
data := buffer[:stop-position]
copy(data, i.data[position:stop])
i.overlay(data, position)
if err := memory.MemWrite(address+position-start, data); err != nil {
return fmt.Errorf("write image chunk: %w", err)
}
position = stop
}
return nil
}
// Mach-O fixup parsing must observe the same rewritten bytes that will be loaded
// into the guest, including instruction patches in mixed code/data sections.
type imageInput struct{ image *Image }
func (r imageInput) ReadAt(data []byte, offset int64) (int, error) {
if offset < 0 {
return 0, fmt.Errorf("invalid image offset %d", offset)
}
if offset >= int64(len(r.image.data)) {
return 0, io.EOF
}
count := copy(data, r.image.data[offset:])
if len(r.image.instructions) > 0 || len(r.image.modified) > 0 {
r.image.overlay(data[:count], uint64(offset))
}
if count < len(data) {
return count, io.EOF
}
return count, nil
}
+207
View File
@@ -0,0 +1,207 @@
package machimage
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
// One instruction page and one data page following the Mach-O headers.
func sharedFixture() []byte {
data := make([]byte, 3*pageSize)
for n, v := range []uint32{0xfeedfacf, uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 6, 2, 176, 0, 0} {
binary.LittleEndian.PutUint32(data[n*4:], v)
}
binary.LittleEndian.PutUint32(data[32:], 25)
binary.LittleEndian.PutUint32(data[36:], 152)
copy(data[40:], "__TEXT")
for n, v := range []uint64{0x100000000, uint64(len(data)), 0, uint64(len(data))} {
binary.LittleEndian.PutUint64(data[56+n*8:], v)
}
for n, v := range []uint32{7, 7, 1, 0} {
binary.LittleEndian.PutUint32(data[88+n*4:], v)
}
copy(data[104:], "__text")
copy(data[120:], "__TEXT")
binary.LittleEndian.PutUint64(data[136:], 0x100001000)
binary.LittleEndian.PutUint64(data[144:], pageSize)
binary.LittleEndian.PutUint32(data[152:], uint32(pageSize))
binary.LittleEndian.PutUint32(data[156:], 2)
binary.LittleEndian.PutUint32(data[168:], 0x80000400)
for n, v := range []uint32{2, 24, 512, 1, 528, 8} {
binary.LittleEndian.PutUint32(data[184+n*4:], v)
}
binary.LittleEndian.PutUint32(data[512:], 1)
data[516], data[517] = 0x0f, 1
binary.LittleEndian.PutUint64(data[520:], 0x100001000)
copy(data[528:], []byte{0, 't', 'a', 'r', 'g', 'e', 't', 0})
binary.LittleEndian.PutUint32(data[4096:], 0xd503233f)
return data
}
type imageMemory struct {
data []byte
base uint64
fail error
}
func (m *imageMemory) MemMap(uint64, uint64) error { return nil }
func (m *imageMemory) MemWrite(address uint64, data []byte) error {
if m.fail != nil {
return m.fail
}
copy(m.data[address-m.base:], data)
return nil
}
var _ = Describe("Shared image preparation", func() {
It("shares instruction patches and isolates relocation and source bytes", func() {
source := sharedFixture()
original := bytes.Clone(source)
first, err := OpenShared("first", source)
Expect(err).NotTo(HaveOccurred())
second, err := OpenShared("second", source)
Expect(err).NotTo(HaveOccurred())
Expect(&first.data[0]).To(BeIdenticalTo(&source[0]))
Expect(&first.instructions[4096][0]).To(BeIdenticalTo(&second.instructions[4096][0]))
Expect(first.modified).To(BeEmpty())
Expect(first.file.Symtab).To(BeIdenticalTo(second.file.Symtab))
exported, err := second.Export("target", 0x300000000)
Expect(err).NotTo(HaveOccurred())
Expect(exported).To(Equal(uint64(0x300001000)))
Expect(second.InstructionRanges()).To(Equal([][2]uint64{{0x100001000, 0x100002000}}))
Expect(second.Symbols()).To(HaveLen(1))
first.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
second.binds = first.binds
Expect(first.Relocate(0x200000000, func(string) (uint64, error) { return 0x1111, nil })).To(Succeed())
Expect(second.Relocate(0x300000000, func(string) (uint64, error) { return 0x2222, nil })).To(Succeed())
Expect(second.putPointer(4092, 0x8877665544332211)).To(Succeed())
Expect(second.pointerAt(4092)).To(Equal(uint64(0x8877665544332211)))
Expect(first.pointerAt(4092)).To(Equal(uint64(0xd503201f00000000)))
for _, test := range []struct {
image *Image
base, value uint64
}{{first, 0x200000000, 0x1111}, {second, 0x300000000, 0x2222}} {
memory := &imageMemory{base: test.base, data: make([]byte, len(source))}
Expect(test.image.Load(memory)).To(Succeed())
Expect(binary.LittleEndian.Uint64(memory.data[8192:])).To(Equal(test.value))
if test.image == first {
Expect(binary.LittleEndian.Uint32(memory.data[4096:])).To(Equal(uint32(0xd503201f)))
}
}
Expect(source).To(Equal(original))
})
It("keeps concurrent guests independent while sharing preparation", func() {
source := sharedFixture()
source[len(source)-2] = 77
finished := make(chan error, 8)
for n := range 8 {
go func() {
image, err := OpenShared("concurrent", source)
if err == nil {
image.binds = []types.Bind{{Name: "target", Segment: "__TEXT", SegOffset: 8192, Type: types.BIND_TYPE_POINTER}}
expected := uint64(n+1) * 4096
err = image.Relocate(uint64(n+1)<<32, func(string) (uint64, error) { return expected, nil })
if err == nil && image.pointerAt(8192) != expected {
err = fmt.Errorf("guest %d has another guest's binding", n)
}
}
finished <- err
}()
}
for range 8 {
Eventually(finished).Should(Receive(BeNil()))
}
})
It("applies cached chained relocations with each guest's own addresses", func() {
source := make([]byte, 4096)
plan := []chainedRelocation{{offset: 0, target: 0x80}, {offset: 8, isBind: true, symbol: "target", addend: -4}}
for _, base := range []uint64{0x1000, 0x2000} {
image := &Image{data: source, modified: map[uint64][]byte{}, fixups: plan}
Expect(image.relocateChained(base, func(string) (uint64, error) { return base + 0x404, nil })).To(Succeed())
Expect(image.pointerAt(0)).To(Equal(base + 0x80))
Expect(image.pointerAt(8)).To(Equal(base + 0x400))
}
Expect(source).To(Equal(make([]byte, 4096)))
})
It("overlays patches across unaligned page, segment, and chunk boundaries", func() {
source := make([]byte, 3*pageSize+13)
image := &Image{data: source, modified: map[uint64][]byte{}}
image.writeInstruction(4094, 0x11223344)
Expect(image.pointerAt(4092)).To(Equal(uint64(0x112233440000)))
var decoded [8]byte
count, err := (imageInput{image}).ReadAt(decoded[:], 4092)
Expect(err).NotTo(HaveOccurred())
Expect(count).To(Equal(8))
Expect(binary.LittleEndian.Uint64(decoded[:])).To(Equal(uint64(0x112233440000)))
Expect(image.putPointer(4095, 0xaabbccddeeff0011)).To(Succeed())
expected := bytes.Clone(source)
binary.LittleEndian.PutUint32(expected[4094:], 0x11223344)
binary.LittleEndian.PutUint64(expected[4095:], 0xaabbccddeeff0011)
memory := &imageMemory{data: make([]byte, len(source))}
Expect(image.writeSegment(memory, 0, 3, uint64(len(source)), make([]byte, 4093))).To(Succeed())
Expect(memory.data[:len(source)-3]).To(Equal(expected[3:]))
})
It("invalidates preparation when any source byte changes", func() {
source := sharedFixture()
first, err := OpenShared("first", source)
Expect(err).NotTo(HaveOccurred())
changed := bytes.Clone(source)
changed[len(changed)-1] = 1
second, err := OpenShared("second", changed)
Expect(err).NotTo(HaveOccurred())
Expect(&first.instructions[4096][0]).NotTo(BeIdenticalTo(&second.instructions[4096][0]))
})
It("preserves write errors and rejects fixups outside the image", func() {
image, err := OpenShared("image", sharedFixture())
Expect(err).NotTo(HaveOccurred())
Expect(image.Relocate(image.Base(), nil)).To(Succeed())
failed := errors.New("write failure")
Expect(errors.Is(image.Load(&imageMemory{fail: failed}), failed)).To(BeTrue())
Expect(image.putPointer(uint64(len(image.data)-7), 1)).NotTo(Succeed())
})
})
var _ = Describe("Image preparation cache bounds", func() {
It("evicts old preparations when the image count is exceeded", func() {
var cache imagePreparationCache
first := sha256.Sum256([]byte{0})
for n := 0; n <= maxImagePreparations; n++ {
cache.put(sha256.Sum256([]byte{byte(n)}), imagePreparation{})
}
_, ok := cache.get(first)
Expect(ok).To(BeFalse())
Expect(cache.entries).To(HaveLen(maxImagePreparations))
})
It("bounds retained patch and fixup storage", func() {
var cache imagePreparationCache
key := sha256.Sum256([]byte("first"))
large := imagePreparation{instructions: map[uint64][]instructionPatch{0: make([]instructionPatch, 0, maxPreparationBytes/16+1)}}
cache.put(key, large)
_, ok := cache.get(key)
Expect(ok).To(BeFalse())
half := imagePreparation{instructions: map[uint64][]instructionPatch{0: large.instructions[0][: 0 : maxPreparationBytes/32+1]}}
cache.put(key, half)
second := sha256.Sum256([]byte("second"))
cache.put(second, half)
_, ok = cache.get(key)
Expect(ok).To(BeFalse())
Expect(cache.bytes).To(BeNumerically("<=", maxPreparationBytes))
})
})
+98
View File
@@ -0,0 +1,98 @@
package machimage
import (
"bytes"
"encoding/binary"
"testing"
"github.com/blacktop/go-macho/types"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestImageGinkgo(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Mach-O Image Suite")
}
func universalImage() []byte {
data := make([]byte, 56)
for index, value := range []uint32{
types.MagicFat.Int(), 2,
uint32(types.CPUAmd64), 3, 48, 4, 0,
uint32(types.CPUArm64), uint32(types.CPUSubtypeArm64E), 52, 4, 0,
} {
binary.BigEndian.PutUint32(data[index*4:], value)
}
copy(data[48:], []byte("x86!arm!"))
return data
}
var _ = Describe("ARM64 image selection", func() {
It("selects arm64e without parsing unused architectures", func() {
input := universalImage()
data, err := ARM64Slice(input)
Expect(err).NotTo(HaveOccurred())
Expect(string(data)).To(Equal("arm!"))
Expect(&data[0]).To(BeIdenticalTo(&input[52]))
})
It("preserves thin image data", func() {
input := []byte("thin image")
data, err := ARM64Slice(input)
Expect(err).NotTo(HaveOccurred())
Expect(&data[0]).To(BeIdenticalTo(&input[0]))
})
It("isolates mutable relocation data from the source bundle", func() {
for _, input := range [][]byte{universalImage(), []byte("thin image")} {
original := bytes.Clone(input)
data, err := arm64Slice(input)
Expect(err).NotTo(HaveOccurred())
data[0] ^= 0xff
Expect(input).To(Equal(original))
}
})
DescribeTable("rejects malformed universal images", func(mutate func([]byte) []byte, message string) {
_, err := ARM64Slice(mutate(universalImage()))
Expect(err).To(MatchError(ContainSubstring(message)))
},
Entry("truncated header", func(b []byte) []byte { return b[:4] }, "header"),
Entry("truncated architecture table", func(b []byte) []byte { return b[:47] }, "architecture count"),
Entry("no architectures", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[4:], 0)
return b
}, "architecture count"),
Entry("excessive count", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[4:], ^uint32(0))
return b
}, "architecture count"),
Entry("no arm64e image", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[32:], 0)
return b
}, "no arm64e slice"),
Entry("slice past the end", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[40:], 5)
return b
}, "exceeds input size"),
Entry("empty slice", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[40:], 0)
return b
}, "exceeds input size"),
Entry("overlapping header", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[36:], 8)
return b
}, "overlaps"),
Entry("large offset", func(b []byte) []byte {
binary.BigEndian.PutUint32(b[36:], ^uint32(0))
return b
}, "exceeds input size"),
)
})
+1 -1
View File
@@ -112,7 +112,7 @@ func openRuntime(ctx context.Context, bundle assets.Bundle, options runtimeOptio
images := make(map[string]*machimage.Image, len(imageSpecs))
for _, spec := range imageSpecs {
image, err := machimage.Open(spec.name, spec.data)
image, err := machimage.OpenShared(spec.name, spec.data)
if err != nil {
return nil, nil, fmt.Errorf("open %s image: %w", spec.name, err)
}
+14 -1
View File
@@ -154,7 +154,20 @@ func (e *Engine) register(handle uintptr) {
purego.RegisterLibFunc(&e.api.open, handle, "uc_open")
purego.RegisterLibFunc(&e.api.close, handle, "uc_close")
purego.RegisterLibFunc(&e.api.query, handle, "uc_query")
purego.RegisterLibFunc(&e.api.ctl, handle, "uc_ctl")
// Darwin ARM64 passes C variadic arguments on the stack. Fill the six
// remaining integer registers so purego places uc_ctl's value there.
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" {
var control func(uintptr, uint32, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, uint32) int32
purego.RegisterLibFunc(&control, handle, "uc_ctl")
e.api.ctl = func(engine uintptr, command, value uint32) int32 {
return control(engine, command, 0, 0, 0, 0, 0, 0, value)
}
} else {
purego.RegisterLibFunc(&e.api.ctl, handle, "uc_ctl")
}
purego.RegisterLibFunc(&e.api.strerror, handle, "uc_strerror")
purego.RegisterLibFunc(&e.api.memMap, handle, "uc_mem_map")
purego.RegisterLibFunc(&e.api.memUnmap, handle, "uc_mem_unmap")
@@ -6,17 +6,18 @@ const (
ucCtlTCGBufferSize = 13
ucCtlIOWrite = 1
ucCtlArgumentCount = 1
tcgBufferSize = 64 << 20
tcgBufferSize = 4 << 20
)
func configureEngine(engine *Engine) error {
// The VirtualAlloc compatibility hook commits this buffer eagerly, so keep
// its upper bound modest instead of using Unicorn's much larger default.
// Bound native JIT memory on every host, including memory-limited Linux
// containers. Unicorn flushes translated blocks when the buffer fills.
control := uint32(ucCtlTCGBufferSize |
ucCtlArgumentCount<<26 |
ucCtlIOWrite<<30)
if err := engine.err(engine.api.ctl(engine.handle, control, tcgBufferSize)); err != nil {
return fmt.Errorf("configure Unicorn translation buffer: %w", err)
}
return nil
}
@@ -1,7 +0,0 @@
//go:build !windows
package unicorn
func configureEngine(*Engine) error {
return nil
}
@@ -0,0 +1,55 @@
package unicorn
import (
"context"
"runtime"
"github.com/ebitengine/purego"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Translation buffer limit", func() {
It("sets the native buffer size before guest memory is mapped", func() {
called := false
engine := &Engine{handle: 123, api: api{ctl: func(handle uintptr, control, value uint32) int32 {
called = true
Expect(handle).To(Equal(uintptr(123)))
Expect(control).To(Equal(uint32(13 | 1<<26 | 1<<30)))
Expect(value).To(Equal(uint32(tcgBufferSize)))
return 0
}}}
Expect(configureEngine(engine)).To(Succeed())
Expect(called).To(BeTrue())
})
It("applies the limit to a real engine before native initialization", func() {
engine, err := New(context.Background())
Expect(err).NotTo(HaveOccurred())
DeferCleanup(engine.Close)
Expect(engine.MemMap(0x1000, 0x1000)).To(Succeed())
var readBufferSize func(uintptr, uint32, *uint32) int32
if (runtime.GOOS == "darwin" || runtime.GOOS == "ios") && runtime.GOARCH == "arm64" {
var control func(uintptr, uint32, uintptr, uintptr, uintptr, uintptr, uintptr, uintptr, *uint32) int32
purego.RegisterLibFunc(&control, engine.library.handle, "uc_ctl")
readBufferSize = func(engine uintptr, command uint32, value *uint32) int32 {
return control(engine, command, 0, 0, 0, 0, 0, 0, value)
}
} else {
purego.RegisterLibFunc(&readBufferSize, engine.library.handle, "uc_ctl")
}
var size uint32
Expect(engine.err(readBufferSize(engine.handle, 13|1<<26|2<<30, &size))).To(Succeed())
Expect(size).To(Equal(uint32(tcgBufferSize)))
Expect(engine.err(readBufferSize(engine.handle, 7|1<<26|2<<30, &size))).To(Succeed())
Expect(size).To(Equal(arm64CPUModelMax))
})
It("reports failure to set the native buffer size", func() {
engine := &Engine{api: api{
ctl: func(uintptr, uint32, uint32) int32 { return 15 },
strerror: func(int32) string { return "invalid argument" },
}}
Expect(configureEngine(engine)).To(MatchError(ContainSubstring("configure Unicorn translation buffer")))
})
})
+52
View File
@@ -26,6 +26,29 @@ func (r *Runtime) symbol(name string) {
}
switch name {
case "AMSError":
// AMSAccountAuthenticationPlugin uses this factory when Apple returns a
// server dialog and native presentation is disabled. Preserve the error
// as an NSError so the framework can finish the request and the caller can
// inspect the original response instead of aborting the guest.
info := map[string]uint64{}
if description := r.arg(1); description != 0 {
info["NSLocalizedDescription"] = description
}
if reason := r.arg(2); reason != 0 {
info["NSLocalizedFailureReason"] = reason
}
if underlying := r.arg(3); underlying != 0 {
info["NSUnderlyingError"] = underlying
}
r.set(r.New("NSError", map[string]uint64{
"domain": r.New("NSString", "AMSErrorDomain"),
"code": r.New("NSNumber", int64(r.arg(0))),
"userInfo": r.New("NSDictionary", info),
}))
case "xpc_get_type":
object := r.objects[r.arg(0)]
if object != nil && object.Class == "HostXPCDictionary" {
@@ -745,6 +768,29 @@ func (r *Runtime) message(receiver uint64, selector string, super bool) {
return
}
// Store tasks use keep-alives to request host process assertions. The guest
// runs synchronously inside the CLI, so retaining a scoped token is enough.
if class == "AMSKeepAlive" {
switch selector {
case "keepAliveWithName:style:", "rbs_keepAliveWithName:style:":
if meta {
value := r.New("AMSKeepAlive", nil)
r.objects[value].Properties["name"] = r.arg(2)
r.objects[value].Properties["style"] = r.arg(3)
r.set(value)
return
}
case "invalidate", "rbs_invalidate":
r.set(0)
return
case "name", "style":
r.set(object.Properties[selector])
return
}
}
if entry := r.lookup(class, selector, meta); !super && entry != 0 {
r.jump(entry, receiver, selector)
@@ -1961,6 +2007,12 @@ func (r *Runtime) formatAt(format string, sp uint64) string {
} else {
obj := r.objects[value]
if obj == nil {
if class := r.classNames[value]; class != "" {
result.WriteString(class)
break
}
panic(fmt.Sprintf("unknown format object %#x", value))
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"io"
"net/http"
"net/url"
"slices"
"strings"
@@ -89,10 +90,58 @@ var _ = Describe("Generated profile response branches", func() {
Entry("version lookup GET", "lookup", http.MethodGet, "application/json", `{"results":{"fixture-value":{"offers":[]}}}`, http.StatusOK, false),
Entry("streamed package range", "download", http.MethodGet, "application/octet-stream", "fixture-value\x00\xff", http.StatusPartialContent, true),
Entry("authentication failure", "authenticate", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>failureType</key><string>2034</string><key>customerMessage</key><string>fixture-value</string></dict></plist>`, http.StatusOK, false),
Entry("authentication server dialog", "authenticate", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>customerMessage</key><string>fixture-value</string><key>dialog</key><dict><key>message</key><string>Account locked</string><key>explanation</key><string>Reset the account to continue.</string><key>okButtonString</key><string>Reset</string><key>okButtonAction</key><dict><key>kind</key><string>OpenURL</string><key>url</key><string>https://iforgot.apple.com/cgi-bin/iforgot.cgi</string></dict></dict></dict></plist>`, http.StatusOK, false),
Entry("purchase failure", "purchase", http.MethodPost, "application/x-apple-plist", `<plist version="1.0"><dict><key>failureType</key><string>9610</string><key>customerMessage</key><string>fixture-value</string></dict></plist>`, http.StatusOK, false),
)
})
var _ = Describe("URL component query setters", func() {
DescribeTable("preserves query values through the runtime bridge", func(selector string, value any, encoded, decoded string) {
ctx := context.Background()
bundle, err := assets.Load(ctx)
Expect(err).NotTo(HaveOccurred())
prepared, err := profile.Load(ctx)
Expect(err).NotTo(HaveOccurred())
guest, err := open(ctx, bundle.AppleMediaServices, prepared, true)
Expect(err).NotTo(HaveOccurred())
DeferCleanup(guest.Close)
u, err := url.Parse("https://example.com/path?old=value#fragment")
Expect(err).NotTo(HaveOccurred())
components := guest.New("NSURLComponents", u)
_, err = guest.Invoke(components, "setQuery:", guest.New("NSString", "old=value"))
Expect(err).NotTo(HaveOccurred())
_, err = guest.Invoke(components, selector, guest.importValue(value))
Expect(err).NotTo(HaveOccurred())
encodedQuery, err := guest.Invoke(components, "percentEncodedQuery")
Expect(err).NotTo(HaveOccurred())
query, err := guest.Invoke(components, "query")
Expect(err).NotTo(HaveOccurred())
expectedURL := "https://example.com/path"
if value == nil {
Expect(encodedQuery).To(BeZero())
Expect(query).To(BeZero())
} else {
Expect(encodedQuery).NotTo(BeZero())
Expect(query).NotTo(BeZero())
Expect(guest.String(encodedQuery)).To(Equal(encoded))
Expect(guest.String(query)).To(Equal(decoded))
expectedURL += "?" + encoded
}
result, err := guest.Invoke(components, "URL")
Expect(err).NotTo(HaveOccurred())
Expect(guest.String(result)).To(Equal(expectedURL + "#fragment"))
},
Entry("clears an encoded query", "setPercentEncodedQuery:", nil, "", ""),
Entry("keeps an empty encoded query delimiter", "setPercentEncodedQuery:", "", "", ""),
Entry("preserves percent escapes and literal plus signs", "setPercentEncodedQuery:", "q=a%20b%2Bc+%26%3D%25%23&symbol=%e2%9c%93", "q=a%20b%2Bc+%26%3D%25%23&symbol=%e2%9c%93", "q=a b+c+&=%#&symbol=✓"),
Entry("preserves query delimiters", "setPercentEncodedQuery:", "q=/?@!$&'()*+,;=:", "q=/?@!$&'()*+,;=:", "q=/?@!$&'()*+,;=:"),
Entry("clears a decoded query", "setQuery:", nil, "", ""),
Entry("keeps an empty decoded query delimiter", "setQuery:", "", "", ""),
Entry("encodes decoded query values", "setQuery:", "q=a b+%&symbol=✓", "q=a%20b+%25&symbol=%E2%9C%93", "q=a b+%&symbol=✓"),
)
})
var _ = Describe("Missing profile snapshots", func() {
It("rejects an omitted page even though its neighbors share a grouped mapping", func() {
ctx := context.Background()
+5 -2
View File
@@ -534,12 +534,15 @@ func (r *Runtime) networkMessage(receiver uint64, class, selector string, meta b
u := object.Value.(*url.URL)
switch selector {
case "setQuery:":
case "setQuery:", "setPercentEncodedQuery:":
u.RawQuery = ""
u.ForceQuery = r.arg(2) != 0
if r.arg(2) != 0 {
u.RawQuery = encodeComponentQuery(r.String(r.arg(2)))
u.RawQuery = r.String(r.arg(2))
if selector == "setQuery:" {
u.RawQuery = encodeComponentQuery(u.RawQuery)
}
}
r.set(0)
+42
View File
@@ -0,0 +1,42 @@
package emulator
import (
"errors"
"fmt"
)
type profileMemory interface{ MemWrite(uint64, []byte) error }
// Batch consecutive guest pages whose source bytes are also consecutive. Gaps
// remain separate writes, so strict profile validation covers the same pages.
func writeProfilePages(memory profileMemory, pages []Page, data []byte) error {
for first := 0; first < len(pages); {
page := pages[first]
if page.Offset > uint64(len(data)) || profilePageSize > uint64(len(data))-page.Offset {
return errors.New("profile page exceeds data")
}
last := first + 1
for last < len(pages) {
next, previous := pages[last], pages[last-1]
if previous.Address > ^uint64(0)-profilePageSize || next.Address != previous.Address+profilePageSize || next.Offset != previous.Offset+profilePageSize {
break
}
if next.Offset > uint64(len(data)) || profilePageSize > uint64(len(data))-next.Offset {
return errors.New("profile page exceeds data")
}
last++
}
end := page.Offset + uint64(last-first)*profilePageSize
if err := memory.MemWrite(page.Address, data[page.Offset:end]); err != nil {
return fmt.Errorf("write Store profile pages: %w", err)
}
first = last
}
return nil
}
@@ -0,0 +1,69 @@
package emulator
import (
"bytes"
"errors"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
type pageWrite struct {
address uint64
data []byte
}
type pageMemory struct {
writes []pageWrite
fail error
}
func (m *pageMemory) MemWrite(address uint64, data []byte) error {
if m.fail != nil {
return m.fail
}
m.writes = append(m.writes, pageWrite{address, bytes.Clone(data)})
return nil
}
var _ = Describe("Store profile page transfers", func() {
It("batches consecutive source and guest pages without writing gaps", func() {
data := make([]byte, 3*profilePageSize)
for n := range data {
data[n] = byte(n/4096 + 1)
}
memory := &pageMemory{}
Expect(writeProfilePages(memory, []Page{{Address: 0x1000, Offset: 0}, {Address: 0x2000, Offset: 4096}, {Address: 0x9000, Offset: 8192}}, data)).To(Succeed())
Expect(memory.writes).To(HaveLen(2))
Expect(memory.writes[0]).To(Equal(pageWrite{0x1000, data[:8192]}))
Expect(memory.writes[1]).To(Equal(pageWrite{0x9000, data[8192:]}))
})
It("preserves writes when source pages or guest addresses are out of order", func() {
data := make([]byte, 3*profilePageSize)
memory := &pageMemory{}
pages := []Page{{Address: 0x2000, Offset: 0}, {Address: 0x1000, Offset: 8192}, {Address: 0x2000, Offset: 4096}}
Expect(writeProfilePages(memory, pages, data)).To(Succeed())
Expect(memory.writes).To(HaveLen(3))
for n, page := range pages {
Expect(memory.writes[n]).To(Equal(pageWrite{page.Address, data[page.Offset : page.Offset+4096]}))
}
})
It("rejects truncated and wrapping source ranges", func() {
for _, offset := range []uint64{1, 4096, ^uint64(0) - 4095} {
memory := &pageMemory{}
Expect(writeProfilePages(memory, []Page{{Address: 0x1000, Offset: offset}}, make([]byte, 4096))).To(MatchError("profile page exceeds data"))
Expect(memory.writes).To(BeEmpty())
}
})
It("does not merge across a wrapping guest address", func() {
memory := &pageMemory{}
Expect(writeProfilePages(memory, []Page{{Address: ^uint64(0) - 4095, Offset: 0}, {Address: 0, Offset: 4096}}, make([]byte, 8192))).To(Succeed())
Expect(memory.writes).To(HaveLen(2))
})
It("preserves memory write errors", func() {
failed := errors.New("write failure")
err := writeProfilePages(&pageMemory{fail: failed}, []Page{{Address: 0x1000}}, make([]byte, 4096))
Expect(errors.Is(err, failed)).To(BeTrue())
})
})
+22 -39
View File
@@ -2,7 +2,6 @@
package emulator
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
@@ -13,7 +12,6 @@ import (
"strings"
"time"
"github.com/blacktop/go-macho"
"github.com/majd/ipatool/v2/internal/sap/machimage"
"github.com/majd/ipatool/v2/internal/sap/unicorn"
storeprofile "github.com/majd/ipatool/v2/internal/store/profile"
@@ -151,8 +149,10 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
}
}
images := make([]*machimage.Image, 0, len(imageInputs))
for name, data := range imageInputs {
image, e := machimage.Open(name, data)
image, e := machimage.OpenShared(name, data)
if e != nil {
return nil, fmt.Errorf("prepare store runtime: %w", e)
}
@@ -164,6 +164,8 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
if e = image.Load(r); e != nil {
return nil, fmt.Errorf("prepare store runtime: %w", e)
}
images = append(images, image)
}
pageData := prepared.Pages
@@ -210,14 +212,8 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
}
}
for _, page := range profile.Pages {
if page.Offset+4096 > uint64(len(pageData)) {
return nil, errors.New("profile page exceeds data")
}
if err = r.MemWrite(page.Address, pageData[page.Offset:page.Offset+4096]); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
if err = writeProfilePages(r, profile.Pages, pageData); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
for _, call := range profile.Calls {
@@ -233,39 +229,26 @@ func open(ctx context.Context, imageData []byte, prepared storeprofile.Data, str
}
}
// Non-fragile ivar offsets are fixed by the Objective-C loader on macOS.
for _, imageBytes := range imageInputs {
file, err := macho.NewFile(bytes.NewReader(imageBytes))
if err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
for _, image := range images {
r.codeRanges = append(r.codeRanges, image.InstructionRanges()...)
defer file.Close()
for _, section := range file.Sections {
if section.Flags.IsPureInstructions() || section.Flags.IsSomeInstructions() {
r.codeRanges = append(r.codeRanges, [2]uint64{section.Addr, section.Addr + section.Size})
for _, sym := range image.Symbols() {
if !strings.HasPrefix(sym.Name, "_OBJC_IVAR_$_") {
continue
}
}
if file.Symtab != nil {
for _, sym := range file.Symtab.Syms {
if !strings.HasPrefix(sym.Name, "_OBJC_IVAR_$_") {
continue
}
parts := strings.SplitN(strings.TrimPrefix(sym.Name, "_OBJC_IVAR_$_"), ".", 2)
if len(parts) != 2 {
continue
}
parts := strings.SplitN(strings.TrimPrefix(sym.Name, "_OBJC_IVAR_$_"), ".", 2)
if len(parts) != 2 {
continue
}
if c := r.classes[parts[0]]; c != nil {
if offset, ok := c.Ivars[parts[1]]; ok {
data := make([]byte, 4)
binary.LittleEndian.PutUint32(data, uint32(offset))
if c := r.classes[parts[0]]; c != nil {
if offset, ok := c.Ivars[parts[1]]; ok {
data := make([]byte, 4)
binary.LittleEndian.PutUint32(data, uint32(offset))
if err = r.MemWrite(sym.Value, data); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
if err = r.MemWrite(sym.Value, data); err != nil {
return nil, fmt.Errorf("prepare store runtime: %w", err)
}
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ func StoreAMDHeaders(ctx context.Context, encoded []byte, endpoint string, hardw
}
if len(state.Provisioning) == 0 {
return nil, nil, errors.New("store AMD state is not provisioned")
return nil, nil, errors.New("store AMD state is not provisioned; run 'ipatool auth login' to authenticate")
}
bundle, err := assets.Load(ctx)
+24 -22
View File
@@ -43,28 +43,30 @@ type AppStore interface {
}
type appstore struct {
keychain keychain.Keychain
loginClient http.Client[loginResult]
searchClient http.Client[searchResult]
purchaseClient http.Client[purchaseResult]
downloadClient http.Client[downloadResult]
kbsyncGenerator kbsyncGenerator
kbsyncCache kbsyncCache
platformClient http.Client[platformVersionLookupResult]
storefrontClient http.Client[[]byte]
bagClient http.Client[bagResult]
ownedAppsClient http.Client[[]byte]
httpClient http.Client[interface{}]
macDecrypterFactory macPackageDecrypterFactory
actionSignerFactory ActionSignerFactory
authRetrySleep func(time.Duration)
machine machine.Machine
os operatingsystem.OperatingSystem
authBackend *store.Backend
authHTTP *gohttp.Client
authStateMu sync.Mutex
anisetteState []byte
authenticationHeaders gohttp.Header
keychain keychain.Keychain
loginClient http.Client[loginResult]
searchClient http.Client[searchResult]
purchaseClient http.Client[purchaseResult]
downloadClient http.Client[downloadResult]
kbsyncGenerator kbsyncGenerator
kbsyncCache kbsyncCache
platformClient http.Client[platformVersionLookupResult]
storefrontClient http.Client[[]byte]
storefrontsMu sync.Mutex
storefrontCountryCodes map[string]string
bagClient http.Client[bagResult]
ownedAppsClient http.Client[[]byte]
httpClient http.Client[interface{}]
macDecrypterFactory macPackageDecrypterFactory
actionSignerFactory ActionSignerFactory
authRetrySleep func(time.Duration)
machine machine.Machine
os operatingsystem.OperatingSystem
authBackend *store.Backend
authHTTP *gohttp.Client
authStateMu sync.Mutex
anisetteState []byte
authenticationHeaders gohttp.Header
}
type Args struct {
@@ -0,0 +1,301 @@
package appstore
import (
"archive/zip"
"bytes"
"context"
"errors"
gohttp "net/http"
"net/http/httptest"
"os"
"path/filepath"
"time"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/util/machine"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
"howett.net/plist"
)
var _ = Describe("Delisted app kbsync recovery", func() {
const guid = "001122334455"
var (
store *appstore
downloads *http.MockClient[downloadResult]
account Account
app App
redownload downloadProductEndpoint
success http.Result[downloadResult]
forbidden error
generated int
)
BeforeEach(func() {
downloads = http.NewMockClient[downloadResult](gomock.NewController(GinkgoT()))
generated = 0
store = &appstore{
downloadClient: downloads,
kbsyncGenerator: func(ctx context.Context, hardwareID []byte, dsid uint64) ([]byte, error) {
Expect(ctx.Err()).NotTo(HaveOccurred())
deadline, ok := ctx.Deadline()
Expect(ok).To(BeTrue())
Expect(time.Until(deadline)).To(BeNumerically("<=", 2*time.Minute))
Expect(hardwareID).To(Equal([]byte{0, 0x11, 0x22, 0x33, 0x44, 0x55}))
Expect(dsid).To(Equal(uint64(1234)))
generated++
return []byte("kbsync blob"), nil
},
}
account = Account{DirectoryServicesID: "1234", PasswordToken: "token", StoreFront: "143469-2,29"}
app = App{ID: 42, BundleID: "com.example.app"}
var err error
redownload, err = newDownloadEndpoint(testRedownloadEndpoint, redownloadProductPath)
Expect(err).NotTo(HaveOccurred())
success = http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{
Items: []downloadItemResult{{URL: "https://example.test/app.ipa", Metadata: map[string]interface{}{
"itemId": app.ID, "softwareVersionBundleId": app.BundleID,
"softwareVersionExternalIdentifier": uint64(1001),
}}},
}}
forbidden = &http.UnexpectedResponseError{StatusCode: gohttp.StatusForbidden}
})
expectRedownload := func(response http.Result[downloadResult], err error) *gomock.Call {
return downloads.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
Expect(req.URL).To(Equal(testRedownloadEndpoint + "?guid=" + guid))
Expect(req.Payload.(*http.XMLPayload).Content).NotTo(HaveKey("appExtVrsId"))
}).Return(response, err)
}
expectCatalog404Recovery := func() *gomock.Call {
ctrl := gomock.NewController(GinkgoT())
bags := http.NewMockClient[bagResult](ctrl)
catalogs := http.NewMockClient[platformVersionLookupResult](ctrl)
store.bagClient = bags
store.platformClient = catalogs
store.storefrontCountryCodes = testStorefrontCountryCodes()
last := bags.EXPECT().Send(gomock.Any()).Return(http.Result[bagResult]{
StatusCode: gohttp.StatusOK, Data: bagResult{URLBag: urlBag{
EntDownloadEndpoint: testEntDownloadEndpoint, RedownloadEndpoint: testRedownloadEndpoint,
}},
}, nil)
// The preferred request and legacy fallback both discover the missing offer.
for attempt := 0; attempt < 2; attempt++ {
for _, catalog := range []string{"enterprisestore", "iphone", "ipad"} {
last = catalogs.EXPECT().Send(store.platformVersionLookupRequest(app.ID, "RU", catalog)).After(last).
Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusOK}, nil)
}
last = catalogs.EXPECT().Send(http.Request{
URL: "https://apps.apple.com/api/apps/v1/catalog/ru/apps/42?platform=iphone",
Method: http.MethodGET, ResponseFormat: http.ResponseFormatJSON,
}).After(last).Return(http.Result[platformVersionLookupResult]{StatusCode: gohttp.StatusNotFound}, nil)
if attempt == 0 {
last = downloads.EXPECT().Send(store.downloadProductRequest(store.volumeStoreEndpoint(account), account, app, guid, "")).After(last).
Return(http.Result[downloadResult]{StatusCode: gohttp.StatusOK}, nil)
}
}
return expectRedownload(http.Result[downloadResult]{}, forbidden).After(last)
}
It("recovers an opaque redownload 403 without consulting the catalog or pinning a version", func() {
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
downloads.EXPECT().Send(gomock.Any()).After(first).Do(func(req http.Request) {
Expect(req.URL).To(Equal(testEntDownloadEndpoint + "?guid=" + guid))
Expect(req.NoRedirects).To(BeTrue())
Expect(req.Headers).To(HaveKeyWithValue("X-Token", account.PasswordToken))
Expect(req.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", account.StoreFront))
payload := req.Payload.(*http.XMLPayload).Content
Expect(payload).To(HaveKey("kbsync"))
Expect(payload).NotTo(HaveKey("externalVersionId"))
}).Return(success, nil)
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).NotTo(HaveOccurred())
Expect(actual).To(Equal(success))
Expect(generated).To(Equal(1))
})
It("keeps a successful redownload without generating kbsync", func() {
expectRedownload(success, nil)
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).NotTo(HaveOccurred())
Expect(actual).To(Equal(success))
Expect(generated).To(BeZero())
})
It("lists versions through the complete catalog-404 and redownload-403 recovery chain", func() {
device := machine.NewMockMachine(gomock.NewController(GinkgoT()))
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
store.machine = device
success.Data.Items[0].Metadata["softwareVersionExternalIdentifiers"] = []interface{}{"1000", "1001"}
last := expectCatalog404Recovery()
downloads.EXPECT().Send(gomock.Any()).After(last).Return(success, nil)
out, err := store.ListVersions(ListVersionsInput{Account: account, App: app})
Expect(err).NotTo(HaveOccurred())
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{"1000", "1001"}))
Expect(out.LatestExternalVersionID).To(Equal("1001"))
Expect(generated).To(Equal(1))
})
DescribeTable("validates recovered packages before replacing the destination", func(supportedPlatform string) {
device := machine.NewMockMachine(gomock.NewController(GinkgoT()))
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
store.machine = device
store.os = operatingsystem.New()
store.httpClient = newDownloadTestClient()
packageBuffer := new(bytes.Buffer)
writer := zip.NewWriter(packageBuffer)
infoWriter, err := writer.Create("Payload/Test.app/Info.plist")
Expect(err).NotTo(HaveOccurred())
info, err := plist.Marshal(map[string]interface{}{
"CFBundleSupportedPlatforms": []string{supportedPlatform},
}, plist.BinaryFormat)
Expect(err).NotTo(HaveOccurred())
_, err = infoWriter.Write(info)
Expect(err).NotTo(HaveOccurred())
Expect(writer.Close()).To(Succeed())
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, _ *gohttp.Request) {
_, _ = w.Write(packageBuffer.Bytes())
}))
DeferCleanup(server.Close)
success.Data.Items[0].URL = server.URL + "/app.ipa"
last := expectCatalog404Recovery()
downloads.EXPECT().Send(gomock.Any()).After(last).Return(success, nil)
destination := filepath.Join(GinkgoT().TempDir(), "app.ipa")
Expect(os.WriteFile(destination, []byte("previous package"), 0600)).To(Succeed())
out, err := store.Download(DownloadInput{Account: account, App: app, OutputPath: destination})
if supportedPlatform == "iPhoneOS" {
Expect(err).NotTo(HaveOccurred())
Expect(out.DestinationPath).To(Equal(destination))
Expect(store.validatePackagePlatform(destination, PlatformIPhone)).To(Succeed())
} else {
Expect(err).To(MatchError(ContainSubstring("does not declare iPhoneOS support")))
Expect(os.ReadFile(destination)).To(Equal([]byte("previous package")))
}
Expect(destination + ".tmp").NotTo(BeAnExistingFile())
},
Entry("iOS", "iPhoneOS"),
Entry("tvOS", "AppleTVOS"),
)
It("preserves authentication recovery without trying another endpoint", func() {
expectRedownload(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{
Dialog: map[string]interface{}{"kind": "authorization"},
Metrics: map[string]interface{}{"messageCode": uint64(2042)},
}}, nil)
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).NotTo(HaveOccurred())
Expect(actual.Data.FailureType).To(Equal(FailureTypePasswordTokenExpired))
Expect(generated).To(BeZero())
})
DescribeTable("preserves actionable errors from ent/download", func(failure, expected string) {
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
downloads.EXPECT().Send(gomock.Any()).After(first).Return(http.Result[downloadResult]{
StatusCode: gohttp.StatusOK, Data: downloadResult{FailureType: failure},
}, nil)
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).NotTo(HaveOccurred())
Expect(actual.Data.FailureType).To(Equal(expected))
},
Entry("expired token", FailureTypePasswordTokenExpired, FailureTypePasswordTokenExpired),
Entry("sign-in required", FailureTypeSignInRequired, FailureTypePasswordTokenExpired),
Entry("missing license", FailureTypeLicenseNotFound, FailureTypeLicenseNotFound),
)
It("tries ent/download after an unavailable dialog and retains the missing-license result if it fails", func() {
expectRedownload(http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{
CustomerMessage: "Redownload Unavailable with This Apple Account",
}}, nil)
downloads.EXPECT().Send(gomock.Any()).Return(http.Result[downloadResult]{}, forbidden)
actual, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).NotTo(HaveOccurred())
Expect(actual.Data.FailureType).To(Equal(FailureTypeLicenseNotFound))
})
DescribeTable("retains the original error when kbsync recovery is unavailable", func(generatorAvailable bool, endpoint string) {
if !generatorAvailable {
store.kbsyncGenerator = nil
}
expectRedownload(http.Result[downloadResult]{}, forbidden)
_, err := store.sendDelistedDownload(context.Background(), redownload, endpoint, account, app, guid)
Expect(errors.Is(err, forbidden)).To(BeTrue())
Expect(generated).To(BeZero())
},
Entry("no generator", false, testEntDownloadEndpoint),
Entry("no endpoint", true, ""),
)
It("reports both endpoint failures and the missing catalog offer", func() {
failed := errors.New("kbsync endpoint failed")
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
downloads.EXPECT().Send(gomock.Any()).After(first).Return(http.Result[downloadResult]{}, failed)
_, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).To(MatchError(ContainSubstring("app 42 has no offer")))
Expect(errors.Is(err, forbidden)).To(BeTrue())
Expect(errors.Is(err, failed)).To(BeTrue())
})
It("rejects an invalid ent/download destination before generating or sending credentials", func() {
expectRedownload(http.Result[downloadResult]{}, forbidden)
_, err := store.sendDelistedDownload(context.Background(), redownload, "https://example.test/ent/download", account, app, guid)
Expect(err).To(MatchError(ContainSubstring("invalid download endpoint in bag")))
Expect(generated).To(BeZero())
})
It("does not start kbsync recovery after cancellation", func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
expectRedownload(http.Result[downloadResult]{}, forbidden).Do(func(http.Request) { cancel() })
_, err := store.sendDelistedDownload(ctx, redownload, testEntDownloadEndpoint, account, app, guid)
Expect(errors.Is(err, context.Canceled)).To(BeTrue())
Expect(generated).To(BeZero())
})
DescribeTable("validates the unpinned ent/download response", func(field string, value interface{}) {
success.Data.Items[0].Metadata[field] = value
first := expectRedownload(http.Result[downloadResult]{}, forbidden)
downloads.EXPECT().Send(gomock.Any()).After(first).Return(success, nil)
_, err := store.sendDelistedDownload(context.Background(), redownload, testEntDownloadEndpoint, account, app, guid)
Expect(err).To(HaveOccurred())
Expect(err).To(MatchError(ContainSubstring("does not match the requested")))
},
Entry("wrong app", "itemId", int64(43)),
Entry("wrong bundle", "softwareVersionBundleId", "com.other.app"),
Entry("missing bundle", "softwareVersionBundleId", nil),
)
})
var _ = Describe("Download failure dialogs", func() {
It("does not reinterpret successful items using metric codes", func() {
result := downloadResult{
Items: []downloadItemResult{{URL: "https://example.test/app.ipa"}},
Metrics: map[string]interface{}{"messageCode": uint64(0)},
}
Expect(normalizeDownloadFailure(result).FailureType).To(BeEmpty())
})
It("keeps authentication recovery when an error response also contains items", func() {
result := downloadResult{FailureType: FailureTypeDeviceVerificationFailed, Items: []downloadItemResult{{}}}
Expect(normalizeDownloadFailure(result).FailureType).To(Equal(FailureTypePasswordTokenExpired))
})
DescribeTable("normalizes plist dialogs and metric codes", func(body, expected string) {
var result downloadResult
_, err := plist.Unmarshal([]byte(`<plist version="1.0"><dict>`+body+`</dict></plist>`), &result)
Expect(err).NotTo(HaveOccurred())
Expect(normalizeDownloadFailure(result).FailureType).To(Equal(expected))
},
Entry("numeric sign-in metric", `<key>metrics</key><dict><key>messageCode</key><integer>2042</integer></dict>`, FailureTypePasswordTokenExpired),
Entry("string expired-token metric", `<key>metrics</key><dict><key>messageCode</key><string>2034</string></dict>`, FailureTypePasswordTokenExpired),
Entry("existing failure", `<key>failureType</key><string>9610</string><key>metrics</key><dict><key>messageCode</key><integer>2042</integer></dict>`, FailureTypeLicenseNotFound),
Entry("sign-in message", `<key>customerMessage</key><string>Sign in to the iTunes Store</string>`, FailureTypePasswordTokenExpired),
Entry("unavailable dialog with Apple spaces", `<key>dialog</key><dict><key>message</key><string>Redownload Unavailable with This Apple Account</string><key>explanation</key><string>This redownload is not available for this Apple Account either because it was bought by a different user or the item was refunded or cancelled.</string></dict>`, FailureTypeLicenseNotFound),
Entry("unavailable with a metric code", `<key>customerMessage</key><string>Redownload Unavailable with This Apple Account</string><key>metrics</key><dict><key>messageCode</key><integer>2059</integer></dict>`, FailureTypeLicenseNotFound),
)
})
+47 -6
View File
@@ -233,24 +233,54 @@ type downloadItemResult struct {
}
type downloadResult struct {
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
Items []downloadItemResult `plist:"songList,omitempty"`
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
Dialog map[string]interface{} `plist:"dialog,omitempty"`
Metrics map[string]interface{} `plist:"metrics,omitempty"`
Items []downloadItemResult `plist:"songList,omitempty"`
}
func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *progressbar.ProgressBar) error {
if ctx == nil {
ctx = context.Background()
}
err := t.downloadFileAttempt(ctx, src, dst, progress, true, "")
var parallelErr *parallelDownloadError
if !errors.As(err, &parallelErr) || ctx.Err() != nil {
return err
}
if fallbackErr := t.downloadFileAttempt(ctx, src, dst, progress, false, parallelErr.validator); fallbackErr != nil {
return errors.Join(err, fmt.Errorf("single-connection fallback failed: %w", fallbackErr))
}
return nil
}
//nolint:nonamedreturns // Deferred close errors must propagate to callers.
func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *progressbar.ProgressBar) (err error) {
func (t *appstore) downloadFileAttempt(ctx context.Context, src, dst string, progress *progressbar.ProgressBar, parallel bool, validator string) (err error) {
req, err := t.httpClient.NewRequest("GET", src, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
if ctx == nil {
ctx = context.Background()
// Staged ranges are expendable; only the contiguous destination is resumed.
if err := os.RemoveAll(downloadPartsPath(dst)); err != nil {
return fmt.Errorf("failed to remove stale download parts: %w", err)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if req != nil {
req = req.WithContext(ctx)
req.Header.Set("Accept-Encoding", "identity")
if validator != "" {
req.Header.Set("If-Range", validator)
}
}
file, err := t.os.OpenFile(dst, os.O_CREATE|os.O_RDWR, 0644)
@@ -310,6 +340,17 @@ func (t *appstore) downloadFile(ctx context.Context, src, dst string, progress *
writer = io.MultiWriter(file, progress)
}
// Combining responses requires a strong validator to keep all ranges on
// the same representation. Servers without one retain the single stream.
if parallel && res.StatusCode == gohttp.StatusPartialContent &&
remaining == total-offset && remaining >= parallelDownloadThreshold && downloadValidator(res) != "" {
if err := t.downloadFileParallel(ctx, cancel, src, dst, file, writer, res, offset, total, progress); err != nil {
return &parallelDownloadError{err: err, validator: downloadValidator(res)}
}
return nil
}
var body io.Reader = res.Body
if remaining >= 0 {
body = io.LimitReader(body, remaining)
+225
View File
@@ -0,0 +1,225 @@
package appstore
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/schollz/progressbar/v3"
)
const (
parallelDownloadThreshold = 128 << 20
parallelDownloadCount = 4
)
type parallelDownloadError struct {
err error
validator string
}
func (e *parallelDownloadError) Error() string {
return fmt.Sprintf("parallel download failed: %s", e.err)
}
func (e *parallelDownloadError) Unwrap() error {
return e.err
}
func downloadPartsPath(destination string) string {
return destination + ".ipatool-parts"
}
func downloadValidator(response *http.Response) string {
etag := response.Header.Get("ETag")
if strings.HasPrefix(etag, `"`) && strings.HasSuffix(etag, `"`) {
return etag
}
return ""
}
// Keep out-of-order bytes out of the main file, so even an unclean process exit
// leaves its length describing a valid contiguous prefix for the next attempt.
//
//nolint:nonamedreturns // Staging cleanup errors must propagate to callers.
func (t *appstore) downloadFileParallel(
ctx context.Context,
cancel context.CancelFunc,
src, dst string,
file *os.File,
writer io.Writer,
response *http.Response,
offset, total int64,
progress *progressbar.ProgressBar,
) (err error) {
directory := downloadPartsPath(dst)
if err := os.Mkdir(directory, 0700); err != nil {
return fmt.Errorf("failed to create download staging directory: %w", err)
}
defer func() {
if cleanupErr := os.RemoveAll(directory); cleanupErr != nil {
err = joinCleanupError(err, "failed to remove download staging directory", cleanupErr)
}
}()
chunkSize := (total - offset) / parallelDownloadCount
validator := downloadValidator(response)
var (
workers sync.WaitGroup
failures [parallelDownloadCount - 1]error
)
for index := range parallelDownloadCount - 1 {
workers.Add(1)
go func() {
defer workers.Done()
start := offset + chunkSize*int64(index+1)
end := start + chunkSize - 1
if index == parallelDownloadCount-2 {
end = total - 1
}
path := filepath.Join(directory, fmt.Sprintf("%d", index))
failures[index] = t.downloadFileRange(ctx, src, path, start, end, total, validator, progress)
if failures[index] != nil {
cancel()
}
}()
}
_, copyErr := io.CopyN(writer, response.Body, chunkSize)
// The initial request covers the entire remainder. Stop reading it once its
// first quarter is written; the other requests supply the remaining ranges.
_ = response.Body.Close()
if copyErr != nil {
cancel()
}
workers.Wait()
for _, failure := range failures {
if failure != nil {
return failure
}
}
if copyErr != nil {
return fmt.Errorf("failed to download first range: %w", copyErr)
}
for index := range parallelDownloadCount - 1 {
if err := ctx.Err(); err != nil {
return fmt.Errorf("download canceled: %w", err)
}
path := filepath.Join(directory, fmt.Sprintf("%d", index))
if err := appendDownloadPart(file, path); err != nil {
return err
}
}
return nil
}
//nolint:nonamedreturns // Deferred close errors must propagate to callers.
func (t *appstore) downloadFileRange(ctx context.Context, src, dst string, start, end, total int64, validator string, progress *progressbar.ProgressBar) (err error) {
req, err := t.httpClient.NewRequest(http.MethodGet, src, nil)
if err != nil {
return fmt.Errorf("failed to create range request: %w", err)
}
req = req.WithContext(ctx)
req.Header.Set("Accept-Encoding", "identity")
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
if validator != "" {
req.Header.Set("If-Range", validator)
}
response, err := t.httpClient.Do(req)
if err != nil {
return fmt.Errorf("range request failed: %w", err)
}
defer response.Body.Close()
_, length, size, _, err := downloadResponseRange(response, start)
if err != nil {
return err
}
if response.StatusCode != http.StatusPartialContent || length != end-start+1 || size != total {
return fmt.Errorf("unexpected download range %q", response.Header.Get("Content-Range"))
}
if encoding := response.Header.Get("Content-Encoding"); encoding != "" && !strings.EqualFold(encoding, "identity") {
return fmt.Errorf("unexpected download content encoding %q", encoding)
}
if etag := response.Header.Get("ETag"); validator != "" && etag != "" && etag != validator {
return fmt.Errorf("download validator changed from %q to %q", validator, etag)
}
file, err := os.OpenFile(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to create download part: %w", err)
}
defer func() {
if closeErr := file.Close(); closeErr != nil {
err = joinCleanupError(err, "failed to close download part", closeErr)
}
}()
var writer io.Writer = file
if progress != nil {
writer = io.MultiWriter(file, progress)
}
written, err := io.Copy(writer, io.LimitReader(response.Body, length+1))
if err != nil {
return fmt.Errorf("failed to write download part: %w", err)
}
if written != length {
return fmt.Errorf("download part is incomplete: %w", io.ErrUnexpectedEOF)
}
return nil
}
func appendDownloadPart(destination io.Writer, path string) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open download part: %w", err)
}
_, copyErr := io.Copy(destination, file)
closeErr := file.Close()
if copyErr != nil {
return fmt.Errorf("failed to append download part: %w", copyErr)
}
if closeErr != nil {
return fmt.Errorf("failed to close download part: %w", closeErr)
}
if err := os.Remove(path); err != nil {
return fmt.Errorf("failed to remove download part: %w", err)
}
return nil
}
@@ -0,0 +1,448 @@
package appstore
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/schollz/progressbar/v3"
)
type downloadFixtureData byte
func (seed downloadFixtureData) ReadAt(buffer []byte, offset int64) (int, error) {
for index := range buffer {
buffer[index] = byte((offset+int64(index))%251) + byte(seed)
}
return len(buffer), nil
}
type downloadFixtureRequest struct {
rangeHeader string
validator string
}
type parallelDownloadFixture struct {
size int64
path string
store *appstore
server *httptest.Server
mu sync.Mutex
requests []downloadFixtureRequest
active atomic.Int64
maximum atomic.Int64
handler http.HandlerFunc
}
func newParallelDownloadFixture(size int64) *parallelDownloadFixture {
fixture := &parallelDownloadFixture{
size: size,
path: filepath.Join(GinkgoT().TempDir(), "app.ipa.tmp"),
store: &appstore{httpClient: newDownloadTestClient(), os: operatingsystem.New()},
}
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
fixture.serve(writer, request, 1, `"fixture"`)
}
fixture.server = httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
defer GinkgoRecover()
active := fixture.active.Add(1)
defer fixture.active.Add(-1)
for maximum := fixture.maximum.Load(); active > maximum; maximum = fixture.maximum.Load() {
if fixture.maximum.CompareAndSwap(maximum, active) {
break
}
}
fixture.mu.Lock()
fixture.requests = append(fixture.requests, downloadFixtureRequest{
rangeHeader: request.Header.Get("Range"),
validator: request.Header.Get("If-Range"),
})
fixture.mu.Unlock()
fixture.handler(writer, request)
}))
DeferCleanup(fixture.server.Close)
return fixture
}
func (fixture *parallelDownloadFixture) serve(writer http.ResponseWriter, request *http.Request, seed downloadFixtureData, validator string) {
if validator != "" {
writer.Header().Set("ETag", validator)
}
http.ServeContent(writer, request, "app.ipa", time.Time{}, io.NewSectionReader(seed, 0, fixture.size))
}
func (fixture *parallelDownloadFixture) recordedRequests() []downloadFixtureRequest {
fixture.mu.Lock()
defer fixture.mu.Unlock()
return append([]downloadFixtureRequest(nil), fixture.requests...)
}
func (fixture *parallelDownloadFixture) writePrefix(size int64) {
file, err := os.Create(fixture.path)
Expect(err).NotTo(HaveOccurred())
_, err = io.Copy(file, io.NewSectionReader(downloadFixtureData(1), 0, size))
Expect(err).NotTo(HaveOccurred())
Expect(file.Close()).To(Succeed())
}
func (fixture *parallelDownloadFixture) expectContents(seed downloadFixtureData) {
file, err := os.Open(fixture.path)
Expect(err).NotTo(HaveOccurred())
defer file.Close()
info, err := file.Stat()
Expect(err).NotTo(HaveOccurred())
Expect(info.Size()).To(Equal(fixture.size))
actual, expected := sha256.New(), sha256.New()
_, err = io.Copy(actual, file)
Expect(err).NotTo(HaveOccurred())
_, err = io.Copy(expected, io.NewSectionReader(seed, 0, fixture.size))
Expect(err).NotTo(HaveOccurred())
Expect(actual.Sum(nil)).To(Equal(expected.Sum(nil)))
Expect(downloadPartsPath(fixture.path)).NotTo(BeAnExistingFile())
Expect(downloadPartsPath(fixture.path)).NotTo(BeADirectory())
}
var _ = Describe("automatic parallel downloads", func() {
It("uses four requests when exactly 128 MiB remains and counts progress once", func() {
const prefix = int64(4096)
fixture := newParallelDownloadFixture(parallelDownloadThreshold + prefix)
fixture.writePrefix(prefix)
progress := progressbar.NewOptions64(1, progressbar.OptionSetWriter(io.Discard))
err := fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, progress)
Expect(err).NotTo(HaveOccurred())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(requests).To(HaveLen(parallelDownloadCount))
Expect(requests[0].rangeHeader).To(Equal("bytes=4096-"))
for _, request := range requests[1:] {
Expect(request.validator).To(Equal(`"fixture"`))
Expect(request.rangeHeader).NotTo(HaveSuffix("-"))
}
Expect(fixture.maximum.Load()).To(Equal(int64(parallelDownloadCount)))
Expect(progress.State().CurrentNum).To(Equal(fixture.size))
})
It("uses one request when one byte less than 128 MiB remains", func() {
const prefix = int64(4097)
fixture := newParallelDownloadFixture(parallelDownloadThreshold + prefix - 1)
fixture.writePrefix(prefix)
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
Expect(fixture.recordedRequests()).To(HaveLen(1))
})
It("uses one request for a small file", func() {
fixture := newParallelDownloadFixture(64 << 10)
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
Expect(fixture.recordedRequests()).To(HaveLen(1))
})
It("keeps one stream when the server ignores the initial range", func() {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
fixture.writePrefix(4096)
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
request.Header.Del("Range")
fixture.serve(writer, request, 1, `"fixture"`)
}
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
Expect(fixture.recordedRequests()).To(HaveLen(1))
})
DescribeTable("falls back to one stream without appending invalid staged bytes", func(status int, contentRange string, body string) {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
if strings.HasSuffix(request.Header.Get("Range"), "-") {
fixture.serve(writer, request, 1, `"fixture"`)
return
}
writer.Header().Set("Content-Range", contentRange)
writer.WriteHeader(status)
_, _ = io.WriteString(writer, body)
}
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(len(requests)).To(BeNumerically(">", 1))
Expect(requests[len(requests)-1].rangeHeader).To(HaveSuffix("-"))
Expect(requests[len(requests)-1].validator).To(Equal(`"fixture"`))
},
Entry("ignored bounded ranges", http.StatusOK, "", "a whole response"),
Entry("wrong offsets", http.StatusPartialContent, "bytes 1-3/134217728", "bad"),
Entry("content-length mismatch", http.StatusPartialContent, "bytes 33554432-67108863/134217728", "bad"),
Entry("server errors", http.StatusServiceUnavailable, "", "unavailable"),
)
It("restarts the fallback when If-Range detects a changed representation", func() {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
var requests atomic.Int64
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
if requests.Add(1) == 1 {
fixture.serve(writer, request, 1, `"old"`)
return
}
fixture.serve(writer, request, 2, `"new"`)
}
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(2)
})
DescribeTable("keeps a single stream without a strong validator", func(validator string) {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
fixture.serve(writer, request, 1, validator)
}
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
Expect(fixture.recordedRequests()).To(HaveLen(1))
},
Entry("missing ETag", ""),
Entry("weak ETag", `W/"fixture"`),
)
It("falls back when a valid range response is truncated mid-body", func() {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
value := request.Header.Get("Range")
if strings.HasSuffix(value, "-") {
fixture.serve(writer, request, 1, `"fixture"`)
return
}
writer.Header().Set("Content-Range", strings.Replace(value, "=", " ", 1)+fmt.Sprintf("/%d", fixture.size))
writer.Header().Set("ETag", `"fixture"`)
writer.WriteHeader(http.StatusPartialContent)
writer.(http.Flusher).Flush()
_, _ = io.WriteString(writer, "truncated")
}
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(len(requests)).To(BeNumerically(">", 1))
Expect(requests[len(requests)-1].rangeHeader).To(HaveSuffix("-"))
})
It("resumes the first stream after a disconnect and resets staged progress", func() {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
var first atomic.Bool
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
if first.CompareAndSwap(false, true) {
writer.Header().Set("ETag", `"fixture"`)
writer.Header().Set("Content-Length", fmt.Sprint(fixture.size))
writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", fixture.size-1, fixture.size))
writer.WriteHeader(http.StatusPartialContent)
_, _ = io.Copy(writer, io.NewSectionReader(downloadFixtureData(1), 0, 4096))
return
}
fixture.serve(writer, request, 1, `"fixture"`)
}
progress := progressbar.NewOptions64(1, progressbar.OptionSetWriter(io.Discard))
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, progress)).To(Succeed())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(len(requests)).To(BeNumerically(">", 1))
Expect(requests[len(requests)-1].rangeHeader).To(Equal("bytes=4096-"))
Expect(progress.State().CurrentNum).To(Equal(fixture.size))
})
It("preserves a contiguous prefix on interruption and resumes with one request below the threshold", func() {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
var interrupted atomic.Bool
interrupted.Store(true)
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
if interrupted.Load() && strings.HasSuffix(request.Header.Get("Range"), "-") {
writer.Header().Set("ETag", `"fixture"`)
writer.Header().Set("Content-Length", fmt.Sprint(fixture.size))
writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", fixture.size-1, fixture.size))
writer.WriteHeader(http.StatusPartialContent)
_, _ = io.Copy(writer, io.NewSectionReader(downloadFixtureData(1), 0, 4096))
writer.(http.Flusher).Flush()
<-request.Context().Done()
return
}
fixture.serve(writer, request, 1, `"fixture"`)
}
ctx, cancel := context.WithCancel(context.Background())
DeferCleanup(cancel)
finished := make(chan error, 1)
go func() {
finished <- fixture.store.downloadFile(ctx, fixture.server.URL, fixture.path, nil)
}()
Eventually(func() int64 {
var staged int64
for index := range parallelDownloadCount - 1 {
info, err := os.Stat(filepath.Join(downloadPartsPath(fixture.path), fmt.Sprint(index)))
if err == nil {
staged += info.Size()
}
}
return staged
}, 10*time.Second).Should(Equal(int64(parallelDownloadThreshold / 4 * 3)))
Eventually(func() int64 {
info, err := os.Stat(fixture.path)
if err != nil {
return 0
}
return info.Size()
}).Should(Equal(int64(4096)))
cancel()
var downloadErr error
Eventually(finished).Should(Receive(&downloadErr))
Expect(errors.Is(downloadErr, context.Canceled)).To(BeTrue())
info, err := os.Stat(fixture.path)
Expect(err).NotTo(HaveOccurred())
Expect(info.Size()).To(Equal(int64(4096)))
Expect(downloadPartsPath(fixture.path)).NotTo(BeADirectory())
interrupted.Store(false)
before := len(fixture.recordedRequests())
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(requests).To(HaveLen(before + 1))
Expect(requests[before].rangeHeader).To(Equal("bytes=4096-"))
})
It("discards orphaned parts after an unclean exit and resumes only the main file", func() {
fixture := newParallelDownloadFixture(64 << 10)
fixture.writePrefix(4096)
directory := downloadPartsPath(fixture.path)
Expect(os.Mkdir(directory, 0700)).To(Succeed())
Expect(os.WriteFile(filepath.Join(directory, "0"), []byte("out-of-order bytes"), 0600)).To(Succeed())
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(requests).To(HaveLen(1))
Expect(requests[0].rangeHeader).To(Equal("bytes=4096-"))
})
It("resumes safely after the downloading process is killed", func() {
fixture := newParallelDownloadFixture(parallelDownloadThreshold)
var interrupted atomic.Bool
interrupted.Store(true)
fixture.handler = func(writer http.ResponseWriter, request *http.Request) {
if interrupted.Load() && strings.HasSuffix(request.Header.Get("Range"), "-") {
writer.Header().Set("ETag", `"fixture"`)
writer.Header().Set("Content-Length", fmt.Sprint(fixture.size))
writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", fixture.size-1, fixture.size))
writer.WriteHeader(http.StatusPartialContent)
_, _ = io.Copy(writer, io.NewSectionReader(downloadFixtureData(1), 0, 4096))
writer.(http.Flusher).Flush()
<-request.Context().Done()
return
}
fixture.serve(writer, request, 1, `"fixture"`)
}
executable, err := os.Executable()
Expect(err).NotTo(HaveOccurred())
child := exec.Command(executable, "-test.run=^TestAppStore$", "-ginkgo.focus=download subprocess helper")
child.Env = append(os.Environ(), "IPATOOL_DOWNLOAD_TEST_URL="+fixture.server.URL, "IPATOOL_DOWNLOAD_TEST_PATH="+fixture.path)
Expect(child.Start()).To(Succeed())
DeferCleanup(func() {
_ = child.Process.Kill()
_ = child.Wait()
})
Eventually(func() int64 {
var size int64
for index := range parallelDownloadCount - 1 {
info, err := os.Stat(filepath.Join(downloadPartsPath(fixture.path), fmt.Sprint(index)))
if err == nil {
size += info.Size()
}
}
return size
}, 15*time.Second).Should(Equal(int64(parallelDownloadThreshold / 4 * 3)))
Eventually(func() int64 {
info, err := os.Stat(fixture.path)
if err != nil {
return 0
}
return info.Size()
}).Should(Equal(int64(4096)))
Expect(child.Process.Kill()).To(Succeed())
Expect(child.Wait()).To(HaveOccurred())
Expect(downloadPartsPath(fixture.path)).To(BeADirectory())
interrupted.Store(false)
before := len(fixture.recordedRequests())
Expect(fixture.store.downloadFile(context.Background(), fixture.server.URL, fixture.path, nil)).To(Succeed())
fixture.expectContents(1)
requests := fixture.recordedRequests()
Expect(requests).To(HaveLen(before + 1))
Expect(requests[before].rangeHeader).To(Equal("bytes=4096-"))
})
})
var _ = Describe("download subprocess helper", func() {
It("downloads the subprocess fixture", func() {
url := os.Getenv("IPATOOL_DOWNLOAD_TEST_URL")
if url == "" {
Skip("only executed by the process-interruption test")
}
store := &appstore{httpClient: newDownloadTestClient(), os: operatingsystem.New()}
Expect(store.downloadFile(context.Background(), url, os.Getenv("IPATOOL_DOWNLOAD_TEST_PATH"), nil)).To(Succeed())
})
})
+75 -3
View File
@@ -107,9 +107,9 @@ func (t *appstore) sendDownloadProduct(ctx context.Context, acc Account, app App
externalVersionID, err = t.lookupLatestExternalVersionID(acc, app, platform)
if errors.Is(err, errIOSCatalogAppNotFound) {
// A delisted app can still be available to this account. Try once
// without a version; Download validates the returned package's platform.
res, err := t.sendUnpinnedRedownload(ctx, redownload, acc, app, guid)
// A delisted app can still be available to this account. Neither
// recovery endpoint needs a catalog version to select its entitled build.
res, err := t.sendDelistedDownload(ctx, redownload, bag.EntDownloadEndpoint, acc, app, guid)
return res, platform, err
}
@@ -139,6 +139,40 @@ func (t *appstore) sendDownloadProduct(ctx context.Context, acc Account, app App
return redownloadRes, platform, nil
}
func (t *appstore) sendDelistedDownload(ctx context.Context, redownload downloadProductEndpoint, entEndpoint string, acc Account, app App, guid string) (http.Result[downloadResult], error) {
res, err := t.sendUnpinnedRedownload(ctx, redownload, acc, app, guid)
if err == nil && res.Data.FailureType != FailureTypeLicenseNotFound {
return res, nil
}
if ctxErr := ctx.Err(); ctxErr != nil {
return res, errors.Join(err, ctxErr)
}
if t.kbsyncGenerator == nil || entEndpoint == "" {
return res, err
}
endpoint, endpointErr := newDownloadEndpoint(entEndpoint, entDownloadPath)
if endpointErr != nil {
return res, errors.Join(err, endpointErr)
}
// Bypass catalog discovery: it already confirmed that there is no offer.
// Download still checks the returned package's platform before publishing it.
entRes, entErr := t.sendEntDownload(ctx, endpoint, acc, app, guid, "")
if entErr == nil || entRes.Data.FailureType == FailureTypePasswordTokenExpired ||
entRes.Data.FailureType == FailureTypeLicenseNotFound {
return entRes, nil
}
if res.Data.FailureType == FailureTypeLicenseNotFound {
return res, nil
}
return entRes, fmt.Errorf("app %d has no offer in the account's App Store catalog and the kbsync fallback failed: %w", app.ID, errors.Join(err, entErr))
}
func (t *appstore) sendUnpinnedRedownload(ctx context.Context, endpoint downloadProductEndpoint, acc Account, app App, guid string) (http.Result[downloadResult], error) {
requestContext, cancel := context.WithTimeout(ctx, http.DefaultAuthenticationTimeout)
defer cancel()
@@ -155,6 +189,8 @@ func (t *appstore) sendUnpinnedRedownload(ctx context.Context, endpoint download
return res, fmt.Errorf("failed to send redownload request: %w", err)
}
res.Data = normalizeDownloadFailure(res.Data)
if err := validateDownloadResponse(res, app, "", "redownload"); err != nil {
return res, err
}
@@ -166,6 +202,42 @@ func (t *appstore) sendUnpinnedRedownload(ctx context.Context, endpoint download
return res, nil
}
func normalizeDownloadFailure(data downloadResult) downloadResult {
if len(data.Items) == 0 && data.FailureType == "" && data.Metrics["messageCode"] != nil {
data.FailureType = strings.TrimSpace(fmt.Sprint(data.Metrics["messageCode"]))
}
if data.FailureType == FailureTypeSignInRequired || data.FailureType == FailureTypeDeviceVerificationFailed {
data.FailureType = FailureTypePasswordTokenExpired
}
if len(data.Items) > 0 {
return data
}
message := strings.Join(strings.Fields(data.CustomerMessage), " ")
if strings.EqualFold(message, "sign in to the itunes store") || strings.EqualFold(message, "sign-in required") {
data.FailureType = FailureTypePasswordTokenExpired
}
if data.FailureType == FailureTypePasswordTokenExpired {
return data
}
const unavailable = "Redownload Unavailable with This Apple Account"
dialogMessage, _ := data.Dialog["message"].(string)
dialogExplanation, _ := data.Dialog["explanation"].(string)
if message == unavailable ||
(strings.Join(strings.Fields(dialogMessage), " ") == unavailable &&
strings.Join(strings.Fields(dialogExplanation), " ") == "This redownload is not available for this Apple Account either because it was bought by a different user or the item was refunded or cancelled.") {
data.FailureType = FailureTypeLicenseNotFound
}
return data
}
func isEmptyRedownloadError(err error) bool {
var unexpected *http.UnexpectedResponseError
@@ -42,9 +42,10 @@ var _ = Describe("AppStore (Download Product)", func() {
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
store = &appstore{
bagClient: mockBagClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
bagClient: mockBagClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
storefrontCountryCodes: testStorefrontCountryCodes(),
}
account = Account{
DirectoryServicesID: "test-dsid",
+40 -23
View File
@@ -15,6 +15,7 @@ import (
"strings"
"time"
"github.com/majd/ipatool/v2/internal/store"
"github.com/majd/ipatool/v2/pkg/http"
"github.com/majd/ipatool/v2/pkg/keychain"
"github.com/majd/ipatool/v2/pkg/util/machine"
@@ -63,16 +64,17 @@ var _ = Describe("AppStore (Download)", func() {
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
keychain: mockKeychain,
bagClient: mockBagClient,
loginClient: mockLoginClient,
purchaseClient: mockPurchaseClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
storefrontClient: mockStorefrontClient,
httpClient: mockHTTPClient,
machine: mockMachine,
os: mockOS,
keychain: mockKeychain,
bagClient: mockBagClient,
loginClient: mockLoginClient,
purchaseClient: mockPurchaseClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
storefrontClient: mockStorefrontClient,
storefrontCountryCodes: testStorefrontCountryCodes(),
httpClient: mockHTTPClient,
machine: mockMachine,
os: mockOS,
}
})
@@ -110,6 +112,19 @@ var _ = Describe("AppStore (Download)", func() {
})
})
DescribeTable("suggests logging in when Store AMD state is not provisioned",
func(state []byte) {
as.(*appstore).authBackend = store.New(nil, nil)
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
mockKeychain.EXPECT().Get(anisetteKeychainKey).Return(state, nil)
_, err := as.Download(DownloadInput{App: App{ID: 1641486558}})
Expect(err).To(MatchError("failed to send http request: generate Store AMD proof: store AMD state is not provisioned; run 'ipatool auth login' to authenticate"))
},
Entry("missing state", nil),
Entry("persisted identity without provisioning", []byte(`{"Identifier":"AAECAwQFBgcICQoLDA0ODw=="}`)),
)
When("request uses a custom pod", func() {
const (
testPod = "42"
@@ -811,12 +826,13 @@ var _ = Describe("AppStore (Download)", func() {
}, nil)
store := &appstore{
downloadClient: mockDownloadClient,
bagClient: mockBagClient,
platformClient: mockPlatformClient,
httpClient: mockHTTPClient,
machine: mockMachine,
os: operatingsystem.New(),
downloadClient: mockDownloadClient,
bagClient: mockBagClient,
platformClient: mockPlatformClient,
httpClient: mockHTTPClient,
machine: mockMachine,
os: operatingsystem.New(),
storefrontCountryCodes: testStorefrontCountryCodes(),
}
out, err := store.Download(DownloadInput{
Account: Account{StoreFront: "143441", Email: "test@example.com"},
@@ -1082,7 +1098,7 @@ var _ = Describe("AppStore (Download)", func() {
Stat(testFile.Name()).
Return(info, nil)
mockHTTPClient.EXPECT().
Do(request.WithContext(context.Background())).
Do(gomock.AssignableToTypeOf(request)).
DoAndReturn(func(request *gohttp.Request) (*gohttp.Response, error) {
Expect(request.Header.Get("range")).To(Equal("bytes=8-"))
@@ -1292,12 +1308,13 @@ var _ = Describe("Downloading delisted tvOS apps", func() {
mockMachine := machine.NewMockMachine(ctrl)
mockMachine.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
store = &appstore{
platformClient: platformClient,
downloadClient: downloadClient,
bagClient: bagClient,
httpClient: httpClient,
machine: mockMachine,
os: operatingsystem.New(),
platformClient: platformClient,
downloadClient: downloadClient,
bagClient: bagClient,
httpClient: httpClient,
machine: mockMachine,
os: operatingsystem.New(),
storefrontCountryCodes: testStorefrontCountryCodes(),
}
input = DownloadInput{
Account: Account{StoreFront: "143441"},
@@ -31,7 +31,7 @@ var _ = Describe("iOS catalog version fallback", func() {
BeforeEach(func() {
client = http.NewMockClient[platformVersionLookupResult](gomock.NewController(GinkgoT()))
store = &appstore{platformClient: client}
store = &appstore{platformClient: client, storefrontCountryCodes: testStorefrontCountryCodes()}
})
DescribeTable("resolves Arcade versions after exhausting the MDM catalogs", func(platform Platform, noOffers bool, quotedVersion bool) {
@@ -115,7 +115,7 @@ var _ = Describe("ListVersions for apps missing from the MDM catalogs", func() {
downloads := http.NewMockClient[downloadResult](ctrl)
bags := http.NewMockClient[bagResult](ctrl)
device := machine.NewMockMachine(ctrl)
store := &appstore{platformClient: catalog, downloadClient: downloads, bagClient: bags, machine: device}
store := &appstore{platformClient: catalog, downloadClient: downloads, bagClient: bags, machine: device, storefrontCountryCodes: testStorefrontCountryCodes()}
device.EXPECT().MacAddress().Return("00:11:22:33:44:55", nil)
result := downloadResult{FailureType: FailureTypeLicenseNotFound}
if licensed {
+14 -8
View File
@@ -133,20 +133,26 @@ func (t *appstore) sendEntDownloadRequest(ctx context.Context, endpoint download
}
}
request.Payload = &http.XMLPayload{Content: map[string]interface{}{
"creditDisplay": "",
"guid": guid,
"kbsync": blob,
"salableAdamId": strconv.FormatInt(app.ID, 10),
"serialNumber": base64.StdEncoding.EncodeToString(serial),
"externalVersionId": versionID,
}}
payload := map[string]interface{}{
"creditDisplay": "",
"guid": guid,
"kbsync": blob,
"salableAdamId": strconv.FormatInt(app.ID, 10),
"serialNumber": base64.StdEncoding.EncodeToString(serial),
}
if versionID != "" {
payload["externalVersionId"] = versionID
}
request.Payload = &http.XMLPayload{Content: payload}
res, err := t.downloadClient.Send(request)
if err != nil {
return res, fmt.Errorf("send ent/download request: %w", err)
}
res.Data = normalizeDownloadFailure(res.Data)
if res.Data.FailureType != "" {
return res, NewErrorWithMetadata(fmt.Errorf("received ent/download error: %s", res.Data.FailureType), res)
}
+1
View File
@@ -42,6 +42,7 @@ var _ = Describe("AppStore (preferred kbsync download)", func() {
generated = 0
store = &appstore{
downloadClient: downloads, bagClient: bags, platformClient: platforms,
storefrontCountryCodes: testStorefrontCountryCodes(),
kbsyncGenerator: func(ctx context.Context, hardwareID []byte, dsid uint64) ([]byte, error) {
Expect(ctx.Err()).NotTo(HaveOccurred())
deadline, ok := ctx.Deadline()
+5 -4
View File
@@ -28,10 +28,11 @@ var _ = Describe("AppStore (ListVersions)", func() {
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
mockMachine = machine.NewMockMachine(ctrl)
as = &appstore{
bagClient: mockBagClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
machine: mockMachine,
bagClient: mockBagClient,
downloadClient: mockDownloadClient,
platformClient: mockPlatformClient,
machine: mockMachine,
storefrontCountryCodes: testStorefrontCountryCodes(),
}
})
+87 -1
View File
@@ -66,6 +66,12 @@ func (t *appstore) legacyLogin(input LoginInput) (LoginOutput, error) {
return LoginOutput{}, err
}
if countryCode := phoneNumberStorefrontCountryCode(input.Email); countryCode != "" {
if _, err = t.discoverStorefrontID(countryCode); err != nil {
return LoginOutput{}, fmt.Errorf("failed to discover storefronts: %w", err)
}
}
macAddr, err := t.machine.MacAddress()
if err != nil {
return LoginOutput{}, fmt.Errorf("failed to get mac address: %w", err)
@@ -153,10 +159,24 @@ type loginAccountResult struct {
Address loginAddressResult `plist:"address,omitempty"`
}
type loginDialogActionResult struct {
Kind string `plist:"kind,omitempty"`
URL string `plist:"url,omitempty"`
}
type loginDialogResult struct {
Message string `plist:"message,omitempty"`
Explanation string `plist:"explanation,omitempty"`
OKButtonString string `plist:"okButtonString,omitempty"`
OKButtonAction loginDialogActionResult `plist:"okButtonAction,omitempty"`
CancelButtonString string `plist:"cancelButtonString,omitempty"`
}
type loginResult struct {
FailureType string `plist:"failureType,omitempty"`
CustomerMessage string `plist:"customerMessage,omitempty"`
Account loginAccountResult `plist:"accountInfo,omitempty"`
Dialog loginDialogResult `plist:"dialog,omitempty"`
DirectoryServicesID string `plist:"dsPersonId,omitempty"`
PasswordToken string `plist:"passwordToken,omitempty"`
}
@@ -377,6 +397,8 @@ func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int
if action := authenticationMachineAction(res.Headers); action != nil {
err = action
} else if dialogErr := authenticationDialogError(res.Data); dialogErr != nil {
err = NewErrorWithMetadata(dialogErr, res)
} else if res.StatusCode >= gohttp.StatusMultipleChoices && res.StatusCode < gohttp.StatusBadRequest {
if redirect, err = res.GetHeader("location"); err != nil {
err = fmt.Errorf("failed to retrieve redirect location: %w", err)
@@ -416,6 +438,70 @@ func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int
return retry, redirect, err
}
func authenticationDialogError(result loginResult) error {
dialog := result.Dialog
if strings.TrimSpace(dialog.Message) == "" && strings.TrimSpace(dialog.Explanation) == "" &&
strings.TrimSpace(dialog.OKButtonString) == "" && strings.TrimSpace(dialog.CancelButtonString) == "" &&
strings.TrimSpace(dialog.OKButtonAction.Kind) == "" && strings.TrimSpace(dialog.OKButtonAction.URL) == "" {
return nil
}
message := strings.TrimSpace(dialog.Message)
explanation := strings.TrimSpace(dialog.Explanation)
if message == "" {
message = strings.TrimSpace(result.CustomerMessage)
}
actionURL := trustedAuthenticationDialogURL(dialog.OKButtonAction)
if message == "" && explanation == "" && actionURL == "" {
return nil
}
parts := make([]string, 0, 2)
if message != "" {
parts = append(parts, message)
}
if explanation != "" && explanation != message {
parts = append(parts, explanation)
}
detail := strings.Join(parts, ": ")
if detail == "" {
detail = "Apple requires action before sign-in can continue"
}
if actionURL != "" {
label := strings.TrimSpace(dialog.OKButtonString)
if label == "" {
label = "Continue"
}
detail += fmt.Sprintf(" (%s: %s)", label, actionURL)
}
return errors.New(detail)
}
func trustedAuthenticationDialogURL(action loginDialogActionResult) string {
if !strings.EqualFold(strings.TrimSpace(action.Kind), "OpenURL") {
return ""
}
value, err := url.Parse(strings.TrimSpace(action.URL))
if err != nil || value.Scheme != "https" || value.User != nil || value.Fragment != "" || value.Port() != "" && value.Port() != "443" {
return ""
}
host := strings.ToLower(value.Hostname())
if host != "apple.com" && !strings.HasSuffix(host, ".apple.com") {
return ""
}
return value.String()
}
func authenticationMachineAction(headers map[string]string) *authenticationMachineActionError {
var action, data string
@@ -529,7 +615,7 @@ func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string
},
},
}
if storefront := phoneNumberStorefront(email); storefront != "" {
if storefront := t.storefrontID(phoneNumberStorefrontCountryCode(email)); storefront != "" {
request.Headers["X-Apple-Store-Front"] = storefront
}
+7 -6
View File
@@ -2,9 +2,10 @@ package appstore
import "strings"
// phoneNumberStorefront supplies a routing hint for phone-based Apple Accounts
// in mainland China and India. It does not change the Apple ID sent to Apple.
func phoneNumberStorefront(appleID string) string {
// phoneNumberStorefrontCountryCode identifies the storefront routing hint for
// phone-based Apple Accounts in mainland China and India. It does not change
// the Apple ID sent to Apple.
func phoneNumberStorefrontCountryCode(appleID string) string {
number := strings.ReplaceAll(strings.TrimSpace(appleID), " ", "")
number = strings.ReplaceAll(number, "-", "")
@@ -30,7 +31,7 @@ func phoneNumberStorefront(appleID string) string {
// match a supported country code and cannot fall back to a local format.
switch {
case len(number) == 13 && strings.HasPrefix(number, "861"):
return storeFronts["CN"]
return "CN"
case len(number) == 12 && strings.HasPrefix(number, "91"):
number = number[2:]
case international:
@@ -38,7 +39,7 @@ func phoneNumberStorefront(appleID string) string {
}
if len(number) == 11 && number[0] == '1' {
return storeFronts["CN"]
return "CN"
}
// India also permits a trunk prefix when writing a national number.
@@ -47,7 +48,7 @@ func phoneNumberStorefront(appleID string) string {
}
if len(number) == 10 && number[0] >= '6' && number[0] <= '9' {
return storeFronts["IN"]
return "IN"
}
return ""
@@ -8,7 +8,7 @@ import (
var _ = Describe("Phone account login routing", func() {
DescribeTable("sets a storefront hint without rewriting the Apple ID", func(appleID, storefront string) {
request := (&appstore{}).loginRequest(appleID, "password", "", "guid", testAuthEndpoint, 1, &stubActionSigner{})
request := (&appstore{storefrontCountryCodes: testStorefrontCountryCodes()}).loginRequest(appleID, "password", "", "guid", testAuthEndpoint, 1, &stubActionSigner{})
Expect(request.Payload.(*http.XMLPayload).Content).To(HaveKeyWithValue("appleId", appleID))
if storefront == "" {
+50 -5
View File
@@ -42,11 +42,12 @@ var _ = Describe("AppStore (Login)", func() {
mockMachine = machine.NewMockMachine(ctrl)
signer = &stubActionSigner{}
as = &appstore{
keychain: mockKeychain,
loginClient: mockClient,
bagClient: mockBagClient,
machine: mockMachine,
authRetrySleep: func(time.Duration) {},
keychain: mockKeychain,
loginClient: mockClient,
bagClient: mockBagClient,
machine: mockMachine,
authRetrySleep: func(time.Duration) {},
storefrontCountryCodes: testStorefrontCountryCodes(),
actionSignerFactory: func(config SAPConfig, machineID []byte) (ActionSigner, error) {
Expect(config).To(Equal(validSAPConfig()))
Expect(machineID).To(Equal([]byte{0, 0, 0, 0, 0, 0}))
@@ -136,6 +137,20 @@ var _ = Describe("AppStore (Login)", func() {
)
})
DescribeTable("does not expose untrusted dialog actions", func(action loginDialogActionResult) {
result := loginResult{Dialog: loginDialogResult{Message: "Account action required", OKButtonString: "Continue", OKButtonAction: action}}
err := authenticationDialogError(result)
Expect(err).To(MatchError("Account action required"))
},
Entry("non-Apple URL", loginDialogActionResult{Kind: "OpenURL", URL: "https://example.com/reset"}),
Entry("insecure URL", loginDialogActionResult{Kind: "OpenURL", URL: "http://iforgot.apple.com/reset"}),
Entry("embedded credentials", loginDialogActionResult{Kind: "OpenURL", URL: "https://user@iforgot.apple.com/reset"}),
Entry("nonstandard port", loginDialogActionResult{Kind: "OpenURL", URL: "https://iforgot.apple.com:8443/reset"}),
Entry("fragment", loginDialogActionResult{Kind: "OpenURL", URL: "https://iforgot.apple.com/reset#token"}),
Entry("non-navigation action", loginDialogActionResult{Kind: "Buy", URL: "https://iforgot.apple.com/reset"}),
)
When("fails to read Machine's MAC address", func() {
BeforeEach(func() {
mockMachine.EXPECT().
@@ -298,6 +313,36 @@ var _ = Describe("AppStore (Login)", func() {
})
})
When("store API returns an account recovery dialog", func() {
BeforeEach(func() {
mockClient.EXPECT().
Send(gomock.Any()).
Return(http.Result[loginResult]{
StatusCode: 200,
Data: loginResult{
CustomerMessage: CustomerMessageAccountDisabled,
Dialog: loginDialogResult{
Message: "This Apple Account has been locked for security reasons.",
Explanation: "Reset your password to continue.",
OKButtonString: "Reset",
OKButtonAction: loginDialogActionResult{
Kind: "OpenURL",
URL: "https://iforgot.apple.com/cgi-bin/iforgot.cgi",
},
},
},
}, nil)
})
It("surfaces the dialog and trusted recovery URL", func() {
_, err := as.Login(LoginInput{Password: testPassword})
Expect(err).To(MatchError(ContainSubstring("This Apple Account has been locked for security reasons.")))
Expect(err).To(MatchError(ContainSubstring("Reset your password to continue.")))
Expect(err).To(MatchError(ContainSubstring("Reset: https://iforgot.apple.com/cgi-bin/iforgot.cgi")))
})
})
When("store API requires 2FA code", func() {
BeforeEach(func() {
mockClient.EXPECT().
+1 -1
View File
@@ -25,7 +25,7 @@ type LookupOutput struct {
}
func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
countryCode, err := t.countryCodeFromStoreFront(input.Account.StoreFront)
if err != nil {
return LookupOutput{}, fmt.Errorf("failed to resolve the country code: %w", err)
}
+2 -1
View File
@@ -21,7 +21,8 @@ var _ = Describe("AppStore (Lookup)", func() {
ctrl = gomock.NewController(GinkgoT())
mockClient = http.NewMockClient[searchResult](ctrl)
as = &appstore{
searchClient: mockClient,
searchClient: mockClient,
storefrontCountryCodes: testStorefrontCountryCodes(),
}
})
@@ -14,7 +14,7 @@ import (
)
func (t *appstore) lookupLatestMacOSExternalVersionID(acc Account, app App) (string, error) {
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
countryCode, err := t.countryCodeFromStoreFront(acc.StoreFront)
if err != nil {
return "", fmt.Errorf("failed to resolve the country code: %w", err)
}
@@ -44,7 +44,7 @@ var _ = Describe("Mac purchase version selection", func() {
defer ctrl.Finish()
downloads := http.NewMockClient[downloadResult](ctrl)
pages := http.NewMockClient[[]byte](ctrl)
store := &appstore{downloadClient: downloads, storefrontClient: pages}
store := &appstore{downloadClient: downloads, storefrontClient: pages, storefrontCountryCodes: testStorefrontCountryCodes()}
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.test/mac.pkg"}}}}
gomock.InOrder(
pages.EXPECT().Send(gomock.Any()).Do(func(req http.Request) {
@@ -74,7 +74,7 @@ var _ = Describe("Mac purchase version selection", func() {
downloads := http.NewMockClient[downloadResult](ctrl)
pages := http.NewMockClient[[]byte](ctrl)
bags := http.NewMockClient[bagResult](ctrl)
store := &appstore{downloadClient: downloads, storefrontClient: pages, bagClient: bags}
store := &appstore{downloadClient: downloads, storefrontClient: pages, bagClient: bags, storefrontCountryCodes: testStorefrontCountryCodes()}
bag := validBagResult()
bag.URLBag.RedownloadEndpoint = testRedownloadEndpoint
expected := http.Result[downloadResult]{StatusCode: gohttp.StatusOK, Data: downloadResult{Items: []downloadItemResult{{URL: "https://example.test/mac.pkg"}}}}
@@ -102,7 +102,7 @@ var _ = Describe("Mac purchase version selection", func() {
ctrl := gomock.NewController(GinkgoT())
defer ctrl.Finish()
pages := http.NewMockClient[[]byte](ctrl)
store := &appstore{storefrontClient: pages, downloadClient: http.NewMockClient[downloadResult](ctrl)}
store := &appstore{storefrontClient: pages, downloadClient: http.NewMockClient[downloadResult](ctrl), storefrontCountryCodes: testStorefrontCountryCodes()}
pages.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, requestErr)
_, _, err := store.sendDownloadProduct(context.Background(), Account{StoreFront: "143443-2,34"}, app, "001122334455", "", PlatformMacOS)
Expect(err).To(HaveOccurred())
@@ -67,7 +67,7 @@ func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform
return "", errors.New("app ID is required for platform version lookup")
}
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
countryCode, err := t.countryCodeFromStoreFront(acc.StoreFront)
if err != nil {
return "", fmt.Errorf("failed to resolve the country code: %w", err)
}
@@ -24,7 +24,7 @@ var _ = Describe("Platform version catalog fallback", func() {
BeforeEach(func() {
client = http.NewMockClient[platformVersionLookupResult](gomock.NewController(GinkgoT()))
store = &appstore{platformClient: client}
store = &appstore{platformClient: client, storefrontCountryCodes: testStorefrontCountryCodes()}
})
expectLookup := func(catalog string, status int, data platformVersionLookupResult, sendErr error) *gomock.Call {
+1
View File
@@ -44,6 +44,7 @@ var _ = Describe("Redownloading delisted iOS apps", func() {
store = &appstore{
platformClient: catalogs, downloadClient: downloads, bagClient: bags,
httpClient: assets, machine: device, os: operatingsystem.New(),
storefrontCountryCodes: testStorefrontCountryCodes(),
}
input = DownloadInput{
Context: context.Background(),
+1 -1
View File
@@ -26,7 +26,7 @@ type SearchOutput struct {
}
func (t *appstore) Search(input SearchInput) (SearchOutput, error) {
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
countryCode, err := t.countryCodeFromStoreFront(input.Account.StoreFront)
if err != nil {
return SearchOutput{}, fmt.Errorf("country code is invalid: %w", err)
}
+3 -2
View File
@@ -24,8 +24,9 @@ var _ = Describe("AppStore (Search)", func() {
mockClient = http.NewMockClient[searchResult](ctrl)
mockStorefrontClient = http.NewMockClient[[]byte](ctrl)
as = &appstore{
searchClient: mockClient,
storefrontClient: mockStorefrontClient,
searchClient: mockClient,
storefrontClient: mockStorefrontClient,
storefrontCountryCodes: testStorefrontCountryCodes(),
}
})
+138 -1
View File
@@ -1,13 +1,39 @@
package appstore
import (
"errors"
"fmt"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)
func testStorefrontCountryCodes() map[string]string {
return map[string]string{
"143441": "US",
"143443": "DE",
"143444": "GB",
"143465": "CN",
"143467": "IN",
"143469": "RU",
}
}
func availableStorefrontsFixture() []byte {
return []byte(`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict><key>storefronts</key><array>
<dict><key>country-code</key><string>US</string><key>id</key><integer>143441</integer></dict>
<dict><key>country-code</key><string>DE</string><key>id</key><integer>143443</integer></dict>
</array></dict></plist>`)
}
func storefrontGenreFixture(identifier, countryCode string) []byte {
return []byte(fmt.Sprintf(`{"storePlatformData":{"genre":{"meta":{"storefront":{"cc":%q,"id":%q}}}}}`, countryCode, identifier))
}
func storefrontSearchItemFixture(kind, adamID, platform, salableAdamID, externalVersionID string) string {
return fmt.Sprintf(`{
"$kind":%q,
@@ -38,13 +64,124 @@ func storefrontPageFixture(items ...string) []byte {
var _ = Describe("App Store storefront data", func() {
DescribeTable("resolves storefront response suffixes", func(storefront, country string) {
Expect(countryCodeFromStoreFront(storefront)).To(Equal(country))
Expect(countryCodeFromStoreFront(storefront, testStorefrontCountryCodes())).To(Equal(country))
},
Entry("comma suffix", "143441,34", "US"),
Entry("dash and comma suffixes", "143441-1,34", "US"),
Entry("bare storefront", "143443", "DE"),
)
Describe("available storefront discovery", func() {
It("fetches and caches the storefront country codes", func() {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{storefrontClient: client}
client.EXPECT().Send(http.Request{
URL: availableStorefrontsURL,
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatRaw,
}).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil).Times(1)
Expect(store.countryCodeFromStoreFront("143441-1,34")).To(Equal("US"))
Expect(store.countryCodeFromStoreFront("143443")).To(Equal("DE"))
})
It("retries discovery after a request failure", func() {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{storefrontClient: client}
requestErr := errors.New("connection reset")
gomock.InOrder(
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{}, requestErr),
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
)
_, err := store.countryCodeFromStoreFront("143441")
Expect(err).To(MatchError(ContainSubstring("available storefronts request failed")))
Expect(errors.Is(err, requestErr)).To(BeTrue())
Expect(store.countryCodeFromStoreFront("143441")).To(Equal("US"))
})
DescribeTable("resolves storefronts omitted from the available list", func(identifier, countryCode string) {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{storefrontClient: client}
gomock.InOrder(
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
client.EXPECT().Send(http.Request{
URL: storefrontGenreURL,
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatRaw,
NoRedirects: true,
Headers: map[string]string{"X-Apple-Store-Front": identifier + "-2,29"},
}).Return(http.Result[[]byte]{StatusCode: 200, Data: storefrontGenreFixture(identifier, countryCode)}, nil),
)
Expect(store.countryCodeFromStoreFront(identifier + "-19,29")).To(Equal(countryCode))
Expect(store.countryCodeFromStoreFront(identifier)).To(Equal(countryCode))
},
Entry("China", "143465", "CN"),
)
DescribeTable("rejects inactive legacy storefronts", func(identifier string) {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{storefrontClient: client}
gomock.InOrder(
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 302}, nil),
)
_, err := store.countryCodeFromStoreFront(identifier)
Expect(err).To(MatchError(fmt.Sprintf("country code mapping for store front (%s) was not found", identifier)))
},
Entry("Bangladesh", "143490"),
Entry("Liechtenstein", "143522"),
)
It("discovers a missing storefront ID for phone login", func() {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{
storefrontClient: client,
storefrontCountryCodes: map[string]string{
"143464": "SG",
"143466": "KR",
},
}
client.EXPECT().Send(gomock.Any()).Do(func(request http.Request) {
Expect(request.URL).To(Equal(storefrontGenreURL))
Expect(request.Headers).To(HaveKeyWithValue("X-Apple-Store-Front", "143465-2,29"))
}).Return(http.Result[[]byte]{StatusCode: 200, Data: storefrontGenreFixture("143465", "CN")}, nil)
Expect(store.discoverStorefrontID("CN")).To(Equal("143465"))
Expect(store.storefrontID("CN")).To(Equal("143465"))
})
It("rejects an unknown ID when Apple defaults it to a known storefront", func() {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{storefrontClient: client}
gomock.InOrder(
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: availableStorefrontsFixture()}, nil),
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: 200, Data: storefrontGenreFixture("143441", "US")}, nil),
)
_, err := store.countryCodeFromStoreFront("999999")
Expect(err).To(MatchError("country code mapping for store front (999999) was not found"))
})
DescribeTable("rejects unusable discovery responses", func(status int, body []byte, message string) {
client := http.NewMockClient[[]byte](gomock.NewController(GinkgoT()))
store := &appstore{storefrontClient: client}
client.EXPECT().Send(gomock.Any()).Return(http.Result[[]byte]{StatusCode: status, Data: body}, nil)
_, err := store.countryCodeFromStoreFront("143441")
Expect(err).To(MatchError(ContainSubstring(message)))
},
Entry("HTTP error", 503, nil, "available storefronts request failed"),
Entry("malformed plist", 200, []byte("not a plist"), "failed to decode available storefronts"),
Entry("empty storefront list", 200, []byte(`<plist><dict><key>storefronts</key><array/></dict></plist>`), "contains no storefronts"),
)
})
Describe("storefrontVisionApps", func() {
It("keeps unique native visionOS apps in storefront order and applies the limit", func() {
body := storefrontPageFixture(
+1 -1
View File
@@ -37,7 +37,7 @@ var _ = Describe("AppStore (Update Product)", func() {
mockBagClient = http.NewMockClient[bagResult](ctrl)
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
mockPlatformClient = http.NewMockClient[platformVersionLookupResult](ctrl)
store = &appstore{bagClient: mockBagClient, downloadClient: mockDownloadClient, platformClient: mockPlatformClient}
store = &appstore{bagClient: mockBagClient, downloadClient: mockDownloadClient, platformClient: mockPlatformClient, storefrontCountryCodes: testStorefrontCountryCodes()}
account = Account{DirectoryServicesID: "test-dsid", Pod: "42", StoreFront: "143441-1,34"}
app = App{ID: 987654321, BundleID: "com.example.app"}
bag = bagResult{}
+285 -142
View File
@@ -1,156 +1,299 @@
package appstore
import (
"encoding/json"
"errors"
"fmt"
gohttp "net/http"
"strconv"
"strings"
"github.com/majd/ipatool/v2/pkg/http"
"howett.net/plist"
)
func countryCodeFromStoreFront(storeFront string) (string, error) {
identifier, _, _ := strings.Cut(strings.TrimSpace(storeFront), ",")
identifier, _, _ = strings.Cut(identifier, "-")
const (
availableStorefrontsURL = "https://itunes.apple.com/WebObjects/MZStore.woa/wa/availableStoreFronts"
storefrontGenreURL = "https://apps.apple.com/genre/id36"
maxStorefrontIDRange = 1000
)
for key, val := range storeFronts {
if identifier == val {
return key, nil
type availableStorefrontsResult struct {
Storefronts []availableStorefront `plist:"storefronts"`
}
type availableStorefront struct {
CountryCode string `plist:"country-code"`
ID int64 `plist:"id"`
}
type storefrontGenrePage struct {
StorePlatformData map[string]struct {
Meta struct {
Storefront struct {
CountryCode string `json:"cc"`
ID string `json:"id"`
} `json:"storefront"`
} `json:"meta"`
} `json:"storePlatformData"`
}
func (t *appstore) countryCodeFromStoreFront(storeFront string) (string, error) {
if err := t.discoverAvailableStorefronts(); err != nil {
return "", err
}
identifier := storefrontIdentifier(storeFront)
if countryCode := t.cachedStorefrontCountryCode(identifier); countryCode != "" {
return countryCode, nil
}
countryCode, found, err := t.discoverStorefrontCountryCode(identifier)
if err != nil {
return "", err
}
if found {
return countryCode, nil
}
return "", storefrontMappingError(storeFront)
}
func (t *appstore) storefrontID(countryCode string) string {
t.storefrontsMu.Lock()
defer t.storefrontsMu.Unlock()
for identifier, code := range t.storefrontCountryCodes {
if code == countryCode {
return identifier
}
}
return "", fmt.Errorf("country code mapping for store front (%s) was not found", storeFront)
return ""
}
var storeFronts = map[string]string{
"AE": "143481",
"AG": "143540",
"AI": "143538",
"AL": "143575",
"AM": "143524",
"AO": "143564",
"AR": "143505",
"AT": "143445",
"AU": "143460",
"AZ": "143568",
"BB": "143541",
"BD": "143490",
"BE": "143446",
"BG": "143526",
"BH": "143559",
"BM": "143542",
"BN": "143560",
"BO": "143556",
"BR": "143503",
"BS": "143539",
"BW": "143525",
"BY": "143565",
"BZ": "143555",
"CA": "143455",
"CH": "143459",
"CI": "143527",
"CL": "143483",
"CN": "143465",
"CO": "143501",
"CR": "143495",
"CY": "143557",
"CZ": "143489",
"DE": "143443",
"DK": "143458",
"DM": "143545",
"DO": "143508",
"DZ": "143563",
"EC": "143509",
"EE": "143518",
"EG": "143516",
"ES": "143454",
"FI": "143447",
"FR": "143442",
"GB": "143444",
"GD": "143546",
"GE": "143615",
"GH": "143573",
"GR": "143448",
"GT": "143504",
"GY": "143553",
"HK": "143463",
"HN": "143510",
"HR": "143494",
"HU": "143482",
"ID": "143476",
"IE": "143449",
"IL": "143491",
"IN": "143467",
"IS": "143558",
"IT": "143450",
"IQ": "143617",
"JM": "143511",
"JO": "143528",
"JP": "143462",
"KE": "143529",
"KN": "143548",
"KR": "143466",
"KW": "143493",
"KY": "143544",
"KZ": "143517",
"LB": "143497",
"LC": "143549",
"LI": "143522",
"LK": "143486",
"LT": "143520",
"LU": "143451",
"LV": "143519",
"MD": "143523",
"MG": "143531",
"MK": "143530",
"ML": "143532",
"MN": "143592",
"MO": "143515",
"MS": "143547",
"MT": "143521",
"MU": "143533",
"MV": "143488",
"MX": "143468",
"MY": "143473",
"NE": "143534",
"NG": "143561",
"NI": "143512",
"NL": "143452",
"NO": "143457",
"NP": "143484",
"NZ": "143461",
"OM": "143562",
"PA": "143485",
"PE": "143507",
"PH": "143474",
"PK": "143477",
"PL": "143478",
"PT": "143453",
"PY": "143513",
"QA": "143498",
"RO": "143487",
"RS": "143500",
"RU": "143469",
"SA": "143479",
"SE": "143456",
"SG": "143464",
"SI": "143499",
"SK": "143496",
"SN": "143535",
"SR": "143554",
"SV": "143506",
"TC": "143552",
"TH": "143475",
"TN": "143536",
"TR": "143480",
"TT": "143551",
"TW": "143470",
"TZ": "143572",
"UA": "143492",
"UG": "143537",
"US": "143441",
"UY": "143514",
"UZ": "143566",
"VC": "143550",
"VE": "143502",
"VG": "143543",
"VN": "143471",
"YE": "143571",
"ZA": "143472",
func (t *appstore) discoverStorefrontID(countryCode string) (string, error) {
if err := t.discoverAvailableStorefronts(); err != nil {
return "", err
}
countryCode = strings.ToUpper(strings.TrimSpace(countryCode))
if identifier := t.storefrontID(countryCode); identifier != "" {
return identifier, nil
}
identifiers, err := t.missingStorefrontIdentifiers()
if err != nil {
return "", err
}
for _, identifier := range identifiers {
resolvedCountryCode, found, resolveErr := t.discoverStorefrontCountryCode(identifier)
if resolveErr != nil {
return "", resolveErr
}
if found && resolvedCountryCode == countryCode {
return identifier, nil
}
}
return "", fmt.Errorf("store front mapping for country code (%s) was not found", countryCode)
}
func (t *appstore) cachedStorefrontCountryCode(identifier string) string {
t.storefrontsMu.Lock()
defer t.storefrontsMu.Unlock()
return t.storefrontCountryCodes[identifier]
}
func (t *appstore) missingStorefrontIdentifiers() ([]string, error) {
t.storefrontsMu.Lock()
defer t.storefrontsMu.Unlock()
minimum, maximum := int64(0), int64(0)
known := make(map[int64]struct{}, len(t.storefrontCountryCodes))
for identifier := range t.storefrontCountryCodes {
value, err := strconv.ParseInt(identifier, 10, 64)
if err != nil || value <= 0 {
continue
}
known[value] = struct{}{}
if minimum == 0 || value < minimum {
minimum = value
}
if value > maximum {
maximum = value
}
}
if minimum == 0 || maximum-minimum > maxStorefrontIDRange {
return nil, errors.New("available storefront identifier range is invalid")
}
identifiers := make([]string, 0, maximum-minimum+1-int64(len(known)))
for identifier := minimum; identifier <= maximum; identifier++ {
if _, ok := known[identifier]; !ok {
identifiers = append(identifiers, strconv.FormatInt(identifier, 10))
}
}
return identifiers, nil
}
func (t *appstore) discoverStorefrontCountryCode(identifier string) (string, bool, error) {
if _, err := strconv.ParseInt(identifier, 10, 64); err != nil {
return "", false, nil
}
if t.storefrontClient == nil {
return "", false, errors.New("storefront client is not configured")
}
res, err := t.storefrontClient.Send(http.Request{
URL: storefrontGenreURL,
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatRaw,
NoRedirects: true,
Headers: map[string]string{
"X-Apple-Store-Front": identifier + "-2,29",
},
})
if err != nil {
return "", false, fmt.Errorf("storefront country code request failed: %w", err)
}
if (res.StatusCode >= gohttp.StatusMultipleChoices && res.StatusCode < gohttp.StatusBadRequest) || res.StatusCode == gohttp.StatusNotFound {
return "", false, nil
}
if res.StatusCode != gohttp.StatusOK {
return "", false, NewErrorWithMetadata(errors.New("storefront country code request failed"), res)
}
var page storefrontGenrePage
if err = json.Unmarshal(res.Data, &page); err != nil {
return "", false, fmt.Errorf("failed to decode storefront country code: %w", err)
}
var (
countryCode string
foundIdentifier bool
)
for _, data := range page.StorePlatformData {
storefront := data.Meta.Storefront
if storefront.ID == identifier {
foundIdentifier = true
countryCode = strings.ToUpper(strings.TrimSpace(storefront.CountryCode))
break
}
}
if !foundIdentifier {
return "", false, nil
}
if len(countryCode) != 2 {
return "", false, errors.New("storefront country code response contains no country code")
}
for _, character := range countryCode {
if character < 'A' || character > 'Z' {
return "", false, errors.New("storefront country code response contains an invalid country code")
}
}
t.storefrontsMu.Lock()
defer t.storefrontsMu.Unlock()
for knownIdentifier, knownCountryCode := range t.storefrontCountryCodes {
if knownCountryCode == countryCode && knownIdentifier != identifier {
return "", false, nil
}
}
t.storefrontCountryCodes[identifier] = countryCode
return countryCode, true, nil
}
func (t *appstore) discoverAvailableStorefronts() error {
t.storefrontsMu.Lock()
defer t.storefrontsMu.Unlock()
if t.storefrontCountryCodes != nil {
return nil
}
if t.storefrontClient == nil {
return errors.New("storefront client is not configured")
}
res, err := t.storefrontClient.Send(http.Request{
URL: availableStorefrontsURL,
Method: http.MethodGET,
ResponseFormat: http.ResponseFormatRaw,
})
if err != nil {
return fmt.Errorf("available storefronts request failed: %w", err)
}
if res.StatusCode != gohttp.StatusOK {
return NewErrorWithMetadata(errors.New("available storefronts request failed"), res)
}
var result availableStorefrontsResult
if _, err = plist.Unmarshal(res.Data, &result); err != nil {
return fmt.Errorf("failed to decode available storefronts: %w", err)
}
countryCodes := make(map[string]string, len(result.Storefronts))
for _, storefront := range result.Storefronts {
countryCode := strings.ToUpper(strings.TrimSpace(storefront.CountryCode))
if storefront.ID <= 0 || countryCode == "" {
continue
}
countryCodes[strconv.FormatInt(storefront.ID, 10)] = countryCode
}
if len(countryCodes) == 0 {
return errors.New("available storefronts response contains no storefronts")
}
t.storefrontCountryCodes = countryCodes
return nil
}
func countryCodeFromStoreFront(storeFront string, countryCodes map[string]string) (string, error) {
identifier := storefrontIdentifier(storeFront)
if countryCode, ok := countryCodes[identifier]; ok {
return countryCode, nil
}
return "", storefrontMappingError(storeFront)
}
func storefrontIdentifier(storeFront string) string {
identifier, _, _ := strings.Cut(strings.TrimSpace(storeFront), ",")
identifier, _, _ = strings.Cut(identifier, "-")
return identifier
}
func storefrontMappingError(storeFront string) error {
return fmt.Errorf("country code mapping for store front (%s) was not found", storeFront)
}