mirror of
https://github.com/majd/ipatool
synced 2026-11-28 02:07:52 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
abd86cb01a | ||
|
|
5f776fe2f5 | ||
|
|
ab79e429d5 | ||
|
|
9032d4c192 | ||
|
|
779a2e66cb | ||
|
|
fd630343bc | ||
|
|
dcddce4650 | ||
|
|
a3fa2f09b3 | ||
|
|
85ae82d9c4 | ||
|
|
1bee8bc568 | ||
|
|
abaeccefec | ||
|
|
8c4e037aa3 | ||
|
|
4142ab48ad | ||
|
|
1858ad7a72 | ||
|
|
2140a26bdf | ||
|
|
e914156036 | ||
|
|
19ffd1bf6b | ||
|
|
7ffd4bf050 | ||
|
|
496595a039 | ||
|
|
7765fd5445 | ||
|
|
6f63cd4776 | ||
|
|
65242569b3 | ||
|
|
14883b4631 | ||
|
|
91ae69cc58 | ||
|
|
80dbbef6c8 | ||
|
|
e3e604925f | ||
|
|
cffa279e31 | ||
|
|
034a0978ab | ||
|
|
9657750fc1 | ||
|
|
9969c18cef | ||
|
|
f09439ecde | ||
|
|
55ef41fc20 | ||
|
|
b4bd8d6580 | ||
|
|
79250ae2a3 | ||
|
|
a3212e0fd2 | ||
|
|
805678138e | ||
|
|
3a537e7571 | ||
|
|
e686248270 | ||
|
|
ac081fa19d | ||
|
|
7136f81fd1 | ||
|
|
34866f5833 | ||
|
|
46f3369de0 | ||
|
|
0bb134e9d7 | ||
|
|
bbf3717456 | ||
|
|
e1eda9f776 | ||
|
|
c406c36819 | ||
|
|
e5291ba16b | ||
|
|
37af8f8468 | ||
|
|
21cbd596bc | ||
|
|
f3c9076ff0 | ||
|
|
d147788501 | ||
|
|
8a23d6fadd | ||
|
|
63ee6fc6a4 | ||
|
|
5b547457f1 | ||
|
|
169af4b2ea | ||
|
|
f68a119963 | ||
|
|
58e9a18778 | ||
|
|
c8624b26d5 | ||
|
|
3199afc494 | ||
|
|
6597f5ac77 | ||
|
|
6ccb4a7f0b | ||
|
|
64c5cc9843 | ||
|
|
19e7261713 | ||
|
|
b031cd20d1 | ||
|
|
9db93c83c0 | ||
|
|
90253c336f | ||
|
|
e1141bd6d2 | ||
|
|
6a7adabbfa | ||
|
|
cfc4a075ae | ||
|
|
74e7588c6d | ||
|
|
67e557e9a7 | ||
|
|
bf33e0d1c4 | ||
|
|
95c3aa6629 | ||
|
|
cf926d7911 | ||
|
|
9a361cf7a0 | ||
|
|
574d5b5148 | ||
|
|
5abc5d1777 | ||
|
|
8762eaf192 |
No files matched your search
@@ -1 +0,0 @@
|
||||
github: majd
|
||||
@@ -12,35 +12,36 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: macos-latest
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
- run: go build -o ipatool-linux-$GOARCH
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
build_macos:
|
||||
name: Build for macOS
|
||||
@@ -48,17 +49,17 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-$GOOS-$GOARCH
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 1
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
@@ -9,20 +9,17 @@ jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool
|
||||
env:
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
- uses: actions/upload-artifact@v2
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: ipatool
|
||||
@@ -36,9 +33,9 @@ jobs:
|
||||
matrix:
|
||||
command: [auth, download, purchase, search]
|
||||
steps:
|
||||
- uses: actions/download-artifact@v2
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool
|
||||
path: build
|
||||
- run: chmod +x ./build/ipatool
|
||||
- run: ./build/ipatool ${{ matrix.command }} --help
|
||||
- run: ./build/ipatool ${{ matrix.command }} --help
|
||||
@@ -1,18 +0,0 @@
|
||||
name: Issues Cleanup
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
schedule:
|
||||
- cron: "0 * * * *" # Every hour, every day
|
||||
|
||||
jobs:
|
||||
scan-issues:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: lee-dohm/no-response@v0.5.0
|
||||
with:
|
||||
token: ${{ github.token }}
|
||||
daysUntilClose: 7
|
||||
closeComment: This issue has been automatically closed because there has been no response from the original author.
|
||||
responseRequiredLabel: auto-close
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- uses: golangci/golangci-lint-action@v8
|
||||
with:
|
||||
version: v2.9
|
||||
@@ -18,84 +18,96 @@ jobs:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
build:
|
||||
name: Build
|
||||
runs-on: macos-latest
|
||||
needs: [get_version, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-arm64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: arm64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-windows-amd64.exe
|
||||
env:
|
||||
GOOS: windows
|
||||
GOARCH: amd64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: arm64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
|
||||
env:
|
||||
GOOS: linux
|
||||
GOARCH: amd64
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-arm64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: arm64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- run: go build -o ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-macos-amd64
|
||||
env:
|
||||
GOOS: darwin
|
||||
GOARCH: amd64
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
CGO_CFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_LDFLAGS: -mmacosx-version-min=10.15
|
||||
CGO_ENABLED: 1
|
||||
- uses: actions/upload-artifact@v2
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-arm64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-windows-amd64.exe
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-amd64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
if-no-files-found: error
|
||||
- uses: actions/upload-artifact@v2
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
if-no-files-found: error
|
||||
build_linux:
|
||||
name: Build for Linux
|
||||
runs-on: ${{ matrix.runner }}
|
||||
needs: [get_version, test]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
- arch: amd64
|
||||
runner: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: go build -ldflags="-X github.com/majd/ipatool/v2/cmd.version=$VERSION" -o ipatool-$VERSION-linux-$GOARCH
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
VERSION: ${{ needs.get_version.outputs.version }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
if-no-files-found: error
|
||||
release_windows:
|
||||
name: Release for Windows
|
||||
runs-on: ubuntu-latest
|
||||
@@ -103,10 +115,10 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/download-artifact@v2
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-windows-${{ matrix.arch }}.exe
|
||||
path: bin
|
||||
@@ -126,18 +138,18 @@ jobs:
|
||||
release_linux:
|
||||
name: Release for Linux
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build, release_windows]
|
||||
needs: [get_version, build_linux, release_windows]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
arch: [ arm64, amd64 ]
|
||||
arch: [arm64, amd64]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/download-artifact@v2
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE
|
||||
- run: chmod +x bin/$FILE && tar -czvf $FILE.tar.gz bin/$FILE
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-linux-${{ matrix.arch }}
|
||||
- run: ./tools/sha256sum.sh $TARBALL > $TARBALL.sha256sum
|
||||
@@ -153,23 +165,23 @@ jobs:
|
||||
release_macos:
|
||||
name: Release for macOS
|
||||
runs-on: ubuntu-latest
|
||||
needs: [get_version, build, release_windows, release_linux]
|
||||
needs: [get_version, build, build_linux, release_windows, release_linux]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
path: ./ipatool
|
||||
- uses: actions/download-artifact@v2
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
path: bin
|
||||
- run: tar -czvf $BIN.tar.gz bin/$BIN && rm -rf bin/
|
||||
- run: chmod +x bin/$BIN && tar -czvf $BIN.tar.gz bin/$BIN && rm -rf bin/
|
||||
env:
|
||||
BIN: ipatool-${{ needs.get_version.outputs.version }}-macos-arm64
|
||||
- uses: actions/download-artifact@v2
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
path: bin
|
||||
- run: tar -czvf $FILE.tar.gz bin/$FILE && rm -rf bin/
|
||||
- run: chmod +x bin/$FILE && tar -czvf $FILE.tar.gz bin/$FILE && rm -rf bin/
|
||||
env:
|
||||
FILE: ipatool-${{ needs.get_version.outputs.version }}-macos-amd64
|
||||
- id: sha256
|
||||
@@ -187,7 +199,7 @@ jobs:
|
||||
tag: ${{ github.ref }}
|
||||
overwrite: false
|
||||
file_glob: true
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ secrets.HOMEBREW_REPO }}
|
||||
ref: main
|
||||
@@ -209,4 +221,4 @@ jobs:
|
||||
git push "https://${{ secrets.GH_TOKEN }}@github.com/${{ secrets.HOMEBREW_REPO }}.git" --set-upstream "main"
|
||||
env:
|
||||
SHA256_ARM64: ${{ steps.sha256.outputs.sha256_arm64 }}
|
||||
SHA256_AMD64: ${{ steps.sha256.outputs.sha256_amd64 }}
|
||||
SHA256_AMD64: ${{ steps.sha256.outputs.sha256_amd64 }}
|
||||
@@ -8,12 +8,16 @@ on:
|
||||
jobs:
|
||||
run_tests:
|
||||
name: Run tests
|
||||
runs-on: macos-latest
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner: [ubuntu-latest, windows-latest, windows-11-arm]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-go@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: '1.19.3'
|
||||
go-version: "1.25.0"
|
||||
cache: true
|
||||
- run: ./tools/version.sh
|
||||
- run: go generate github.com/majd/ipatool/...
|
||||
- run: go test -v github.com/majd/ipatool/...
|
||||
+2
-1
@@ -3,4 +3,5 @@
|
||||
.LSOverride
|
||||
.vscode/
|
||||
.idea/
|
||||
cmd/version.go
|
||||
**/*_mock.go
|
||||
exp/
|
||||
@@ -0,0 +1,38 @@
|
||||
version: "2"
|
||||
linters:
|
||||
enable:
|
||||
- ginkgolinter
|
||||
- godot
|
||||
- godox
|
||||
- importas
|
||||
- nlreturn
|
||||
- nonamedreturns
|
||||
- prealloc
|
||||
- predeclared
|
||||
- unconvert
|
||||
- unparam
|
||||
- usestdlibvars
|
||||
- wastedassign
|
||||
- wrapcheck
|
||||
- wsl
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- goimports
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
@@ -0,0 +1,34 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance for coding agents working in this repository.
|
||||
|
||||
## Repository overview
|
||||
- Project: `ipatool`
|
||||
- Language: Go
|
||||
- Entry point: `main.go`
|
||||
- CLI command implementations: `cmd/`
|
||||
|
||||
## Development workflow
|
||||
1. Keep changes focused and minimal.
|
||||
2. Prefer idiomatic Go and keep command behavior consistent with existing commands in `cmd/`.
|
||||
3. Run formatting and tests before finalizing changes.
|
||||
|
||||
## Local checks
|
||||
Use these commands from the repository root:
|
||||
|
||||
```bash
|
||||
go generate ./...
|
||||
go test ./...
|
||||
go build ./...
|
||||
```
|
||||
|
||||
## Coding conventions
|
||||
- Follow standard Go formatting (`gofmt`).
|
||||
- Avoid introducing new dependencies unless necessary.
|
||||
- Keep user-facing text consistent with existing CLI help/output tone.
|
||||
- Preserve backward compatibility for CLI flags and output formats unless explicitly asked to change them.
|
||||
|
||||
## Commit/PR guidance
|
||||
- Write clear, scoped commit messages.
|
||||
- Summarize what changed and why in PR descriptions.
|
||||
- Include test/build results in your handoff.
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
## Changelog
|
||||
|
||||
### Version [2.0.3](https://github.com/majd/ipatool/releases/tag/v2.0.3)
|
||||
|
||||
- Added support for downloading Apple Arcade games.
|
||||
- Fixed windows builds not having exe extension.
|
||||
|
||||
|
||||
### Version [2.0.2](https://github.com/majd/ipatool/releases/tag/v2.0.2)
|
||||
|
||||
- Fixed Sinf patches when the app contains an Apple Watch app.
|
||||
- Added storefront code for Albania.
|
||||
- Fixed default output path to be current working directory.
|
||||
|
||||
### Version [2.0.1](https://github.com/majd/ipatool/releases/tag/v2.0.1)
|
||||
|
||||
- Linux & Windows releases now include the sha256 hash.
|
||||
- Added storefront code for Mongolia.
|
||||
|
||||
### Version [2.0.0](https://github.com/majd/ipatool/releases/tag/v2.0.0)
|
||||
|
||||
- Added support for Windows.
|
||||
- Added support for Linux.
|
||||
- Added support for generating autocompletion script using the `completion` command.
|
||||
- Implemented new `auth info` command.
|
||||
- Implemented `--verbose` flag that replaces the `--debug-level` flag to enable verbose logging.
|
||||
- Implemented `--format` which allows specifying logs output format to either text or json (default: text).
|
||||
- Implemented `--non-interactive` flag to disable running the tool in an interactive session.
|
||||
- The relevant command (i.e. purchase) will now automatically determine the country and the device family from the authenticated account. The following flags have been deprecated.
|
||||
- `--country`
|
||||
- `--device-family`
|
||||
- Improved structured logging.
|
||||
- Improved error handling.
|
||||
- Improved support for automated systems.
|
||||
- Added unit tests to cover the majority of the private App Store API logic.
|
||||
|
||||
### Version [1.1.4](https://github.com/majd/ipatool/releases/tag/v1.1.4)
|
||||
|
||||
- Add support for patching old code signature revisions as a fallback mechanism.
|
||||
|
||||
### Version [1.1.3](https://github.com/majd/ipatool/releases/tag/v1.1.3)
|
||||
|
||||
- Fixed keychain access on iOS.
|
||||
|
||||
### Version [1.1.2](https://github.com/majd/ipatool/releases/tag/v1.1.2)
|
||||
|
||||
- Improved error message for expired token.
|
||||
- Disabled print buffering and output errors to stderr.
|
||||
- Added linter.
|
||||
- Add support for running on iOS.
|
||||
|
||||
### Version [1.1.1](https://github.com/majd/ipatool/releases/tag/v1.1.1)
|
||||
|
||||
- Update swift-argument-parser dependency.
|
||||
- Remove usage of Swift concurrency.
|
||||
- Add backward-compatibility for macOS 10.11+.
|
||||
|
||||
### Version [1.1.0](https://github.com/majd/ipatool/releases/tag/v1.1.0)
|
||||
|
||||
- Added support for purchasing apps.
|
||||
- Implemented auth command.
|
||||
- Implemented purchase command.
|
||||
- Implemented --purchase flag in download command.
|
||||
- Added price checks for purchase flow.
|
||||
|
||||
|
||||
### Version [1.0.9](https://github.com/majd/ipatool/releases/tag/v1.0.9)
|
||||
|
||||
- Fixed building for older macOS versions.
|
||||
- Fixed 2FA code not being requested.
|
||||
|
||||
|
||||
### Version [1.0.8](https://github.com/majd/ipatool/releases/tag/v1.0.8)
|
||||
|
||||
- Added --output option to the download command for specifying the destination path for the downloaded app package.
|
||||
|
||||
### Version [1.0.7](https://github.com/majd/ipatool/releases/tag/v1.0.7)
|
||||
|
||||
- Fixed login requests to the store API when the 2FA code is required.
|
||||
|
||||
### Version [1.0.6](https://github.com/majd/ipatool/releases/tag/v1.0.6)
|
||||
|
||||
- Added support for supplying 2FA code in non-interactive sessions.
|
||||
|
||||
### Version [1.0.5](https://github.com/majd/ipatool/releases/tag/v1.0.5)
|
||||
|
||||
- Added support for specifying device family.
|
||||
|
||||
### Version [1.0.4](https://github.com/majd/ipatool/releases/tag/v1.0.4)
|
||||
|
||||
- Added support for specifying the iTunes Store region.
|
||||
|
||||
### Version [1.0.3](https://github.com/majd/ipatool/releases/tag/v1.0.3)
|
||||
|
||||
- Improved console logging.
|
||||
|
||||
### Version [1.0.2](https://github.com/majd/ipatool/releases/tag/v1.0.2)
|
||||
|
||||
- Improved error messages.
|
||||
|
||||
### Version [1.0.1](https://github.com/majd/ipatool/releases/tag/v1.0.1)
|
||||
|
||||
- Grammatical fixes.
|
||||
|
||||
### Version [1.0.0](https://github.com/majd/ipatool/releases/tag/v1.0.0)
|
||||
|
||||
- Initial release.
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
`ipatool` is a command line tool that allows you to search for iOS apps on the [App Store](https://apps.apple.com) and download a copy of the app package, known as an _ipa_ file.
|
||||
|
||||

|
||||

|
||||
|
||||
- [Requirements](#requirements)
|
||||
- [Installation](#installation)
|
||||
@@ -14,10 +14,11 @@
|
||||
- [Usage](#usage)
|
||||
- [Compiling](#compiling)
|
||||
- [License](#license)
|
||||
- [Changelog](https://github.com/majd/ipatool/blob/main/CHANGELOG.md)
|
||||
- [Releases](https://github.com/majd/ipatool/releases)
|
||||
- [FAQ](https://github.com/majd/ipatool/wiki/FAQ)
|
||||
|
||||
## Requirements
|
||||
|
||||
- Supported operating system (Windows, Linux or macOS).
|
||||
- Apple ID set up to use the App Store.
|
||||
|
||||
@@ -32,7 +33,6 @@ You can grab the latest version of `ipatool` from [GitHub releases](https://gith
|
||||
You can install `ipatool` using [Homebrew](https://brew.sh).
|
||||
|
||||
```shell
|
||||
$ brew tap majd/repo
|
||||
$ brew install ipatool
|
||||
```
|
||||
|
||||
@@ -65,14 +65,15 @@ Use "ipatool auth [command] --help" for more information about a command.
|
||||
To search for apps on the App Store, use the `search` command.
|
||||
|
||||
```
|
||||
Search for iOS apps available on the App Store
|
||||
Search for iOS and tvOS apps available on the App Store
|
||||
|
||||
Usage:
|
||||
ipatool search <term> [flags]
|
||||
|
||||
Flags:
|
||||
-h, --help help for search
|
||||
-l, --limit int maximum amount of search results to retrieve (default 5)
|
||||
-h, --help help for search
|
||||
-l, --limit int maximum amount of search results to retrieve (default 5)
|
||||
--platform string Platform to search: iphone, ipad, or appletv
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
@@ -98,24 +99,69 @@ Global Flags:
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To obtain a list of availble app versions to download, use the `list-versions` command.
|
||||
|
||||
```
|
||||
List the available versions of an iOS app
|
||||
|
||||
Usage:
|
||||
ipatool list-versions [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
-h, --help help for list-versions
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To download a copy of the ipa file, use the `download` command.
|
||||
|
||||
```
|
||||
Download (encrypted) iOS app packages from the App Store
|
||||
Download (encrypted) iOS and tvOS app packages from the App Store
|
||||
|
||||
Usage:
|
||||
ipatool download [flags]
|
||||
|
||||
Flags:
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (required)
|
||||
-h, --help help for download
|
||||
-o, --output string The destination path of the downloaded app package
|
||||
--purchase Obtain a license for the app if needed
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target iOS app (defaults to latest version when not specified)
|
||||
-h, --help help for download
|
||||
-o, --output string The destination path of the downloaded app package
|
||||
--platform string Platform to download for: iphone, ipad, or appletv
|
||||
--purchase Obtain a license for the app if needed
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
To resolve an external version identifier, returned by the `list-versions` command, use the `get-version-metadata` command.
|
||||
|
||||
```
|
||||
Retrieves the metadata for a specific version of an app
|
||||
|
||||
Usage:
|
||||
ipatool get-version-metadata [flags]
|
||||
|
||||
Flags:
|
||||
-i, --app-id int ID of the target iOS app (required)
|
||||
-b, --bundle-identifier string The bundle identifier of the target iOS app (overrides the app ID)
|
||||
--external-version-id string External version identifier of the target iOS app (required)
|
||||
-h, --help help for get-version-metadata
|
||||
|
||||
Global Flags:
|
||||
--format format sets output format for command; can be 'text', 'json' (default text)
|
||||
--keychain-passphrase string passphrase for unlocking keychain
|
||||
--non-interactive run in non-interactive session
|
||||
--verbose enables verbose logs
|
||||
```
|
||||
|
||||
**Note:** the tool runs in interactive mode by default. Use the `--non-interactive` flag
|
||||
@@ -129,10 +175,11 @@ The tool can be compiled using the Go toolchain.
|
||||
$ go build -o ipatool
|
||||
```
|
||||
|
||||
Unit tests can be executed with the following command.
|
||||
Unit tests can be executed with the following commands.
|
||||
|
||||
```shell
|
||||
$ go test -v github.com/majd/ipatool/...
|
||||
$ go generate ./...
|
||||
$ go test -v ./...
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
+107
-23
@@ -1,12 +1,18 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
var keychainPassphrase string
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func authCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
@@ -14,10 +20,6 @@ func authCmd() *cobra.Command {
|
||||
Short: "Authenticate with the App Store",
|
||||
}
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
cmd.AddCommand(loginCmd())
|
||||
cmd.AddCommand(infoCmd())
|
||||
cmd.AddCommand(revokeCmd())
|
||||
@@ -26,25 +28,97 @@ func authCmd() *cobra.Command {
|
||||
}
|
||||
|
||||
func loginCmd() *cobra.Command {
|
||||
var email string
|
||||
var password string
|
||||
var authCode string
|
||||
promptForAuthCode := func() (string, error) {
|
||||
authCode, err := bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read string: %w", err)
|
||||
}
|
||||
|
||||
authCode = strings.Trim(authCode, "\n")
|
||||
authCode = strings.Trim(authCode, "\r")
|
||||
|
||||
return authCode, nil
|
||||
}
|
||||
|
||||
var email, password, authCode string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
Short: "Login to the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
interactive := cmd.Context().Value(interactiveKey).(bool)
|
||||
|
||||
if password == "" && !interactive {
|
||||
return errors.New("password is required when not running in interactive mode; use the \"--password\" flag")
|
||||
}
|
||||
|
||||
return appstore.Login(email, password, authCode)
|
||||
if password == "" && interactive {
|
||||
dependencies.Logger.Log().Msg("enter password:")
|
||||
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
password = string(bytes)
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
|
||||
// nolint:wrapcheck
|
||||
return retry.Do(func() error {
|
||||
if errors.Is(lastErr, appstore.ErrAuthCodeRequired) && interactive {
|
||||
dependencies.Logger.Log().Msg("enter 2FA code:")
|
||||
|
||||
var err error
|
||||
authCode, err = promptForAuthCode()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read auth code: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies.Logger.Verbose().
|
||||
Str("email", email).
|
||||
Bool("authCodeProvided", authCode != "").
|
||||
Msg("logging in")
|
||||
|
||||
output, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: email,
|
||||
Password: password,
|
||||
AuthCode: authCode,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, appstore.ErrAuthCodeRequired) && !interactive {
|
||||
dependencies.Logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("name", output.Account.Name).
|
||||
Str("email", output.Account.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrAuthCodeRequired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&email, "email", "e", "", "email address for the Apple ID (required)")
|
||||
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required")
|
||||
cmd.Flags().StringVarP(&password, "password", "p", "", "password for the Apple ID (required)")
|
||||
cmd.Flags().StringVar(&authCode, "auth-code", "", "2FA code for the Apple ID")
|
||||
|
||||
_ = cmd.MarkFlagRequired("email")
|
||||
@@ -52,32 +126,42 @@ func loginCmd() *cobra.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func infoCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "info",
|
||||
Short: "Show current account info",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
output, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
return err
|
||||
}
|
||||
|
||||
return appstore.Info()
|
||||
dependencies.Logger.Log().
|
||||
Str("name", output.Account.Name).
|
||||
Str("email", output.Account.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:wrapcheck
|
||||
func revokeCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "revoke",
|
||||
Short: "Revoke your App Store credentials",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
err := dependencies.AppStore.Revoke()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
return err
|
||||
}
|
||||
|
||||
return appstore.Revoke()
|
||||
dependencies.Logger.Log().Bool("success", true).Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
+104
-138
@@ -1,124 +1,40 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/juju/persistent-cookiejar"
|
||||
"github.com/majd/ipatool/pkg/appstore"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/exp/slices"
|
||||
"golang.org/x/term"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/byteness/keyring"
|
||||
cookiejar "github.com/juju/persistent-cookiejar"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/log"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func newCookieJar() (*cookiejar.Jar, error) {
|
||||
machine := util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: util.NewOperatingSystem(),
|
||||
})
|
||||
jar, err := cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create cookie jar")
|
||||
}
|
||||
var dependencies = Dependencies{}
|
||||
var keychainPassphrase string
|
||||
|
||||
return jar, nil
|
||||
}
|
||||
|
||||
func keyringBackendType() keyring.BackendType {
|
||||
allowedBackends := []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
}
|
||||
|
||||
for _, backend := range allowedBackends {
|
||||
if slices.Contains(keyring.AvailableBackends(), backend) {
|
||||
return backend
|
||||
}
|
||||
}
|
||||
|
||||
return keyring.FileBackend
|
||||
}
|
||||
|
||||
func newKeyring(logger log.Logger, passphrase string, interactive bool) (keyring.Keyring, error) {
|
||||
machine := util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: util.NewOperatingSystem(),
|
||||
})
|
||||
|
||||
ring, err := keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyringBackendType(),
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
FilePasswordFunc: func(s string) (string, error) {
|
||||
if passphrase == "" && !interactive {
|
||||
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
|
||||
}
|
||||
|
||||
if passphrase != "" {
|
||||
return passphrase, nil
|
||||
}
|
||||
|
||||
path := strings.Split(s, " unlock ")[1]
|
||||
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "failed to read password")
|
||||
}
|
||||
|
||||
password := string(bytes)
|
||||
password = strings.Trim(password, "\n")
|
||||
password = strings.Trim(password, "\r")
|
||||
|
||||
return password, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to open keyring")
|
||||
}
|
||||
|
||||
return ring, nil
|
||||
}
|
||||
|
||||
func configureConfigDirectory() error {
|
||||
os := util.NewOperatingSystem()
|
||||
machine := util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: os,
|
||||
})
|
||||
|
||||
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
|
||||
_, err := os.Stat(configDirectoryPath)
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
err = os.MkdirAll(configDirectoryPath, 0700)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create config directory")
|
||||
}
|
||||
} else if err != nil {
|
||||
return errors.Wrap(err, "could not read metadata")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseOutputFormat(value string) (OutputFormat, error) {
|
||||
switch value {
|
||||
case "json":
|
||||
return OutputFormatJSON, nil
|
||||
case "text":
|
||||
return OutputFormatText, nil
|
||||
default:
|
||||
return OutputFormatJSON, errors.Errorf("invalid output format: %s", value)
|
||||
}
|
||||
type Dependencies struct {
|
||||
Logger log.Logger
|
||||
OS operatingsystem.OperatingSystem
|
||||
Machine machine.Machine
|
||||
CookieJar http.CookieJar
|
||||
Keychain keychain.Keychain
|
||||
AppStore appstore.AppStore
|
||||
}
|
||||
|
||||
// newLogger returns a new logger instance.
|
||||
func newLogger(format OutputFormat, verbose bool) log.Logger {
|
||||
var writer io.Writer
|
||||
|
||||
@@ -129,41 +45,91 @@ func newLogger(format OutputFormat, verbose bool) log.Logger {
|
||||
writer = log.NewWriter()
|
||||
}
|
||||
|
||||
return log.NewLogger(log.LoggerArgs{
|
||||
return log.NewLogger(log.Args{
|
||||
Verbose: verbose,
|
||||
Writer: writer,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// newCookieJar returns a new cookie jar instance.
|
||||
func newCookieJar(machine machine.Machine) http.CookieJar {
|
||||
return util.Must(cookiejar.New(&cookiejar.Options{
|
||||
Filename: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName, CookieJarFileName),
|
||||
}))
|
||||
}
|
||||
|
||||
// newKeychain returns a new keychain instance.
|
||||
func newKeychain(machine machine.Machine, logger log.Logger, interactive bool) keychain.Keychain {
|
||||
ring := util.Must(keyring.Open(keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{
|
||||
keyring.KeychainBackend,
|
||||
keyring.SecretServiceBackend,
|
||||
keyring.FileBackend,
|
||||
},
|
||||
ServiceName: KeychainServiceName,
|
||||
FileDir: filepath.Join(machine.HomeDirectory(), ConfigDirectoryName),
|
||||
FilePasswordFunc: func(s string) (string, error) {
|
||||
if keychainPassphrase == "" && !interactive {
|
||||
return "", errors.New("keychain passphrase is required when not running in interactive mode; use the \"--keychain-passphrase\" flag")
|
||||
}
|
||||
|
||||
if keychainPassphrase != "" {
|
||||
return keychainPassphrase, nil
|
||||
}
|
||||
|
||||
path := strings.Split(s, " unlock ")[1]
|
||||
logger.Log().Msgf("enter passphrase to unlock %s (this is separate from your Apple ID password): ", path)
|
||||
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read password: %w", err)
|
||||
}
|
||||
|
||||
password := string(bytes)
|
||||
password = strings.Trim(password, "\n")
|
||||
password = strings.Trim(password, "\r")
|
||||
|
||||
return password, nil
|
||||
},
|
||||
}))
|
||||
|
||||
return keychain.New(keychain.Args{Keyring: ring})
|
||||
}
|
||||
|
||||
// initWithCommand initializes the dependencies of the command.
|
||||
func initWithCommand(cmd *cobra.Command) {
|
||||
verbose := cmd.Flag("verbose").Value.String() == "true"
|
||||
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
|
||||
format := util.Must(OutputFormatFromString(cmd.Flag("format").Value.String()))
|
||||
|
||||
dependencies.Logger = newLogger(format, verbose)
|
||||
dependencies.OS = operatingsystem.New()
|
||||
dependencies.Machine = machine.New(machine.Args{OS: dependencies.OS})
|
||||
dependencies.CookieJar = newCookieJar(dependencies.Machine)
|
||||
dependencies.Keychain = newKeychain(dependencies.Machine, dependencies.Logger, interactive)
|
||||
dependencies.AppStore = appstore.NewAppStore(appstore.Args{
|
||||
CookieJar: dependencies.CookieJar,
|
||||
OperatingSystem: dependencies.OS,
|
||||
Keychain: dependencies.Keychain,
|
||||
Machine: dependencies.Machine,
|
||||
})
|
||||
|
||||
util.Must("", createConfigDirectory(dependencies.OS, dependencies.Machine))
|
||||
}
|
||||
|
||||
func newAppStore(
|
||||
cmd *cobra.Command,
|
||||
keychainPassphrase string,
|
||||
) (appstore.AppStore, error) {
|
||||
logger := cmd.Context().Value("logger").(log.Logger)
|
||||
interactive := cmd.Context().Value("interactive").(bool)
|
||||
// createConfigDirectory creates the configuration directory for the CLI tool, if needed.
|
||||
func createConfigDirectory(os operatingsystem.OperatingSystem, machine machine.Machine) error {
|
||||
configDirectoryPath := filepath.Join(machine.HomeDirectory(), ConfigDirectoryName)
|
||||
_, err := os.Stat(configDirectoryPath)
|
||||
|
||||
cookieJar, err := newCookieJar()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create cookie jar")
|
||||
if err != nil && os.IsNotExist(err) {
|
||||
err = os.MkdirAll(configDirectoryPath, 0700)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("could not read metadata: %w", err)
|
||||
}
|
||||
|
||||
os := util.NewOperatingSystem()
|
||||
|
||||
keyring, err := newKeyring(logger, keychainPassphrase, interactive)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to create keyring")
|
||||
}
|
||||
|
||||
return appstore.NewAppStore(appstore.AppStoreArgs{
|
||||
Logger: logger,
|
||||
CookieJar: cookieJar,
|
||||
Keychain: keychain.NewKeychain(keychain.KeychainArgs{
|
||||
Keyring: keyring,
|
||||
}),
|
||||
Interactive: interactive,
|
||||
Machine: util.NewMachine(util.MachineArgs{
|
||||
OperatingSystem: os,
|
||||
}),
|
||||
OperatingSystem: os,
|
||||
}), nil
|
||||
return nil
|
||||
}
|
||||
@@ -1,14 +1,5 @@
|
||||
package cmd
|
||||
|
||||
import "github.com/thediveo/enumflag/v2"
|
||||
|
||||
type OutputFormat enumflag.Flag
|
||||
|
||||
const (
|
||||
OutputFormatText OutputFormat = iota
|
||||
OutputFormatJSON
|
||||
)
|
||||
|
||||
const (
|
||||
ConfigDirectoryName = ".ipatool"
|
||||
CookieJarFileName = "cookies"
|
||||
|
||||
+139
-18
@@ -1,39 +1,160 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func downloadCmd() *cobra.Command {
|
||||
var keychainPassphrase string
|
||||
var acquireLicense bool
|
||||
var outputPath string
|
||||
var bundleID string
|
||||
var (
|
||||
acquireLicense bool
|
||||
outputPath string
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "download",
|
||||
Short: "Download (encrypted) iOS app packages from the App Store",
|
||||
Short: "Download (encrypted) iOS and tvOS app packages from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
return appstore.Download(bundleID, outputPath, acquireLicense)
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
purchased := false
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{
|
||||
Account: acc,
|
||||
BundleID: bundleID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrLicenseRequired) {
|
||||
err := dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: app})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
purchased = true
|
||||
dependencies.Logger.Verbose().
|
||||
Bool("success", true).
|
||||
Msg("purchase")
|
||||
}
|
||||
|
||||
interactive, _ := cmd.Context().Value(interactiveKey).(bool)
|
||||
var progress *progressbar.ProgressBar
|
||||
if interactive {
|
||||
progress = progressbar.NewOptions64(1,
|
||||
progressbar.OptionSetDescription("downloading"),
|
||||
progressbar.OptionSetWriter(os.Stdout),
|
||||
progressbar.OptionShowBytes(true),
|
||||
progressbar.OptionSetWidth(20),
|
||||
progressbar.OptionFullWidth(),
|
||||
progressbar.OptionThrottle(65*time.Millisecond),
|
||||
progressbar.OptionShowCount(),
|
||||
progressbar.OptionClearOnFinish(),
|
||||
progressbar.OptionSpinnerType(14),
|
||||
progressbar.OptionSetRenderBlankState(true),
|
||||
progressbar.OptionSetElapsedTime(false),
|
||||
progressbar.OptionSetPredictTime(false),
|
||||
)
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.Download(appstore.DownloadInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
OutputPath: outputPath,
|
||||
Progress: progress,
|
||||
ExternalVersionID: externalVersionID,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = dependencies.AppStore.ReplicateSinf(appstore.ReplicateSinfInput{Sinfs: out.Sinfs, PackagePath: out.DestinationPath})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("output", out.DestinationPath).
|
||||
Bool("purchased", purchased).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(3),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
if errors.Is(err, appstore.ErrPasswordTokenExpired) {
|
||||
return true
|
||||
}
|
||||
|
||||
if errors.Is(err, appstore.ErrLicenseRequired) && acquireLicense {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (required)")
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
cmd.Flags().StringVarP(&outputPath, "output", "o", "", "The destination path of the downloaded app package")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (defaults to latest version when not specified)")
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to download for: iphone, ipad, or appletv")
|
||||
cmd.Flags().BoolVar(&acquireLicense, "purchase", false, "Obtain a license for the app if needed")
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.Flags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
_ = cmd.MarkFlagRequired("bundle-identifier")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func getVersionMetadataCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
externalVersionID string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get-version-metadata",
|
||||
Short: "Retrieves the metadata for a specific version of an app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.GetVersionMetadata(appstore.GetVersionMetadataInput{
|
||||
Account: acc,
|
||||
App: app,
|
||||
VersionID: externalVersionID,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Str("externalVersionID", externalVersionID).
|
||||
Str("displayVersion", out.DisplayVersion).
|
||||
Time("releaseDate", out.ReleaseDate).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
cmd.Flags().StringVar(&externalVersionID, "external-version-id", "", "External version identifier of the target iOS app (required)")
|
||||
|
||||
_ = cmd.MarkFlagRequired("external-version-id")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func ListVersionsCmd() *cobra.Command {
|
||||
var (
|
||||
appID int64
|
||||
bundleID string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "list-versions",
|
||||
Short: "List the available versions of an iOS app",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if appID == 0 && bundleID == "" {
|
||||
return errors.New("either the app ID or the bundle identifier must be specified")
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
app := appstore.App{ID: appID}
|
||||
if bundleID != "" {
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
app = lookupResult.App
|
||||
}
|
||||
|
||||
out, err := dependencies.AppStore.ListVersions(appstore.ListVersionsInput{Account: acc, App: app})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Interface("externalVersionIdentifiers", out.ExternalVersionIdentifiers).
|
||||
Str("bundleID", app.BundleID).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&appID, "app-id", "i", 0, "ID of the target iOS app (required)")
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "The bundle identifier of the target iOS app (overrides the app ID)")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
)
|
||||
|
||||
type OutputFormat enumflag.Flag
|
||||
|
||||
const (
|
||||
OutputFormatText OutputFormat = iota
|
||||
OutputFormatJSON
|
||||
)
|
||||
|
||||
func OutputFormatFromString(value string) (OutputFormat, error) {
|
||||
switch value {
|
||||
case "json":
|
||||
return OutputFormatJSON, nil
|
||||
case "text":
|
||||
return OutputFormatText, nil
|
||||
default:
|
||||
return OutputFormatJSON, fmt.Errorf("invalid output format '%s'", value)
|
||||
}
|
||||
}
|
||||
+55
-13
@@ -1,34 +1,76 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func purchaseCmd() *cobra.Command {
|
||||
var keychainPassphrase string
|
||||
var bundleID string
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "purchase",
|
||||
Short: "Obtain a license for the app from the App Store",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
}
|
||||
var lastErr error
|
||||
var acc appstore.Account
|
||||
|
||||
return appstore.Purchase(bundleID)
|
||||
return retry.Do(func() error {
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = infoResult.Account
|
||||
|
||||
if errors.Is(lastErr, appstore.ErrPasswordTokenExpired) {
|
||||
loginResult, err := dependencies.AppStore.Login(appstore.LoginInput{
|
||||
Email: acc.Email,
|
||||
Password: acc.Password,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
acc = loginResult.Account
|
||||
}
|
||||
|
||||
lookupResult, err := dependencies.AppStore.Lookup(appstore.LookupInput{Account: acc, BundleID: bundleID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = dependencies.AppStore.Purchase(appstore.PurchaseInput{Account: acc, App: lookupResult.App})
|
||||
if err != nil && !errors.Is(err, appstore.ErrLicenseAlreadyExists) {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Bool("alreadyOwned", errors.Is(err, appstore.ErrLicenseAlreadyExists)).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
retry.LastErrorOnly(true),
|
||||
retry.DelayType(retry.FixedDelay),
|
||||
retry.Delay(time.Millisecond),
|
||||
retry.Attempts(2),
|
||||
retry.RetryIf(func(err error) bool {
|
||||
lastErr = err
|
||||
|
||||
return errors.Is(err, appstore.ErrPasswordTokenExpired)
|
||||
}),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&bundleID, "bundle-identifier", "b", "", "Bundle identifier of the target iOS app (required)")
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.Flags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
|
||||
_ = cmd.MarkFlagRequired("bundle-identifier")
|
||||
|
||||
return cmd
|
||||
|
||||
+40
-28
@@ -1,16 +1,27 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/thediveo/enumflag/v2"
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
var version = "dev"
|
||||
|
||||
type contextKey string
|
||||
|
||||
const interactiveKey contextKey = "interactive"
|
||||
|
||||
func rootCmd() *cobra.Command {
|
||||
var verbose bool
|
||||
var nonInteractive bool
|
||||
var format OutputFormat
|
||||
var (
|
||||
verbose bool
|
||||
nonInteractive bool
|
||||
format OutputFormat
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "ipatool",
|
||||
@@ -18,17 +29,10 @@ func rootCmd() *cobra.Command {
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
Version: version,
|
||||
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
ctx := context.WithValue(context.Background(), "logger", newLogger(format, verbose))
|
||||
ctx = context.WithValue(ctx, "interactive", nonInteractive == false)
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
ctx := context.WithValue(context.Background(), interactiveKey, !nonInteractive)
|
||||
cmd.SetContext(ctx)
|
||||
|
||||
err := configureConfigDirectory()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to configure config directory")
|
||||
}
|
||||
|
||||
return nil
|
||||
initWithCommand(cmd)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -39,37 +43,45 @@ func rootCmd() *cobra.Command {
|
||||
}, enumflag.EnumCaseSensitive), "format", "", "sets output format for command; can be 'text', 'json'")
|
||||
cmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "enables verbose logs")
|
||||
cmd.PersistentFlags().BoolVarP(&nonInteractive, "non-interactive", "", false, "run in non-interactive session")
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
|
||||
cmd.AddCommand(authCmd())
|
||||
cmd.AddCommand(downloadCmd())
|
||||
cmd.AddCommand(purchaseCmd())
|
||||
cmd.AddCommand(searchCmd())
|
||||
cmd.AddCommand(ListVersionsCmd())
|
||||
cmd.AddCommand(getVersionMetadataCmd())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Execute runs the program and returns the approperiate exit status code.
|
||||
func Execute() (exitCode int) {
|
||||
// Execute runs the program and returns the appropriate exit status code.
|
||||
func Execute() int {
|
||||
cmd := rootCmd()
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
exitCode = 1
|
||||
|
||||
logger := newLogger(OutputFormatText, false)
|
||||
outputFormat, parseErr := parseOutputFormat(cmd.Flag("format").Value.String())
|
||||
if parseErr != nil {
|
||||
logger.Error().Err(parseErr).Send()
|
||||
return
|
||||
if err != nil {
|
||||
if reflect.ValueOf(dependencies).IsZero() {
|
||||
initWithCommand(cmd)
|
||||
}
|
||||
|
||||
logger = newLogger(outputFormat, cmd.Flag("verbose").Value.String() == "true")
|
||||
var appstoreErr *appstore.Error
|
||||
if errors.As(err, &appstoreErr) {
|
||||
dependencies.Logger.Verbose().Stack().
|
||||
Err(err).
|
||||
Interface("metadata", appstoreErr.Metadata).
|
||||
Send()
|
||||
} else {
|
||||
dependencies.Logger.Verbose().Stack().Err(err).Send()
|
||||
}
|
||||
|
||||
logger.Verbose().Stack().Err(err).Send()
|
||||
logger.Error().
|
||||
dependencies.Logger.Error().
|
||||
Err(err).
|
||||
Bool("success", false).
|
||||
Send()
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
return
|
||||
return 0
|
||||
}
|
||||
+31
-12
@@ -1,34 +1,53 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"github.com/99designs/keyring"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/majd/ipatool/v2/pkg/appstore"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// nolint:wrapcheck
|
||||
func searchCmd() *cobra.Command {
|
||||
var keychainPassphrase string
|
||||
var limit int64
|
||||
var (
|
||||
limit int64
|
||||
platformValue string
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "search <term>",
|
||||
Short: "Search for iOS apps available on the App Store",
|
||||
Short: "Search for iOS and tvOS apps available on the App Store",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
appstore, err := newAppStore(cmd, keychainPassphrase)
|
||||
infoResult, err := dependencies.AppStore.AccountInfo()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to create appstore client")
|
||||
return err
|
||||
}
|
||||
|
||||
return appstore.Search(args[0], limit)
|
||||
platform, err := appstore.ParsePlatform(platformValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
output, err := dependencies.AppStore.Search(appstore.SearchInput{
|
||||
Account: infoResult.Account,
|
||||
Term: args[0],
|
||||
Limit: limit,
|
||||
Platform: platform,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dependencies.Logger.Log().
|
||||
Int("count", output.Count).
|
||||
Array("apps", appstore.Apps(output.Results)).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().Int64VarP(&limit, "limit", "l", 5, "maximum amount of search results to retrieve")
|
||||
|
||||
if keyringBackendType() == keyring.FileBackend {
|
||||
cmd.PersistentFlags().StringVar(&keychainPassphrase, "keychain-passphrase", "", "passphrase for unlocking keychain")
|
||||
}
|
||||
cmd.Flags().StringVar(&platformValue, "platform", "", "Platform to search: iphone, ipad, or appletv")
|
||||
|
||||
return cmd
|
||||
}
|
||||
@@ -1,43 +1,78 @@
|
||||
module github.com/majd/ipatool
|
||||
module github.com/majd/ipatool/v2
|
||||
|
||||
go 1.19
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/99designs/keyring v1.2.1
|
||||
github.com/golang/mock v1.6.0
|
||||
github.com/avast/retry-go v3.0.0+incompatible
|
||||
github.com/blacktop/go-macho v1.1.282
|
||||
github.com/bodgit/sevenzip v1.6.3
|
||||
github.com/byteness/keyring v1.9.0
|
||||
github.com/ebitengine/purego v0.10.2
|
||||
github.com/juju/persistent-cookiejar v1.0.0
|
||||
github.com/klauspost/compress v1.18.6
|
||||
github.com/onsi/ginkgo/v2 v2.5.0
|
||||
github.com/onsi/gomega v1.24.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/rs/zerolog v1.28.0
|
||||
github.com/schollz/progressbar/v3 v3.13.1
|
||||
github.com/spf13/cobra v1.6.1
|
||||
github.com/thediveo/enumflag/v2 v2.0.1
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
|
||||
golang.org/x/net v0.8.0
|
||||
golang.org/x/term v0.6.0
|
||||
go.uber.org/mock v0.4.0
|
||||
golang.org/x/term v0.43.0
|
||||
howett.net/plist v1.0.0
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
|
||||
github.com/danieljoos/wincred v1.1.2 // indirect
|
||||
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
|
||||
github.com/go-logr/logr v1.2.3 // indirect
|
||||
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
|
||||
github.com/google/go-cmp v0.5.9 // indirect
|
||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b // indirect
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 // indirect
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/blacktop/go-dwarf v1.0.14 // indirect
|
||||
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||
github.com/bodgit/windows v1.0.1 // indirect
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 // indirect
|
||||
github.com/byteness/percent v0.2.2 // indirect
|
||||
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
|
||||
github.com/extism/go-sdk v1.7.1 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.2 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.1 // indirect
|
||||
github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/mattn/go-isatty v0.0.17 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect
|
||||
github.com/mtibben/percent v0.2.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.3 // indirect
|
||||
github.com/schollz/progressbar/v3 v3.12.1 // indirect
|
||||
github.com/noamcohen97/touchid-go v0.3.0 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.26 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
golang.org/x/sys v0.6.0 // indirect
|
||||
golang.org/x/text v0.8.0 // indirect
|
||||
github.com/stangelandcl/ppmd v0.1.0 // indirect
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible // indirect
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
|
||||
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
|
||||
golang.org/x/crypto v0.52.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect
|
||||
golang.org/x/mod v0.35.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.45.0 // indirect
|
||||
golang.org/x/text v0.37.0 // indirect
|
||||
golang.org/x/tools v0.44.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/errgo.v1 v1.0.1 // indirect
|
||||
gopkg.in/retry.v1 v1.0.3 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -1,31 +1,66 @@
|
||||
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs=
|
||||
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4=
|
||||
github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o=
|
||||
github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA=
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b h1:sVddTkAGVmDXJbZKgp+W1zC7hN4lLz9Nus1XmjbY7eo=
|
||||
github.com/1Password/connect-sdk-go v1.5.4-0.20250417152128-c154b387248b/go.mod h1:5rSymY4oIYtS4G3t0oMkGAXBeoYiukV3vkqlnEjIDJs=
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1 h1:b/tt+bAXFXR5f3/irmPAaytfmsN6+5Nj6pbsx5nmKZA=
|
||||
github.com/1password/onepassword-sdk-go v0.4.1-beta.1/go.mod h1:j/CbzhucTywjlYrd6SE6k0LcQaFZ2l8OLBsAsOYtvD0=
|
||||
github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM=
|
||||
github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo=
|
||||
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0=
|
||||
github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY=
|
||||
github.com/blacktop/go-dwarf v1.0.14 h1:OjmzfSgg/qAKckn2tWFebcgKgJ7HOqCj7bS+CiE1lrY=
|
||||
github.com/blacktop/go-dwarf v1.0.14/go.mod h1:4W2FKgSFYcZLDwnR7k+apv5i3nrau4NGl9N6VQ9DSTo=
|
||||
github.com/blacktop/go-macho v1.1.282 h1:DW3HYz5zVCT6+Jlp1+hxauYvEgxqZsGMvu8/1j4+Ibg=
|
||||
github.com/blacktop/go-macho v1.1.282/go.mod h1:Hc5E2Lvt/U1VT+jOxr1O5l/LNFJeMYK4eAmDfazTiGc=
|
||||
github.com/bodgit/plumbing v1.3.0 h1:pf9Itz1JOQgn7vEOE7v7nlEfBykYqvUYioC61TwWCFU=
|
||||
github.com/bodgit/plumbing v1.3.0/go.mod h1:JOTb4XiRu5xfnmdnDJo6GmSbSbtSyufrsyZFByMtKEs=
|
||||
github.com/bodgit/sevenzip v1.6.3 h1:t7K1jcgPnXdZyRHr68vq5L9vO/WmjDJEiGUwTR6i6gk=
|
||||
github.com/bodgit/sevenzip v1.6.3/go.mod h1:a29jn+ZL8UfQr/L+8jJT1wmhCMulGOfaT5d1HWxwD5g=
|
||||
github.com/bodgit/windows v1.0.1 h1:tF7K6KOluPYygXa3Z2594zxlkbKPAOvqr97etrGNIz4=
|
||||
github.com/bodgit/windows v1.0.1/go.mod h1:a6JLwrB4KrTR5hBpp8FI9/9W9jJfeQ2h4XDXU74ZCdM=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:HFl8GFmwK19hYuXB8OQ0rTO9WOCgZY9JUy964zaYawY=
|
||||
github.com/byteness/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:9HlL8SWBRtCZE7sCNq+c3//H/oHywgSwtocmPTdOij8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0 h1:j59wGsxaBk6aFBuuYofk2oznMGZYyzFovjDqavlJHM8=
|
||||
github.com/byteness/go-libsecret v0.0.0-20260108215642-107379d3dee0/go.mod h1:3FrDGTXj08zj6qtqlIvt0vS8eWNrrYpnXOEbcQgFmvM=
|
||||
github.com/byteness/keyring v1.9.0 h1:9m+7pru+JkMJ8wxma5id5m6pSt2Zx/xPj77kyM+yAVE=
|
||||
github.com/byteness/keyring v1.9.0/go.mod h1:a6CV8t/qfEUERPTP+dqeVfKgib2wz3PIYbMWRfmvmes=
|
||||
github.com/byteness/percent v0.2.2 h1:vnIFh8WBR1xoC+U2etz0EMB1cgp+vsK6vynqTCeDziU=
|
||||
github.com/byteness/percent v0.2.2/go.mod h1:nwavge92FhIyfnldz4YWZD8uxPVvdh8NlzLRd1VYRDs=
|
||||
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0=
|
||||
github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0=
|
||||
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
|
||||
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM=
|
||||
github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0 h1:LqkkVKAlHFfH9LOEl5fe4p/zL02OhWE7pCufMBG2jLA=
|
||||
github.com/dvsekhvalnov/jose2go v1.8.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/ebitengine/purego v0.10.2 h1:W809HbnvzAxgdm+aOvlSekrM16wGCdT/e76+9tS7gzE=
|
||||
github.com/ebitengine/purego v0.10.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
|
||||
github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY=
|
||||
github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20=
|
||||
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
|
||||
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0=
|
||||
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||
github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ=
|
||||
github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU=
|
||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f h1:Fnl4pzx8SR7k7JuzyW8lEtSFH6EQ8xgcypgIn8pcGIE=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20251118225945-96ee0021ea0f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
github.com/inconshreveable/mousetrap v1.0.1 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc=
|
||||
github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||
@@ -34,6 +69,8 @@ github.com/juju/go4 v0.0.0-20160222163258-40d72ab9641a/go.mod h1:RVHtZuvrpETIepi
|
||||
github.com/juju/persistent-cookiejar v1.0.0 h1:Ag7+QLzqC2m+OYXy2QQnRjb3gTkEBSZagZ6QozwT3EQ=
|
||||
github.com/juju/persistent-cookiejar v1.0.0/go.mod h1:zrbmo4nBKaiP/Ez3F67ewkMbzGYfXyMvRtbOfuAwG0w=
|
||||
github.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
@@ -43,99 +80,107 @@ github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb
|
||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
|
||||
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
|
||||
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=
|
||||
github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=
|
||||
github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs=
|
||||
github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/noamcohen97/touchid-go v0.3.0 h1:fcXxVCizysD7KHRR6hrURt3nyNIs5JBGSbOIidD/3wo=
|
||||
github.com/noamcohen97/touchid-go v0.3.0/go.mod h1:X9MRNIBGEmPqwpDm1G3fQOAQX7fwBlhzUbnkDTxuta0=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0 h1:TRtrvv2vdQqzkwrQ1ke6vtXf7IK34RBUJafIy1wMwls=
|
||||
github.com/onsi/ginkgo/v2 v2.5.0/go.mod h1:Luc4sArBICYCS8THh8v3i3i5CuSZO+RaQRaJoeNwomw=
|
||||
github.com/onsi/gomega v1.24.0 h1:+0glovB9Jd6z3VR+ScSwQqXVTIfJcGA9UBM8yzQxhqg=
|
||||
github.com/onsi/gomega v1.24.0/go.mod h1:Z/NWtiqwBrwUt4/2loMmHL63EDLnYHmVbuBpDr2vQAg=
|
||||
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
|
||||
github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.2/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
|
||||
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM=
|
||||
github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ=
|
||||
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
|
||||
github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/schollz/progressbar/v3 v3.12.1 h1:JAhtIrLWAn6/p7i82SrpSG3fgAwlAxi+Sy12r4AzBvQ=
|
||||
github.com/schollz/progressbar/v3 v3.12.1/go.mod h1:g7QSuwyGpqCjVQPFZXA31MSxtrhka9Y9LMdF+XT77/Y=
|
||||
github.com/schollz/progressbar/v3 v3.13.1 h1:o8rySDYiQ59Mwzy2FELeHY5ZARXZTVJC7iHD6PEFUiE=
|
||||
github.com/schollz/progressbar/v3 v3.13.1/go.mod h1:xvrbki8kfT1fzWzBT/UZd9L6GA+jdL7HAgq2RFnO6fQ=
|
||||
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA=
|
||||
github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stangelandcl/ppmd v0.1.0 h1:0gOKtSdWyXxpRW55H/dZ3AgaJqjrtlIrAvsokFwp7ug=
|
||||
github.com/stangelandcl/ppmd v0.1.0/go.mod h1:Rrv7M+/2P5jYr/GMLhBl7Ug3uJ1bUiVzr5LbbaV6xgY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1 h1:2bmWZPD2uSARDsOjXIdLRlNcYBFNF9xX0RNUNF2vKic=
|
||||
github.com/thediveo/enumflag/v2 v2.0.1/go.mod h1:SyxyCNvv0QeRtZ7fjuaUz4FRLC3cWuDiD7QdORU0MGg=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible h1:D6wyKGCecFaSRUpo8lCVbaOOb6ThwMmTEbhRwtKR97o=
|
||||
github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible h1:td4jdvLcExb4cBISKIpHuGoVXh+dVKhn2Um6rjCsSsg=
|
||||
github.com/uber/jaeger-lib v2.4.1+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
|
||||
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
|
||||
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU=
|
||||
go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc=
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f h1:ziUVAjmTPwQMBmYR1tbdRFJPtTcQUI12fH9QQjfb0Sw=
|
||||
go4.org v0.0.0-20260112195520-a5071408f32f/go.mod h1:ZRJnO5ZI4zAwMFp+dS1+V6J6MSyAowhRqAE+DPa1Xp0=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA=
|
||||
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
|
||||
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
|
||||
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
|
||||
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A=
|
||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM=
|
||||
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
|
||||
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
|
||||
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
|
||||
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
|
||||
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@@ -149,3 +194,5 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
|
||||
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847 h1:jHX+2Sv8rQNb1nG2G9pcQLdVoWXBLW5fcd2gnfHluCU=
|
||||
howett.net/ranger v0.0.0-20171016084633-e2e137620847/go.mod h1:ZWGIG4mR6Ck+CdmFqK2/jox5vO2OAS8Qpb33HB8z0og=
|
||||
@@ -0,0 +1,377 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/bzip2"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/blacktop/go-macho/pkg/xar"
|
||||
"howett.net/ranger"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/cpio"
|
||||
)
|
||||
|
||||
const (
|
||||
updateURL = "https://swcdn.apple.com/content/downloads/27/34/041-98128-A_SYPWICN3KH/5dqkl4rqgbsr18yzy61yeie9g3cmjc5hiv/OSXUpd10.9.pkg"
|
||||
payloadName = "Payload"
|
||||
payloadBZOffset = int64(0x352F40D5)
|
||||
payloadCPIO = int64(0x3A4)
|
||||
)
|
||||
|
||||
type Bundle struct {
|
||||
CommerceKit []byte
|
||||
CommerceCore []byte
|
||||
CoreFP []byte
|
||||
CoreFPICXS []byte
|
||||
}
|
||||
|
||||
type fileSpec struct {
|
||||
name string
|
||||
path string
|
||||
size int
|
||||
digest [32]byte
|
||||
}
|
||||
|
||||
var requiredFiles = []fileSpec{
|
||||
{
|
||||
name: "CommerceKit",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/CommerceKit",
|
||||
size: 3271840,
|
||||
digest: mustDigest("b84ff12c21987856c0a17b78f1ad82b73195a6dec5f3b208a17d245555a2c8a2"),
|
||||
},
|
||||
{
|
||||
name: "CommerceCore",
|
||||
path: "./System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Frameworks/CommerceCore.framework/Versions/A/CommerceCore",
|
||||
size: 207744,
|
||||
digest: mustDigest("c5401e57402230f3c876409d295319ddf1e61287bc882683c5d61277be7bc1f2"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP",
|
||||
path: "./System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP",
|
||||
size: 29014912,
|
||||
digest: mustDigest("f19141336be4198d0f8991bb00017c915efc7aeaece36c345f7faa1237ea6074"),
|
||||
},
|
||||
{
|
||||
name: "CoreFP.icxs",
|
||||
path: "./System/Library/PrivateFrameworks/CoreFP.framework/Versions/A/CoreFP.icxs",
|
||||
size: 5288352,
|
||||
digest: mustDigest("473e78af86979f5bd4f6269561caf770b3d16c098d918846eeac8cdd2fe6566a"),
|
||||
},
|
||||
}
|
||||
|
||||
func Load(ctx context.Context) (Bundle, error) {
|
||||
directory, err := cacheDirectory()
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if bundle, err := readCache(directory); err == nil {
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
bundle, err := download(ctx)
|
||||
if err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
if err := writeCache(directory, bundle); err != nil {
|
||||
return Bundle{}, fmt.Errorf("cache Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func download(ctx context.Context) (Bundle, error) {
|
||||
parsed, err := url.Parse(updateURL)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("parse Apple software update URL: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 2 * time.Minute,
|
||||
Transport: contextTransport{ctx: ctx, next: http.DefaultTransport},
|
||||
}
|
||||
|
||||
remote, err := ranger.NewReader(&ranger.HTTPRanger{Client: client, URL: parsed})
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("open Apple software update: %w", err)
|
||||
}
|
||||
|
||||
length, err := remote.Length()
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("measure Apple software update: %w", err)
|
||||
}
|
||||
|
||||
container, err := xar.NewReader(remote, length)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read Apple software update: %w", err)
|
||||
}
|
||||
|
||||
var payload *xar.File
|
||||
|
||||
for _, candidate := range container.Files {
|
||||
if candidate.Name == payloadName {
|
||||
payload = candidate
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if payload == nil {
|
||||
return Bundle{}, &fs.PathError{Op: "open", Path: payloadName, Err: fs.ErrNotExist}
|
||||
}
|
||||
|
||||
raw := payload.OpenRaw()
|
||||
if _, err := raw.Seek(payloadBZOffset, io.SeekStart); err != nil {
|
||||
return Bundle{}, fmt.Errorf("seek Apple update payload: %w", err)
|
||||
}
|
||||
|
||||
compressed := io.MultiReader(bytes.NewReader([]byte{'B', 'Z', 'h', '9'}), raw)
|
||||
|
||||
archive := bzip2.NewReader(compressed)
|
||||
if _, err := io.CopyN(io.Discard, archive, payloadCPIO); err != nil {
|
||||
return Bundle{}, fmt.Errorf("seek Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
wanted := make(map[string]fileSpec, len(requiredFiles))
|
||||
for _, spec := range requiredFiles {
|
||||
wanted[spec.path] = spec
|
||||
}
|
||||
|
||||
found := make(map[string][]byte, len(requiredFiles))
|
||||
reader := cpio.NewReader(archive)
|
||||
|
||||
for len(found) != len(wanted) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Bundle{}, fmt.Errorf("download Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
path, body, err := reader.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read Apple payload archive: %w", err)
|
||||
}
|
||||
|
||||
spec, ok := wanted[path]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(body, int64(spec.size)+1))
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
found[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(found)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func cacheDirectory() (string, error) {
|
||||
root, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("find user cache directory: %w", err)
|
||||
}
|
||||
|
||||
return filepath.Join(root, "ipatool", "sap", "apple-assets-v2"), nil
|
||||
}
|
||||
|
||||
func readCache(directory string) (Bundle, error) {
|
||||
files := make(map[string][]byte, len(requiredFiles))
|
||||
|
||||
for _, spec := range requiredFiles {
|
||||
data, err := readCacheFile(filepath.Join(directory, spec.name), spec.size)
|
||||
if err != nil {
|
||||
return Bundle{}, fmt.Errorf("read cached Apple SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
|
||||
files[spec.name] = data
|
||||
}
|
||||
|
||||
bundle := bundleFrom(files)
|
||||
if err := validate(bundle); err != nil {
|
||||
return Bundle{}, err
|
||||
}
|
||||
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func readCacheFile(path string, expectedSize int) ([]byte, error) {
|
||||
if expectedSize < 0 {
|
||||
return nil, errors.New("invalid expected size")
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open cached asset: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inspect cached asset: %w", err)
|
||||
}
|
||||
|
||||
if info.Size() != int64(expectedSize) {
|
||||
return nil, fmt.Errorf("has size %d, expected %d", info.Size(), expectedSize)
|
||||
}
|
||||
|
||||
data := make([]byte, expectedSize)
|
||||
if _, err := io.ReadFull(file, data); err != nil {
|
||||
return nil, fmt.Errorf("read cached asset: %w", err)
|
||||
}
|
||||
|
||||
var extra [1]byte
|
||||
if count, err := io.ReadFull(file, extra[:]); err == nil || count != 0 {
|
||||
return nil, fmt.Errorf("grew beyond expected size %d while being read", expectedSize)
|
||||
} else if !errors.Is(err, io.EOF) {
|
||||
return nil, fmt.Errorf("verify cached asset length: %w", err)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func writeCache(directory string, bundle Bundle) error {
|
||||
if err := validate(bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return fmt.Errorf("create SAP asset cache: %w", err)
|
||||
}
|
||||
|
||||
files := bundleFiles(bundle)
|
||||
for _, spec := range requiredFiles {
|
||||
if err := replaceFile(filepath.Join(directory, spec.name), files[spec.name]); err != nil {
|
||||
return fmt.Errorf("write cached SAP asset %s: %w", spec.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func replaceFile(path string, data []byte) error {
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".download-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
|
||||
if err := temporary.Chmod(0o600); err != nil {
|
||||
_ = temporary.Close()
|
||||
|
||||
return fmt.Errorf("set cache file permissions: %w", err)
|
||||
}
|
||||
|
||||
if _, err := temporary.Write(data); err != nil {
|
||||
_ = temporary.Close()
|
||||
|
||||
return fmt.Errorf("write temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := temporary.Close(); err != nil {
|
||||
return fmt.Errorf("close temporary cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(temporaryPath, path); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("remove existing cache file: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(temporaryPath, path); err != nil {
|
||||
return fmt.Errorf("install cache file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
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 sha256.Sum256(data) != spec.digest {
|
||||
return fmt.Errorf("apple SAP asset %s failed integrity verification", spec.name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func bundleFrom(files map[string][]byte) Bundle {
|
||||
return Bundle{
|
||||
CommerceKit: files["CommerceKit"],
|
||||
CommerceCore: files["CommerceCore"],
|
||||
CoreFP: files["CoreFP"],
|
||||
CoreFPICXS: files["CoreFP.icxs"],
|
||||
}
|
||||
}
|
||||
|
||||
func bundleFiles(bundle Bundle) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
"CommerceKit": bundle.CommerceKit,
|
||||
"CommerceCore": bundle.CommerceCore,
|
||||
"CoreFP": bundle.CoreFP,
|
||||
"CoreFP.icxs": bundle.CoreFPICXS,
|
||||
}
|
||||
}
|
||||
|
||||
func mustDigest(value string) [32]byte {
|
||||
var digest [32]byte
|
||||
|
||||
decoded, err := hex.DecodeString(value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if len(decoded) != len(digest) {
|
||||
panic("invalid SHA-256 length")
|
||||
}
|
||||
|
||||
copy(digest[:], decoded)
|
||||
|
||||
return digest
|
||||
}
|
||||
|
||||
type contextTransport struct {
|
||||
ctx context.Context
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (t contextTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := t.next.RoundTrip(request.Clone(t.ctx))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch Apple software update: %w", err)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package assets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadCacheFile(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
data []byte
|
||||
expectedSize int
|
||||
wantErr string
|
||||
}{
|
||||
{name: "exact size", data: []byte("12345678"), expectedSize: 8},
|
||||
{name: "too short", data: []byte("1234"), expectedSize: 8, wantErr: "has size 4, expected 8"},
|
||||
{name: "too large", data: bytes.Repeat([]byte{1}, 64), expectedSize: 8, wantErr: "has size 64, expected 8"},
|
||||
{name: "invalid expected size", expectedSize: -1, wantErr: "invalid expected size"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "asset")
|
||||
if err := os.WriteFile(path, test.data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := readCacheFile(path, test.expectedSize)
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("readCacheFile() error = %v", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(got, test.data) {
|
||||
t.Fatalf("readCacheFile() = %q, want %q", got, test.data)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("readCacheFile() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Package cpio reads the old portable ASCII CPIO format used by Apple's
|
||||
// software-update payload. It streams entry bodies so unrelated files are not
|
||||
// retained while locating the small set needed by the SAP emulator.
|
||||
package cpio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
const (
|
||||
headerSize = 76
|
||||
nameSizeOffset = 59
|
||||
fileSizeOffset = 65
|
||||
)
|
||||
|
||||
var (
|
||||
headerMagic = []byte("070707")
|
||||
trailerName = []byte("TRAILER!!!")
|
||||
)
|
||||
|
||||
type Reader struct {
|
||||
source io.Reader
|
||||
current *io.LimitedReader
|
||||
}
|
||||
|
||||
func NewReader(source io.Reader) *Reader {
|
||||
return &Reader{source: source}
|
||||
}
|
||||
|
||||
func (r *Reader) Next() (string, io.Reader, error) {
|
||||
if r.current != nil {
|
||||
if _, err := io.Copy(io.Discard, r.current); err != nil {
|
||||
return "", nil, fmt.Errorf("skip CPIO entry: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
header := make([]byte, headerSize)
|
||||
if _, err := io.ReadFull(r.source, header); err != nil {
|
||||
return "", nil, fmt.Errorf("read CPIO header: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(header[:len(headerMagic)], headerMagic) {
|
||||
return "", nil, fmt.Errorf("invalid CPIO magic %q", header[:len(headerMagic)])
|
||||
}
|
||||
|
||||
nameSize, err := parseOctal(header[nameSizeOffset:fileSizeOffset])
|
||||
if err != nil || nameSize < 1 {
|
||||
return "", nil, fmt.Errorf("invalid CPIO name size %q", header[nameSizeOffset:fileSizeOffset])
|
||||
}
|
||||
|
||||
fileSize, err := parseOctal(header[fileSizeOffset:headerSize])
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("invalid CPIO file size %q", header[fileSizeOffset:headerSize])
|
||||
}
|
||||
|
||||
name := make([]byte, nameSize)
|
||||
if _, err := io.ReadFull(r.source, name); err != nil {
|
||||
return "", nil, fmt.Errorf("read CPIO name: %w", err)
|
||||
}
|
||||
|
||||
if name[len(name)-1] != 0 {
|
||||
return "", nil, errors.New("CPIO name is not NUL-terminated")
|
||||
}
|
||||
|
||||
name = name[:len(name)-1]
|
||||
if bytes.Equal(name, trailerName) {
|
||||
return "", nil, io.EOF
|
||||
}
|
||||
|
||||
r.current = &io.LimitedReader{R: r.source, N: int64(fileSize)}
|
||||
|
||||
return string(name), r.current, nil
|
||||
}
|
||||
|
||||
func parseOctal(value []byte) (uint64, error) {
|
||||
parsed, err := strconv.ParseUint(string(value), 8, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("parse CPIO octal value: %w", err)
|
||||
}
|
||||
|
||||
return parsed, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cpio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReaderStreamsEntries(t *testing.T) {
|
||||
archive := append(cpioEntry("first", []byte("ignored")), cpioEntry("second", []byte("wanted"))...)
|
||||
archive = append(archive, cpioEntry("TRAILER!!!", nil)...)
|
||||
reader := NewReader(bytes.NewReader(archive))
|
||||
|
||||
name, _, err := reader.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if name != "first" {
|
||||
t.Fatalf("name = %q, want first", name)
|
||||
}
|
||||
|
||||
name, body, err := reader.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if name != "second" || string(data) != "wanted" {
|
||||
t.Fatalf("entry = %q %q, want second wanted", name, data)
|
||||
}
|
||||
|
||||
if _, _, err := reader.Next(); err != io.EOF {
|
||||
t.Fatalf("trailer error = %v, want EOF", err)
|
||||
}
|
||||
}
|
||||
|
||||
func cpioEntry(name string, body []byte) []byte {
|
||||
nameBytes := append([]byte(name), 0)
|
||||
header := fmt.Sprintf(
|
||||
"070707%06o%06o%06o%06o%06o%06o%06o%011o%06o%011o",
|
||||
0, 0, 0, 0, 0, 1, 0, 0, len(nameBytes), len(body),
|
||||
)
|
||||
entry := append([]byte(header), nameBytes...)
|
||||
|
||||
return append(entry, body...)
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/blacktop/go-macho"
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
const (
|
||||
pageSize = uint64(0x1000)
|
||||
maxImageSpan = uint64(1 << 30)
|
||||
pointerSize = uint64(8)
|
||||
)
|
||||
|
||||
type Memory interface {
|
||||
MemMap(address, size uint64) error
|
||||
MemWrite(address uint64, data []byte) error
|
||||
}
|
||||
|
||||
type segment struct {
|
||||
name string
|
||||
address uint64
|
||||
size uint64
|
||||
fileOff uint64
|
||||
fileSize uint64
|
||||
}
|
||||
|
||||
type Image struct {
|
||||
name string
|
||||
data []byte
|
||||
file *macho.File
|
||||
base uint64
|
||||
segments []segment
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
relocated bool
|
||||
loadedBase uint64
|
||||
}
|
||||
|
||||
func Open(name string, input []byte) (*Image, error) {
|
||||
data, err := amd64Slice(input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s: %w", name, err)
|
||||
}
|
||||
|
||||
file, err := macho.NewFile(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open %s Mach-O: %w", name, err)
|
||||
}
|
||||
|
||||
if file.CPU != types.CPUAmd64 {
|
||||
return nil, fmt.Errorf("open %s: expected x86-64 Mach-O, found %s", name, file.CPU)
|
||||
}
|
||||
|
||||
image := &Image{
|
||||
name: name,
|
||||
data: data,
|
||||
file: file,
|
||||
base: file.GetBaseAddress(),
|
||||
}
|
||||
for _, item := range file.Segments() {
|
||||
image.segments = append(image.segments, segment{
|
||||
name: item.Name,
|
||||
address: item.Addr,
|
||||
size: item.Memsz,
|
||||
fileOff: item.Offset,
|
||||
fileSize: item.Filesz,
|
||||
})
|
||||
}
|
||||
|
||||
if err := image.validateSegments(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
image.binds, err = file.GetBindInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s bindings: %w", name, err)
|
||||
}
|
||||
|
||||
image.rebases, err = file.GetRebaseInfo()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read %s rebases: %w", name, err)
|
||||
}
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
func amd64Slice(input []byte) ([]byte, error) {
|
||||
fat, err := macho.NewFatFile(bytes.NewReader(input))
|
||||
if err != nil {
|
||||
return bytes.Clone(input), nil
|
||||
}
|
||||
|
||||
for _, architecture := range fat.Arches {
|
||||
if architecture.CPU != types.CPUAmd64 {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(uint64(architecture.Offset), uint64(architecture.Size))
|
||||
if overflow || end > uint64(len(input)) {
|
||||
return nil, errors.New("x86-64 slice exceeds input size")
|
||||
}
|
||||
|
||||
return bytes.Clone(input[architecture.Offset:end]), nil
|
||||
}
|
||||
|
||||
return nil, errors.New("universal binary has no x86-64 slice")
|
||||
}
|
||||
|
||||
func (i *Image) Export(name string, loadBase uint64) (uint64, error) {
|
||||
address, err := i.file.FindSymbolAddress(name)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("find %s in %s: %w", name, i.name, err)
|
||||
}
|
||||
|
||||
if address < i.base {
|
||||
return 0, fmt.Errorf("symbol %s in %s precedes image base", name, i.name)
|
||||
}
|
||||
|
||||
result, overflow := add(loadBase, address-i.base)
|
||||
if overflow {
|
||||
return 0, fmt.Errorf("symbol %s address overflows in %s", name, i.name)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (i *Image) Relocate(loadBase uint64, resolve func(string) (uint64, error)) error {
|
||||
if i.relocated {
|
||||
return fmt.Errorf("%s is already relocated", i.name)
|
||||
}
|
||||
|
||||
for _, relocation := range i.rebases {
|
||||
if relocation.Type != types.REBASE_TYPE_POINTER {
|
||||
return fmt.Errorf("%s uses unsupported rebase type %d", i.name, relocation.Type)
|
||||
}
|
||||
|
||||
if relocation.Value < i.base {
|
||||
return fmt.Errorf("%s contains a rebase below its image base", i.name)
|
||||
}
|
||||
|
||||
offset, err := i.segmentFileOffset(relocation.Segment, relocation.Offset, pointerSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, overflow := add(loadBase, relocation.Value-i.base)
|
||||
if overflow {
|
||||
return fmt.Errorf("rebase address overflows in %s", i.name)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, binding := range i.binds {
|
||||
// Lazy bind streams may omit SET_TYPE; dyld's default is a pointer bind.
|
||||
if binding.Type != 0 && binding.Type != types.BIND_TYPE_POINTER {
|
||||
return fmt.Errorf("%s uses unsupported bind type %d for %s", i.name, binding.Type, binding.Name)
|
||||
}
|
||||
|
||||
offset, err := i.segmentFileOffset(binding.Segment, binding.SegOffset, pointerSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, err := resolve(binding.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve %s for %s: %w", binding.Name, i.name, err)
|
||||
}
|
||||
|
||||
address, err = addSigned(address, binding.Addend)
|
||||
if err != nil {
|
||||
return fmt.Errorf("apply addend for %s in %s: %w", binding.Name, i.name, err)
|
||||
}
|
||||
|
||||
if err := i.putPointer(offset, address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
i.relocated = true
|
||||
i.loadedBase = loadBase
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) Load(memory Memory) error {
|
||||
if !i.relocated {
|
||||
return fmt.Errorf("%s must be relocated before loading", i.name)
|
||||
}
|
||||
|
||||
var span uint64
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.size == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if item.address < i.base {
|
||||
return fmt.Errorf("segment %s in %s precedes image base", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(item.address-i.base, item.size)
|
||||
if overflow || end > maxImageSpan {
|
||||
return fmt.Errorf("segment %s makes %s too large", item.name, i.name)
|
||||
}
|
||||
|
||||
span = max(span, end)
|
||||
}
|
||||
|
||||
span = align(span, pageSize)
|
||||
if span == 0 {
|
||||
return fmt.Errorf("%s has no loadable segments", i.name)
|
||||
}
|
||||
|
||||
if _, overflow := add(i.loadedBase, span); overflow {
|
||||
return fmt.Errorf("load range for %s overflows", i.name)
|
||||
}
|
||||
|
||||
if err := memory.MemMap(i.loadedBase, span); err != nil {
|
||||
return fmt.Errorf("map %s: %w", i.name, err)
|
||||
}
|
||||
|
||||
for _, item := range i.segments {
|
||||
if item.name == "__PAGEZERO" || item.fileSize == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
end, overflow := add(item.fileOff, item.fileSize)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
|
||||
}
|
||||
|
||||
address, overflow := add(i.loadedBase, item.address-i.base)
|
||||
if overflow {
|
||||
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 {
|
||||
return fmt.Errorf("write segment %s from %s: %w", item.name, i.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) validateSegments() error {
|
||||
for _, item := range i.segments {
|
||||
if item.fileSize > item.size {
|
||||
return fmt.Errorf("segment %s file data exceeds its memory size in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
if _, overflow := add(item.address, item.size); overflow {
|
||||
return fmt.Errorf("segment %s address range overflows in %s", item.name, i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(item.fileOff, item.fileSize)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("segment %s data exceeds %s", item.name, i.name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Image) segmentFileOffset(name string, offset, size uint64) (uint64, error) {
|
||||
for _, item := range i.segments {
|
||||
if item.name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
segmentEnd, overflow := add(offset, size)
|
||||
if overflow || segmentEnd > item.size {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds segment %s in %s", offset, name, i.name)
|
||||
}
|
||||
|
||||
if segmentEnd > item.fileSize {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds file data for segment %s in %s", offset, name, i.name)
|
||||
}
|
||||
|
||||
result, overflow := add(item.fileOff, offset)
|
||||
if overflow {
|
||||
return 0, fmt.Errorf("fixup offset overflows in %s", i.name)
|
||||
}
|
||||
|
||||
end, overflow := add(result, size)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return 0, fmt.Errorf("fixup at %#x exceeds %s", result, i.name)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("fixup references unknown segment %s in %s", name, i.name)
|
||||
}
|
||||
|
||||
func (i *Image) putPointer(offset, value uint64) error {
|
||||
end, overflow := add(offset, 8)
|
||||
if overflow || end > uint64(len(i.data)) {
|
||||
return fmt.Errorf("fixup at %#x exceeds %s", offset, i.name)
|
||||
}
|
||||
|
||||
binary.LittleEndian.PutUint64(i.data[offset:end], value)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func addSigned(value uint64, delta int64) (uint64, error) {
|
||||
if delta >= 0 {
|
||||
result, overflow := add(value, uint64(delta))
|
||||
if overflow {
|
||||
return 0, errors.New("address overflow")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
magnitude := uint64(-(delta + 1)) + 1
|
||||
if magnitude > value {
|
||||
return 0, errors.New("address underflow")
|
||||
}
|
||||
|
||||
return value - magnitude, nil
|
||||
}
|
||||
|
||||
func add(left, right uint64) (uint64, bool) {
|
||||
return left + right, right > math.MaxUint64-left
|
||||
}
|
||||
|
||||
func align(value, alignment uint64) uint64 {
|
||||
return (value + alignment - 1) &^ (alignment - 1)
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package machimage
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/blacktop/go-macho/types"
|
||||
)
|
||||
|
||||
func TestValidateSegments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
dataLen int
|
||||
segment segment
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "valid",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
|
||||
},
|
||||
{
|
||||
name: "file data exceeds memory",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 8, fileOff: 8, fileSize: 16},
|
||||
wantErr: "file data exceeds its memory size",
|
||||
},
|
||||
{
|
||||
name: "file data exceeds image",
|
||||
dataLen: 16,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: 8, fileSize: 16},
|
||||
wantErr: "data exceeds",
|
||||
},
|
||||
{
|
||||
name: "file range overflows",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: 0x1000, size: 16, fileOff: math.MaxUint64 - 7, fileSize: 16},
|
||||
wantErr: "data exceeds",
|
||||
},
|
||||
{
|
||||
name: "address range overflows",
|
||||
dataLen: 32,
|
||||
segment: segment{name: "__DATA", address: math.MaxUint64 - 7, size: 16},
|
||||
wantErr: "address range overflows",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
image := Image{name: "test", data: make([]byte, test.dataLen), segments: []segment{test.segment}}
|
||||
|
||||
err := image.validateSegments()
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("validateSegments() error = %v", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("validateSegments() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSegmentFileOffsetBounds(t *testing.T) {
|
||||
image := Image{
|
||||
name: "test",
|
||||
data: make([]byte, 64),
|
||||
segments: []segment{
|
||||
{name: "__DATA", address: 0x1000, size: 24, fileOff: 16, fileSize: 16},
|
||||
{name: "__SHORT", address: 0x2000, size: 16, fileOff: 56, fileSize: 16},
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
segment string
|
||||
offset uint64
|
||||
want uint64
|
||||
wantErr string
|
||||
}{
|
||||
{name: "valid at end", segment: "__DATA", offset: 8, want: 24},
|
||||
{name: "past file data", segment: "__DATA", offset: 9, wantErr: "exceeds file data"},
|
||||
{name: "past memory", segment: "__DATA", offset: 17, wantErr: "exceeds segment"},
|
||||
{name: "past image", segment: "__SHORT", offset: 8, wantErr: "exceeds test"},
|
||||
{name: "offset overflow", segment: "__DATA", offset: math.MaxUint64 - 3, wantErr: "exceeds segment"},
|
||||
{name: "unknown segment", segment: "__MISSING", wantErr: "unknown segment"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := image.segmentFileOffset(test.segment, test.offset, pointerSize)
|
||||
if test.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("segmentFileOffset() error = %v", err)
|
||||
}
|
||||
|
||||
if got != test.want {
|
||||
t.Fatalf("segmentFileOffset() = %#x, want %#x", got, test.want)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
|
||||
t.Fatalf("segmentFileOffset() error = %v, want error containing %q", err, test.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelocateRejectsFixupsOutsideTheirSegments(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
binds []types.Bind
|
||||
rebases []types.Rebase
|
||||
}{
|
||||
{
|
||||
name: "bind",
|
||||
binds: []types.Bind{{Name: "symbol", Segment: "__DATA", SegOffset: 9}},
|
||||
},
|
||||
{
|
||||
name: "rebase",
|
||||
rebases: []types.Rebase{{Type: types.REBASE_TYPE_POINTER, Segment: "__DATA", Offset: 9, Value: 0x1000}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
image := Image{
|
||||
name: "test",
|
||||
data: make([]byte, 64),
|
||||
base: 0x1000,
|
||||
segments: []segment{{name: "__DATA", address: 0x1000, size: 32, fileOff: 16, fileSize: 16}},
|
||||
binds: test.binds,
|
||||
rebases: test.rebases,
|
||||
}
|
||||
|
||||
err := image.Relocate(0x2000, func(string) (uint64, error) { return 0x3000, nil })
|
||||
if err == nil || !strings.Contains(err.Error(), "exceeds file data") {
|
||||
t.Fatalf("Relocate() error = %v, want file-data bounds error", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machimage"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const (
|
||||
returnAddress = uint64(0x0000000100000000)
|
||||
coreFPBase = uint64(0x0000100000000000)
|
||||
commerceBase = uint64(0x0000100040000000)
|
||||
kitBase = uint64(0x0000100080000000)
|
||||
scratchBase = uint64(0x0000300000000000)
|
||||
scratchSize = uint64(32 << 20)
|
||||
heapBase = uint64(0x0000400000000000)
|
||||
heapSize = uint64(64 << 20)
|
||||
stackBase = uint64(0x0000500000000000)
|
||||
stackSize = uint64(8 << 20)
|
||||
stackEnd = stackBase + stackSize
|
||||
pageSize = uint64(0x1000)
|
||||
maxOutputSize = uint64(16 << 20)
|
||||
)
|
||||
|
||||
var coreExportNames = []string{
|
||||
"_WIn9UJ86JKdV4dM",
|
||||
"_X46O5IeS",
|
||||
"_YlCJ3lg",
|
||||
"_dku592fbFAj",
|
||||
"_fdjkDSAFjklaf2s",
|
||||
"_lxpgvVMLd0S7uRl",
|
||||
}
|
||||
|
||||
type entryPoints struct {
|
||||
initialize uint64
|
||||
exchange uint64
|
||||
sign uint64
|
||||
teardown uint64
|
||||
dispose uint64
|
||||
}
|
||||
|
||||
type Machine struct {
|
||||
engine *unicorn.Engine
|
||||
services *shims
|
||||
entry entryPoints
|
||||
scratchCursor uint64
|
||||
closed bool
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, bundle assets.Bundle) (*Machine, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("SAP runtime context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
coreFP, err := machimage.Open("CoreFP", bundle.CoreFP)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CoreFP image: %w", err)
|
||||
}
|
||||
|
||||
commerceCore, err := machimage.Open("CommerceCore", bundle.CommerceCore)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CommerceCore image: %w", err)
|
||||
}
|
||||
|
||||
commerceKit, err := machimage.Open("CommerceKit", bundle.CommerceKit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open CommerceKit image: %w", err)
|
||||
}
|
||||
|
||||
exports := make(map[string]uint64)
|
||||
coreExports := make(map[string]uint64, len(coreExportNames))
|
||||
|
||||
for _, name := range coreExportNames {
|
||||
address, err := coreFP.Export(name, coreFPBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CoreFP export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
coreExports[name] = address
|
||||
}
|
||||
|
||||
macAddress, err := commerceCore.Export("_get_mac_address", commerceBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CommerceCore MAC address export: %w", err)
|
||||
}
|
||||
|
||||
exports["_get_mac_address"] = macAddress
|
||||
|
||||
entryNames := []string{
|
||||
"_cp2g1b9ro",
|
||||
"_Mib5yocT",
|
||||
"_Fc3vhtJDvr",
|
||||
"_IPaI1oem5iL",
|
||||
"_jEHf8Xzsv8K",
|
||||
}
|
||||
resolvedEntries := make(map[string]uint64, len(entryNames))
|
||||
|
||||
for _, name := range entryNames {
|
||||
address, err := commerceKit.Export(name, kitBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve CommerceKit export %s: %w", name, err)
|
||||
}
|
||||
|
||||
exports[name] = address
|
||||
resolvedEntries[name] = address
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("open SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
engine, err := unicorn.New(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
}
|
||||
|
||||
machine := &Machine{engine: engine}
|
||||
ready := false
|
||||
|
||||
defer func() {
|
||||
if !ready {
|
||||
_ = machine.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for _, region := range []struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}{
|
||||
{returnAddress, pageSize},
|
||||
{scratchBase, scratchSize},
|
||||
{heapBase, heapSize},
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
if err := engine.MemMap(region.address, region.size); err != nil {
|
||||
return nil, fmt.Errorf("map SAP guest memory at %#x: %w", region.address, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
return nil, fmt.Errorf("write SAP guest return instruction: %w", err)
|
||||
}
|
||||
|
||||
machine.services, err = newShims(engine, coreExports, bundle.CoreFPICXS)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resolver := func(name string) (uint64, error) {
|
||||
if address, ok := exports[name]; ok {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
return machine.services.resolve(name)
|
||||
}
|
||||
for _, item := range []struct {
|
||||
image *machimage.Image
|
||||
base uint64
|
||||
}{
|
||||
{coreFP, coreFPBase},
|
||||
{commerceCore, commerceBase},
|
||||
{commerceKit, kitBase},
|
||||
} {
|
||||
if err := item.image.Relocate(item.base, resolver); err != nil {
|
||||
return nil, fmt.Errorf("relocate SAP guest image: %w", err)
|
||||
}
|
||||
|
||||
if err := item.image.Load(engine); err != nil {
|
||||
return nil, fmt.Errorf("load SAP guest image: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
machine.entry = entryPoints{
|
||||
initialize: resolvedEntries["_cp2g1b9ro"],
|
||||
exchange: resolvedEntries["_Mib5yocT"],
|
||||
sign: resolvedEntries["_Fc3vhtJDvr"],
|
||||
teardown: resolvedEntries["_IPaI1oem5iL"],
|
||||
dispose: resolvedEntries["_jEHf8Xzsv8K"],
|
||||
}
|
||||
ready = true
|
||||
|
||||
return machine, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Initialize(hardwareID []byte) (uint64, error) {
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
m.beginCall()
|
||||
|
||||
defer m.clearScratch()
|
||||
|
||||
contextField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
hardwareAddress, err := m.scratch(hardware, uint64(len(hardware)))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(m.entry.initialize, contextField, hardwareAddress)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return 0, fmt.Errorf("SAP initialization returned %d", int32(status))
|
||||
}
|
||||
|
||||
contextValue, err := m.readUint64(contextField)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if contextValue == 0 {
|
||||
return 0, errors.New("SAP initialization returned a null context")
|
||||
}
|
||||
|
||||
return contextValue, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Exchange(version uint32, hardwareID []byte, contextValue uint64, input []byte) ([]byte, int32, error) {
|
||||
if uint64(len(input)) > math.MaxUint32 {
|
||||
return nil, 0, errors.New("SAP exchange input is too large")
|
||||
}
|
||||
|
||||
hardware, err := hardwareBlock(hardwareID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
m.beginCall()
|
||||
|
||||
defer m.clearScratch()
|
||||
|
||||
hardwareAddress, err := m.scratch(hardware, uint64(len(hardware)))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
inputAddress, err := m.scratch(input, uint64(len(input)))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
outputField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
lengthField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
resultField, err := m.scratch(nil, 4)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(
|
||||
m.entry.exchange,
|
||||
uint64(version),
|
||||
hardwareAddress,
|
||||
contextValue,
|
||||
inputAddress,
|
||||
uint64(len(input)),
|
||||
outputField,
|
||||
lengthField,
|
||||
resultField,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return nil, 0, fmt.Errorf("SAP exchange returned %d", int32(status))
|
||||
}
|
||||
|
||||
output, err := m.consumeOutput(outputField, lengthField)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
result, err := m.readUint32(resultField)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return output, int32(result), nil
|
||||
}
|
||||
|
||||
func (m *Machine) Sign(contextValue uint64, input []byte) ([]byte, error) {
|
||||
if uint64(len(input)) > math.MaxUint32 {
|
||||
return nil, errors.New("SAP signing input is too large")
|
||||
}
|
||||
|
||||
m.beginCall()
|
||||
|
||||
defer m.clearScratch()
|
||||
|
||||
inputAddress, err := m.scratch(input, uint64(len(input)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lengthField, err := m.scratch(nil, 8)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status, err := m.invoke(
|
||||
m.entry.sign,
|
||||
contextValue,
|
||||
inputAddress,
|
||||
uint64(len(input)),
|
||||
outputField,
|
||||
lengthField,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return nil, fmt.Errorf("SAP signing returned %d", int32(status))
|
||||
}
|
||||
|
||||
output, err := m.consumeOutput(outputField, lengthField)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (m *Machine) Teardown(contextValue uint64) error {
|
||||
status, err := m.invoke(m.entry.teardown, contextValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return fmt.Errorf("SAP teardown returned %d", int32(status))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) dispose(output uint64) error {
|
||||
status, err := m.invoke(m.entry.dispose, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if int32(status) != 0 {
|
||||
return fmt.Errorf("SAP storage disposal returned %d", int32(status))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) invoke(function uint64, arguments ...uint64) (uint64, error) {
|
||||
if m.closed {
|
||||
return 0, errors.New("SAP guest machine is closed")
|
||||
}
|
||||
|
||||
if function == 0 {
|
||||
return 0, errors.New("SAP guest entry point is unavailable")
|
||||
}
|
||||
|
||||
registers := [...]int{
|
||||
unicorn.RegRDI,
|
||||
unicorn.RegRSI,
|
||||
unicorn.RegRDX,
|
||||
unicorn.RegRCX,
|
||||
unicorn.RegR8,
|
||||
unicorn.RegR9,
|
||||
}
|
||||
for index, register := range registers {
|
||||
var value uint64
|
||||
if index < len(arguments) {
|
||||
value = arguments[index]
|
||||
}
|
||||
|
||||
if err := m.engine.RegWrite(register, value); err != nil {
|
||||
return 0, fmt.Errorf("write SAP guest argument register: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
extra := max(len(arguments)-len(registers), 0)
|
||||
|
||||
stackPointer := stackEnd - uint64(extra+1)*8
|
||||
if stackPointer%16 != 8 {
|
||||
stackPointer -= 8
|
||||
}
|
||||
|
||||
if err := m.writeUint64(stackPointer, returnAddress); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
for index := range extra {
|
||||
if err := m.writeUint64(stackPointer+8+uint64(index)*8, arguments[len(registers)+index]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := m.engine.RegWrite(unicorn.RegRSP, stackPointer); err != nil {
|
||||
return 0, fmt.Errorf("write SAP guest stack register: %w", err)
|
||||
}
|
||||
|
||||
m.services.resetFault()
|
||||
|
||||
if err := m.engine.StartBounded(function, returnAddress, 10*time.Second, 100_000_000); err != nil {
|
||||
if m.services.fault != nil {
|
||||
return 0, m.services.fault
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("execute SAP guest function: %w", err)
|
||||
}
|
||||
|
||||
if m.services.fault != nil {
|
||||
return 0, m.services.fault
|
||||
}
|
||||
|
||||
instruction, err := m.engine.RegRead(unicorn.RegRIP)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest instruction register: %w", err)
|
||||
}
|
||||
|
||||
if instruction != returnAddress {
|
||||
return 0, fmt.Errorf("SAP guest stopped unexpectedly at %#x", instruction)
|
||||
}
|
||||
|
||||
result, err := m.engine.RegRead(unicorn.RegRAX)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest result register: %w", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *Machine) beginCall() {
|
||||
m.scratchCursor = 0
|
||||
}
|
||||
|
||||
func (m *Machine) scratch(data []byte, size uint64) (uint64, error) {
|
||||
reserved := align(max(size, 1), 16)
|
||||
if m.scratchCursor > scratchSize || reserved > scratchSize-m.scratchCursor {
|
||||
return 0, errors.New("SAP guest scratch space exhausted")
|
||||
}
|
||||
|
||||
address := scratchBase + m.scratchCursor
|
||||
m.scratchCursor += reserved
|
||||
|
||||
if len(data) != 0 {
|
||||
if uint64(len(data)) > size {
|
||||
return 0, errors.New("scratch data exceeds reservation")
|
||||
}
|
||||
|
||||
if err := m.engine.MemWrite(address, data); err != nil {
|
||||
return 0, fmt.Errorf("write SAP guest scratch data: %w", err)
|
||||
}
|
||||
} else if size != 0 {
|
||||
if err := m.engine.MemWrite(address, make([]byte, size)); err != nil {
|
||||
return 0, fmt.Errorf("clear SAP guest scratch data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (m *Machine) clearScratch() {
|
||||
if m.scratchCursor != 0 && m.engine != nil && !m.closed {
|
||||
_ = m.engine.MemWrite(scratchBase, make([]byte, m.scratchCursor))
|
||||
}
|
||||
|
||||
m.scratchCursor = 0
|
||||
}
|
||||
|
||||
func (m *Machine) consumeOutput(pointerField, lengthField uint64) ([]byte, error) {
|
||||
pointer, err := m.readUint64(pointerField)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
length, err := m.readUint64(lengthField)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var output []byte
|
||||
|
||||
var outputErr error
|
||||
|
||||
switch {
|
||||
case length > maxOutputSize:
|
||||
outputErr = fmt.Errorf("SAP output is %d bytes, maximum is %d", length, maxOutputSize)
|
||||
case length == 0:
|
||||
case pointer == 0:
|
||||
outputErr = errors.New("SAP returned a null output pointer")
|
||||
default:
|
||||
output, outputErr = m.engine.MemRead(pointer, length)
|
||||
}
|
||||
|
||||
var disposeErr error
|
||||
if pointer != 0 {
|
||||
disposeErr = m.dispose(pointer)
|
||||
}
|
||||
|
||||
return output, errors.Join(outputErr, disposeErr)
|
||||
}
|
||||
|
||||
func (m *Machine) readUint32(address uint64) (uint32, error) {
|
||||
data, err := m.engine.MemRead(address, 4)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest uint32: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(data), nil
|
||||
}
|
||||
|
||||
func (m *Machine) readUint64(address uint64) (uint64, error) {
|
||||
data, err := m.engine.MemRead(address, 8)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read SAP guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(data), nil
|
||||
}
|
||||
|
||||
func (m *Machine) writeUint64(address, value uint64) error {
|
||||
var data [8]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(data[:], value)
|
||||
|
||||
if err := m.engine.MemWrite(address, data[:]); err != nil {
|
||||
return fmt.Errorf("write SAP guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) Close() error {
|
||||
if m == nil || m.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.closed = true
|
||||
|
||||
var errs []error
|
||||
|
||||
if m.services != nil {
|
||||
errs = append(errs, m.services.close())
|
||||
}
|
||||
|
||||
if m.engine != nil {
|
||||
errs = append(errs, m.engine.Close())
|
||||
}
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
func hardwareBlock(hardwareID []byte) ([]byte, error) {
|
||||
if len(hardwareID) == 0 || len(hardwareID) > 20 {
|
||||
return nil, errors.New("hardware ID must contain between 1 and 20 bytes")
|
||||
}
|
||||
|
||||
result := make([]byte, 24)
|
||||
binary.LittleEndian.PutUint32(result[0:4], uint32(len(hardwareID)))
|
||||
copy(result[4:], hardwareID)
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func align(value, alignment uint64) uint64 {
|
||||
return (value + alignment - 1) &^ (alignment - 1)
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
func TestOpenHonorsCanceledContext(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if _, err := Open(ctx, assets.Bundle{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Open error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHardwareBlock(t *testing.T) {
|
||||
identifier := []byte{1, 2, 3, 4, 5, 6}
|
||||
|
||||
block, err := hardwareBlock(identifier)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(block) != 24 || binary.LittleEndian.Uint32(block[:4]) != uint32(len(identifier)) {
|
||||
t.Fatalf("unexpected hardware block header: %x", block)
|
||||
}
|
||||
|
||||
if string(block[4:10]) != string(identifier) {
|
||||
t.Fatalf("hardware ID = %x", block[4:10])
|
||||
}
|
||||
|
||||
if _, err := hardwareBlock(make([]byte, 21)); err == nil {
|
||||
t.Fatal("oversized hardware ID was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestServiceDispatchAndStackArguments(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.addFunction("test.stackArguments", func() error {
|
||||
seventh, err := machine.services.argument(6)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
eighth, err := machine.services.argument(7)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return machine.services.setResult(seventh + eighth)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(address, 1, 2, 3, 4, 5, 6, 7, 8)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 15 {
|
||||
t.Fatalf("result = %d, want 15", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownGuestServiceFailsClosed(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.resolve("test.unsupported")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := machine.invoke(address); err == nil || !strings.Contains(err.Error(), "unsupported import") {
|
||||
t.Fatalf("invoke error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestAllocatorReusesAndClearsFreedMemory(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.allocate(64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.engine.MemWrite(address, bytes.Repeat([]byte{0xa5}, 64)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.services.release(address); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reused, err := machine.services.allocate(32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if reused != address {
|
||||
t.Fatalf("reused address = %#x, want %#x", reused, address)
|
||||
}
|
||||
|
||||
data, err := machine.engine.MemRead(reused, 32)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(data, make([]byte, 32)) {
|
||||
t.Fatalf("reused allocation was not cleared: %x", data)
|
||||
}
|
||||
|
||||
if err := machine.services.release(reused); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if machine.services.heapCursor != 0 || len(machine.services.freeBlocks) != 0 {
|
||||
t.Fatalf("released heap was not reclaimed: cursor=%d free=%v", machine.services.heapCursor, machine.services.freeBlocks)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMallocSizeReturnsUsableSize(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
address, err := machine.services.allocate(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols["_malloc_size"], address)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 16 {
|
||||
t.Fatalf("malloc_size = %d, want 16", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrncmpStopsAtMappedPageBoundary(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
left := returnAddress + pageSize - 2
|
||||
right := stackBase + pageSize - 2
|
||||
|
||||
for _, address := range []uint64{left, right} {
|
||||
if err := machine.engine.MemWrite(address, []byte{'a', 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols["_strncmp"], left, right, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
t.Fatalf("strncmp = %d, want 0", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlatformServicesInitializeOutputs(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
buffer := stackBase + pageSize
|
||||
|
||||
if err := machine.engine.MemWrite(buffer, bytes.Repeat([]byte{0xa5}, 16)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols["_CFStringGetCString"], fakeHandle, buffer, 16, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 1 {
|
||||
t.Fatalf("CFStringGetCString = %d, want 1", result)
|
||||
}
|
||||
|
||||
data, err := machine.engine.MemRead(buffer, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if data[0] != 0 {
|
||||
t.Fatalf("CFStringGetCString output = %#x, want NUL", data[0])
|
||||
}
|
||||
|
||||
for _, name := range []string{"_IORegistryEntryGetParentEntry", "_IOServiceGetMatchingServices"} {
|
||||
if err := machine.engine.MemWrite(buffer, bytes.Repeat([]byte{0xa5}, 4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := machine.invoke(machine.services.symbols[name], 0, 0, buffer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != 0 {
|
||||
t.Fatalf("%s = %d, want 0", name, result)
|
||||
}
|
||||
|
||||
data, err := machine.engine.MemRead(buffer, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if binary.LittleEndian.Uint32(data) != math.MaxUint32 {
|
||||
t.Fatalf("%s output = %x, want uint32 max", name, data)
|
||||
}
|
||||
}
|
||||
|
||||
result, err = machine.invoke(machine.services.symbols["_statfs"], 0, buffer)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if result != math.MaxUint64 {
|
||||
t.Fatalf("statfs = %#x, want -1", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumeOutputDisposesAllocation(t *testing.T) {
|
||||
machine := newServiceTestMachine(t)
|
||||
|
||||
output, err := machine.services.allocate(4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.engine.MemWrite(output, []byte("test")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pointerField := scratchBase
|
||||
lengthField := scratchBase + 8
|
||||
|
||||
if err := machine.writeUint64(pointerField, output); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := machine.writeUint64(lengthField, 4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
machine.entry.dispose, err = machine.services.addFunction("test.dispose", machine.services.free)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, err := machine.consumeOutput(pointerField, lengthField)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(data) != "test" {
|
||||
t.Fatalf("output = %q, want test", data)
|
||||
}
|
||||
|
||||
if _, ok := machine.services.allocations[output]; ok {
|
||||
t.Fatal("output allocation was not released")
|
||||
}
|
||||
}
|
||||
|
||||
func newServiceTestMachine(t *testing.T) *Machine {
|
||||
t.Helper()
|
||||
|
||||
engine, err := unicorn.New(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("create Unicorn engine: %v", err)
|
||||
}
|
||||
|
||||
for _, region := range []struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}{
|
||||
{returnAddress, pageSize},
|
||||
{scratchBase, scratchSize},
|
||||
{heapBase, heapSize},
|
||||
{stackBase, stackSize},
|
||||
} {
|
||||
if err := engine.MemMap(region.address, region.size); err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(returnAddress, []byte{0xF4}); err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
services, err := newShims(engine, map[string]uint64{}, nil)
|
||||
if err != nil {
|
||||
_ = engine.Close()
|
||||
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
machine := &Machine{engine: engine, services: services}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := machine.Close(); err != nil {
|
||||
t.Errorf("close machine: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
return machine
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
const maxGuestTransfer = uint64(64 << 20)
|
||||
|
||||
func (s *shims) registerMemoryServices() error {
|
||||
services := []struct {
|
||||
names []string
|
||||
handler shimHandler
|
||||
}{
|
||||
{[]string{"_malloc"}, s.malloc},
|
||||
{[]string{"_malloc_good_size"}, s.mallocGoodSize},
|
||||
{[]string{"_malloc_size"}, s.mallocSize},
|
||||
{[]string{"_calloc"}, s.calloc},
|
||||
{[]string{"_realloc", "_reallocf"}, s.realloc},
|
||||
{[]string{"_free"}, s.free},
|
||||
{[]string{"_memcpy", "_memmove"}, s.memmove},
|
||||
{[]string{"_memset"}, s.memset},
|
||||
{[]string{"___bzero"}, s.bzero},
|
||||
{[]string{"___memcpy_chk"}, s.checkedMemcpy},
|
||||
{[]string{"___memset_chk"}, s.checkedMemset},
|
||||
{[]string{"_memcmp"}, s.memcmp},
|
||||
{[]string{"_strcmp"}, s.strcmp},
|
||||
{[]string{"_strncmp"}, s.strncmp},
|
||||
{[]string{"_strlen"}, s.strlen},
|
||||
}
|
||||
for _, service := range services {
|
||||
if err := s.addAliases(service.names, service.handler); err != nil {
|
||||
return fmt.Errorf("clear allocated guest memory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) malloc() error {
|
||||
size, err := s.argument(0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
address, err := s.allocate(size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
func (s *shims) mallocGoodSize() error {
|
||||
size, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(align(max(size, 1), 16))
|
||||
}
|
||||
|
||||
func (s *shims) mallocSize() error {
|
||||
address, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
allocation, ok := s.allocations[address]
|
||||
if !ok {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
return s.setResult(allocation.reserved)
|
||||
}
|
||||
|
||||
func (s *shims) calloc() error {
|
||||
count, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
size, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if count != 0 && size > math.MaxUint64/count {
|
||||
return errors.New("allocation size overflows")
|
||||
}
|
||||
|
||||
total := count * size
|
||||
|
||||
address, err := s.allocate(total)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if total != 0 {
|
||||
if err := s.engine.MemWrite(address, make([]byte, total)); err != nil {
|
||||
_ = s.release(address)
|
||||
|
||||
return fmt.Errorf("clear allocated guest memory: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
func (s *shims) realloc() error {
|
||||
oldAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
newSize, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if oldAddress == 0 {
|
||||
address, err := s.allocate(newSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
oldAllocation, ok := s.allocations[oldAddress]
|
||||
if !ok {
|
||||
return fmt.Errorf("reallocate unknown pointer %#x", oldAddress)
|
||||
}
|
||||
|
||||
if newSize <= oldAllocation.reserved {
|
||||
oldAllocation.size = newSize
|
||||
s.allocations[oldAddress] = oldAllocation
|
||||
|
||||
return s.setResult(oldAddress)
|
||||
}
|
||||
|
||||
newAddress, err := s.allocate(newSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := s.engine.MemRead(oldAddress, oldAllocation.size)
|
||||
if err != nil {
|
||||
_ = s.release(newAddress)
|
||||
|
||||
return fmt.Errorf("read reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(newAddress, data); err != nil {
|
||||
_ = s.release(newAddress)
|
||||
|
||||
return fmt.Errorf("write reallocated guest memory: %w", err)
|
||||
}
|
||||
|
||||
if err := s.release(oldAddress); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(newAddress)
|
||||
}
|
||||
|
||||
func (s *shims) free() error {
|
||||
address, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if address != 0 {
|
||||
if err := s.release(address); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) allocate(size uint64) (uint64, error) {
|
||||
if size > maxGuestTransfer {
|
||||
return 0, fmt.Errorf("allocation size %d exceeds limit", size)
|
||||
}
|
||||
|
||||
reserved := align(max(size, 1), 16)
|
||||
for index, block := range s.freeBlocks {
|
||||
if block.size < reserved {
|
||||
continue
|
||||
}
|
||||
|
||||
address := block.address
|
||||
|
||||
if block.size == reserved {
|
||||
s.freeBlocks = append(s.freeBlocks[:index], s.freeBlocks[index+1:]...)
|
||||
} else {
|
||||
s.freeBlocks[index].address += reserved
|
||||
s.freeBlocks[index].size -= reserved
|
||||
}
|
||||
|
||||
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
if s.heapCursor > heapSize || reserved > heapSize-s.heapCursor {
|
||||
return 0, errors.New("guest heap exhausted")
|
||||
}
|
||||
|
||||
address := heapBase + s.heapCursor
|
||||
s.heapCursor += reserved
|
||||
s.allocations[address] = guestAllocation{size: size, reserved: reserved}
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (s *shims) release(address uint64) error {
|
||||
allocation, ok := s.allocations[address]
|
||||
if !ok {
|
||||
return fmt.Errorf("free unknown pointer %#x", address)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(address, make([]byte, allocation.reserved)); err != nil {
|
||||
return fmt.Errorf("clear released guest memory: %w", err)
|
||||
}
|
||||
|
||||
delete(s.allocations, address)
|
||||
s.freeBlocks = append(s.freeBlocks, freeBlock{address: address, size: allocation.reserved})
|
||||
s.coalesceFreeBlocks()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) coalesceFreeBlocks() {
|
||||
sort.Slice(s.freeBlocks, func(left, right int) bool {
|
||||
return s.freeBlocks[left].address < s.freeBlocks[right].address
|
||||
})
|
||||
|
||||
merged := s.freeBlocks[:0]
|
||||
for _, block := range s.freeBlocks {
|
||||
last := len(merged) - 1
|
||||
if last >= 0 && merged[last].address+merged[last].size == block.address {
|
||||
merged[last].size += block.size
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
merged = append(merged, block)
|
||||
}
|
||||
|
||||
s.freeBlocks = merged
|
||||
for len(s.freeBlocks) != 0 {
|
||||
last := len(s.freeBlocks) - 1
|
||||
|
||||
block := s.freeBlocks[last]
|
||||
if block.address+block.size != heapBase+s.heapCursor {
|
||||
break
|
||||
}
|
||||
|
||||
s.heapCursor -= block.size
|
||||
s.freeBlocks = s.freeBlocks[:last]
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) memmove() error {
|
||||
destination, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
source, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := checkedSize(length); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := s.engine.MemRead(source, length)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read memmove source: %w", err)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(destination, data); err != nil {
|
||||
return fmt.Errorf("write memmove destination: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(destination)
|
||||
}
|
||||
|
||||
func (s *shims) memset() error {
|
||||
destination, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
size, err := checkedSize(length)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(destination, bytes.Repeat([]byte{byte(value)}, size)); err != nil {
|
||||
return fmt.Errorf("write guest memory fill: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(destination)
|
||||
}
|
||||
|
||||
func (s *shims) bzero() error {
|
||||
destination, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
size, err := checkedSize(length)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(destination, make([]byte, size)); err != nil {
|
||||
return fmt.Errorf("clear guest memory: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(destination)
|
||||
}
|
||||
|
||||
func (s *shims) checkedMemcpy() error {
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity, err := s.argument(3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if length > capacity {
|
||||
return errors.New("checked copy exceeds destination")
|
||||
}
|
||||
|
||||
return s.memmove()
|
||||
}
|
||||
|
||||
func (s *shims) checkedMemset() error {
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity, err := s.argument(3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if length > capacity {
|
||||
return errors.New("checked fill exceeds destination")
|
||||
}
|
||||
|
||||
return s.memset()
|
||||
}
|
||||
|
||||
func (s *shims) memcmp() error {
|
||||
left, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
right, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := checkedSize(length); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
a, err := s.engine.MemRead(left, length)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read left memory operand: %w", err)
|
||||
}
|
||||
|
||||
b, err := s.engine.MemRead(right, length)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read right memory operand: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(uint64(int64(bytes.Compare(a, b))))
|
||||
}
|
||||
|
||||
func (s *shims) strcmp() error {
|
||||
left, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
right, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
a, err := s.readCString(left)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b, err := s.readCString(right)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(uint64(int64(bytes.Compare([]byte(a), []byte(b)))))
|
||||
}
|
||||
|
||||
func (s *shims) strncmp() error {
|
||||
left, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
right, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
length, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := checkedSize(length); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for offset := uint64(0); offset < length; {
|
||||
if left > math.MaxUint64-offset || right > math.MaxUint64-offset {
|
||||
return errors.New("string comparison address overflows")
|
||||
}
|
||||
|
||||
leftAddress := left + offset
|
||||
rightAddress := right + offset
|
||||
chunk := min(
|
||||
length-offset,
|
||||
pageSize-leftAddress%pageSize,
|
||||
pageSize-rightAddress%pageSize,
|
||||
)
|
||||
|
||||
a, err := s.engine.MemRead(leftAddress, chunk)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read left memory page: %w", err)
|
||||
}
|
||||
|
||||
b, err := s.engine.MemRead(rightAddress, chunk)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read right memory page: %w", err)
|
||||
}
|
||||
|
||||
for index := range a {
|
||||
if a[index] != b[index] {
|
||||
return s.setResult(uint64(int64(int(a[index]) - int(b[index]))))
|
||||
}
|
||||
|
||||
if a[index] == 0 {
|
||||
return s.setResult(0)
|
||||
}
|
||||
}
|
||||
|
||||
offset += chunk
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) strlen() error {
|
||||
address, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.readCString(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(uint64(len(value)))
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const (
|
||||
fakeHandle = uint64(math.MaxUint64)
|
||||
coreFPFile = uint64(3)
|
||||
coreFPPath = "/System/Library/PrivateFrameworks/CoreFP.framework/CoreFP"
|
||||
icxsPath = "./../CoreFP.icxs"
|
||||
keySerial = "IOPlatformSerialNumber"
|
||||
keyUUID = "IOPlatformUUID"
|
||||
keyBoard = "board-id"
|
||||
keyedMessage = "objectForKey:"
|
||||
)
|
||||
|
||||
func (s *shims) registerPlatformServices() error {
|
||||
services := []struct {
|
||||
names []string
|
||||
handler shimHandler
|
||||
}{
|
||||
{[]string{"_CFBundleGetMainBundle", "_CFDataGetBytePtr", "_CFDataGetLength", "_CFStringGetLength", "_CFStringGetMaximumSizeForEncoding", "_CFUUIDCreateString", "_IORegistryEntryFromPath", "_IORegistryEntrySearchCFProperty", "_IOServiceMatching", "_getenv", "_pthread_self"}, s.returnZero},
|
||||
{[]string{"_CFDictionaryGetValue", "_DADiskCopyDescription", "_DADiskCreateFromBSDName", "_DASessionCreate", "_IORegistryEntryCreateCFProperty"}, s.returnFakeHandle},
|
||||
{[]string{"_CFRelease", "_IOObjectRelease", "_close", "_close$UNIX2003", "_pthread_mutex_lock", "_pthread_mutex_unlock", "_pthread_rwlock_init", "_pthread_rwlock_init$UNIX2003", "_pthread_rwlock_unlock", "_pthread_rwlock_unlock$UNIX2003", "_pthread_rwlock_wrlock", "_pthread_rwlock_wrlock$UNIX2003"}, s.returnZero},
|
||||
{[]string{"_CFStringCreateWithCString"}, s.cfStringCreate},
|
||||
{[]string{"_CFStringCreateWithCStringNoCopy"}, s.returnZero},
|
||||
{[]string{"_CFStringGetCString"}, s.cfStringGetCString},
|
||||
{[]string{"_IOIteratorNext"}, s.ioIteratorNext},
|
||||
{[]string{"_IORegistryEntryGetParentEntry"}, s.ioRegistryEntryGetParentEntry},
|
||||
{[]string{"_IOServiceGetMatchingServices"}, s.ioServiceGetMatchingServices},
|
||||
{[]string{"_IOServiceGetMatchingService"}, s.returnUint32Max},
|
||||
{[]string{"_OSAtomicCompareAndSwap32Barrier"}, s.compareAndSwap32},
|
||||
{[]string{"___error"}, s.errorPointer},
|
||||
{[]string{"_abort", "___stack_chk_fail", "dyld_stub_binder"}, s.abort},
|
||||
{[]string{"_arc4random"}, s.arc4random},
|
||||
{[]string{"_dlopen"}, s.dlopen},
|
||||
{[]string{"_dlsym"}, s.dlsym},
|
||||
{[]string{"_fcntl", "_fcntl$UNIX2003", "_lstat$INODE64", "_statfs", "_statfs$INODE64"}, s.returnMinusOne},
|
||||
{[]string{"_gettimeofday"}, s.gettimeofday},
|
||||
{[]string{"_objc_msgSend"}, s.objcMsgSend},
|
||||
{[]string{"_open", "_open$UNIX2003"}, s.open},
|
||||
{[]string{"_pthread_once"}, s.pthreadOnce},
|
||||
{[]string{"_read", "_read$UNIX2003"}, s.read},
|
||||
{[]string{"_sysctl"}, s.returnMinusOne},
|
||||
{[]string{"_sysctlbyname"}, s.sysctlbyname},
|
||||
}
|
||||
for _, service := range services {
|
||||
if err := s.addAliases(service.names, service.handler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
s.errno, err = s.addData("guest.errno", make([]byte, 8))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := s.addData("___stack_chk_guard", []byte{0xA5, 0x71, 0x3C, 0xD9, 0x86, 0x42, 0xEF, 0x10}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, name := range []string{
|
||||
"_kCFAllocatorDefault",
|
||||
"_kCFAllocatorNull",
|
||||
"_kDADiskDescriptionVolumeUUIDKey",
|
||||
"_kIOMasterPortDefault",
|
||||
} {
|
||||
if _, err := s.addData(name, make([]byte, 8)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) returnZero() error {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) returnFakeHandle() error {
|
||||
return s.setResult(fakeHandle)
|
||||
}
|
||||
|
||||
func (s *shims) returnUint32Max() error {
|
||||
return s.setResult(math.MaxUint32)
|
||||
}
|
||||
|
||||
func (s *shims) returnMinusOne() error {
|
||||
return s.setResult(math.MaxUint64)
|
||||
}
|
||||
|
||||
func (s *shims) cfStringCreate() error {
|
||||
address, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.readCString(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch value {
|
||||
case keySerial, keyUUID, keyBoard:
|
||||
return s.setResult(fakeHandle)
|
||||
default:
|
||||
return s.setResult(0)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) cfStringGetCString() error {
|
||||
buffer, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
capacity, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if buffer == 0 || capacity == 0 {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
if err := s.engine.MemWrite(buffer, []byte{0}); err != nil {
|
||||
return fmt.Errorf("terminate guest string buffer: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(1)
|
||||
}
|
||||
|
||||
func (s *shims) ioIteratorNext() error {
|
||||
s.iterator++
|
||||
|
||||
return s.setResult(uint64(s.iterator % 2))
|
||||
}
|
||||
|
||||
func (s *shims) ioRegistryEntryGetParentEntry() error {
|
||||
parent, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if parent == 0 {
|
||||
return errors.New("parent registry entry output is null")
|
||||
}
|
||||
|
||||
if err := s.writeUint32(parent, math.MaxUint32); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) ioServiceGetMatchingServices() error {
|
||||
iterator, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if iterator == 0 {
|
||||
return errors.New("matching services iterator output is null")
|
||||
}
|
||||
|
||||
s.iterator = 0
|
||||
if err := s.writeUint32(iterator, math.MaxUint32); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) compareAndSwap32() error {
|
||||
oldValue, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
newValue, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
current, err := s.readUint32(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if current != uint32(oldValue) {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
if err := s.writeUint32(address, uint32(newValue)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return s.setResult(1)
|
||||
}
|
||||
|
||||
func (s *shims) errorPointer() error {
|
||||
return s.setResult(s.errno)
|
||||
}
|
||||
|
||||
func (s *shims) abort() error {
|
||||
return errors.New("guest aborted")
|
||||
}
|
||||
|
||||
func (s *shims) arc4random() error {
|
||||
var value [4]byte
|
||||
if _, err := rand.Read(value[:]); err != nil {
|
||||
return fmt.Errorf("generate guest random value: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(uint64(binary.LittleEndian.Uint32(value[:])))
|
||||
}
|
||||
|
||||
func (s *shims) dlopen() error {
|
||||
pathAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path, err := s.readCString(pathAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if path == coreFPPath {
|
||||
return s.setResult(fakeHandle)
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) dlsym() error {
|
||||
nameAddress, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
name, err := s.readCString(nameAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
address := s.coreExports["_"+name]
|
||||
|
||||
return s.setResult(address)
|
||||
}
|
||||
|
||||
func (s *shims) gettimeofday() error {
|
||||
timeAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
zoneAddress, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
if timeAddress != 0 {
|
||||
var value [16]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(value[0:8], uint64(now.Unix()))
|
||||
binary.LittleEndian.PutUint32(value[8:12], uint32(now.Nanosecond()/1000))
|
||||
|
||||
if err := s.engine.MemWrite(timeAddress, value[:]); err != nil {
|
||||
return fmt.Errorf("write guest time value: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if zoneAddress != 0 {
|
||||
if err := s.engine.MemWrite(zoneAddress, make([]byte, 8)); err != nil {
|
||||
return fmt.Errorf("clear guest time zone: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) objcMsgSend() error {
|
||||
selectorAddress, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
selector, err := s.readCString(selectorAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if selector == keyedMessage {
|
||||
return s.setResult(fakeHandle)
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) open() error {
|
||||
pathAddress, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path, err := s.readCString(pathAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if path == icxsPath {
|
||||
s.icxsOffset = 0
|
||||
|
||||
return s.setResult(coreFPFile)
|
||||
}
|
||||
|
||||
return s.returnMinusOne()
|
||||
}
|
||||
|
||||
func (s *shims) pthreadOnce() error {
|
||||
control, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
initializer, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
value, err := s.readUint64(control)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if value == 0 {
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
if err := s.writeUint64(control, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stack, err := s.engine.RegRead(unicorn.RegRSP)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read guest stack register: %w", err)
|
||||
}
|
||||
|
||||
stack -= 8
|
||||
if err := s.writeUint64(stack, initializer); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.engine.RegWrite(unicorn.RegRSP, stack); err != nil {
|
||||
return fmt.Errorf("write guest stack register: %w", err)
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
|
||||
func (s *shims) read() error {
|
||||
descriptor, err := s.argument(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
buffer, err := s.argument(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
requested, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if descriptor != coreFPFile {
|
||||
return s.returnMinusOne()
|
||||
}
|
||||
|
||||
size, err := checkedSize(requested)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
remaining := len(s.icxs) - s.icxsOffset
|
||||
if size > remaining {
|
||||
size = remaining
|
||||
}
|
||||
|
||||
if size != 0 {
|
||||
if err := s.engine.MemWrite(buffer, s.icxs[s.icxsOffset:s.icxsOffset+size]); err != nil {
|
||||
return fmt.Errorf("write guest ICXS data: %w", err)
|
||||
}
|
||||
|
||||
s.icxsOffset += size
|
||||
}
|
||||
|
||||
return s.setResult(uint64(size))
|
||||
}
|
||||
|
||||
func (s *shims) sysctlbyname() error {
|
||||
lengthAddress, err := s.argument(2)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if lengthAddress != 0 {
|
||||
if err := s.writeUint64(lengthAddress, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return s.setResult(0)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package machine
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/unicorn"
|
||||
)
|
||||
|
||||
const (
|
||||
shimBase = uint64(0x0000200000000000)
|
||||
shimCodeSize = uint64(0x0000000000080000)
|
||||
shimSize = uint64(0x0000000000100000)
|
||||
shimSlotSize = uint64(16)
|
||||
)
|
||||
|
||||
type shimHandler func() error
|
||||
|
||||
type shimEntry struct {
|
||||
name string
|
||||
handler shimHandler
|
||||
}
|
||||
|
||||
type guestAllocation struct {
|
||||
size uint64
|
||||
reserved uint64
|
||||
}
|
||||
|
||||
type freeBlock struct {
|
||||
address uint64
|
||||
size uint64
|
||||
}
|
||||
|
||||
type shims struct {
|
||||
engine *unicorn.Engine
|
||||
hook *unicorn.Hook
|
||||
entries map[uint64]shimEntry
|
||||
symbols map[string]uint64
|
||||
codeCursor uint64
|
||||
dataCursor uint64
|
||||
fault error
|
||||
coreExports map[string]uint64
|
||||
icxs []byte
|
||||
icxsOffset int
|
||||
errno uint64
|
||||
heapCursor uint64
|
||||
allocations map[uint64]guestAllocation
|
||||
freeBlocks []freeBlock
|
||||
iterator uint32
|
||||
}
|
||||
|
||||
func newShims(engine *unicorn.Engine, coreExports map[string]uint64, icxs []byte) (*shims, error) {
|
||||
if err := engine.MemMap(shimBase, shimSize); err != nil {
|
||||
return nil, fmt.Errorf("map guest service area: %w", err)
|
||||
}
|
||||
|
||||
s := &shims{
|
||||
engine: engine,
|
||||
entries: make(map[uint64]shimEntry),
|
||||
symbols: make(map[string]uint64),
|
||||
codeCursor: shimBase,
|
||||
dataCursor: shimBase + shimCodeSize,
|
||||
coreExports: coreExports,
|
||||
icxs: icxs,
|
||||
allocations: make(map[uint64]guestAllocation),
|
||||
}
|
||||
if err := s.registerMemoryServices(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.registerPlatformServices(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var err error
|
||||
|
||||
s.hook, err = engine.AddCodeHook(shimBase, shimBase+shimCodeSize-1, s.dispatch)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("register guest service dispatcher: %w", err)
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *shims) close() error {
|
||||
if s.hook == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := s.hook.Close()
|
||||
s.hook = nil
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("close guest service hook: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) resolve(name string) (uint64, error) {
|
||||
if address, ok := s.symbols[name]; ok {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
return s.addFunction(name, func() error {
|
||||
return fmt.Errorf("guest called unsupported import %s", name)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *shims) addAliases(names []string, handler shimHandler) error {
|
||||
for _, name := range names {
|
||||
if _, err := s.addFunction(name, handler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) addFunction(name string, handler shimHandler) (uint64, error) {
|
||||
if address, exists := s.symbols[name]; exists {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
if s.codeCursor+shimSlotSize > shimBase+shimCodeSize {
|
||||
return 0, errors.New("guest service code area is full")
|
||||
}
|
||||
|
||||
address := s.codeCursor
|
||||
s.codeCursor += shimSlotSize
|
||||
|
||||
if err := s.engine.MemWrite(address, []byte{0xC3}); err != nil {
|
||||
return 0, fmt.Errorf("write guest service stub: %w", err)
|
||||
}
|
||||
|
||||
s.entries[address] = shimEntry{name: name, handler: handler}
|
||||
s.symbols[name] = address
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (s *shims) addData(name string, data []byte) (uint64, error) {
|
||||
if address, exists := s.symbols[name]; exists {
|
||||
return address, nil
|
||||
}
|
||||
|
||||
s.dataCursor = align(s.dataCursor, 8)
|
||||
if s.dataCursor+uint64(len(data)) > shimBase+shimSize {
|
||||
return 0, errors.New("guest service data area is full")
|
||||
}
|
||||
|
||||
address := s.dataCursor
|
||||
s.dataCursor += uint64(max(len(data), 8))
|
||||
|
||||
if err := s.engine.MemWrite(address, data); err != nil {
|
||||
return 0, fmt.Errorf("write guest service data: %w", err)
|
||||
}
|
||||
|
||||
s.symbols[name] = address
|
||||
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func (s *shims) dispatch(address uint64, _ uint32) {
|
||||
entry, ok := s.entries[address]
|
||||
if !ok {
|
||||
s.fail(fmt.Errorf("guest entered unknown service address %#x", address))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if err := entry.handler(); err != nil {
|
||||
s.fail(fmt.Errorf("%s: %w", entry.name, err))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) fail(err error) {
|
||||
if s.fault == nil {
|
||||
s.fault = err
|
||||
}
|
||||
|
||||
if stopErr := s.engine.Stop(); stopErr != nil && s.fault == nil {
|
||||
s.fault = stopErr
|
||||
}
|
||||
}
|
||||
|
||||
func (s *shims) resetFault() {
|
||||
s.fault = nil
|
||||
}
|
||||
|
||||
func (s *shims) argument(index int) (uint64, error) {
|
||||
registers := [...]int{
|
||||
unicorn.RegRDI,
|
||||
unicorn.RegRSI,
|
||||
unicorn.RegRDX,
|
||||
unicorn.RegRCX,
|
||||
unicorn.RegR8,
|
||||
unicorn.RegR9,
|
||||
}
|
||||
if index >= 0 && index < len(registers) {
|
||||
value, err := s.engine.RegRead(registers[index])
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest argument register: %w", err)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
if index < 0 {
|
||||
return 0, errors.New("negative guest argument index")
|
||||
}
|
||||
|
||||
stack, err := s.engine.RegRead(unicorn.RegRSP)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest stack register: %w", err)
|
||||
}
|
||||
|
||||
data, err := s.engine.MemRead(stack+8+uint64(index-len(registers))*8, 8)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest stack argument: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(data), nil
|
||||
}
|
||||
|
||||
func (s *shims) setResult(value uint64) error {
|
||||
if err := s.engine.RegWrite(unicorn.RegRAX, value); err != nil {
|
||||
return fmt.Errorf("write guest result register: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) readUint32(address uint64) (uint32, error) {
|
||||
data, err := s.engine.MemRead(address, 4)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest uint32: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint32(data), nil
|
||||
}
|
||||
|
||||
func (s *shims) writeUint32(address uint64, value uint32) error {
|
||||
var data [4]byte
|
||||
|
||||
binary.LittleEndian.PutUint32(data[:], value)
|
||||
|
||||
if err := s.engine.MemWrite(address, data[:]); err != nil {
|
||||
return fmt.Errorf("write guest uint32: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) readUint64(address uint64) (uint64, error) {
|
||||
data, err := s.engine.MemRead(address, 8)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return binary.LittleEndian.Uint64(data), nil
|
||||
}
|
||||
|
||||
func (s *shims) writeUint64(address, value uint64) error {
|
||||
var data [8]byte
|
||||
|
||||
binary.LittleEndian.PutUint64(data[:], value)
|
||||
|
||||
if err := s.engine.MemWrite(address, data[:]); err != nil {
|
||||
return fmt.Errorf("write guest uint64: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *shims) readCString(address uint64) (string, error) {
|
||||
const maximum = 4096
|
||||
|
||||
value := make([]byte, 0, 64)
|
||||
for len(value) < maximum {
|
||||
item, err := s.engine.MemRead(address+uint64(len(value)), 1)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read guest string: %w", err)
|
||||
}
|
||||
|
||||
if item[0] == 0 {
|
||||
return string(value), nil
|
||||
}
|
||||
|
||||
value = append(value, item[0])
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("guest string exceeds %d bytes", maximum)
|
||||
}
|
||||
|
||||
func checkedSize(value uint64) (int, error) {
|
||||
if value > uint64(math.MaxInt) || value > maxGuestTransfer {
|
||||
return 0, fmt.Errorf("guest transfer size %d exceeds limit", value)
|
||||
}
|
||||
|
||||
return int(value), nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"howett.net/plist"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
const (
|
||||
setupCertificateKey = "sign-sap-setup-cert"
|
||||
setupBufferKey = "sign-sap-setup-buffer"
|
||||
maxSetupBody = int64(1 << 20)
|
||||
)
|
||||
|
||||
type setupProtocol struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func (p setupProtocol) certificate(ctx context.Context, endpoint string) ([]byte, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP certificate request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
|
||||
body, err := p.send(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("fetch SAP certificate: %w", err)
|
||||
}
|
||||
|
||||
return plistBytes(body, setupCertificateKey)
|
||||
}
|
||||
|
||||
func (p setupProtocol) exchange(ctx context.Context, endpoint string, input []byte) ([]byte, error) {
|
||||
envelope, err := plist.Marshal(map[string]any{setupBufferKey: input}, plist.XMLFormat)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode SAP setup message: %w", err)
|
||||
}
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(envelope))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP setup request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("Content-Type", "application/x-plist")
|
||||
request.Header.Set("User-Agent", apphttp.DefaultUserAgent)
|
||||
|
||||
body, err := p.send(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("exchange SAP setup message: %w", err)
|
||||
}
|
||||
|
||||
return plistBytes(body, setupBufferKey)
|
||||
}
|
||||
|
||||
func (p setupProtocol) send(request *http.Request) ([]byte, error) {
|
||||
response, err := p.client.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("send SAP request: %w", err)
|
||||
}
|
||||
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxSetupBody))
|
||||
|
||||
return nil, fmt.Errorf("apple returned %s", response.Status)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxSetupBody+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read SAP response: %w", err)
|
||||
}
|
||||
|
||||
if int64(len(body)) > maxSetupBody {
|
||||
return nil, fmt.Errorf("apple response exceeds %d bytes", maxSetupBody)
|
||||
}
|
||||
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func plistBytes(document []byte, key string) ([]byte, error) {
|
||||
var values map[string]any
|
||||
if _, err := plist.Unmarshal(document, &values); err != nil {
|
||||
return nil, fmt.Errorf("decode Apple plist: %w", err)
|
||||
}
|
||||
|
||||
value, ok := values[key].([]byte)
|
||||
if !ok || len(value) == 0 {
|
||||
return nil, errors.New("Apple plist is missing " + key)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
return function(request)
|
||||
}
|
||||
|
||||
func TestSetupProtocol(t *testing.T) {
|
||||
protocol := setupProtocol{client: &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
if request.Header.Get("User-Agent") == "" {
|
||||
t.Error("User-Agent is empty")
|
||||
}
|
||||
key := setupCertificateKey
|
||||
value := []byte("certificate")
|
||||
if request.Method == http.MethodPost {
|
||||
if request.Header.Get("Content-Type") != "application/x-plist" {
|
||||
t.Errorf("Content-Type = %q", request.Header.Get("Content-Type"))
|
||||
}
|
||||
requestBody, err := io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := plistBytes(requestBody, setupBufferKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(decoded, []byte("request")) {
|
||||
t.Errorf("request data = %q", decoded)
|
||||
}
|
||||
key = setupBufferKey
|
||||
value = []byte("reply")
|
||||
}
|
||||
body, err := plist.Marshal(map[string]any{key: value}, plist.XMLFormat)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}}
|
||||
|
||||
certificate, err := protocol.certificate(context.Background(), "https://example.com/certificate")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(certificate) != "certificate" {
|
||||
t.Fatalf("certificate = %q", certificate)
|
||||
}
|
||||
|
||||
reply, err := protocol.exchange(context.Background(), "https://example.com/setup", []byte("request"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if string(reply) != "reply" {
|
||||
t.Fatalf("reply = %q", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupProtocolRejectsOversizedResponse(t *testing.T) {
|
||||
protocol := setupProtocol{client: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Status: "200 OK",
|
||||
Body: io.NopCloser(strings.NewReader(strings.Repeat("x", int(maxSetupBody)+1))),
|
||||
Header: make(http.Header),
|
||||
}, nil
|
||||
})}}
|
||||
if _, err := protocol.certificate(context.Background(), "https://example.com/certificate"); err == nil {
|
||||
t.Fatal("oversized response was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const supportedVersion = uint32(200)
|
||||
|
||||
var errSignerClosed = errors.New("SAP signer is closed")
|
||||
|
||||
type Config struct {
|
||||
SetupURL string
|
||||
CertificateURL string
|
||||
Version uint32
|
||||
HardwareID []byte
|
||||
}
|
||||
|
||||
type ActionSigner interface {
|
||||
Sign(input []byte) ([]byte, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
if config.Version != supportedVersion {
|
||||
return fmt.Errorf("unsupported SAP version %d", config.Version)
|
||||
}
|
||||
|
||||
if len(config.HardwareID) == 0 || len(config.HardwareID) > 20 {
|
||||
return errors.New("SAP hardware ID must contain between 1 and 20 bytes")
|
||||
}
|
||||
|
||||
if err := validateEndpoint("setup", config.SetupURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validateEndpoint("certificate", config.CertificateURL); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateEndpoint(label, value string) error {
|
||||
endpoint, err := url.Parse(value)
|
||||
if err != nil || endpoint.Scheme != "https" || endpoint.Host == "" || endpoint.User != nil {
|
||||
return fmt.Errorf("SAP %s URL must be an absolute HTTPS URL", label)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSignerIntegration(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
signer, err := NewSigner(ctx, Config{
|
||||
SetupURL: "https://fpinit.itunes.apple.com/v1/signSapSetup/legacy",
|
||||
CertificateURL: "https://s.mzstatic.com/sap/setupCert.plist",
|
||||
Version: 200,
|
||||
HardwareID: []byte{0x02, 0, 0, 0, 0, 1},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := signer.Close(); err != nil {
|
||||
t.Errorf("close signer: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
signature, err := signer.Sign([]byte("ipatool SAP smoke test"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(signature) == 0 {
|
||||
t.Fatal("signature is empty")
|
||||
}
|
||||
|
||||
second, err := signer.Sign([]byte("ipatool second SAP smoke test"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(second) == 0 || bytes.Equal(signature, second) {
|
||||
t.Fatal("second signature is empty or unexpectedly reused")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap/assets"
|
||||
"github.com/majd/ipatool/v2/internal/sap/machine"
|
||||
)
|
||||
|
||||
type Signer struct {
|
||||
mu sync.Mutex
|
||||
machine *machine.Machine
|
||||
context uint64
|
||||
hardware []byte
|
||||
closed bool
|
||||
}
|
||||
|
||||
func NewSigner(ctx context.Context, config Config) (ActionSigner, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("SAP signer context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("create SAP signer: %w", err)
|
||||
}
|
||||
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bundle, err := assets.Load(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Apple SAP assets: %w", err)
|
||||
}
|
||||
|
||||
guest, err := machine.Open(ctx, bundle)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("start Apple SAP runtime: %w", err)
|
||||
}
|
||||
|
||||
signer := &Signer{
|
||||
machine: guest,
|
||||
hardware: append([]byte(nil), config.HardwareID...),
|
||||
}
|
||||
complete := false
|
||||
|
||||
defer func() {
|
||||
if !complete {
|
||||
_ = signer.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
signer.context, err = guest.Initialize(signer.hardware)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initialize Apple SAP session: %w", err)
|
||||
}
|
||||
|
||||
protocol := setupProtocol{client: &http.Client{Timeout: 30 * time.Second}}
|
||||
|
||||
certificate, err := protocol.certificate(ctx, config.CertificateURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
request, state, err := guest.Exchange(config.Version, signer.hardware, signer.context, certificate)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP setup message: %w", err)
|
||||
}
|
||||
|
||||
if state != 1 {
|
||||
return nil, fmt.Errorf("SAP setup entered unexpected state %d", state)
|
||||
}
|
||||
|
||||
if len(request) == 0 {
|
||||
return nil, errors.New("SAP setup message is empty")
|
||||
}
|
||||
|
||||
reply, err := protocol.exchange(ctx, config.SetupURL, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, state, err = guest.Exchange(config.Version, signer.hardware, signer.context, reply)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("complete SAP setup: %w", err)
|
||||
}
|
||||
|
||||
if state != 0 {
|
||||
return nil, fmt.Errorf("SAP setup completed in unexpected state %d", state)
|
||||
}
|
||||
|
||||
complete = true
|
||||
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
func (s *Signer) Sign(input []byte) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return nil, errSignerClosed
|
||||
}
|
||||
|
||||
signature, err := s.machine.Sign(s.context, input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sign Apple request: %w", err)
|
||||
}
|
||||
|
||||
if len(signature) == 0 {
|
||||
return nil, errors.New("sign Apple request: signature is empty")
|
||||
}
|
||||
|
||||
return signature, nil
|
||||
}
|
||||
|
||||
func (s *Signer) Close() error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.closed {
|
||||
return nil
|
||||
}
|
||||
|
||||
s.closed = true
|
||||
|
||||
var closeErrors []error
|
||||
if s.machine != nil && s.context != 0 {
|
||||
closeErrors = append(closeErrors, s.machine.Teardown(s.context))
|
||||
s.context = 0
|
||||
}
|
||||
|
||||
if s.machine != nil {
|
||||
closeErrors = append(closeErrors, s.machine.Close())
|
||||
s.machine = nil
|
||||
}
|
||||
|
||||
for index := range s.hardware {
|
||||
s.hardware[index] = 0
|
||||
}
|
||||
|
||||
return errors.Join(closeErrors...)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClosedSigner(t *testing.T) {
|
||||
signer := &Signer{closed: true}
|
||||
if _, err := signer.Sign([]byte("message")); !errors.Is(err, errSignerClosed) {
|
||||
t.Fatalf("Sign error = %v, want %v", err, errSignerClosed)
|
||||
}
|
||||
|
||||
if err := signer.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package sap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewSignerRejectsInvalidContext(t *testing.T) {
|
||||
config := Config{
|
||||
SetupURL: "https://example.apple.com/setup",
|
||||
CertificateURL: "https://example.apple.com/certificate",
|
||||
Version: 200,
|
||||
HardwareID: []byte{1, 2, 3, 4, 5, 6},
|
||||
}
|
||||
//nolint:staticcheck // This test verifies that a nil context is rejected.
|
||||
if _, err := NewSigner(nil, config); err == nil {
|
||||
t.Fatal("NewSigner accepted a nil context")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
if _, err := NewSigner(ctx, config); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("NewSigner error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig(t *testing.T) {
|
||||
valid := Config{
|
||||
SetupURL: "https://example.apple.com/setup",
|
||||
CertificateURL: "https://example.apple.com/certificate",
|
||||
Version: 200,
|
||||
HardwareID: []byte{1, 2, 3, 4, 5, 6},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Config)
|
||||
}{
|
||||
{"version", func(config *Config) { config.Version = 210 }},
|
||||
{"empty hardware ID", func(config *Config) { config.HardwareID = nil }},
|
||||
{"long hardware ID", func(config *Config) { config.HardwareID = make([]byte, 21) }},
|
||||
{"relative setup URL", func(config *Config) { config.SetupURL = "/setup" }},
|
||||
{"HTTP certificate URL", func(config *Config) { config.CertificateURL = "http://example.apple.com/cert" }},
|
||||
{"credentialed URL", func(config *Config) { config.SetupURL = "https://user@example.apple.com/setup" }},
|
||||
}
|
||||
|
||||
if err := validateConfig(valid); err != nil {
|
||||
t.Fatalf("valid config: %v", err)
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
config := valid
|
||||
test.mutate(&config)
|
||||
|
||||
if err := validateConfig(config); err == nil {
|
||||
t.Fatal("validateConfig accepted invalid config")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package unicorn
|
||||
|
||||
import "io"
|
||||
|
||||
type archiveFormat uint8
|
||||
|
||||
const (
|
||||
archiveZIP archiveFormat = iota
|
||||
archiveSevenZip
|
||||
archiveTarZstd
|
||||
)
|
||||
|
||||
type archiveEntry struct {
|
||||
reader io.Reader
|
||||
size uint64
|
||||
close func() error
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//go:build windows
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/bodgit/sevenzip"
|
||||
)
|
||||
|
||||
func openArchiveEntry(path, name string, format archiveFormat) (archiveEntry, error) {
|
||||
switch format {
|
||||
case archiveZIP:
|
||||
return openZIPEntry(path, name)
|
||||
case archiveSevenZip:
|
||||
return openSevenZipEntry(path, name)
|
||||
case archiveTarZstd:
|
||||
return openTarZstdEntry(path, name)
|
||||
default:
|
||||
return archiveEntry{}, fmt.Errorf("unsupported Unicorn archive format %d", format)
|
||||
}
|
||||
}
|
||||
|
||||
func openSevenZipEntry(path, name string) (archiveEntry, error) {
|
||||
archive, err := sevenzip.OpenReader(path)
|
||||
if err != nil {
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
for _, candidate := range archive.File {
|
||||
if candidate.Name != name {
|
||||
continue
|
||||
}
|
||||
if candidate.FileInfo().IsDir() {
|
||||
_ = archive.Close()
|
||||
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
|
||||
}
|
||||
|
||||
reader, err := candidate.Open()
|
||||
if err != nil {
|
||||
_ = archive.Close()
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn library entry: %w", err)
|
||||
}
|
||||
return archiveEntry{
|
||||
reader: reader,
|
||||
size: candidate.UncompressedSize,
|
||||
close: func() error {
|
||||
return errors.Join(reader.Close(), archive.Close())
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
_ = archive.Close()
|
||||
return archiveEntry{}, fmt.Errorf("Unicorn archive does not contain %q", name)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
func openTarZstdEntry(path, name string) (archiveEntry, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
decoder, err := zstd.NewReader(file)
|
||||
if err != nil {
|
||||
_ = file.Close()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
closeArchive := func() error {
|
||||
decoder.Close()
|
||||
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
reader := tar.NewReader(decoder)
|
||||
|
||||
for {
|
||||
header, err := reader.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
_ = closeArchive()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("unicorn archive does not contain %q", name)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
_ = closeArchive()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("read Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
if header.Name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
if header.Typeflag != tar.TypeReg || header.Size < 0 {
|
||||
_ = closeArchive()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
|
||||
}
|
||||
|
||||
return archiveEntry{
|
||||
reader: io.LimitReader(reader, header.Size),
|
||||
size: uint64(header.Size),
|
||||
close: closeArchive,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
func TestOpenTarZstdEntry(t *testing.T) {
|
||||
const name = "clangarm64/bin/libunicorn.dll"
|
||||
|
||||
payload := []byte("test Unicorn library")
|
||||
|
||||
var compressed bytes.Buffer
|
||||
|
||||
encoder, err := zstd.NewWriter(&compressed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
archive := tar.NewWriter(encoder)
|
||||
if err := archive.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(payload))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := archive.Write(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := encoder.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
path := filepath.Join(t.TempDir(), "runtime.pkg.tar.zst")
|
||||
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
entry, err := openTarZstdEntry(path, name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Cleanup(func() {
|
||||
if err := entry.close(); err != nil {
|
||||
t.Errorf("close archive entry: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
actual, err := io.ReadAll(entry.reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(actual, payload) {
|
||||
t.Fatalf("contents = %q, want %q", actual, payload)
|
||||
}
|
||||
|
||||
if entry.size != uint64(len(payload)) {
|
||||
t.Fatalf("size = %d, want %d", entry.size, len(payload))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
import "fmt"
|
||||
|
||||
func openArchiveEntry(path, name string, format archiveFormat) (archiveEntry, error) {
|
||||
if format != archiveZIP {
|
||||
return archiveEntry{}, fmt.Errorf("unsupported Unicorn archive format %d", format)
|
||||
}
|
||||
|
||||
return openZIPEntry(path, name)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func openZIPEntry(path, name string) (archiveEntry, error) {
|
||||
archive, err := zip.OpenReader(path)
|
||||
if err != nil {
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn archive: %w", err)
|
||||
}
|
||||
|
||||
for _, candidate := range archive.File {
|
||||
if candidate.Name != name {
|
||||
continue
|
||||
}
|
||||
|
||||
if candidate.FileInfo().IsDir() {
|
||||
_ = archive.Close()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("invalid Unicorn library entry %q", name)
|
||||
}
|
||||
|
||||
reader, err := candidate.Open()
|
||||
if err != nil {
|
||||
_ = archive.Close()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("open Unicorn library entry: %w", err)
|
||||
}
|
||||
|
||||
return archiveEntry{
|
||||
reader: reader,
|
||||
size: candidate.UncompressedSize64,
|
||||
close: func() error {
|
||||
return errors.Join(reader.Close(), archive.Close())
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
_ = archive.Close()
|
||||
|
||||
return archiveEntry{}, fmt.Errorf("unicorn archive does not contain %q", name)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package unicorn
|
||||
|
||||
import "fmt"
|
||||
|
||||
const unicornVersion = "2.1.4"
|
||||
|
||||
type artifact struct {
|
||||
url string
|
||||
archiveSHA256 string
|
||||
librarySHA256 string
|
||||
member string
|
||||
filename string
|
||||
format archiveFormat
|
||||
dependencies []artifact
|
||||
}
|
||||
|
||||
func artifactFor(goos, goarch string) (artifact, error) {
|
||||
switch goos + "/" + goarch {
|
||||
case "darwin/amd64":
|
||||
return artifact{
|
||||
url: "https://files.pythonhosted.org/packages/c8/a7/92b47771e2107a201632a199cec91e8a81ee8a071ca6b7e7d600d8c61ac9/unicorn-2.1.4-cp37-abi3-macosx_10_9_x86_64.whl",
|
||||
archiveSHA256: "2a6f738fab5fabffa56af1e7bbf16ea1e91466c342f8dc64f125bd70f36c6b80",
|
||||
librarySHA256: "51c4a6f3ce22628ecd3acd1c49b921a818ffb989ca2c473134cc7eb06094f256",
|
||||
member: "unicorn/lib/libunicorn.2.dylib",
|
||||
filename: "libunicorn.2.dylib",
|
||||
}, nil
|
||||
case "darwin/arm64":
|
||||
return artifact{
|
||||
url: "https://files.pythonhosted.org/packages/6c/ae/4943c6f8524d729ec7d5e69df6407ea05d710fe77471d91cecf3fc64eb57/unicorn-2.1.4-cp37-abi3-macosx_11_0_arm64.whl",
|
||||
archiveSHA256: "d6c93e0f60328d8f4a1792af3f834137a28050fcc2305f2ec01efe8558a9844e",
|
||||
librarySHA256: "7207c8e3d7a63118fb0bca73e01816797fd51b1d8a39a4cbc7abfd562ee59c85",
|
||||
member: "unicorn/lib/libunicorn.2.dylib",
|
||||
filename: "libunicorn.2.dylib",
|
||||
}, nil
|
||||
case "linux/amd64":
|
||||
return artifact{
|
||||
url: "https://files.pythonhosted.org/packages/e7/df/ded5e3684c2d7600b30cc8a7530277b8cb36644a1a9d34cade7ebb45604c/unicorn-2.1.4-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
|
||||
archiveSHA256: "9d6e6dea140560de4ebd8446661f7ef84a357d428c14a3ef09dacd306ec8c239",
|
||||
librarySHA256: "ddb196ec82b52e502c18e4a34478bf7b9f61c83c2ebaa95c74d8ded45a95da9c",
|
||||
member: "unicorn/lib/libunicorn.so.2",
|
||||
filename: "libunicorn.so.2",
|
||||
}, nil
|
||||
case "linux/arm64":
|
||||
return artifact{
|
||||
url: "https://files.pythonhosted.org/packages/33/9f/32d41eb942221bcf4417cdc65537fc8b3bbbd6079d6c161e621f1dd4e94a/unicorn-2.1.4-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl",
|
||||
archiveSHA256: "bd1fb0c9af5f57e356d8a96928b4fe045b2e18f308ef23b481d5f970008aa722",
|
||||
librarySHA256: "a0b99458a82e268aee258205a40590411c3a9f28e42abf2942ce4e87b7d9ac65",
|
||||
member: "unicorn/lib/libunicorn.so.2",
|
||||
filename: "libunicorn.so.2",
|
||||
}, nil
|
||||
case "linux-musl/amd64":
|
||||
return artifact{
|
||||
url: "https://files.pythonhosted.org/packages/ed/4b/4628ccb20eb3ad1af400de8181d1f4e5c1a3fc2affa1b3410c1b2d71af36/unicorn-2.1.4-cp37-abi3-musllinux_1_2_x86_64.whl",
|
||||
archiveSHA256: "d348a90ee90219d141cb115ef8ed7e3fd1af42afaee105f7580761d775b25e32",
|
||||
librarySHA256: "cc1a208c69b151fdd23439736b0fac9ac6e14409dae77deee900369e6daab302",
|
||||
member: "unicorn/lib/libunicorn.so.2",
|
||||
filename: "libunicorn.so.2",
|
||||
}, nil
|
||||
case "linux-musl/arm64":
|
||||
return artifact{
|
||||
url: "https://files.pythonhosted.org/packages/70/38/ba5a051c844026e59ab6e0017db8cec77dbe20ab5f1d6edae1ce9d885b06/unicorn-2.1.4-cp37-abi3-musllinux_1_2_aarch64.whl",
|
||||
archiveSHA256: "01d744ba01c5cc68f1d7afe3d183f1868720fd440ec4eaedc4d1d5d9bf54b84c",
|
||||
librarySHA256: "52179305928b32c937d2d527ad6fef9d500c6fa7cdb14bf32abf7021d67271a2",
|
||||
member: "unicorn/lib/libunicorn.so.2",
|
||||
filename: "libunicorn.so.2",
|
||||
}, nil
|
||||
case "windows/amd64":
|
||||
return artifact{
|
||||
url: "https://github.com/unicorn-engine/unicorn/releases/download/2.1.4/windows-mingw64-shared.7z",
|
||||
archiveSHA256: "0960f938e66fa12c448742bddd2a03aa88abeeb2b3cda7156493a2da86228d3a",
|
||||
librarySHA256: "d8f9a89222ffa74493a1d47090e17f8e1db8ac171a3128c6a76a4ea09de11469",
|
||||
member: "bin/libunicorn.dll",
|
||||
filename: "libunicorn.dll",
|
||||
format: archiveSevenZip,
|
||||
}, nil
|
||||
case "windows/arm64":
|
||||
return artifact{
|
||||
url: "https://mirror.msys2.org/mingw/clangarm64/mingw-w64-clang-aarch64-unicorn-2.1.4-5-any.pkg.tar.zst",
|
||||
archiveSHA256: "e28aab2165d9cff048c29c58d6a40eb97928b23cf8ddeb78056a4b5b9805ac61",
|
||||
librarySHA256: "0ee1ebab91653645ef2b0615a8225123f7af9a49df4b6fcc5fb5d45d540ae9c2",
|
||||
member: "clangarm64/bin/libunicorn.dll",
|
||||
filename: "libunicorn.dll",
|
||||
format: archiveTarZstd,
|
||||
dependencies: []artifact{
|
||||
{
|
||||
url: "https://mirror.msys2.org/mingw/clangarm64/mingw-w64-clang-aarch64-libwinpthread-14.0.0.r302.gd7f3c5201-1-any.pkg.tar.zst",
|
||||
archiveSHA256: "dd20ad17543608915a2ff9ef6f39146d5621298531e0f50706fd1e78bf1da834",
|
||||
librarySHA256: "b80722a2586c0d1de605724569a564f3c139d184deaa33b7df7415477d733467",
|
||||
member: "clangarm64/bin/libwinpthread-1.dll",
|
||||
filename: "libwinpthread-1.dll",
|
||||
format: archiveTarZstd,
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
default:
|
||||
return artifact{}, fmt.Errorf("unsupported platform %s/%s", goos, goarch)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArtifactForSupportedPlatforms(t *testing.T) {
|
||||
tests := []struct {
|
||||
goos string
|
||||
goarch string
|
||||
filename string
|
||||
}{
|
||||
{goos: "darwin", goarch: "amd64", filename: "libunicorn.2.dylib"},
|
||||
{goos: "darwin", goarch: "arm64", filename: "libunicorn.2.dylib"},
|
||||
{goos: "linux", goarch: "amd64", filename: "libunicorn.so.2"},
|
||||
{goos: "linux", goarch: "arm64", filename: "libunicorn.so.2"},
|
||||
{goos: "linux-musl", goarch: "amd64", filename: "libunicorn.so.2"},
|
||||
{goos: "linux-musl", goarch: "arm64", filename: "libunicorn.so.2"},
|
||||
{goos: "windows", goarch: "amd64", filename: "libunicorn.dll"},
|
||||
{goos: "windows", goarch: "arm64", filename: "libunicorn.dll"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.goos+"/"+test.goarch, func(t *testing.T) {
|
||||
selected, err := artifactFor(test.goos, test.goarch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if selected.filename != test.filename {
|
||||
t.Fatalf("filename = %q, want %q", selected.filename, test.filename)
|
||||
}
|
||||
|
||||
artifacts := append([]artifact{selected}, selected.dependencies...)
|
||||
for _, item := range artifacts {
|
||||
if !strings.HasPrefix(item.url, "https://") {
|
||||
t.Fatalf("artifact URL is not HTTPS: %q", item.url)
|
||||
}
|
||||
|
||||
if len(item.archiveSHA256) != 64 || len(item.librarySHA256) != 64 {
|
||||
t.Fatal("artifact is missing a SHA-256 checksum")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactForWindowsARM64IncludesRuntimeDependency(t *testing.T) {
|
||||
selected, err := artifactFor("windows", "arm64")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if selected.format != archiveTarZstd {
|
||||
t.Fatalf("archive format = %d, want %d", selected.format, archiveTarZstd)
|
||||
}
|
||||
|
||||
if len(selected.dependencies) != 1 {
|
||||
t.Fatalf("dependencies = %d, want 1", len(selected.dependencies))
|
||||
}
|
||||
|
||||
dependency := selected.dependencies[0]
|
||||
if dependency.filename != "libwinpthread-1.dll" || dependency.format != archiveTarZstd {
|
||||
t.Fatalf("unexpected dependency: %+v", dependency)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxArtifactSize = 64 << 20
|
||||
|
||||
var artifactHTTPClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
type runtimePaths struct {
|
||||
library string
|
||||
dependencies []string
|
||||
}
|
||||
|
||||
func cachedRuntimePaths(ctx context.Context) (runtimePaths, error) {
|
||||
goos := runtime.GOOS
|
||||
if goos == "linux" && linuxUsesMusl() {
|
||||
goos = "linux-musl"
|
||||
}
|
||||
|
||||
selected, err := artifactFor(goos, runtime.GOARCH)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return runtimePaths{}, fmt.Errorf("locate user cache: %w", err)
|
||||
}
|
||||
|
||||
root := filepath.Join(cache, "ipatool", "unicorn", unicornVersion)
|
||||
paths := runtimePaths{dependencies: make([]string, 0, len(selected.dependencies))}
|
||||
|
||||
for _, dependency := range selected.dependencies {
|
||||
path, err := ensureLibrary(ctx, root, dependency, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.dependencies = append(paths.dependencies, path)
|
||||
}
|
||||
|
||||
paths.library, err = ensureLibrary(ctx, root, selected, artifactHTTPClient)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
paths.library, err = prepareRuntimeLibrary(paths.library)
|
||||
if err != nil {
|
||||
return runtimePaths{}, err
|
||||
}
|
||||
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
func linuxUsesMusl() bool {
|
||||
loaders, _ := filepath.Glob("/lib/ld-musl-*.so.1")
|
||||
if len(loaders) != 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
loaders, _ = filepath.Glob("/usr/lib/ld-musl-*.so.1")
|
||||
if len(loaders) != 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
_, err := os.Stat("/etc/alpine-release")
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func ensureLibrary(ctx context.Context, root string, selected artifact, client *http.Client) (string, error) {
|
||||
if filepath.Base(selected.filename) != selected.filename {
|
||||
return "", fmt.Errorf("invalid library filename %q", selected.filename)
|
||||
}
|
||||
|
||||
directory := filepath.Join(root, selected.librarySHA256)
|
||||
destination := filepath.Join(directory, selected.filename)
|
||||
|
||||
valid, err := fileMatchesSHA256(destination, selected.librarySHA256)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("verify cached Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
if valid {
|
||||
return destination, nil
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(directory, 0o700); err != nil {
|
||||
return "", fmt.Errorf("create Unicorn cache: %w", err)
|
||||
}
|
||||
|
||||
archive, err := downloadArtifact(ctx, directory, selected, client)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer os.Remove(archive)
|
||||
|
||||
temporary, err := extractLibrary(archive, directory, selected)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer os.Remove(temporary)
|
||||
|
||||
if err := installLibrary(temporary, destination, selected.librarySHA256); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return destination, nil
|
||||
}
|
||||
|
||||
//nolint:nonamedreturns // Deferred cleanup must update the returned error.
|
||||
func downloadArtifact(ctx context.Context, directory string, selected artifact, client *http.Client) (path string, err error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, selected.url, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create Unicorn download request: %w", err)
|
||||
}
|
||||
|
||||
request.Header.Set("User-Agent", "ipatool Unicorn runtime downloader")
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("download Unicorn %s: %w", unicornVersion, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("download Unicorn %s: unexpected HTTP status %s", unicornVersion, response.Status)
|
||||
}
|
||||
|
||||
if response.ContentLength > maxArtifactSize {
|
||||
return "", fmt.Errorf("download Unicorn %s: artifact exceeds %d bytes", unicornVersion, maxArtifactSize)
|
||||
}
|
||||
|
||||
file, err := os.CreateTemp(directory, ".unicorn-artifact-*")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create Unicorn download: %w", err)
|
||||
}
|
||||
|
||||
path = file.Name()
|
||||
|
||||
defer func() {
|
||||
if closeErr := file.Close(); err == nil && closeErr != nil {
|
||||
err = fmt.Errorf("close Unicorn download: %w", closeErr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
}()
|
||||
|
||||
hash := sha256.New()
|
||||
|
||||
written, err := io.Copy(io.MultiWriter(file, hash), io.LimitReader(response.Body, maxArtifactSize+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("save Unicorn download: %w", err)
|
||||
}
|
||||
|
||||
if written > maxArtifactSize {
|
||||
return "", fmt.Errorf("download Unicorn %s: artifact exceeds %d bytes", unicornVersion, maxArtifactSize)
|
||||
}
|
||||
|
||||
if actual := hex.EncodeToString(hash.Sum(nil)); actual != selected.archiveSHA256 {
|
||||
return "", fmt.Errorf("download Unicorn %s: archive SHA-256 is %s, want %s", unicornVersion, actual, selected.archiveSHA256)
|
||||
}
|
||||
|
||||
if err := file.Sync(); err != nil {
|
||||
return "", fmt.Errorf("sync Unicorn download: %w", err)
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
//nolint:nonamedreturns // Deferred cleanup must update the returned error.
|
||||
func extractLibrary(archive, directory string, selected artifact) (path string, err error) {
|
||||
entry, err := openArchiveEntry(archive, selected.member, selected.format)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := entry.close(); err == nil && closeErr != nil {
|
||||
err = fmt.Errorf("close Unicorn archive entry: %w", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
if entry.size > maxArtifactSize {
|
||||
return "", fmt.Errorf("invalid Unicorn library entry %q", selected.member)
|
||||
}
|
||||
|
||||
destination, err := os.CreateTemp(directory, ".unicorn-library-*")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create cached Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
path = destination.Name()
|
||||
|
||||
defer func() {
|
||||
if closeErr := destination.Close(); err == nil && closeErr != nil {
|
||||
err = fmt.Errorf("close cached Unicorn library: %w", closeErr)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
_ = os.Remove(path)
|
||||
}
|
||||
}()
|
||||
|
||||
hash := sha256.New()
|
||||
|
||||
written, err := io.Copy(io.MultiWriter(destination, hash), io.LimitReader(entry.reader, maxArtifactSize+1))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("extract Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
if written > maxArtifactSize || uint64(written) != entry.size {
|
||||
return "", fmt.Errorf("invalid size for Unicorn library entry %q", selected.member)
|
||||
}
|
||||
|
||||
if actual := hex.EncodeToString(hash.Sum(nil)); actual != selected.librarySHA256 {
|
||||
return "", fmt.Errorf("extracted Unicorn library SHA-256 is %s, want %s", actual, selected.librarySHA256)
|
||||
}
|
||||
|
||||
if err := destination.Sync(); err != nil {
|
||||
return "", fmt.Errorf("sync cached Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func installLibrary(source, destination, checksum string) error {
|
||||
if err := os.Rename(source, destination); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Another process may have populated the same content-addressed cache entry.
|
||||
valid, verifyErr := fileMatchesSHA256(destination, checksum)
|
||||
if verifyErr == nil && valid {
|
||||
return nil
|
||||
}
|
||||
|
||||
if verifyErr != nil && !errors.Is(verifyErr, os.ErrNotExist) {
|
||||
return fmt.Errorf("verify concurrently cached Unicorn library: %w", verifyErr)
|
||||
}
|
||||
|
||||
if err := os.Remove(destination); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("replace cached Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Rename(source, destination); err != nil {
|
||||
return fmt.Errorf("install cached Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fileMatchesSHA256(path, expected string) (bool, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("open checksum target: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("inspect checksum target: %w", err)
|
||||
}
|
||||
|
||||
if info.Size() < 0 || info.Size() > maxArtifactSize {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return false, fmt.Errorf("checksum target: %w", err)
|
||||
}
|
||||
|
||||
return hex.EncodeToString(hash.Sum(nil)) == expected, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnsureLibraryHonorsCanceledContext(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
selected := artifact{
|
||||
url: "https://example.invalid/unicorn",
|
||||
archiveSHA256: "unused",
|
||||
librarySHA256: "unused",
|
||||
member: "unused",
|
||||
filename: "libunicorn.test",
|
||||
}
|
||||
|
||||
_, err := ensureLibrary(ctx, t.TempDir(), selected, http.DefaultClient)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("ensureLibrary error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnsureLibraryDownloadsVerifiesAndCaches(t *testing.T) {
|
||||
const member = "unicorn/lib/libunicorn.so.2"
|
||||
|
||||
payload := []byte("test Unicorn library")
|
||||
archive := testZip(t, member, payload)
|
||||
|
||||
var requests atomic.Int32
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
|
||||
_, _ = response.Write(archive)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
selected := artifact{
|
||||
url: server.URL,
|
||||
archiveSHA256: testSHA256(archive),
|
||||
librarySHA256: testSHA256(payload),
|
||||
member: member,
|
||||
filename: "libunicorn.so.2",
|
||||
}
|
||||
root := t.TempDir()
|
||||
|
||||
path, err := ensureLibrary(context.Background(), root, selected, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assertFileContents(t, path, payload)
|
||||
|
||||
cachedPath, err := ensureLibrary(context.Background(), root, selected, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if cachedPath != path {
|
||||
t.Fatalf("cached path = %q, want %q", cachedPath, path)
|
||||
}
|
||||
|
||||
if count := requests.Load(); count != 1 {
|
||||
t.Fatalf("download requests = %d, want 1", count)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte("corrupted"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repairedPath, err := ensureLibrary(context.Background(), root, selected, server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assertFileContents(t, repairedPath, payload)
|
||||
|
||||
if count := requests.Load(); count != 2 {
|
||||
t.Fatalf("download requests after repair = %d, want 2", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureLibraryRejectsArchiveChecksumMismatch(t *testing.T) {
|
||||
const member = "unicorn/lib/libunicorn.so.2"
|
||||
|
||||
payload := []byte("test Unicorn library")
|
||||
archive := testZip(t, member, payload)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = response.Write(archive)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
selected := artifact{
|
||||
url: server.URL,
|
||||
archiveSHA256: testSHA256([]byte("different archive")),
|
||||
librarySHA256: testSHA256(payload),
|
||||
member: member,
|
||||
filename: "libunicorn.so.2",
|
||||
}
|
||||
if _, err := ensureLibrary(context.Background(), t.TempDir(), selected, server.Client()); err == nil {
|
||||
t.Fatal("expected checksum error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureLibraryRejectsLibraryChecksumMismatch(t *testing.T) {
|
||||
const member = "unicorn/lib/libunicorn.so.2"
|
||||
|
||||
payload := []byte("test Unicorn library")
|
||||
archive := testZip(t, member, payload)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = response.Write(archive)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
selected := artifact{
|
||||
url: server.URL,
|
||||
archiveSHA256: testSHA256(archive),
|
||||
librarySHA256: testSHA256([]byte("different library")),
|
||||
member: member,
|
||||
filename: "libunicorn.so.2",
|
||||
}
|
||||
if _, err := ensureLibrary(context.Background(), t.TempDir(), selected, server.Client()); err == nil {
|
||||
t.Fatal("expected checksum error")
|
||||
}
|
||||
}
|
||||
|
||||
func testZip(t *testing.T, name string, contents []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
var buffer bytes.Buffer
|
||||
archive := zip.NewWriter(&buffer)
|
||||
|
||||
entry, err := archive.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := entry.Write(contents); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func testSHA256(contents []byte) string {
|
||||
sum := sha256.Sum256(contents)
|
||||
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func assertFileContents(t *testing.T, path string, expected []byte) {
|
||||
t.Helper()
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
actual, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(actual, expected) {
|
||||
t.Fatalf("contents = %q, want %q", actual, expected)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
const (
|
||||
archX86 = 4
|
||||
mode64 = 8
|
||||
protAll = 7
|
||||
|
||||
RegRAX = 35
|
||||
RegRCX = 38
|
||||
RegRDI = 39
|
||||
RegRDX = 40
|
||||
RegRIP = 41
|
||||
RegRSI = 43
|
||||
RegRSP = 44
|
||||
RegR8 = 106
|
||||
RegR9 = 107
|
||||
)
|
||||
|
||||
var errEngineClosed = errors.New("unicorn engine is closed")
|
||||
|
||||
type api struct {
|
||||
version func(*uint32, *uint32) uint32
|
||||
open func(int32, int32, *uintptr) int32
|
||||
close func(uintptr) int32
|
||||
ctl func(uintptr, uint32, uint32) int32
|
||||
strerror func(int32) string
|
||||
memMap func(uintptr, uint64, uint64, uint32) int32
|
||||
memUnmap func(uintptr, uint64, uint64) int32
|
||||
memRead func(uintptr, uint64, unsafe.Pointer, uint64) int32
|
||||
memWrite func(uintptr, uint64, unsafe.Pointer, uint64) int32
|
||||
regRead func(uintptr, int32, unsafe.Pointer) int32
|
||||
regWrite func(uintptr, int32, unsafe.Pointer) int32
|
||||
emuStart func(uintptr, uint64, uint64, uint64, uint64) int32
|
||||
emuStop func(uintptr) int32
|
||||
hookAdd func(uintptr, *uintptr, int32, uintptr, uintptr, uint64, uint64) int32
|
||||
hookDel func(uintptr, uintptr) int32
|
||||
}
|
||||
|
||||
type Engine struct {
|
||||
api api
|
||||
handle uintptr
|
||||
library library
|
||||
hooks hookState
|
||||
stateMu sync.Mutex
|
||||
active sync.WaitGroup
|
||||
closing bool
|
||||
closeDone chan struct{}
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func New(ctx context.Context) (*Engine, error) {
|
||||
return newEngine(ctx, openLibrary)
|
||||
}
|
||||
|
||||
func newEngine(ctx context.Context, loadLibrary func(context.Context) (library, error)) (*Engine, error) {
|
||||
if ctx == nil {
|
||||
return nil, errors.New("unicorn context is nil")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
}
|
||||
|
||||
library, err := loadLibrary(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load Unicorn: %w", err)
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
if library.handle != 0 && library.close != nil {
|
||||
_ = library.close()
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("create Unicorn engine: %w", err)
|
||||
}
|
||||
|
||||
engine := &Engine{
|
||||
library: library,
|
||||
closeDone: make(chan struct{}),
|
||||
}
|
||||
engine.register(library.handle)
|
||||
|
||||
var major, minor uint32
|
||||
|
||||
engine.api.version(&major, &minor)
|
||||
|
||||
if major != 2 || minor != 1 {
|
||||
_ = library.close()
|
||||
|
||||
return nil, fmt.Errorf("unsupported Unicorn API version %d.%d", major, minor)
|
||||
}
|
||||
|
||||
if err := engine.err(engine.api.open(archX86, mode64, &engine.handle)); err != nil {
|
||||
_ = library.close()
|
||||
|
||||
return nil, fmt.Errorf("create x86-64 emulator: %w", err)
|
||||
}
|
||||
|
||||
if err := configureEngine(engine); err != nil {
|
||||
_ = engine.api.close(engine.handle)
|
||||
_ = library.close()
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
runtime.SetFinalizer(engine, func(engine *Engine) {
|
||||
_ = engine.Close()
|
||||
})
|
||||
|
||||
return engine, nil
|
||||
}
|
||||
|
||||
func (e *Engine) register(handle uintptr) {
|
||||
purego.RegisterLibFunc(&e.api.version, handle, "uc_version")
|
||||
purego.RegisterLibFunc(&e.api.open, handle, "uc_open")
|
||||
purego.RegisterLibFunc(&e.api.close, handle, "uc_close")
|
||||
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")
|
||||
purego.RegisterLibFunc(&e.api.memRead, handle, "uc_mem_read")
|
||||
purego.RegisterLibFunc(&e.api.memWrite, handle, "uc_mem_write")
|
||||
purego.RegisterLibFunc(&e.api.regRead, handle, "uc_reg_read")
|
||||
purego.RegisterLibFunc(&e.api.regWrite, handle, "uc_reg_write")
|
||||
purego.RegisterLibFunc(&e.api.emuStart, handle, "uc_emu_start")
|
||||
purego.RegisterLibFunc(&e.api.emuStop, handle, "uc_emu_stop")
|
||||
purego.RegisterLibFunc(&e.api.hookAdd, handle, "uc_hook_add")
|
||||
purego.RegisterLibFunc(&e.api.hookDel, handle, "uc_hook_del")
|
||||
}
|
||||
|
||||
func (e *Engine) MemMap(address, size uint64) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.memMap(handle, address, size, protAll))
|
||||
}
|
||||
|
||||
func (e *Engine) MemUnmap(address, size uint64) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.memUnmap(handle, address, size))
|
||||
}
|
||||
|
||||
func (e *Engine) MemRead(address, size uint64) ([]byte, error) {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer done()
|
||||
|
||||
data := make([]byte, size)
|
||||
if len(data) == 0 {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
err = e.err(e.api.memRead(handle, address, unsafe.Pointer(&data[0]), size))
|
||||
|
||||
return data, err
|
||||
}
|
||||
|
||||
func (e *Engine) MemReadInto(data []byte, address uint64) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return e.err(e.api.memRead(handle, address, unsafe.Pointer(&data[0]), uint64(len(data))))
|
||||
}
|
||||
|
||||
func (e *Engine) MemWrite(address uint64, data []byte) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return e.err(e.api.memWrite(handle, address, unsafe.Pointer(&data[0]), uint64(len(data))))
|
||||
}
|
||||
|
||||
func (e *Engine) RegRead(register int) (uint64, error) {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer done()
|
||||
|
||||
var value uint64
|
||||
err = e.err(e.api.regRead(handle, int32(register), unsafe.Pointer(&value)))
|
||||
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (e *Engine) RegWrite(register int, value uint64) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.regWrite(handle, int32(register), unsafe.Pointer(&value)))
|
||||
}
|
||||
|
||||
func (e *Engine) Start(begin, end uint64) error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.emuStart(handle, begin, end, 0, 0))
|
||||
}
|
||||
|
||||
func (e *Engine) StartBounded(begin, end uint64, timeout time.Duration, instructionLimit uint64) error {
|
||||
if timeout <= 0 {
|
||||
return errors.New("unicorn timeout must be positive")
|
||||
}
|
||||
|
||||
microseconds := uint64(timeout / time.Microsecond)
|
||||
if microseconds == 0 {
|
||||
microseconds = 1
|
||||
}
|
||||
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.emuStart(handle, begin, end, microseconds, instructionLimit))
|
||||
}
|
||||
|
||||
func (e *Engine) Stop() error {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
return e.err(e.api.emuStop(handle))
|
||||
}
|
||||
|
||||
func (e *Engine) Close() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
e.stateMu.Lock()
|
||||
if e.closing {
|
||||
done := e.closeDone
|
||||
e.stateMu.Unlock()
|
||||
<-done
|
||||
e.stateMu.Lock()
|
||||
err := e.closeErr
|
||||
e.stateMu.Unlock()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
e.closing = true
|
||||
e.stateMu.Unlock()
|
||||
|
||||
runtime.SetFinalizer(e, nil)
|
||||
e.active.Wait()
|
||||
e.clearCodeHooks()
|
||||
|
||||
e.stateMu.Lock()
|
||||
handle := e.handle
|
||||
loadedLibrary := e.library
|
||||
e.handle = 0
|
||||
e.library = library{}
|
||||
e.stateMu.Unlock()
|
||||
|
||||
var errs []error
|
||||
|
||||
if handle != 0 {
|
||||
if err := e.err(e.api.close(handle)); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
if loadedLibrary.handle != 0 {
|
||||
if err := loadedLibrary.close(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
}
|
||||
|
||||
closeErr := errors.Join(errs...)
|
||||
|
||||
e.stateMu.Lock()
|
||||
e.closeErr = closeErr
|
||||
close(e.closeDone)
|
||||
e.stateMu.Unlock()
|
||||
|
||||
return closeErr
|
||||
}
|
||||
|
||||
func (e *Engine) beginOperation() (uintptr, func(), error) {
|
||||
if e == nil {
|
||||
return 0, nil, errEngineClosed
|
||||
}
|
||||
|
||||
e.stateMu.Lock()
|
||||
defer e.stateMu.Unlock()
|
||||
|
||||
if e.closing || e.handle == 0 {
|
||||
return 0, nil, errEngineClosed
|
||||
}
|
||||
|
||||
e.active.Add(1)
|
||||
|
||||
return e.handle, e.active.Done, nil
|
||||
}
|
||||
|
||||
func (e *Engine) err(code int32) error {
|
||||
if code == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
message := "unknown error"
|
||||
if description := e.api.strerror(code); description != "" {
|
||||
message = description
|
||||
}
|
||||
|
||||
return fmt.Errorf("unicorn error %d: %s", code, message)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !windows
|
||||
|
||||
package unicorn
|
||||
|
||||
func configureEngine(*Engine) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package unicorn
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
ucCtlTCGBufferSize = 13
|
||||
ucCtlIOWrite = 1
|
||||
ucCtlArgumentCount = 1
|
||||
tcgBufferSize = 64 << 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.
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewPassesContextToLibraryLoader(t *testing.T) {
|
||||
type contextKey struct{}
|
||||
|
||||
ctx := context.WithValue(context.Background(), contextKey{}, "value")
|
||||
wantErr := errors.New("loader error")
|
||||
called := false
|
||||
_, err := newEngine(ctx, func(received context.Context) (library, error) {
|
||||
called = true
|
||||
|
||||
if received.Value(contextKey{}) != "value" {
|
||||
t.Fatal("library loader did not receive constructor context")
|
||||
}
|
||||
|
||||
return library{}, wantErr
|
||||
})
|
||||
|
||||
if !called {
|
||||
t.Fatal("library loader was not called")
|
||||
}
|
||||
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("New error = %v, want %v", err, wantErr)
|
||||
}
|
||||
|
||||
canceled, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
called = false
|
||||
|
||||
_, err = newEngine(canceled, func(context.Context) (library, error) {
|
||||
called = true
|
||||
|
||||
return library{}, nil
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("New canceled error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
|
||||
if called {
|
||||
t.Fatal("library loader ran for an already canceled context")
|
||||
}
|
||||
|
||||
duringLoad, cancelDuringLoad := context.WithCancel(context.Background())
|
||||
libraryClosed := false
|
||||
|
||||
_, err = newEngine(duringLoad, func(context.Context) (library, error) {
|
||||
cancelDuringLoad()
|
||||
|
||||
return library{
|
||||
handle: 1,
|
||||
close: func() error {
|
||||
libraryClosed = true
|
||||
|
||||
return nil
|
||||
},
|
||||
}, nil
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("New mid-load cancellation error = %v, want %v", err, context.Canceled)
|
||||
}
|
||||
|
||||
if !libraryClosed {
|
||||
t.Fatal("library loaded during cancellation was not closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineOperationsFailAfterClose(t *testing.T) {
|
||||
engine := &Engine{
|
||||
handle: 1,
|
||||
closeDone: make(chan struct{}),
|
||||
api: api{
|
||||
close: func(uintptr) int32 { return 0 },
|
||||
},
|
||||
}
|
||||
if err := engine.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
call func() error
|
||||
}{
|
||||
{"MemMap", func() error { return engine.MemMap(0, 0x1000) }},
|
||||
{"MemUnmap", func() error { return engine.MemUnmap(0, 0x1000) }},
|
||||
{"MemRead", func() error {
|
||||
_, err := engine.MemRead(0, 0)
|
||||
|
||||
return err
|
||||
}},
|
||||
{"MemReadInto", func() error { return engine.MemReadInto(nil, 0) }},
|
||||
{"MemWrite", func() error { return engine.MemWrite(0, nil) }},
|
||||
{"RegRead", func() error {
|
||||
_, err := engine.RegRead(RegRAX)
|
||||
|
||||
return err
|
||||
}},
|
||||
{"RegWrite", func() error { return engine.RegWrite(RegRAX, 0) }},
|
||||
{"Start", func() error { return engine.Start(0, 1) }},
|
||||
{"StartBounded", func() error { return engine.StartBounded(0, 1, time.Second, 1) }},
|
||||
{"Stop", engine.Stop},
|
||||
{"AddCodeHook", func() error {
|
||||
_, err := engine.AddCodeHook(0, 1, func(uint64, uint32) {})
|
||||
|
||||
return err
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if err := test.call(); !errors.Is(err, errEngineClosed) {
|
||||
t.Fatalf("error = %v, want %v", err, errEngineClosed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentCloseWaitsForActiveOperation(t *testing.T) {
|
||||
operationStarted := make(chan struct{})
|
||||
releaseOperation := make(chan struct{})
|
||||
|
||||
var closeCalls atomic.Int32
|
||||
|
||||
engine := &Engine{
|
||||
handle: 1,
|
||||
closeDone: make(chan struct{}),
|
||||
api: api{
|
||||
memMap: func(uintptr, uint64, uint64, uint32) int32 {
|
||||
close(operationStarted)
|
||||
<-releaseOperation
|
||||
|
||||
return 0
|
||||
},
|
||||
close: func(uintptr) int32 {
|
||||
closeCalls.Add(1)
|
||||
|
||||
return 0
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
operationErr := make(chan error, 1)
|
||||
go func() {
|
||||
operationErr <- engine.MemMap(0x1000, 0x1000)
|
||||
}()
|
||||
<-operationStarted
|
||||
|
||||
firstClose := make(chan error, 1)
|
||||
secondClose := make(chan error, 1)
|
||||
|
||||
go func() { firstClose <- engine.Close() }()
|
||||
waitForEngineClosing(t, engine)
|
||||
|
||||
go func() { secondClose <- engine.Close() }()
|
||||
|
||||
if closeCalls.Load() != 0 {
|
||||
t.Fatal("native engine closed while an operation was active")
|
||||
}
|
||||
|
||||
close(releaseOperation)
|
||||
waitForResult(t, operationErr)
|
||||
waitForResult(t, firstClose)
|
||||
waitForResult(t, secondClose)
|
||||
|
||||
if closeCalls.Load() != 1 {
|
||||
t.Fatalf("native close calls = %d, want 1", closeCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func waitForEngineClosing(t *testing.T, engine *Engine) {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(time.Second)
|
||||
|
||||
for {
|
||||
engine.stateMu.Lock()
|
||||
closing := engine.closing
|
||||
engine.stateMu.Unlock()
|
||||
|
||||
if closing {
|
||||
return
|
||||
}
|
||||
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("engine did not begin closing")
|
||||
}
|
||||
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
|
||||
func waitForResult(t *testing.T, result <-chan error) {
|
||||
t.Helper()
|
||||
select {
|
||||
case err := <-result:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("operation did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEngineExecutesX8664(t *testing.T) {
|
||||
engine := newTestEngine(t)
|
||||
defer engine.Close()
|
||||
|
||||
const address = uint64(0x1000000)
|
||||
if err := engine.MemMap(address, 0x1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// mov rax, 0x1234; hlt
|
||||
code := []byte{0x48, 0xc7, 0xc0, 0x34, 0x12, 0x00, 0x00, 0xf4}
|
||||
if err := engine.MemWrite(address, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.Start(address, address+uint64(len(code))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
value, err := engine.RegRead(RegRAX)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if value != 0x1234 {
|
||||
t.Fatalf("RAX = %#x, want %#x", value, uint64(0x1234))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
const hookCode = 1 << 2
|
||||
|
||||
type CodeHook func(address uint64, size uint32)
|
||||
|
||||
type hookState struct {
|
||||
mu sync.Mutex
|
||||
ids map[uintptr]struct{}
|
||||
}
|
||||
|
||||
type Hook struct {
|
||||
mu sync.Mutex
|
||||
engine *Engine
|
||||
handle uintptr
|
||||
id uintptr
|
||||
}
|
||||
|
||||
var (
|
||||
codeHookID atomic.Uint64
|
||||
codeHookCallbacks sync.Map
|
||||
codeHookTrampoline = purego.NewCallback(func(
|
||||
_ purego.CDecl,
|
||||
_ uintptr,
|
||||
address uint64,
|
||||
size uint32,
|
||||
userData uintptr,
|
||||
) uintptr {
|
||||
callback, ok := codeHookCallbacks.Load(userData)
|
||||
if ok {
|
||||
callback.(CodeHook)(address, size)
|
||||
}
|
||||
|
||||
return 0
|
||||
})
|
||||
)
|
||||
|
||||
// AddCodeHook registers callback for instructions whose start address is in
|
||||
// the inclusive range [begin, end]. The callback is retained until the Hook or
|
||||
// Engine is closed; it runs through a C ABI trampoline and must not panic.
|
||||
func (e *Engine) AddCodeHook(begin, end uint64, callback CodeHook) (*Hook, error) {
|
||||
handle, done, err := e.beginOperation()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer done()
|
||||
|
||||
if callback == nil {
|
||||
return nil, errors.New("unicorn code hook callback is nil")
|
||||
}
|
||||
|
||||
id := uintptr(codeHookID.Add(1))
|
||||
if id == 0 {
|
||||
id = uintptr(codeHookID.Add(1))
|
||||
}
|
||||
|
||||
codeHookCallbacks.Store(id, callback)
|
||||
|
||||
var hookHandle uintptr
|
||||
if err := e.err(e.api.hookAdd(handle, &hookHandle, hookCode, codeHookTrampoline, id, begin, end)); err != nil {
|
||||
codeHookCallbacks.Delete(id)
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e.hooks.mu.Lock()
|
||||
if e.hooks.ids == nil {
|
||||
e.hooks.ids = make(map[uintptr]struct{})
|
||||
}
|
||||
|
||||
e.hooks.ids[id] = struct{}{}
|
||||
e.hooks.mu.Unlock()
|
||||
|
||||
return &Hook{engine: e, handle: hookHandle, id: id}, nil
|
||||
}
|
||||
|
||||
func (h *Hook) Close() error {
|
||||
if h == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
if h.engine == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
engine := h.engine
|
||||
handle, done, err := engine.beginOperation()
|
||||
|
||||
if err == nil {
|
||||
err = engine.err(engine.api.hookDel(handle, h.handle))
|
||||
|
||||
done()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if !errors.Is(err, errEngineClosed) {
|
||||
return err
|
||||
}
|
||||
|
||||
codeHookCallbacks.Delete(h.id)
|
||||
engine.hooks.mu.Lock()
|
||||
delete(engine.hooks.ids, h.id)
|
||||
engine.hooks.mu.Unlock()
|
||||
|
||||
h.engine = nil
|
||||
h.handle = 0
|
||||
h.id = 0
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *Engine) clearCodeHooks() {
|
||||
e.hooks.mu.Lock()
|
||||
defer e.hooks.mu.Unlock()
|
||||
|
||||
for id := range e.hooks.ids {
|
||||
codeHookCallbacks.Delete(id)
|
||||
}
|
||||
|
||||
clear(e.hooks.ids)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package unicorn
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCodeHookStopsEmulation(t *testing.T) {
|
||||
engine := newTestEngine(t)
|
||||
defer engine.Close()
|
||||
|
||||
const address = uint64(0x2000000)
|
||||
if err := engine.MemMap(address, 0x1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// mov rax, 1; inc rax; ud2
|
||||
code := []byte{0x48, 0xc7, 0xc0, 0x01, 0x00, 0x00, 0x00, 0x48, 0xff, 0xc0, 0x0f, 0x0b}
|
||||
if err := engine.MemWrite(address, code); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var (
|
||||
calls int
|
||||
hookAddress uint64
|
||||
hookSize uint32
|
||||
stopErr error
|
||||
)
|
||||
|
||||
hook, err := engine.AddCodeHook(address+7, address+7, func(current uint64, size uint32) {
|
||||
calls++
|
||||
hookAddress = current
|
||||
hookSize = size
|
||||
stopErr = engine.Stop()
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
defer hook.Close()
|
||||
|
||||
if err := engine.Start(address, address+uint64(len(code))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if stopErr != nil {
|
||||
t.Fatal(stopErr)
|
||||
}
|
||||
|
||||
if calls != 1 {
|
||||
t.Fatalf("callback calls = %d, want 1", calls)
|
||||
}
|
||||
|
||||
if hookAddress != address+7 || hookSize != 3 {
|
||||
t.Fatalf("callback instruction = (%#x, %d), want (%#x, 3)", hookAddress, hookSize, address+7)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClosedCodeHookDoesNotRun(t *testing.T) {
|
||||
engine := newTestEngine(t)
|
||||
defer engine.Close()
|
||||
|
||||
const address = uint64(0x3000000)
|
||||
if err := engine.MemMap(address, 0x1000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.MemWrite(address, []byte{0x90, 0xf4}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
called := false
|
||||
|
||||
hook, err := engine.AddCodeHook(address, address, func(uint64, uint32) {
|
||||
called = true
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := hook.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := hook.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := engine.Start(address, address+2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if called {
|
||||
t.Fatal("closed callback ran")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHookCloseIsSafeDuringEngineClose(t *testing.T) {
|
||||
hookDeleteStarted := make(chan struct{})
|
||||
releaseHookDelete := make(chan struct{})
|
||||
engine := &Engine{
|
||||
handle: 1,
|
||||
closeDone: make(chan struct{}),
|
||||
api: api{
|
||||
hookAdd: func(_ uintptr, handle *uintptr, _ int32, _, _ uintptr, _, _ uint64) int32 {
|
||||
*handle = 2
|
||||
|
||||
return 0
|
||||
},
|
||||
hookDel: func(uintptr, uintptr) int32 {
|
||||
close(hookDeleteStarted)
|
||||
<-releaseHookDelete
|
||||
|
||||
return 0
|
||||
},
|
||||
close: func(uintptr) int32 { return 0 },
|
||||
},
|
||||
}
|
||||
|
||||
hook, err := engine.AddCodeHook(0, 1, func(uint64, uint32) {})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id := hook.id
|
||||
|
||||
hookErr := make(chan error, 1)
|
||||
go func() { hookErr <- hook.Close() }()
|
||||
<-hookDeleteStarted
|
||||
|
||||
closeErr := make(chan error, 1)
|
||||
|
||||
go func() { closeErr <- engine.Close() }()
|
||||
waitForEngineClosing(t, engine)
|
||||
|
||||
close(releaseHookDelete)
|
||||
waitForResult(t, hookErr)
|
||||
waitForResult(t, closeErr)
|
||||
|
||||
if _, exists := codeHookCallbacks.Load(id); exists {
|
||||
t.Fatal("closed hook callback remains registered")
|
||||
}
|
||||
|
||||
if err := hook.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHookCloseAfterEngineClose(t *testing.T) {
|
||||
engine := &Engine{
|
||||
handle: 1,
|
||||
closeDone: make(chan struct{}),
|
||||
api: api{
|
||||
hookAdd: func(_ uintptr, handle *uintptr, _ int32, _, _ uintptr, _, _ uint64) int32 {
|
||||
*handle = 2
|
||||
|
||||
return 0
|
||||
},
|
||||
close: func(uintptr) int32 { return 0 },
|
||||
},
|
||||
}
|
||||
|
||||
hook, err := engine.AddCodeHook(0, 1, func(uint64, uint32) {})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id := hook.id
|
||||
|
||||
if err := engine.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := hook.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, exists := codeHookCallbacks.Load(id); exists {
|
||||
t.Fatal("closed hook callback remains registered")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package unicorn
|
||||
|
||||
type library struct {
|
||||
handle uintptr
|
||||
close func() error
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
peSignature = 0x00004550
|
||||
pe32PlusMagic = 0x020b
|
||||
peImportDirectory = 1
|
||||
peOptionalHeaderOffset = 24
|
||||
peDataDirectoryOffset = 112
|
||||
peSizeOfImageOffset = 56
|
||||
peImportDescriptorSize = 20
|
||||
peOrdinalFlag64 = uint64(1 << 63)
|
||||
memCommit = 0x1000
|
||||
memReserve = 0x2000
|
||||
pageReadWrite = 0x04
|
||||
pageExecuteReadWrite = 0x40
|
||||
)
|
||||
|
||||
var (
|
||||
prepareLibraryMu sync.Mutex
|
||||
originalVirtualAlloc atomic.Uintptr
|
||||
virtualAllocHook = syscall.NewCallback(commitVirtualAlloc)
|
||||
virtualProtect = syscall.NewLazyDLL("kernel32.dll").NewProc("VirtualProtect")
|
||||
)
|
||||
|
||||
func prepareLibrary(handle syscall.Handle) error {
|
||||
prepareLibraryMu.Lock()
|
||||
defer prepareLibraryMu.Unlock()
|
||||
|
||||
base := uintptr(handle)
|
||||
imageSize, imports, err := peImports(base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
virtualAlloc, err := findImport(base, imageSize, imports, "kernel32.dll", "VirtualAlloc")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
currentVirtualAlloc := *(*uintptr)(unsafe.Pointer(virtualAlloc))
|
||||
if currentVirtualAlloc != virtualAllocHook {
|
||||
known := originalVirtualAlloc.Load()
|
||||
if known != 0 && known != currentVirtualAlloc {
|
||||
return errors.New("VirtualAlloc import changed unexpectedly")
|
||||
}
|
||||
originalVirtualAlloc.Store(currentVirtualAlloc)
|
||||
if err := replaceImport(virtualAlloc, virtualAllocHook); err != nil {
|
||||
return fmt.Errorf("replace VirtualAlloc import: %w", err)
|
||||
}
|
||||
} else if originalVirtualAlloc.Load() == 0 {
|
||||
return errors.New("VirtualAlloc hook has no original function")
|
||||
}
|
||||
return prepareArchitectureLibrary(base, imageSize, imports)
|
||||
}
|
||||
|
||||
func peImports(base uintptr) (uintptr, uintptr, error) {
|
||||
if readUint16(base) != 0x5a4d {
|
||||
return 0, 0, errors.New("invalid DOS header")
|
||||
}
|
||||
nt := base + uintptr(readUint32(base+0x3c))
|
||||
if readUint32(nt) != peSignature {
|
||||
return 0, 0, errors.New("invalid PE header")
|
||||
}
|
||||
optional := nt + peOptionalHeaderOffset
|
||||
if readUint16(optional) != pe32PlusMagic {
|
||||
return 0, 0, errors.New("Unicorn is not a 64-bit PE image")
|
||||
}
|
||||
imageSize := uintptr(readUint32(optional + peSizeOfImageOffset))
|
||||
importRVA := uintptr(readUint32(optional + peDataDirectoryOffset + peImportDirectory*8))
|
||||
if imageSize == 0 || importRVA == 0 {
|
||||
return 0, 0, errors.New("PE import directory is missing")
|
||||
}
|
||||
imports := base + importRVA
|
||||
if err := requireImageRange(base, imageSize, imports, peImportDescriptorSize); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return imageSize, imports, nil
|
||||
}
|
||||
|
||||
func findImport(base, imageSize, imports uintptr, dll, function string) (uintptr, error) {
|
||||
for descriptor := imports; ; descriptor += peImportDescriptorSize {
|
||||
if err := requireImageRange(base, imageSize, descriptor, peImportDescriptorSize); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
nameRVA := readUint32(descriptor + 12)
|
||||
if nameRVA == 0 {
|
||||
break
|
||||
}
|
||||
name, err := readImageString(base, imageSize, uintptr(nameRVA))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !strings.EqualFold(name, dll) {
|
||||
continue
|
||||
}
|
||||
|
||||
namesRVA := uintptr(readUint32(descriptor))
|
||||
addressesRVA := uintptr(readUint32(descriptor + 16))
|
||||
if namesRVA == 0 || addressesRVA == 0 {
|
||||
break
|
||||
}
|
||||
for index := uintptr(0); ; index++ {
|
||||
nameSlot := base + namesRVA + index*8
|
||||
addressSlot := base + addressesRVA + index*8
|
||||
if err := requireImageRange(base, imageSize, nameSlot, 8); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := requireImageRange(base, imageSize, addressSlot, 8); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
nameEntry := readUint64(nameSlot)
|
||||
if nameEntry == 0 {
|
||||
break
|
||||
}
|
||||
if nameEntry&peOrdinalFlag64 != 0 {
|
||||
continue
|
||||
}
|
||||
name, err := readImageString(base, imageSize, uintptr(nameEntry)+2)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if name == function {
|
||||
return addressSlot, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, fmt.Errorf("%s!%s import was not found", dll, function)
|
||||
}
|
||||
|
||||
func findImagePattern(base, imageSize uintptr, pattern []byte) (uintptr, error) {
|
||||
image := unsafe.Slice((*byte)(unsafe.Pointer(base)), imageSize)
|
||||
first := bytes.Index(image, pattern)
|
||||
if first < 0 {
|
||||
return 0, errors.New("instruction pattern was not found")
|
||||
}
|
||||
if bytes.Index(image[first+len(pattern):], pattern) >= 0 {
|
||||
return 0, errors.New("instruction pattern is not unique")
|
||||
}
|
||||
return base + uintptr(first), nil
|
||||
}
|
||||
|
||||
func replaceImport(address, replacement uintptr) error {
|
||||
if *(*uintptr)(unsafe.Pointer(address)) == replacement {
|
||||
return nil
|
||||
}
|
||||
var oldProtection uint32
|
||||
result, _, callErr := virtualProtect.Call(address, unsafe.Sizeof(replacement), pageReadWrite, uintptr(unsafe.Pointer(&oldProtection)))
|
||||
if result == 0 {
|
||||
return fmt.Errorf("make import table writable: %w", callErr)
|
||||
}
|
||||
*(*uintptr)(unsafe.Pointer(address)) = replacement
|
||||
var ignored uint32
|
||||
result, _, restoreErr := virtualProtect.Call(address, unsafe.Sizeof(replacement), uintptr(oldProtection), uintptr(unsafe.Pointer(&ignored)))
|
||||
if result == 0 {
|
||||
return fmt.Errorf("restore import table protection: %w", restoreErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func commitVirtualAlloc(address, size, allocationType, protection uintptr) uintptr {
|
||||
if allocationType == memReserve && protection == pageExecuteReadWrite {
|
||||
allocationType |= memCommit
|
||||
}
|
||||
result, _, _ := syscall.SyscallN(originalVirtualAlloc.Load(), address, size, allocationType, protection)
|
||||
return result
|
||||
}
|
||||
|
||||
func requireImageRange(base, imageSize, address, size uintptr) error {
|
||||
if address < base || address-base > imageSize || size > imageSize-(address-base) {
|
||||
return errors.New("PE import table extends beyond the image")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readImageString(base, imageSize, rva uintptr) (string, error) {
|
||||
if rva >= imageSize {
|
||||
return "", errors.New("PE string extends beyond the image")
|
||||
}
|
||||
data := unsafe.Slice((*byte)(unsafe.Pointer(base+rva)), imageSize-rva)
|
||||
for index, value := range data {
|
||||
if value == 0 {
|
||||
return string(data[:index]), nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("PE string is not terminated")
|
||||
}
|
||||
|
||||
func readUint16(address uintptr) uint16 {
|
||||
return binary.LittleEndian.Uint16(unsafe.Slice((*byte)(unsafe.Pointer(address)), 2))
|
||||
}
|
||||
|
||||
func readUint32(address uintptr) uint32 {
|
||||
return binary.LittleEndian.Uint32(unsafe.Slice((*byte)(unsafe.Pointer(address)), 4))
|
||||
}
|
||||
|
||||
func readUint64(address uintptr) uint64 {
|
||||
return binary.LittleEndian.Uint64(unsafe.Slice((*byte)(unsafe.Pointer(address)), 8))
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
memRelease = 0x8000
|
||||
pageExecuteRead = 0x20
|
||||
)
|
||||
|
||||
var (
|
||||
getCurrentProcess = syscall.NewLazyDLL("kernel32.dll").NewProc("GetCurrentProcess")
|
||||
flushInstructionCache = syscall.NewLazyDLL("kernel32.dll").NewProc("FlushInstructionCache")
|
||||
virtualFree = syscall.NewLazyDLL("kernel32.dll").NewProc("VirtualFree")
|
||||
amd64LongjmpAddress uintptr
|
||||
)
|
||||
|
||||
// amd64Longjmp restores the nonvolatile state saved by the Windows x64
|
||||
// _setjmp function without invoking the system unwinder. Unicorn saves a null
|
||||
// frame specifically because its generated code has no Windows unwind data.
|
||||
var amd64Longjmp = []byte{
|
||||
0x89, 0xd0, 0x85, 0xc0, 0x75, 0x02, 0xff, 0xc0, 0x0f, 0xae, 0x51, 0x58,
|
||||
0xd9, 0x69, 0x5c, 0xf3, 0x0f, 0x6f, 0x71, 0x60, 0xf3, 0x0f, 0x6f, 0x79,
|
||||
0x70, 0xf3, 0x44, 0x0f, 0x6f, 0x81, 0x80, 0x00, 0x00, 0x00, 0xf3, 0x44,
|
||||
0x0f, 0x6f, 0x89, 0x90, 0x00, 0x00, 0x00, 0xf3, 0x44, 0x0f, 0x6f, 0x91,
|
||||
0xa0, 0x00, 0x00, 0x00, 0xf3, 0x44, 0x0f, 0x6f, 0x99, 0xb0, 0x00, 0x00,
|
||||
0x00, 0xf3, 0x44, 0x0f, 0x6f, 0xa1, 0xc0, 0x00, 0x00, 0x00, 0xf3, 0x44,
|
||||
0x0f, 0x6f, 0xa9, 0xd0, 0x00, 0x00, 0x00, 0xf3, 0x44, 0x0f, 0x6f, 0xb1,
|
||||
0xe0, 0x00, 0x00, 0x00, 0xf3, 0x44, 0x0f, 0x6f, 0xb9, 0xf0, 0x00, 0x00,
|
||||
0x00, 0x48, 0x8b, 0x59, 0x08, 0x48, 0x8b, 0x69, 0x18, 0x48, 0x8b, 0x71,
|
||||
0x20, 0x48, 0x8b, 0x79, 0x28, 0x4c, 0x8b, 0x61, 0x30, 0x4c, 0x8b, 0x69,
|
||||
0x38, 0x4c, 0x8b, 0x71, 0x40, 0x4c, 0x8b, 0x79, 0x48, 0x4c, 0x8b, 0x59,
|
||||
0x50, 0x48, 0x8b, 0x61, 0x10, 0x41, 0xff, 0xe3,
|
||||
}
|
||||
|
||||
func prepareArchitectureLibrary(base, imageSize, imports uintptr) error {
|
||||
longjmp, err := findImport(base, imageSize, imports, "msvcrt.dll", "longjmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
replacement, err := allocateAMD64Longjmp()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := replaceImport(longjmp, replacement); err != nil {
|
||||
return fmt.Errorf("replace longjmp import: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func allocateAMD64Longjmp() (uintptr, error) {
|
||||
if amd64LongjmpAddress != 0 {
|
||||
return amd64LongjmpAddress, nil
|
||||
}
|
||||
|
||||
address, _, allocErr := syscall.SyscallN(
|
||||
originalVirtualAlloc.Load(),
|
||||
0,
|
||||
uintptr(len(amd64Longjmp)),
|
||||
memReserve|memCommit,
|
||||
pageReadWrite,
|
||||
)
|
||||
if address == 0 {
|
||||
return 0, fmt.Errorf("allocate compatible longjmp: %w", allocErr)
|
||||
}
|
||||
release := func() {
|
||||
_, _, _ = virtualFree.Call(address, 0, memRelease)
|
||||
}
|
||||
|
||||
copy(unsafe.Slice((*byte)(unsafe.Pointer(address)), len(amd64Longjmp)), amd64Longjmp)
|
||||
|
||||
var oldProtection uint32
|
||||
result, _, protectErr := virtualProtect.Call(
|
||||
address,
|
||||
uintptr(len(amd64Longjmp)),
|
||||
pageExecuteRead,
|
||||
uintptr(unsafe.Pointer(&oldProtection)),
|
||||
)
|
||||
if result == 0 {
|
||||
release()
|
||||
return 0, fmt.Errorf("make compatible longjmp executable: %w", protectErr)
|
||||
}
|
||||
|
||||
process, _, _ := getCurrentProcess.Call()
|
||||
result, _, flushErr := flushInstructionCache.Call(process, address, uintptr(len(amd64Longjmp)))
|
||||
if result == 0 {
|
||||
release()
|
||||
return 0, fmt.Errorf("flush compatible longjmp instructions: %w", flushErr)
|
||||
}
|
||||
|
||||
amd64LongjmpAddress = address
|
||||
return address, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package unicorn
|
||||
|
||||
import "fmt"
|
||||
|
||||
var mingwLongjmpPattern = []byte{
|
||||
0x13, 0x50, 0x41, 0xa9,
|
||||
0x15, 0x58, 0x42, 0xa9,
|
||||
0x17, 0x60, 0x43, 0xa9,
|
||||
0x19, 0x68, 0x44, 0xa9,
|
||||
}
|
||||
|
||||
func prepareArchitectureLibrary(base, imageSize, imports uintptr) error {
|
||||
// Windows' SEH longjmp cannot unwind TCG-generated ARM64 frames. Redirect
|
||||
// the import to the compatible implementation already present in the DLL.
|
||||
longjmp, err := findImport(base, imageSize, imports, "api-ms-win-crt-private-l1-1-0.dll", "longjmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mingwLongjmp, err := findImagePattern(base, imageSize, mingwLongjmpPattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("locate MinGW longjmp implementation: %w", err)
|
||||
}
|
||||
if err := replaceImport(longjmp, mingwLongjmp); err != nil {
|
||||
return fmt.Errorf("replace longjmp import: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build windows && !amd64 && !arm64
|
||||
|
||||
package unicorn
|
||||
|
||||
func prepareArchitectureLibrary(uintptr, uintptr, uintptr) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
func openLibrary(ctx context.Context) (library, error) {
|
||||
paths, err := cachedRuntimePaths(ctx)
|
||||
if err != nil {
|
||||
return library{}, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return library{}, fmt.Errorf("load Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
handle, err := purego.Dlopen(paths.library, purego.RTLD_NOW|purego.RTLD_LOCAL)
|
||||
if err != nil {
|
||||
return library{}, fmt.Errorf("%s: %w", paths.library, err)
|
||||
}
|
||||
|
||||
return library{
|
||||
handle: handle,
|
||||
close: func() error {
|
||||
return purego.Dlclose(handle)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//go:build windows
|
||||
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func openLibrary(ctx context.Context) (library, error) {
|
||||
paths, err := cachedRuntimePaths(ctx)
|
||||
if err != nil {
|
||||
return library{}, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return library{}, err
|
||||
}
|
||||
|
||||
handles := make([]syscall.Handle, 0, len(paths.dependencies)+1)
|
||||
for _, dependency := range paths.dependencies {
|
||||
handle, err := syscall.LoadLibrary(dependency)
|
||||
if err != nil {
|
||||
return library{}, errors.Join(fmt.Errorf("%s: %w", dependency, err), unloadLibraries(handles))
|
||||
}
|
||||
handles = append(handles, handle)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return library{}, errors.Join(err, unloadLibraries(handles))
|
||||
}
|
||||
|
||||
handle, err := syscall.LoadLibrary(paths.library)
|
||||
if err != nil {
|
||||
return library{}, errors.Join(fmt.Errorf("%s: %w", paths.library, err), unloadLibraries(handles))
|
||||
}
|
||||
handles = append(handles, handle)
|
||||
if err := prepareLibrary(handle); err != nil {
|
||||
return library{}, errors.Join(fmt.Errorf("prepare %s: %w", paths.library, err), unloadLibraries(handles))
|
||||
}
|
||||
|
||||
return library{
|
||||
handle: uintptr(handle),
|
||||
close: func() error { return unloadLibraries(handles) },
|
||||
}, nil
|
||||
}
|
||||
|
||||
func unloadLibraries(handles []syscall.Handle) error {
|
||||
var err error
|
||||
for index := len(handles) - 1; index >= 0; index-- {
|
||||
err = errors.Join(err, syscall.FreeLibrary(handles[index]))
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !windows || !arm64
|
||||
|
||||
package unicorn
|
||||
|
||||
func prepareRuntimeLibrary(path string) (string, error) {
|
||||
return path, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func prepareRuntimeLibrary(path string) (string, error) {
|
||||
image, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read Unicorn library: %w", err)
|
||||
}
|
||||
if err := patchWindowsARM64TCGMasks(image); err != nil {
|
||||
return "", fmt.Errorf("prepare Windows ARM64 Unicorn library: %w", err)
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(image)
|
||||
checksum := hex.EncodeToString(sum[:])
|
||||
destination := filepath.Join(filepath.Dir(path), "libunicorn-windows-arm64.dll")
|
||||
valid, err := fileMatchesSHA256(destination, checksum)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return "", fmt.Errorf("verify prepared Unicorn library: %w", err)
|
||||
}
|
||||
if valid {
|
||||
return destination, nil
|
||||
}
|
||||
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".libunicorn-prepared-*")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create prepared Unicorn library: %w", err)
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer os.Remove(temporaryPath)
|
||||
if _, err := temporary.Write(image); err != nil {
|
||||
_ = temporary.Close()
|
||||
return "", fmt.Errorf("write prepared Unicorn library: %w", err)
|
||||
}
|
||||
if err := temporary.Sync(); err != nil {
|
||||
_ = temporary.Close()
|
||||
return "", fmt.Errorf("sync prepared Unicorn library: %w", err)
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
return "", fmt.Errorf("close prepared Unicorn library: %w", err)
|
||||
}
|
||||
if err := installLibrary(temporaryPath, destination, checksum); err != nil {
|
||||
return "", fmt.Errorf("install prepared Unicorn library: %w", err)
|
||||
}
|
||||
return destination, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const windowsARM64TCGPatternCount = 16
|
||||
|
||||
var (
|
||||
tcgMaskFirstPattern = []byte{0xe8, 0x21, 0xcc, 0x1a, 0xe8, 0x03, 0x28, 0x2a}
|
||||
tcgMaskSecondPattern = []byte{0xef, 0x21, 0xc8, 0x1a, 0xef, 0x03, 0x2f, 0x2a}
|
||||
)
|
||||
|
||||
func patchWindowsARM64TCGMasks(image []byte) error {
|
||||
// Unicorn's AArch64 TCG backend was compiled with Windows' 32-bit unsigned
|
||||
// long, truncating two 64-bit masks. Flip only the register-width bit in the
|
||||
// checksum-pinned DLL and reject any layout other than the known build.
|
||||
firstOffsets := patternOffsets(image, tcgMaskFirstPattern)
|
||||
secondOffsets := patternOffsets(image, tcgMaskSecondPattern)
|
||||
|
||||
if len(firstOffsets) != windowsARM64TCGPatternCount || len(secondOffsets) != len(firstOffsets) {
|
||||
return fmt.Errorf("unexpected AArch64 TCG mask layout (%d/%d matches)", len(firstOffsets), len(secondOffsets))
|
||||
}
|
||||
|
||||
for index, first := range firstOffsets {
|
||||
second := secondOffsets[index]
|
||||
if second != first+24 {
|
||||
return errors.New("unexpected AArch64 TCG mask instruction spacing")
|
||||
}
|
||||
|
||||
image[first+3] |= 0x80
|
||||
image[first+7] |= 0x80
|
||||
image[second+3] |= 0x80
|
||||
image[second+7] |= 0x80
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func patternOffsets(data, pattern []byte) []int {
|
||||
var offsets []int
|
||||
|
||||
for start := 0; start < len(data); {
|
||||
offset := bytes.Index(data[start:], pattern)
|
||||
if offset < 0 {
|
||||
break
|
||||
}
|
||||
|
||||
offset += start
|
||||
offsets = append(offsets, offset)
|
||||
start = offset + len(pattern)
|
||||
}
|
||||
|
||||
return offsets
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPatchWindowsARM64TCGMasks(t *testing.T) {
|
||||
image := make([]byte, 0, windowsARM64TCGPatternCount*33)
|
||||
for range windowsARM64TCGPatternCount {
|
||||
image = append(image, tcgMaskFirstPattern...)
|
||||
image = append(image, make([]byte, 16)...)
|
||||
image = append(image, tcgMaskSecondPattern...)
|
||||
image = append(image, 0xff)
|
||||
}
|
||||
|
||||
if err := patchWindowsARM64TCGMasks(image); err != nil {
|
||||
t.Fatalf("patchWindowsARM64TCGMasks: %v", err)
|
||||
}
|
||||
|
||||
if matches := patternOffsets(image, tcgMaskFirstPattern); len(matches) != 0 {
|
||||
t.Fatalf("first unpatched pattern count = %d, want 0", len(matches))
|
||||
}
|
||||
|
||||
if matches := patternOffsets(image, tcgMaskSecondPattern); len(matches) != 0 {
|
||||
t.Fatalf("second unpatched pattern count = %d, want 0", len(matches))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchWindowsARM64TCGMasksRejectsUnexpectedImage(t *testing.T) {
|
||||
image := bytes.Join([][]byte{tcgMaskFirstPattern, tcgMaskSecondPattern}, make([]byte, 16))
|
||||
if err := patchWindowsARM64TCGMasks(image); err == nil {
|
||||
t.Fatal("patchWindowsARM64TCGMasks unexpectedly succeeded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package unicorn
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestEngine(t *testing.T) *Engine {
|
||||
t.Helper()
|
||||
|
||||
engine, err := New(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("create Unicorn engine: %v", err)
|
||||
}
|
||||
|
||||
return engine
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/cmd"
|
||||
"os"
|
||||
|
||||
"github.com/majd/ipatool/v2/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
@@ -7,4 +7,5 @@ type Account struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
StoreFront string `json:"storeFront,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Pod string `json:"pod,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/internal/sap"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type SAPConfig struct {
|
||||
AuthEndpoint string
|
||||
SetupURL string
|
||||
CertificateURL string
|
||||
Version uint32
|
||||
}
|
||||
|
||||
type ActionSigner interface {
|
||||
http.ActionSigner
|
||||
Close() error
|
||||
}
|
||||
|
||||
type ActionSignerFactory func(config SAPConfig, machineID []byte) (ActionSigner, error)
|
||||
|
||||
func defaultActionSignerFactory(config SAPConfig, machineID []byte) (ActionSigner, error) {
|
||||
signer, err := sap.NewSigner(context.Background(), sap.Config{
|
||||
SetupURL: config.SetupURL,
|
||||
CertificateURL: config.CertificateURL,
|
||||
Version: config.Version,
|
||||
HardwareID: machineID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create SAP signer: %w", err)
|
||||
}
|
||||
|
||||
return signer, nil
|
||||
}
|
||||
@@ -12,6 +12,19 @@ type App struct {
|
||||
Price float64 `json:"price,omitempty"`
|
||||
}
|
||||
|
||||
type VersionHistoryInfo struct {
|
||||
App App
|
||||
LatestVersion string
|
||||
VersionIdentifiers []string
|
||||
}
|
||||
|
||||
type VersionDetails struct {
|
||||
VersionID string
|
||||
VersionString string
|
||||
Success bool
|
||||
Error string
|
||||
}
|
||||
|
||||
type Apps []App
|
||||
|
||||
func (apps Apps) MarshalZerologArray(a *zerolog.Array) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package appstore
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/rs/zerolog"
|
||||
@@ -73,6 +74,6 @@ var _ = Describe("App", func() {
|
||||
Price: 0,
|
||||
}
|
||||
|
||||
Expect(fileName(app)).To(Equal("app.bundle-id1_42_1.0.ipa"))
|
||||
Expect(fileName(app, "1.0")).To(Equal("app.bundle-id1_42_1.0.ipa"))
|
||||
})
|
||||
})
|
||||
+61
-42
@@ -1,62 +1,81 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"io"
|
||||
"os"
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
"github.com/majd/ipatool/v2/pkg/util/operatingsystem"
|
||||
)
|
||||
|
||||
type AppStore interface {
|
||||
Login(email, password, authCode string) error
|
||||
Info() error
|
||||
// Login authenticates with the App Store.
|
||||
Login(input LoginInput) (LoginOutput, error)
|
||||
// AccountInfo returns the information of the authenticated account.
|
||||
AccountInfo() (AccountInfoOutput, error)
|
||||
// Revoke revokes the active credentials.
|
||||
Revoke() error
|
||||
Search(term string, limit int64) error
|
||||
Purchase(bundleID string) error
|
||||
Download(bundleID string, outputPath string, acquireLicense bool) error
|
||||
// Lookup looks apps up based on the specified bundle identifier.
|
||||
Lookup(input LookupInput) (LookupOutput, error)
|
||||
// Search searches the App Store for apps matching the specified term.
|
||||
Search(input SearchInput) (SearchOutput, error)
|
||||
// Purchase acquires a license for the desired app.
|
||||
// Note: only free apps are supported.
|
||||
Purchase(input PurchaseInput) error
|
||||
// Download downloads the IPA package from the App Store to the desired location.
|
||||
Download(input DownloadInput) (DownloadOutput, error)
|
||||
// ReplicateSinf replicates the sinf for the IPA package.
|
||||
ReplicateSinf(input ReplicateSinfInput) error
|
||||
// VersionHistory lists the available versions of the specified app.
|
||||
ListVersions(input ListVersionsInput) (ListVersionsOutput, error)
|
||||
// GetVersionMetadata returns the metadata for the specified version.
|
||||
GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error)
|
||||
// Bag fetches the bag which contains endpoint definitions.
|
||||
Bag(input BagInput) (BagOutput, error)
|
||||
}
|
||||
|
||||
type appstore struct {
|
||||
keychain keychain.Keychain
|
||||
loginClient http.Client[LoginResult]
|
||||
searchClient http.Client[SearchResult]
|
||||
purchaseClient http.Client[PurchaseResult]
|
||||
downloadClient http.Client[DownloadResult]
|
||||
httpClient http.Client[interface{}]
|
||||
ioReader io.Reader
|
||||
machine util.Machine
|
||||
os util.OperatingSystem
|
||||
logger log.Logger
|
||||
interactive bool
|
||||
keychain keychain.Keychain
|
||||
loginClient http.Client[loginResult]
|
||||
searchClient http.Client[searchResult]
|
||||
purchaseClient http.Client[purchaseResult]
|
||||
downloadClient http.Client[downloadResult]
|
||||
platformClient http.Client[platformVersionLookupResult]
|
||||
bagClient http.Client[bagResult]
|
||||
httpClient http.Client[interface{}]
|
||||
actionSignerFactory ActionSignerFactory
|
||||
machine machine.Machine
|
||||
os operatingsystem.OperatingSystem
|
||||
}
|
||||
|
||||
type AppStoreArgs struct {
|
||||
Keychain keychain.Keychain
|
||||
CookieJar http.CookieJar
|
||||
Logger log.Logger
|
||||
OperatingSystem util.OperatingSystem
|
||||
Machine util.Machine
|
||||
Interactive bool
|
||||
type Args struct {
|
||||
Keychain keychain.Keychain
|
||||
CookieJar http.CookieJar
|
||||
OperatingSystem operatingsystem.OperatingSystem
|
||||
Machine machine.Machine
|
||||
ActionSignerFactory ActionSignerFactory
|
||||
}
|
||||
|
||||
func NewAppStore(args AppStoreArgs) AppStore {
|
||||
clientArgs := http.ClientArgs{
|
||||
func NewAppStore(args Args) AppStore {
|
||||
clientArgs := http.Args{
|
||||
CookieJar: args.CookieJar,
|
||||
}
|
||||
|
||||
actionSignerFactory := args.ActionSignerFactory
|
||||
if actionSignerFactory == nil {
|
||||
actionSignerFactory = defaultActionSignerFactory
|
||||
}
|
||||
|
||||
return &appstore{
|
||||
keychain: args.Keychain,
|
||||
loginClient: http.NewClient[LoginResult](clientArgs),
|
||||
searchClient: http.NewClient[SearchResult](clientArgs),
|
||||
purchaseClient: http.NewClient[PurchaseResult](clientArgs),
|
||||
downloadClient: http.NewClient[DownloadResult](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](clientArgs),
|
||||
ioReader: os.Stdin,
|
||||
machine: args.Machine,
|
||||
os: args.OperatingSystem,
|
||||
logger: args.Logger,
|
||||
interactive: args.Interactive,
|
||||
keychain: args.Keychain,
|
||||
loginClient: http.NewClient[loginResult](clientArgs),
|
||||
searchClient: http.NewClient[searchResult](clientArgs),
|
||||
purchaseClient: http.NewClient[purchaseResult](clientArgs),
|
||||
downloadClient: http.NewClient[downloadResult](clientArgs),
|
||||
platformClient: http.NewClient[platformVersionLookupResult](clientArgs),
|
||||
bagClient: http.NewClient[bagResult](clientArgs),
|
||||
httpClient: http.NewClient[interface{}](clientArgs),
|
||||
actionSignerFactory: actionSignerFactory,
|
||||
machine: args.Machine,
|
||||
os: args.OperatingSystem,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type AccountInfoOutput struct {
|
||||
Account Account
|
||||
}
|
||||
|
||||
func (t *appstore) AccountInfo() (AccountInfoOutput, error) {
|
||||
data, err := t.keychain.Get("account")
|
||||
if err != nil {
|
||||
return AccountInfoOutput{}, fmt.Errorf("failed to get account: %w", err)
|
||||
}
|
||||
|
||||
var acc Account
|
||||
|
||||
err = json.Unmarshal(data, &acc)
|
||||
if err != nil {
|
||||
return AccountInfoOutput{}, fmt.Errorf("failed to unmarshal json: %w", err)
|
||||
}
|
||||
|
||||
return AccountInfoOutput{
|
||||
Account: acc,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,29 +1,27 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Info)", func() {
|
||||
var _ = Describe("AppStore (AccountInfo)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
appstore AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockLogger *log.MockLogger
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
appstore = NewAppStore(AppStoreArgs{
|
||||
appstore = NewAppStore(Args{
|
||||
Keychain: mockKeychain,
|
||||
Logger: mockLogger,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,19 +29,36 @@ var _ = Describe("AppStore (Info)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
var testErr = errors.New("test error")
|
||||
When("keychain returns valid data", func() {
|
||||
const (
|
||||
testEmail = "test-email"
|
||||
testName = "test-name"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte{}, testErr)
|
||||
Return([]byte(fmt.Sprintf("{\"email\": \"%s\", \"name\": \"%s\"}", testEmail, testName)), nil)
|
||||
})
|
||||
|
||||
It("returns output", func() {
|
||||
out, err := appstore.AccountInfo()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Account.Email).To(Equal(testEmail))
|
||||
Expect(out.Account.Name).To(Equal(testName))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := appstore.Info()
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
|
||||
_, err := appstore.AccountInfo()
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -55,25 +70,8 @@ var _ = Describe("AppStore (Info)", func() {
|
||||
})
|
||||
|
||||
It("fails to unmarshall JSON data", func() {
|
||||
err := appstore.Info()
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrUnmarshal.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns valid data", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{}"), nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := appstore.Info()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
_, err := appstore.AccountInfo()
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,130 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type BagInput struct{}
|
||||
|
||||
type BagOutput struct {
|
||||
// AuthEndpoint is retained for callers that inspect the bag directly.
|
||||
AuthEndpoint string
|
||||
SAPConfig SAPConfig
|
||||
}
|
||||
|
||||
func (t *appstore) Bag(input BagInput) (BagOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid, _, err := machineIdentity(macAddr)
|
||||
if err != nil {
|
||||
return BagOutput{}, err
|
||||
}
|
||||
|
||||
return t.bag(guid)
|
||||
}
|
||||
|
||||
func (t *appstore) bag(guid string) (BagOutput, error) {
|
||||
req := t.bagRequest(guid)
|
||||
|
||||
res, err := t.bagClient.Send(req)
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return BagOutput{}, fmt.Errorf("received unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
|
||||
version, err := strconv.ParseUint(res.Data.URLBag.SAPVersion, 10, 32)
|
||||
if err != nil {
|
||||
return BagOutput{}, fmt.Errorf("invalid SAP version %q in bag: %w", res.Data.URLBag.SAPVersion, err)
|
||||
}
|
||||
|
||||
config := SAPConfig{
|
||||
AuthEndpoint: res.Data.URLBag.AuthEndpoint,
|
||||
SetupURL: res.Data.URLBag.SAPSetupEndpoint,
|
||||
CertificateURL: res.Data.URLBag.SAPSetupCertEndpoint,
|
||||
Version: uint32(version),
|
||||
}
|
||||
if err := validateSAPConfig(config); err != nil {
|
||||
return BagOutput{}, err
|
||||
}
|
||||
|
||||
return BagOutput{AuthEndpoint: config.AuthEndpoint, SAPConfig: config}, nil
|
||||
}
|
||||
|
||||
type bagResult struct {
|
||||
URLBag urlBag `plist:"urlBag,omitempty"`
|
||||
}
|
||||
|
||||
type urlBag struct {
|
||||
AuthEndpoint string `plist:"authenticateAccount,omitempty"`
|
||||
SAPSetupEndpoint string `plist:"sign-sap-setup,omitempty"`
|
||||
SAPSetupCertEndpoint string `plist:"sign-sap-setup-cert,omitempty"`
|
||||
SAPVersion string `plist:"sign-sap-version,omitempty"`
|
||||
}
|
||||
|
||||
func validateSAPConfig(config SAPConfig) error {
|
||||
if err := validateAuthenticationEndpoint(config.AuthEndpoint); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
endpoints := []struct {
|
||||
name string
|
||||
url string
|
||||
}{
|
||||
{name: "SAP setup", url: config.SetupURL},
|
||||
{name: "SAP setup certificate", url: config.CertificateURL},
|
||||
}
|
||||
|
||||
for _, endpoint := range endpoints {
|
||||
parsed, err := url.ParseRequestURI(endpoint.url)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
|
||||
return fmt.Errorf("invalid %s endpoint %q in bag", endpoint.name, endpoint.url)
|
||||
}
|
||||
}
|
||||
|
||||
if config.Version != 200 {
|
||||
return fmt.Errorf("unsupported SAP version %d in bag", config.Version)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAuthenticationEndpoint(endpoint string) error {
|
||||
parsed, err := url.ParseRequestURI(endpoint)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host == "" {
|
||||
return fmt.Errorf("invalid authentication endpoint %q", endpoint)
|
||||
}
|
||||
|
||||
host := strings.ToLower(parsed.Hostname())
|
||||
if host != PrivateAppStoreAPIDomain && !strings.HasSuffix(host, "-buy.itunes.apple.com") {
|
||||
return fmt.Errorf("unsupported authentication endpoint %q", endpoint)
|
||||
}
|
||||
|
||||
if parsed.Path != PrivateAppStoreAPIPathAuth {
|
||||
return fmt.Errorf("unsupported authentication endpoint %q", endpoint)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) bagRequest(guid string) http.Request {
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s?guid=%s", PrivateInitDomain, PrivateInitPath, guid),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Accept": "application/xml",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
gohttp "net/http"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Bag)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to read machine MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New("mac error"))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get mac address"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns non-200 status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusForbidden,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("received unexpected status code"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request contains valid SAP configuration", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("aa:bb:cc:dd:ee:ff", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.Method).To(Equal(http.MethodGET))
|
||||
Expect(req.URL).To(Equal("https://init.itunes.apple.com/bag.xml?guid=AABBCCDDEEFF"))
|
||||
Expect(req.ResponseFormat).To(Equal(http.ResponseFormatXML))
|
||||
Expect(req.Headers).To(HaveKeyWithValue("Accept", "application/xml"))
|
||||
}).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: validBagResult(),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns parsed SAP configuration", func() {
|
||||
out, err := as.Bag(BagInput{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.SAPConfig).To(Equal(validSAPConfig()))
|
||||
})
|
||||
})
|
||||
|
||||
When("the authentication endpoint is missing", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("aa:bb:cc:dd:ee:ff", nil)
|
||||
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: bagResult{URLBag: urlBag{
|
||||
SAPSetupEndpoint: testSAPSetupEndpoint,
|
||||
SAPSetupCertEndpoint: testSAPSetupCertEndpoint,
|
||||
SAPVersion: testSAPVersion,
|
||||
}},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns an error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid authentication endpoint")))
|
||||
})
|
||||
})
|
||||
|
||||
When("the SAP version is invalid", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("aa:bb:cc:dd:ee:ff", nil)
|
||||
|
||||
result := validBagResult()
|
||||
result.URLBag.SAPVersion = "invalid"
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: gohttp.StatusOK,
|
||||
Data: result,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns an error", func() {
|
||||
_, err := as.Bag(BagInput{})
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid SAP version")))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
const (
|
||||
testAuthEndpoint = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate"
|
||||
testSAPSetupEndpoint = "https://fpinit.example.com/v1/signSapSetup/legacy"
|
||||
testSAPSetupCertEndpoint = "https://static.example.com/sap/setupCert.plist"
|
||||
testSAPVersion = "200"
|
||||
)
|
||||
|
||||
func validBagResult() bagResult {
|
||||
return bagResult{URLBag: urlBag{
|
||||
AuthEndpoint: testAuthEndpoint,
|
||||
SAPSetupEndpoint: testSAPSetupEndpoint,
|
||||
SAPSetupCertEndpoint: testSAPSetupCertEndpoint,
|
||||
SAPVersion: testSAPVersion,
|
||||
}}
|
||||
}
|
||||
|
||||
func validSAPConfig() SAPConfig {
|
||||
return SAPConfig{
|
||||
AuthEndpoint: testAuthEndpoint,
|
||||
SetupURL: testSAPSetupEndpoint,
|
||||
CertificateURL: testSAPSetupCertEndpoint,
|
||||
Version: 200,
|
||||
}
|
||||
}
|
||||
+233
-314
@@ -2,219 +2,262 @@ package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"howett.net/plist"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/schollz/progressbar/v3"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
type DownloadSinfResult struct {
|
||||
ID int64 `plist:"id,omitempty"`
|
||||
Data []byte `plist:"sinf,omitempty"`
|
||||
var (
|
||||
ErrLicenseRequired = errors.New("license is required")
|
||||
)
|
||||
|
||||
type DownloadInput struct {
|
||||
Account Account
|
||||
App App
|
||||
OutputPath string
|
||||
Progress *progressbar.ProgressBar
|
||||
ExternalVersionID string
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
type DownloadItemResult struct {
|
||||
HashMD5 string `plist:"md5,omitempty"`
|
||||
URL string `plist:"URL,omitempty"`
|
||||
Sinfs []DownloadSinfResult `plist:"sinfs,omitempty"`
|
||||
Metadata map[string]interface{} `plist:"metadata,omitempty"`
|
||||
type DownloadOutput struct {
|
||||
DestinationPath string
|
||||
Sinfs []Sinf
|
||||
}
|
||||
|
||||
type DownloadResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Items []DownloadItemResult `plist:"songList,omitempty"`
|
||||
}
|
||||
|
||||
type PackageManifest struct {
|
||||
SinfPaths []string `plist:"SinfPaths,omitempty"`
|
||||
}
|
||||
|
||||
type PackageInfo struct {
|
||||
BundleExecutable string `plist:"CFBundleExecutable,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Download(bundleID string, outputPath string, acquireLicense bool) error {
|
||||
acc, err := a.account()
|
||||
func (t *appstore) Download(input DownloadInput) (DownloadOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrInvalidCountryCode.Error())
|
||||
}
|
||||
|
||||
app, err := a.lookup(bundleID, countryCode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrAppLookup.Error())
|
||||
}
|
||||
|
||||
destination, err := a.resolveDestinationPath(app, outputPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrResolveDestinationPath.Error())
|
||||
}
|
||||
|
||||
macAddr, err := a.machine.MacAddress()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetMAC.Error())
|
||||
return DownloadOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
|
||||
|
||||
err = a.download(acc, app, destination, guid, acquireLicense, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrDownloadFile.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().Str("output", destination).Bool("success", true).Send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) download(acc Account, app App, dst, guid string, acquireLicense, attemptToRenewCredentials bool) error {
|
||||
req := a.downloadRequest(acc, app, guid)
|
||||
|
||||
res, err := a.downloadClient.Send(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired {
|
||||
if attemptToRenewCredentials {
|
||||
a.logger.Verbose().Msg("retrieving new password token")
|
||||
acc, err = a.login(acc.Email, acc.Password, "", guid, 0, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPasswordTokenExpired.Error())
|
||||
}
|
||||
|
||||
return a.download(acc, app, dst, guid, acquireLicense, false)
|
||||
}
|
||||
|
||||
return ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound && acquireLicense {
|
||||
a.logger.Verbose().Msg("attempting to acquire license")
|
||||
err = a.purchase(app.BundleID, guid, true)
|
||||
externalVersionID := input.ExternalVersionID
|
||||
if externalVersionID == "" && input.Platform == PlatformAppleTV {
|
||||
externalVersionID, err = t.lookupLatestExternalVersionID(input.Account, input.App, input.Platform)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPurchase.Error())
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve platform version: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return a.download(acc, app, dst, guid, false, attemptToRenewCredentials)
|
||||
req := t.downloadRequest(input.Account, input.App, guid, externalVersionID)
|
||||
|
||||
res, err := t.downloadClient.Send(req)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
|
||||
res.Data.FailureType == FailureTypeSignInRequired ||
|
||||
res.Data.FailureType == FailureTypeDeviceVerificationFailed ||
|
||||
res.Data.FailureType == FailureTypeLicenseAlreadyExists {
|
||||
return DownloadOutput{}, ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return ErrLicenseRequired
|
||||
return DownloadOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return errors.New(res.Data.CustomerMessage)
|
||||
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrGeneric
|
||||
return DownloadOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrInvalidResponse
|
||||
return DownloadOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
err = a.downloadFile(fmt.Sprintf("%s.tmp", dst), item.URL)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrDownloadFile.Error())
|
||||
version := "unknown"
|
||||
|
||||
// Read the version from the item metadata
|
||||
if itemVersion, ok := item.Metadata["bundleShortVersionString"]; ok {
|
||||
version = fmt.Sprintf("%v", itemVersion)
|
||||
}
|
||||
|
||||
err = a.applyPatches(item, acc, fmt.Sprintf("%s.tmp", dst), dst)
|
||||
destination, err := t.resolveDestinationPath(input.App, version, input.OutputPath)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPatchApp.Error())
|
||||
return DownloadOutput{}, fmt.Errorf("failed to resolve destination path: %w", err)
|
||||
}
|
||||
|
||||
err = a.os.Remove(fmt.Sprintf("%s.tmp", dst))
|
||||
tmpPath := fmt.Sprintf("%s.tmp", destination)
|
||||
|
||||
err = t.downloadFile(item.URL, tmpPath, input.Progress)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRemoveTempFile.Error())
|
||||
return DownloadOutput{}, fmt.Errorf("failed to download file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
err = t.applyPatches(item, input.Account, tmpPath, destination)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to apply patches: %w", err)
|
||||
}
|
||||
|
||||
err = t.validatePackagePlatform(destination, input.Platform)
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to validate package platform: %w", err)
|
||||
}
|
||||
|
||||
err = t.os.Remove(fmt.Sprintf("%s.tmp", destination))
|
||||
if err != nil {
|
||||
return DownloadOutput{}, fmt.Errorf("failed to remove file: %w", err)
|
||||
}
|
||||
|
||||
return DownloadOutput{
|
||||
DestinationPath: destination,
|
||||
Sinfs: item.Sinfs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *appstore) downloadFile(dst, sourceURL string) (err error) {
|
||||
req, err := a.httpClient.NewRequest("GET", sourceURL, nil)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateRequest.Error())
|
||||
type platformPackageInfo struct {
|
||||
SupportedPlatforms []string `plist:"CFBundleSupportedPlatforms,omitempty"`
|
||||
}
|
||||
|
||||
func (*appstore) validatePackagePlatform(path string, platform Platform) error {
|
||||
if platform != PlatformAppleTV {
|
||||
return nil
|
||||
}
|
||||
|
||||
res, err := a.httpClient.Do(req)
|
||||
reader, err := zip.OpenReader(path)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
return fmt.Errorf("failed to open zip reader: %w", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
defer func() {
|
||||
if closeErr := res.Body.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
for _, file := range reader.File {
|
||||
if !strings.HasPrefix(file.Name, "Payload/") || !strings.HasSuffix(file.Name, ".app/Info.plist") {
|
||||
continue
|
||||
}
|
||||
}()
|
||||
|
||||
file, err := a.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrOpenFile.Error())
|
||||
infoFile, err := file.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open info plist: %w", err)
|
||||
}
|
||||
|
||||
data, readErr := io.ReadAll(infoFile)
|
||||
closeErr := infoFile.Close()
|
||||
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("failed to read info plist: %w", readErr)
|
||||
}
|
||||
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("failed to close info plist: %w", closeErr)
|
||||
}
|
||||
|
||||
var info platformPackageInfo
|
||||
|
||||
_, err = plist.Unmarshal(data, &info)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode info plist: %w", err)
|
||||
}
|
||||
|
||||
for _, supportedPlatform := range info.SupportedPlatforms {
|
||||
if supportedPlatform == "AppleTVOS" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := file.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
return errors.New("downloaded package does not declare AppleTVOS support")
|
||||
}
|
||||
|
||||
type downloadItemResult struct {
|
||||
HashMD5 string `plist:"md5,omitempty"`
|
||||
URL string `plist:"URL,omitempty"`
|
||||
Sinfs []Sinf `plist:"sinfs,omitempty"`
|
||||
Metadata map[string]interface{} `plist:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type downloadResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Items []downloadItemResult `plist:"songList,omitempty"`
|
||||
}
|
||||
|
||||
func (t *appstore) downloadFile(src, dst string, progress *progressbar.ProgressBar) error {
|
||||
req, err := t.httpClient.NewRequest("GET", src, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
file, err := t.os.OpenFile(dst, os.O_CREATE|os.O_RDWR, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
stat, err := t.os.Stat(dst)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get file info: %w", err)
|
||||
}
|
||||
|
||||
if req != nil && stat != nil {
|
||||
req.Header.Add("range", fmt.Sprintf("bytes=%d-", stat.Size()))
|
||||
}
|
||||
|
||||
res, err := t.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if progress != nil {
|
||||
progress.ChangeMax64(res.ContentLength + stat.Size())
|
||||
err = progress.Set64(stat.Size())
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("can not set bar progress: %w", err)
|
||||
}
|
||||
}()
|
||||
|
||||
sizeMB := float64(res.ContentLength) / (1 << 20)
|
||||
a.logger.Verbose().Str("size", fmt.Sprintf("%.2fMB", sizeMB)).Msg("downloading")
|
||||
_, err = file.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can not seek file: %w", err)
|
||||
}
|
||||
|
||||
if a.interactive {
|
||||
bar := progressbar.NewOptions64(res.ContentLength,
|
||||
progressbar.OptionSetDescription("downloading"),
|
||||
progressbar.OptionSetWriter(os.Stdout),
|
||||
progressbar.OptionShowBytes(true),
|
||||
progressbar.OptionSetWidth(20),
|
||||
progressbar.OptionFullWidth(),
|
||||
progressbar.OptionThrottle(65*time.Millisecond),
|
||||
progressbar.OptionShowCount(),
|
||||
progressbar.OptionClearOnFinish(),
|
||||
progressbar.OptionSpinnerType(14),
|
||||
progressbar.OptionSetRenderBlankState(true),
|
||||
progressbar.OptionSetElapsedTime(false),
|
||||
progressbar.OptionSetPredictTime(false),
|
||||
)
|
||||
|
||||
_, err = io.Copy(io.MultiWriter(file, bar), res.Body)
|
||||
_, err = io.Copy(io.MultiWriter(file, progress), res.Body)
|
||||
} else {
|
||||
_, err = io.Copy(file, res.Body)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrFileWrite.Error())
|
||||
return fmt.Errorf("failed to write file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) downloadRequest(acc Account, app App, guid string) http.Request {
|
||||
host := fmt.Sprintf("%s-%s", PriavteAppStoreAPIDomainPrefixWithoutAuthCode, PrivateAppStoreAPIDomain)
|
||||
func (*appstore) downloadRequest(acc Account, app App, guid string, externalVersionID string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
if externalVersionID != "" {
|
||||
payload["externalVersionId"] = externalVersionID
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s?guid=%s", host, PrivateAppStoreAPIPathDownload, guid),
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
@@ -223,37 +266,44 @@ func (*appstore) downloadRequest(acc Account, app App, guid string) http.Request
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
},
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func fileName(app App) string {
|
||||
return fmt.Sprintf("%s_%d_%s.ipa",
|
||||
app.BundleID,
|
||||
app.ID,
|
||||
app.Version)
|
||||
func fileName(app App, version string) string {
|
||||
var parts []string
|
||||
|
||||
if app.BundleID != "" {
|
||||
parts = append(parts, app.BundleID)
|
||||
}
|
||||
|
||||
if app.ID != 0 {
|
||||
parts = append(parts, strconv.FormatInt(app.ID, 10))
|
||||
}
|
||||
|
||||
if version != "" {
|
||||
parts = append(parts, version)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s.ipa", strings.Join(parts, "_"))
|
||||
}
|
||||
|
||||
func (a *appstore) resolveDestinationPath(app App, path string) (string, error) {
|
||||
file := fileName(app)
|
||||
func (t *appstore) resolveDestinationPath(app App, version string, path string) (string, error) {
|
||||
file := fileName(app, version)
|
||||
|
||||
if path == "" {
|
||||
workdir, err := a.os.Getwd()
|
||||
workdir, err := t.os.Getwd()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetCurrentDirectory.Error())
|
||||
return "", fmt.Errorf("failed to get current directory: %w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/%s", workdir, file), nil
|
||||
}
|
||||
|
||||
isDir, err := a.isDirectory(path)
|
||||
isDir, err := t.isDirectory(path)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrCheckDirectory.Error())
|
||||
return "", fmt.Errorf("failed to determine whether path is a directory: %w", err)
|
||||
}
|
||||
|
||||
if isDir {
|
||||
@@ -263,10 +313,10 @@ func (a *appstore) resolveDestinationPath(app App, path string) (string, error)
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func (a *appstore) isDirectory(path string) (bool, error) {
|
||||
info, err := a.os.Stat(path)
|
||||
func (t *appstore) isDirectory(path string) (bool, error) {
|
||||
info, err := t.os.Stat(path)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return false, errors.Wrap(err, ErrGetFileMetadata.Error())
|
||||
return false, fmt.Errorf("failed to read file metadata: %w", err)
|
||||
}
|
||||
|
||||
if info == nil {
|
||||
@@ -276,183 +326,52 @@ func (a *appstore) isDirectory(path string) (bool, error) {
|
||||
return info.IsDir(), nil
|
||||
}
|
||||
|
||||
func (a *appstore) applyPatches(item DownloadItemResult, acc Account, src, dst string) (err error) {
|
||||
dstFile, err := a.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrOpenFile.Error())
|
||||
}
|
||||
|
||||
func (t *appstore) applyPatches(item downloadItemResult, acc Account, src, dst string) error {
|
||||
srcZip, err := zip.OpenReader(src)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrOpenZipFile.Error())
|
||||
return fmt.Errorf("failed to open zip reader: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := srcZip.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
defer srcZip.Close()
|
||||
|
||||
dstFile, err := t.os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
dstZip := zip.NewWriter(dstFile)
|
||||
defer func() {
|
||||
if closeErr := dstZip.Close(); closeErr != err && err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
}()
|
||||
defer dstZip.Close()
|
||||
|
||||
manifestData := new(bytes.Buffer)
|
||||
infoData := new(bytes.Buffer)
|
||||
|
||||
appBundle, err := a.replicateZip(srcZip, dstZip, infoData, manifestData)
|
||||
err = t.replicateZip(srcZip, dstZip)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrReplicateZip.Error())
|
||||
return fmt.Errorf("failed to replicate zip: %w", err)
|
||||
}
|
||||
|
||||
err = a.writeMetadata(item.Metadata, acc, dstZip)
|
||||
err = t.writeMetadata(item.Metadata, acc, dstZip)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteMetadataFile.Error())
|
||||
}
|
||||
|
||||
if manifestData.Len() > 0 {
|
||||
err = a.applySinfPatches(item, dstZip, manifestData.Bytes(), appBundle)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrApplyPatches.Error())
|
||||
}
|
||||
} else {
|
||||
err = a.applyLegacySinfPatches(item, dstZip, infoData.Bytes(), appBundle)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrApplyLegacyPatches.Error())
|
||||
}
|
||||
return fmt.Errorf("failed to write metadata: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) writeMetadata(metadata map[string]interface{}, acc Account, zip *zip.Writer) error {
|
||||
func (t *appstore) writeMetadata(metadata map[string]interface{}, acc Account, zip *zip.Writer) error {
|
||||
metadata["apple-id"] = acc.Email
|
||||
metadata["userName"] = acc.Email
|
||||
|
||||
metadataFile, err := zip.Create("iTunesMetadata.plist")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateMetadataFile.Error())
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
data, err := plist.Marshal(metadata, plist.BinaryFormat)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrEncodeMetadataFile.Error())
|
||||
return fmt.Errorf("failed to marshal data: %w", err)
|
||||
}
|
||||
|
||||
_, err = metadataFile.Write(data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteMetadataFile.Error())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer, info *bytes.Buffer, manifest *bytes.Buffer) (appBundle string, err error) {
|
||||
for _, file := range src.File {
|
||||
srcFile, err := file.OpenRaw()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrOpenFile.Error())
|
||||
}
|
||||
|
||||
if strings.HasSuffix(file.Name, ".app/SC_Info/Manifest.plist") {
|
||||
srcFileD, err := file.Open()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrDecompressManifestFile.Error())
|
||||
}
|
||||
|
||||
_, err = io.Copy(manifest, srcFileD)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetManifestFile.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Contains(file.Name, ".app/Info.plist") {
|
||||
srcFileD, err := file.Open()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrDecompressInfoFile.Error())
|
||||
}
|
||||
|
||||
if !strings.Contains(file.Name, "/Watch/") {
|
||||
appBundle = filepath.Base(strings.TrimSuffix(file.Name, ".app/Info.plist"))
|
||||
}
|
||||
|
||||
_, err = io.Copy(info, srcFileD)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetInfoFile.Error())
|
||||
}
|
||||
}
|
||||
|
||||
header := file.FileHeader
|
||||
dstFile, err := dst.CreateRaw(&header)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrCreateDestinationFile.Error())
|
||||
}
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrFileWrite.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if appBundle == "" {
|
||||
return "", ErrGetBundleName
|
||||
}
|
||||
|
||||
return appBundle, nil
|
||||
}
|
||||
|
||||
func (a *appstore) applySinfPatches(item DownloadItemResult, zip *zip.Writer, manifestData []byte, appBundle string) error {
|
||||
var manifest PackageManifest
|
||||
_, err := plist.Unmarshal(manifestData, &manifest)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrUnmarshal.Error())
|
||||
}
|
||||
|
||||
zipped, err := util.Zip(item.Sinfs, manifest.SinfPaths)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrZipSinfs.Error())
|
||||
}
|
||||
|
||||
for _, pair := range zipped {
|
||||
sp := fmt.Sprintf("Payload/%s.app/%s", appBundle, pair.Second)
|
||||
a.logger.Verbose().Str("path", sp).Msg("writing sinf data")
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateSinfFile.Error())
|
||||
}
|
||||
|
||||
_, err = file.Write(pair.First.Data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteSinfData.Error())
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) applyLegacySinfPatches(item DownloadItemResult, zip *zip.Writer, infoData []byte, appBundle string) error {
|
||||
a.logger.Verbose().Msg("applying legacy sinf patches")
|
||||
|
||||
var info PackageInfo
|
||||
_, err := plist.Unmarshal(infoData, &info)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrUnmarshal.Error())
|
||||
}
|
||||
|
||||
sp := fmt.Sprintf("Payload/%s.app/SC_Info/%s.sinf", appBundle, info.BundleExecutable)
|
||||
a.logger.Verbose().Str("path", sp).Msg("writing sinf data")
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrCreateSinfFile.Error())
|
||||
}
|
||||
|
||||
_, err = file.Write(item.Sinfs[0].Data)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrWriteSinfData.Error())
|
||||
return fmt.Errorf("failed to write data: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,98 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type GetVersionMetadataInput struct {
|
||||
Account Account
|
||||
App App
|
||||
VersionID string
|
||||
}
|
||||
|
||||
type GetVersionMetadataOutput struct {
|
||||
DisplayVersion string
|
||||
ReleaseDate time.Time
|
||||
}
|
||||
|
||||
func (t *appstore) GetVersionMetadata(input GetVersionMetadataInput) (GetVersionMetadataOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
req := t.getVersionMetadataRequest(input.Account, input.App, guid, input.VersionID)
|
||||
res, err := t.downloadClient.Send(req)
|
||||
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
return GetVersionMetadataOutput{}, ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return GetVersionMetadataOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
return GetVersionMetadataOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
// Do not fall back to item.Metadata here. The App Store download API can
|
||||
// return stale version and release date values, so the IPA Info.plist is the
|
||||
// source of truth and failures should be visible to callers.
|
||||
metadata, err := t.readVersionMetadataFromIPA(item.URL)
|
||||
if err != nil {
|
||||
return GetVersionMetadataOutput{}, fmt.Errorf("failed to read version metadata: %w", err)
|
||||
}
|
||||
|
||||
return GetVersionMetadataOutput(metadata), nil
|
||||
}
|
||||
|
||||
func (t *appstore) getVersionMetadataRequest(acc Account, app App, guid string, version string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"externalVersionId": version,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
gohttp "net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
func testIPA(displayVersion string, releaseDate interface{}, modified time.Time) []byte {
|
||||
buffer := new(bytes.Buffer)
|
||||
zipWriter := zip.NewWriter(buffer)
|
||||
|
||||
fillerHeader := &zip.FileHeader{
|
||||
Name: "Payload/Test.app/Filler.bin",
|
||||
Method: zip.Store,
|
||||
}
|
||||
filler, err := zipWriter.CreateHeader(fillerHeader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = filler.Write(make([]byte, 1024*1024))
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
infoHeader := &zip.FileHeader{
|
||||
Name: "Payload/Test.app/Info.plist",
|
||||
Method: zip.Deflate,
|
||||
Modified: modified,
|
||||
}
|
||||
|
||||
infoFile, err := zipWriter.CreateHeader(infoHeader)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info := map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
"CFBundleShortVersionString": displayVersion,
|
||||
}
|
||||
if releaseDate != nil {
|
||||
info["releaseDate"] = releaseDate
|
||||
}
|
||||
|
||||
infoData, err := plist.Marshal(info, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = infoFile.Write(infoData)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
err = zipWriter.Close()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func testIPAServer(data []byte) (*httptest.Server, *int64, *int64) {
|
||||
return testIPAServerWithRangeLog(data, nil)
|
||||
}
|
||||
|
||||
func testIPAServerWithRangeLog(data []byte, rangeLog *[]string) (*httptest.Server, *int64, *int64) {
|
||||
var (
|
||||
servedBytes int64
|
||||
wholeGetCount int64
|
||||
)
|
||||
|
||||
server := httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
|
||||
if r.Method != gohttp.MethodGet {
|
||||
w.WriteHeader(gohttp.StatusMethodNotAllowed)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rangeHeader := r.Header.Get("Range")
|
||||
if rangeLog != nil {
|
||||
*rangeLog = append(*rangeLog, rangeHeader)
|
||||
}
|
||||
|
||||
if rangeHeader == "" {
|
||||
atomic.AddInt64(&wholeGetCount, 1)
|
||||
w.WriteHeader(gohttp.StatusOK)
|
||||
_, _ = w.Write(data)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
start, end, err := testRangeBounds(rangeHeader, len(data))
|
||||
if err != nil {
|
||||
w.WriteHeader(gohttp.StatusRequestedRangeNotSatisfiable)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Accept-Ranges", "bytes")
|
||||
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(data)))
|
||||
w.Header().Set("Content-Length", strconv.Itoa(end-start+1))
|
||||
w.WriteHeader(gohttp.StatusPartialContent)
|
||||
|
||||
n, _ := w.Write(data[start : end+1])
|
||||
atomic.AddInt64(&servedBytes, int64(n))
|
||||
}))
|
||||
|
||||
return server, &servedBytes, &wholeGetCount
|
||||
}
|
||||
|
||||
func testRangeBounds(header string, size int) (int, int, error) {
|
||||
if !strings.HasPrefix(header, "bytes=") {
|
||||
return 0, 0, fmt.Errorf("invalid range header: %s", header)
|
||||
}
|
||||
|
||||
parts := strings.Split(strings.TrimPrefix(header, "bytes="), "-")
|
||||
if len(parts) != 2 {
|
||||
return 0, 0, fmt.Errorf("invalid range header: %s", header)
|
||||
}
|
||||
|
||||
start, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to parse range start: %w", err)
|
||||
}
|
||||
|
||||
end := size - 1
|
||||
if parts[1] != "" {
|
||||
end, err = strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("failed to parse range end: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if start < 0 || start >= size || end < start {
|
||||
return 0, 0, fmt.Errorf("invalid range bounds: %s", header)
|
||||
}
|
||||
|
||||
if end >= size {
|
||||
end = size - 1
|
||||
}
|
||||
|
||||
return start, end, nil
|
||||
}
|
||||
|
||||
var _ = Describe("HTTPRangeReaderAt", func() {
|
||||
It("clamps reads that cross EOF", func() {
|
||||
data := []byte("abcdef")
|
||||
rangeLog := []string{}
|
||||
server, _, _ := testIPAServerWithRangeLog(data, &rangeLog)
|
||||
defer server.Close()
|
||||
|
||||
reader, size, err := newHTTPRangeReaderAt(http.NewClient[interface{}](http.Args{}), server.URL)
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(size).To(Equal(int64(len(data))))
|
||||
|
||||
buf := make([]byte, 4)
|
||||
n, err := reader.ReadAt(buf, 4)
|
||||
Expect(n).To(Equal(2))
|
||||
Expect(err).To(Equal(io.EOF))
|
||||
Expect(string(buf[:n])).To(Equal("ef"))
|
||||
Expect(rangeLog).To(ContainElement("bytes=4-5"))
|
||||
})
|
||||
})
|
||||
|
||||
var _ = Describe("AppStore (GetVersionMetadata)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockMachine *machine.MockMachine
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
as = &appstore{
|
||||
machine: mockMachine,
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: http.NewClient[interface{}](http.Args{}),
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to get MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New("mac error"))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get mac address"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("sends the request to the pod-specific host", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{
|
||||
Account: Account{
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to send http request"))
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(Equal(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(Equal(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("license is missing", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(Equal(ErrLicenseRequired))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
})
|
||||
|
||||
When("response contains customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "SOME_ERROR",
|
||||
CustomerMessage: "Customer error message",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns customer message as error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("Customer error message"))
|
||||
})
|
||||
})
|
||||
|
||||
When("response does not contain customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "SOME_ERROR",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns generic error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("SOME_ERROR"))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns no items", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("invalid response"))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to parse release date", func() {
|
||||
var server *httptest.Server
|
||||
|
||||
BeforeEach(func() {
|
||||
ipa := testIPA("1.0.0", "invalid-date", time.Date(2024, 3, 19, 12, 0, 0, 0, time.UTC))
|
||||
server, _, _ = testIPAServer(ipa)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
URL: server.URL,
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "1.0.0",
|
||||
"releaseDate": "invalid-date",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to parse release date"))
|
||||
})
|
||||
})
|
||||
|
||||
When("IPA metadata cannot be read", func() {
|
||||
var server *httptest.Server
|
||||
|
||||
BeforeEach(func() {
|
||||
server = httptest.NewServer(gohttp.HandlerFunc(func(w gohttp.ResponseWriter, r *gohttp.Request) {
|
||||
w.WriteHeader(gohttp.StatusOK)
|
||||
}))
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
URL: server.URL,
|
||||
Metadata: map[string]interface{}{
|
||||
"bundleShortVersionString": "1.0.0",
|
||||
"releaseDate": "2024-03-20T12:00:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns error instead of falling back to API metadata", func() {
|
||||
_, err := as.GetVersionMetadata(GetVersionMetadataInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to read version metadata"))
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully gets version metadata", func() {
|
||||
var (
|
||||
server *httptest.Server
|
||||
ipa []byte
|
||||
servedBytes *int64
|
||||
wholeGetCount *int64
|
||||
releaseDate time.Time
|
||||
displayVersion string
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
releaseDate = time.Date(2024, 4, 2, 12, 0, 0, 0, time.UTC)
|
||||
displayVersion = "2.0.0"
|
||||
ipa = testIPA(displayVersion, fmt.Sprintf(" \n%s\t", releaseDate.Format(time.RFC3339)), time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC))
|
||||
server, servedBytes, wholeGetCount = testIPAServer(ipa)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
URL: server.URL,
|
||||
Metadata: map[string]interface{}{
|
||||
"releaseDate": "2020-01-01T00:00:00Z",
|
||||
"bundleShortVersionString": "1.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
It("returns version metadata", func() {
|
||||
output, err := as.GetVersionMetadata(GetVersionMetadataInput{
|
||||
Account: Account{
|
||||
DirectoryServicesID: "test-dsid",
|
||||
},
|
||||
App: App{
|
||||
ID: 1234567890,
|
||||
},
|
||||
VersionID: "test-version",
|
||||
})
|
||||
|
||||
Expect(err).NotTo(HaveOccurred())
|
||||
Expect(output.DisplayVersion).To(Equal(displayVersion))
|
||||
Expect(output.ReleaseDate).To(Equal(releaseDate))
|
||||
Expect(atomic.LoadInt64(wholeGetCount)).To(BeZero())
|
||||
Expect(atomic.LoadInt64(servedBytes)).To(BeNumerically("<", int64(len(ipa)/2)))
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,36 +0,0 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func (a *appstore) Info() error {
|
||||
acc, err := a.account()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().
|
||||
Str("name", acc.Name).
|
||||
Str("email", acc.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) account() (Account, error) {
|
||||
data, err := a.keychain.Get("account")
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrGetKeychainItem.Error())
|
||||
}
|
||||
|
||||
var acc Account
|
||||
err = json.Unmarshal(data, &acc)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrUnmarshal.Error())
|
||||
}
|
||||
|
||||
return acc, err
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type ListVersionsInput struct {
|
||||
Account Account
|
||||
App App
|
||||
}
|
||||
|
||||
type ListVersionsOutput struct {
|
||||
ExternalVersionIdentifiers []string
|
||||
LatestExternalVersionID string
|
||||
}
|
||||
|
||||
func (t *appstore) ListVersions(input ListVersionsInput) (ListVersionsOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
req := t.listVersionsRequest(input.Account, input.App, guid)
|
||||
res, err := t.downloadClient.Send(req)
|
||||
|
||||
if err != nil {
|
||||
return ListVersionsOutput{}, fmt.Errorf("failed to send http request: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired || res.Data.FailureType == FailureTypeSignInRequired {
|
||||
return ListVersionsOutput{}, ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseNotFound {
|
||||
return ListVersionsOutput{}, ErrLicenseRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("received error: %s", res.Data.FailureType), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Items) == 0 {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
item := res.Data.Items[0]
|
||||
|
||||
rawIdentifiers, ok := item.Metadata["softwareVersionExternalIdentifiers"].([]interface{})
|
||||
if !ok {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("failed to get version identifiers from item metadata"), item.Metadata)
|
||||
}
|
||||
|
||||
externalVersionIdentifiers := make([]string, len(rawIdentifiers))
|
||||
for i, val := range rawIdentifiers {
|
||||
externalVersionIdentifiers[i] = fmt.Sprintf("%v", val)
|
||||
}
|
||||
|
||||
latestExternalVersionID := item.Metadata["softwareVersionExternalIdentifier"]
|
||||
if latestExternalVersionID == nil {
|
||||
return ListVersionsOutput{}, NewErrorWithMetadata(fmt.Errorf("failed to get latest version from item metadata"), item.Metadata)
|
||||
}
|
||||
|
||||
return ListVersionsOutput{
|
||||
ExternalVersionIdentifiers: externalVersionIdentifiers,
|
||||
LatestExternalVersionID: fmt.Sprintf("%v", latestExternalVersionID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *appstore) listVersionsRequest(acc Account, app App, guid string) http.Request {
|
||||
payload := map[string]interface{}{
|
||||
"creditDisplay": "",
|
||||
"guid": guid,
|
||||
"salableAdamId": app.ID,
|
||||
"serialNumber": "0",
|
||||
}
|
||||
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s%s?guid=%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathDownload, guid),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-apple-plist",
|
||||
"iCloud-DSID": acc.DirectoryServicesID,
|
||||
"X-Dsid": acc.DirectoryServicesID,
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (ListVersions)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
downloadClient: mockDownloadClient,
|
||||
machine: mockMachine,
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("fails to get MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathDownload + "?guid=" + testGUID
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
}).
|
||||
Return(http.Result[downloadResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("sends the request to the pod-specific host", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{
|
||||
Account: Account{
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("license is required", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: FailureTypeLicenseNotFound,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error with customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "test-failure",
|
||||
CustomerMessage: "test error message",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error with customer message", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("test error message"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns error without customer message", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
FailureType: "test-failure",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error with failure type", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("test-failure"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns no items", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("version identifiers not found in metadata", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"someOtherKey": "someValue",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get version identifiers from item metadata"))
|
||||
})
|
||||
})
|
||||
|
||||
When("latest version not found in metadata", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{"12345678", "87654321"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to get latest version from item metadata"))
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully lists versions", func() {
|
||||
const (
|
||||
testVersion1 = "12345678"
|
||||
testVersion2 = "87654321"
|
||||
testLatest = "87654321"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockDownloadClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[downloadResult]{
|
||||
Data: downloadResult{
|
||||
Items: []downloadItemResult{
|
||||
{
|
||||
Metadata: map[string]interface{}{
|
||||
"softwareVersionExternalIdentifiers": []interface{}{testVersion1, testVersion2},
|
||||
"softwareVersionExternalIdentifier": testLatest,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns versions", func() {
|
||||
out, err := as.ListVersions(ListVersionsInput{})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.ExternalVersionIdentifiers).To(Equal([]string{testVersion1, testVersion2}))
|
||||
Expect(out.LatestExternalVersionID).To(Equal(testLatest))
|
||||
})
|
||||
})
|
||||
})
|
||||
+160
-131
@@ -1,116 +1,147 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
gohttp "net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
)
|
||||
|
||||
type LoginAddressResult struct {
|
||||
var (
|
||||
ErrAuthCodeRequired = errors.New("auth code is required")
|
||||
)
|
||||
|
||||
type LoginInput struct {
|
||||
Email string
|
||||
Password string
|
||||
AuthCode string
|
||||
// Endpoint is deprecated. Login always uses the SAP configuration from
|
||||
// Apple's current bag so unsigned or caller-selected fallbacks are impossible.
|
||||
Endpoint string
|
||||
}
|
||||
|
||||
type LoginOutput struct {
|
||||
Account Account
|
||||
}
|
||||
|
||||
func (t *appstore) Login(input LoginInput) (LoginOutput, error) {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid, machineID, err := machineIdentity(macAddr)
|
||||
if err != nil {
|
||||
return LoginOutput{}, err
|
||||
}
|
||||
|
||||
bag, err := t.bag(guid)
|
||||
if err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to get bag: %w", err)
|
||||
}
|
||||
|
||||
if t.actionSignerFactory == nil {
|
||||
return LoginOutput{}, errors.New("SAP action signer is not configured")
|
||||
}
|
||||
|
||||
signer, err := t.actionSignerFactory(bag.SAPConfig, machineID)
|
||||
if err != nil {
|
||||
return LoginOutput{}, fmt.Errorf("failed to initialize SAP action signer: %w", err)
|
||||
}
|
||||
|
||||
if signer == nil {
|
||||
return LoginOutput{}, errors.New("SAP action signer factory returned nil")
|
||||
}
|
||||
|
||||
acc, loginErr := t.login(input.Email, input.Password, input.AuthCode, guid, bag.SAPConfig.AuthEndpoint, signer)
|
||||
closeErr := signer.Close()
|
||||
|
||||
if closeErr != nil {
|
||||
closeErr = fmt.Errorf("failed to close SAP action signer: %w", closeErr)
|
||||
}
|
||||
|
||||
if loginErr != nil {
|
||||
if closeErr != nil {
|
||||
return LoginOutput{}, errors.Join(loginErr, closeErr)
|
||||
}
|
||||
|
||||
return LoginOutput{}, loginErr
|
||||
}
|
||||
|
||||
output := LoginOutput{Account: acc}
|
||||
if closeErr != nil {
|
||||
return output, closeErr
|
||||
}
|
||||
|
||||
return output, nil
|
||||
}
|
||||
|
||||
type loginAddressResult struct {
|
||||
FirstName string `plist:"firstName,omitempty"`
|
||||
LastName string `plist:"lastName,omitempty"`
|
||||
}
|
||||
|
||||
type LoginAccountResult struct {
|
||||
type loginAccountResult struct {
|
||||
Email string `plist:"appleId,omitempty"`
|
||||
Address LoginAddressResult `plist:"address,omitempty"`
|
||||
Address loginAddressResult `plist:"address,omitempty"`
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
type loginResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
Account LoginAccountResult `plist:"accountInfo,omitempty"`
|
||||
Account loginAccountResult `plist:"accountInfo,omitempty"`
|
||||
DirectoryServicesID string `plist:"dsPersonId,omitempty"`
|
||||
PasswordToken string `plist:"passwordToken,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Login(email, password, authCode string) error {
|
||||
if password == "" && !a.interactive {
|
||||
return ErrPasswordRequired
|
||||
}
|
||||
func (t *appstore) login(email, password, authCode, guid, endpoint string, signer ActionSigner) (Account, error) {
|
||||
redirect := ""
|
||||
|
||||
if password == "" && a.interactive {
|
||||
a.logger.Log().Msg("enter password:")
|
||||
var (
|
||||
err error
|
||||
res http.Result[loginResult]
|
||||
)
|
||||
|
||||
retry := true
|
||||
|
||||
for attempt := 1; retry && attempt <= 4; attempt++ {
|
||||
requestAttempt := attempt
|
||||
if redirect != "" {
|
||||
// The pod redirect is part of the same authentication attempt. Apple
|
||||
// expects the original XML plist body, including its attempt value.
|
||||
requestAttempt = 1
|
||||
}
|
||||
|
||||
request := t.loginRequest(email, password, authCode, guid, endpoint, requestAttempt, signer)
|
||||
request.URL, _ = util.IfEmpty(redirect, request.URL), ""
|
||||
res, err = t.loginClient.Send(request)
|
||||
|
||||
var err error
|
||||
password, err = a.promptForPassword()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetData.Error())
|
||||
return Account{}, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if retry, redirect, err = t.parseLoginResponse(&res, attempt, authCode); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
}
|
||||
|
||||
macAddr, err := a.machine.MacAddress()
|
||||
if retry {
|
||||
return Account{}, NewErrorWithMetadata(errors.New("too many attempts"), res)
|
||||
}
|
||||
|
||||
sf, err := res.GetHeader(HTTPHeaderStoreFront)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetMAC.Error())
|
||||
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get storefront header: %w", err), res)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
|
||||
|
||||
acc, err := a.login(email, password, authCode, guid, 0, false)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrLogin.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().
|
||||
Str("name", acc.Name).
|
||||
Str("email", acc.Email).
|
||||
Bool("success", true).
|
||||
Send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) login(email, password, authCode, guid string, attempt int, failOnAuthCodeRequirement bool) (Account, error) {
|
||||
a.logger.Verbose().
|
||||
Int("attempt", attempt).
|
||||
Str("password", password).
|
||||
Str("email", email).
|
||||
Str("authCode", util.IfEmpty(authCode, "<nil>")).
|
||||
Msg("sending login request")
|
||||
|
||||
request := a.loginRequest(email, password, authCode, guid)
|
||||
res, err := a.loginClient.Send(request)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrRequest.Error())
|
||||
}
|
||||
|
||||
if attempt == 0 && res.Data.FailureType == FailureTypeInvalidCredentials {
|
||||
return a.login(email, password, authCode, guid, 1, failOnAuthCodeRequirement)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return Account{}, errors.New(res.Data.CustomerMessage)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return Account{}, ErrGeneric
|
||||
}
|
||||
|
||||
if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
|
||||
if failOnAuthCodeRequirement {
|
||||
return Account{}, ErrAuthCodeRequired
|
||||
}
|
||||
|
||||
if a.interactive {
|
||||
a.logger.Log().Msg("enter 2FA code:")
|
||||
authCode, err = a.promptForAuthCode()
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
|
||||
return a.login(email, password, authCode, guid, 0, failOnAuthCodeRequirement)
|
||||
} else {
|
||||
a.logger.Log().Msg("2FA code is required; run the command again and supply a code using the `--auth-code` flag")
|
||||
return Account{}, nil
|
||||
}
|
||||
pod, err := res.GetHeader(HTTPHeaderPod)
|
||||
if err != nil && !errors.Is(err, http.ErrHeaderNotFound) {
|
||||
return Account{}, NewErrorWithMetadata(fmt.Errorf("failed to get pod header: %w", err), res)
|
||||
}
|
||||
|
||||
addr := res.Data.Account.Address
|
||||
@@ -119,78 +150,76 @@ func (a *appstore) login(email, password, authCode, guid string, attempt int, fa
|
||||
Email: res.Data.Account.Email,
|
||||
PasswordToken: res.Data.PasswordToken,
|
||||
DirectoryServicesID: res.Data.DirectoryServicesID,
|
||||
StoreFront: res.Headers[HTTPHeaderStoreFront],
|
||||
StoreFront: sf,
|
||||
Password: password,
|
||||
Pod: pod,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(acc)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrMarshal.Error())
|
||||
return Account{}, fmt.Errorf("failed to marshal json: %w", err)
|
||||
}
|
||||
|
||||
err = a.keychain.Set("account", data)
|
||||
err = t.keychain.Set("account", data)
|
||||
if err != nil {
|
||||
return Account{}, errors.Wrap(err, ErrSetKeychainItem.Error())
|
||||
return Account{}, fmt.Errorf("failed to save account in keychain: %w", err)
|
||||
}
|
||||
|
||||
return acc, nil
|
||||
}
|
||||
|
||||
func (a *appstore) loginRequest(email, password, authCode, guid string) http.Request {
|
||||
attempt := "4"
|
||||
if authCode != "" {
|
||||
attempt = "2"
|
||||
func (t *appstore) parseLoginResponse(res *http.Result[loginResult], attempt int, authCode string) (bool, string, error) {
|
||||
var (
|
||||
retry bool
|
||||
redirect string
|
||||
err error
|
||||
)
|
||||
|
||||
if res.StatusCode == gohttp.StatusFound {
|
||||
if redirect, err = res.GetHeader("location"); err != nil {
|
||||
err = fmt.Errorf("failed to retrieve redirect location: %w", err)
|
||||
} else if err = validateAuthenticationEndpoint(redirect); err != nil {
|
||||
err = fmt.Errorf("invalid authentication redirect: %w", err)
|
||||
} else {
|
||||
retry = true
|
||||
}
|
||||
} else if attempt == 1 && res.Data.FailureType == FailureTypeInvalidCredentials {
|
||||
retry = true
|
||||
} else if res.Data.FailureType == "" && authCode == "" && res.Data.CustomerMessage == CustomerMessageBadLogin {
|
||||
err = ErrAuthCodeRequired
|
||||
} else if res.Data.FailureType == "" && res.Data.CustomerMessage == CustomerMessageAccountDisabled {
|
||||
err = NewErrorWithMetadata(errors.New("account is disabled"), res)
|
||||
} else if res.Data.FailureType != "" {
|
||||
if res.Data.CustomerMessage != "" {
|
||||
err = NewErrorWithMetadata(errors.New(res.Data.CustomerMessage), res)
|
||||
} else {
|
||||
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
} else if res.StatusCode != gohttp.StatusOK || res.Data.PasswordToken == "" || res.Data.DirectoryServicesID == "" {
|
||||
err = NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
|
||||
return retry, redirect, err
|
||||
}
|
||||
|
||||
func (t *appstore) loginRequest(email, password, authCode, guid, endpoint string, attempt int, signer ActionSigner) http.Request {
|
||||
return http.Request{
|
||||
Method: http.MethodPOST,
|
||||
URL: a.authDomain(authCode, guid),
|
||||
URL: endpoint,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
ActionSigner: signer,
|
||||
Headers: map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
Payload: &http.XMLPayload{
|
||||
Content: map[string]interface{}{
|
||||
"appleId": email,
|
||||
"attempt": attempt,
|
||||
"createSession": "true",
|
||||
"guid": guid,
|
||||
"password": fmt.Sprintf("%s%s", password, authCode),
|
||||
"rmp": "0",
|
||||
"why": "signIn",
|
||||
"appleId": email,
|
||||
"attempt": strconv.Itoa(attempt),
|
||||
"guid": guid,
|
||||
"password": fmt.Sprintf("%s%s", password, strings.ReplaceAll(authCode, " ", "")),
|
||||
"rmp": "0",
|
||||
"why": "signIn",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (a *appstore) promptForAuthCode() (string, error) {
|
||||
reader := bufio.NewReader(a.ioReader)
|
||||
authCode, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
|
||||
authCode = strings.Trim(authCode, "\n")
|
||||
authCode = strings.Trim(authCode, "\r")
|
||||
|
||||
return authCode, nil
|
||||
}
|
||||
|
||||
func (*appstore) authDomain(authCode, guid string) string {
|
||||
prefix := PriavteAppStoreAPIDomainPrefixWithoutAuthCode
|
||||
if authCode != "" {
|
||||
prefix = PriavteAppStoreAPIDomainPrefixWithAuthCode
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"https://%s-%s%s?guid=%s", prefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathAuthenticate, guid)
|
||||
}
|
||||
|
||||
func (a *appstore) promptForPassword() (string, error) {
|
||||
password, err := a.machine.ReadPassword(int(os.Stdin.Fd()))
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, ErrGetData.Error())
|
||||
}
|
||||
|
||||
return string(password), nil
|
||||
}
|
||||
+229
-210
@@ -2,161 +2,161 @@ package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Login)", func() {
|
||||
const (
|
||||
testPassword = "test-password"
|
||||
testPassword = "test-password"
|
||||
testEmail = "test-email"
|
||||
testFirstName = "test-first-name"
|
||||
testLastName = "test-last-name"
|
||||
testPod = "42"
|
||||
)
|
||||
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
as AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockClient *http.MockClient[LoginResult]
|
||||
mockMachine *util.MockMachine
|
||||
mockLogger *log.MockLogger
|
||||
testErr = errors.New("test")
|
||||
ctrl *gomock.Controller
|
||||
as *appstore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockClient *http.MockClient[loginResult]
|
||||
mockBagClient *http.MockClient[bagResult]
|
||||
mockMachine *machine.MockMachine
|
||||
signer *stubActionSigner
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockClient = http.NewMockClient[LoginResult](ctrl)
|
||||
mockMachine = util.NewMockMachine(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
mockClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockBagClient = http.NewMockClient[bagResult](ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
signer = &stubActionSigner{}
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockClient,
|
||||
ioReader: os.Stdin,
|
||||
bagClient: mockBagClient,
|
||||
machine: mockMachine,
|
||||
logger: mockLogger,
|
||||
interactive: true,
|
||||
}
|
||||
actionSignerFactory: func(config SAPConfig, machineID []byte) (ActionSigner, error) {
|
||||
Expect(config).To(Equal(validSAPConfig()))
|
||||
Expect(machineID).To(Equal([]byte{0, 0, 0, 0, 0, 0}))
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
MaxTimes(4)
|
||||
return signer, nil
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("not running in interactive mode and password is not supplied", func() {
|
||||
BeforeEach(func() {
|
||||
as.(*appstore).interactive = false
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", "", "")
|
||||
Expect(err).To(MatchError(ContainSubstring("password is required")))
|
||||
})
|
||||
})
|
||||
|
||||
When("prompts user for password", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
When("user enters password", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", errors.New("success"))
|
||||
|
||||
mockMachine.EXPECT().
|
||||
ReadPassword(syscall.Stdin).
|
||||
Return([]byte(testPassword), nil)
|
||||
})
|
||||
|
||||
It("succeeds", func() {
|
||||
err := as.Login("", "", "")
|
||||
Expect(err).To(MatchError(ContainSubstring("success")))
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to read password from stdin", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
ReadPassword(syscall.Stdin).
|
||||
Return(nil, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", "", "")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetData.Error())))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to read Machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", testErr)
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("sucessfully reads Machine's MAC address", func() {
|
||||
When("successfully reads machine's MAC address", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
mockBagClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal("https://init.itunes.apple.com/bag.xml?guid=000000000000"))
|
||||
}).
|
||||
Return(http.Result[bagResult]{
|
||||
StatusCode: 200,
|
||||
Data: validBagResult(),
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("client returns error", func() {
|
||||
var clientErr error
|
||||
|
||||
BeforeEach(func() {
|
||||
clientErr = errors.New("client error")
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{}, testErr)
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, clientErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(errors.Is(err, clientErr)).To(BeTrue())
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
|
||||
It("preserves both the request and cleanup errors", func() {
|
||||
cleanupErr := errors.New("cleanup failed")
|
||||
signer.closeErr = cleanupErr
|
||||
|
||||
_, err := as.Login(LoginInput{Password: testPassword})
|
||||
Expect(errors.Is(err, clientErr)).To(BeTrue())
|
||||
Expect(errors.Is(err, cleanupErr)).To(BeTrue())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to close SAP action signer"))
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns invalid first response", func() {
|
||||
const testCustomerMessage = "test"
|
||||
When("the SAP signer fails to initialize", func() {
|
||||
BeforeEach(func() {
|
||||
as.actionSignerFactory = func(SAPConfig, []byte) (ActionSigner, error) {
|
||||
return nil, errors.New("signer error")
|
||||
}
|
||||
})
|
||||
|
||||
It("returns a wrapped error", func() {
|
||||
_, err := as.Login(LoginInput{Password: testPassword})
|
||||
Expect(err).To(MatchError("failed to initialize SAP action signer: signer error"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns invalid credentials on first attempt", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: FailureTypeInvalidCredentials,
|
||||
CustomerMessage: "test",
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
}).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
FailureType: FailureTypeInvalidCredentials,
|
||||
},
|
||||
}, nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("retries one more time", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testCustomerMessage)))
|
||||
It("retries once then returns an error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -164,119 +164,139 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
FailureType: "random-error",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API indicates account is disabled", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
CustomerMessage: CustomerMessageAccountDisabled,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns account disabled error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
Expect(err.Error()).To(ContainSubstring("account is disabled"))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API requires 2FA code", func() {
|
||||
When("not running in interactive mode", func() {
|
||||
BeforeEach(func() {
|
||||
as.(*appstore).interactive = false
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("prints message", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
Data: loginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("user enters 2FA code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil).
|
||||
Times(2)
|
||||
|
||||
as.(*appstore).ioReader = strings.NewReader("123456\n")
|
||||
It("returns ErrAuthCodeRequired error", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(Equal(ErrAuthCodeRequired))
|
||||
})
|
||||
})
|
||||
|
||||
It("successfully authenticates", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
When("store API redirects", func() {
|
||||
const (
|
||||
testRedirectLocation = "https://p42-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
firstCall := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testAuthEndpoint))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
x := req.Payload.(*http.XMLPayload)
|
||||
Expect(x.Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 302,
|
||||
Headers: map[string]string{"Location": testRedirectLocation},
|
||||
}, nil)
|
||||
secondCall := mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
Expect(req.URL).To(Equal(testRedirectLocation))
|
||||
Expect(req.ActionSigner).To(BeIdenticalTo(signer))
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
x := req.Payload.(*http.XMLPayload)
|
||||
Expect(x.Content).To(HaveKeyWithValue("attempt", "1"))
|
||||
}).
|
||||
Return(http.Result[loginResult]{}, errors.New("test complete"))
|
||||
gomock.InOrder(firstCall, secondCall)
|
||||
})
|
||||
|
||||
When("prompts user for 2FA code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
as.(*appstore).ioReader = strings.NewReader("123456")
|
||||
It("follows the redirect while preserving the original request body", func() {
|
||||
_, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).To(MatchError("request failed: test complete"))
|
||||
})
|
||||
})
|
||||
|
||||
It("fails to read 2FA code from stdin", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetData.Error())))
|
||||
})
|
||||
When("store API redirects outside Apple's authentication pods", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 302,
|
||||
Headers: map[string]string{"Location": "https://example.com/steal"},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("rejects the redirect before reposting credentials", func() {
|
||||
_, err := as.Login(LoginInput{Password: testPassword})
|
||||
Expect(err).To(MatchError(ContainSubstring("invalid authentication redirect")))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns valid response", func() {
|
||||
const (
|
||||
testEmail = "test-email"
|
||||
testFirstName = "test-first-name"
|
||||
testLastName = "test-last-name"
|
||||
testPasswordToken = "test-password-token"
|
||||
testDirectoryServicesID = "directory-services-id"
|
||||
testStoreFront = "test-storefront"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
Return(http.Result[loginResult]{
|
||||
StatusCode: 200,
|
||||
Headers: map[string]string{
|
||||
HTTPHeaderStoreFront: testStoreFront,
|
||||
HTTPHeaderPod: testPod,
|
||||
},
|
||||
Data: loginResult{
|
||||
PasswordToken: testPasswordToken,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
Account: LoginAccountResult{
|
||||
Account: loginAccountResult{
|
||||
Email: testEmail,
|
||||
Address: LoginAddressResult{
|
||||
Address: loginAddressResult{
|
||||
FirstName: testFirstName,
|
||||
LastName: testLastName,
|
||||
},
|
||||
@@ -285,7 +305,7 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("fails to save account in keychain", func() {
|
||||
When("successfully saves account in keychain", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
@@ -296,53 +316,52 @@ var _ = Describe("AppStore (Login)", func() {
|
||||
PasswordToken: testPasswordToken,
|
||||
Password: testPassword,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
StoreFront: testStoreFront,
|
||||
Pod: testPod,
|
||||
}
|
||||
|
||||
var got Account
|
||||
err := json.Unmarshal(data, &got)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(got).To(Equal(want))
|
||||
}).
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrSetKeychainItem.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("sucessfully saves account in keychain", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Do(func(key string, data []byte) {
|
||||
want := Account{
|
||||
Name: fmt.Sprintf("%s %s", testFirstName, testLastName),
|
||||
Email: testEmail,
|
||||
PasswordToken: testPasswordToken,
|
||||
Password: testPassword,
|
||||
DirectoryServicesID: testDirectoryServicesID,
|
||||
}
|
||||
|
||||
var got Account
|
||||
err := json.Unmarshal(data, &got)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(json.Unmarshal(data, &got)).To(Succeed())
|
||||
Expect(got).To(Equal(want))
|
||||
}).
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Login("", testPassword, "")
|
||||
out, err := as.Login(LoginInput{
|
||||
Password: testPassword,
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(out.Account.Email).To(Equal(testEmail))
|
||||
Expect(out.Account.Name).To(Equal(strings.Join([]string{testFirstName, testLastName}, " ")))
|
||||
})
|
||||
|
||||
It("returns the persisted account with a signer cleanup error", func() {
|
||||
cleanupErr := errors.New("cleanup failed")
|
||||
signer.closeErr = cleanupErr
|
||||
|
||||
out, err := as.Login(LoginInput{Password: testPassword})
|
||||
Expect(errors.Is(err, cleanupErr)).To(BeTrue())
|
||||
Expect(err.Error()).To(ContainSubstring("failed to close SAP action signer"))
|
||||
Expect(out.Account.Email).To(Equal(testEmail))
|
||||
Expect(signer.closeCalls).To(Equal(1))
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
type stubActionSigner struct {
|
||||
closeCalls int
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (*stubActionSigner) Sign(data []byte) ([]byte, error) {
|
||||
return append([]byte(nil), data...), nil
|
||||
}
|
||||
|
||||
func (s *stubActionSigner) Close() error {
|
||||
s.closeCalls++
|
||||
|
||||
return s.closeErr
|
||||
}
|
||||
@@ -1,51 +1,78 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/pkg/errors"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
func (a *appstore) lookup(bundleID, countryCode string) (App, error) {
|
||||
if StoreFronts[countryCode] == "" {
|
||||
return App{}, ErrInvalidCountryCode
|
||||
}
|
||||
type LookupInput struct {
|
||||
Account Account
|
||||
BundleID string
|
||||
Platform Platform
|
||||
}
|
||||
|
||||
request := a.lookupRequest(bundleID, countryCode)
|
||||
type LookupOutput struct {
|
||||
App App
|
||||
}
|
||||
|
||||
res, err := a.searchClient.Send(request)
|
||||
func (t *appstore) Lookup(input LookupInput) (LookupOutput, error) {
|
||||
countryCode, err := countryCodeFromStoreFront(input.Account.StoreFront)
|
||||
if err != nil {
|
||||
return App{}, errors.Wrap(err, ErrRequest.Error())
|
||||
return LookupOutput{}, fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != 200 {
|
||||
a.logger.Verbose().Interface("data", res.Data).Int("status", res.StatusCode).Send()
|
||||
return App{}, ErrRequest
|
||||
request, err := t.lookupRequest(input.BundleID, countryCode, input.Platform)
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("failed to create lookup request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.searchClient.Send(request)
|
||||
if err != nil {
|
||||
return LookupOutput{}, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return LookupOutput{}, NewErrorWithMetadata(errors.New("invalid response"), res)
|
||||
}
|
||||
|
||||
if len(res.Data.Results) == 0 {
|
||||
return App{}, ErrAppNotFound
|
||||
return LookupOutput{}, errors.New("app not found")
|
||||
}
|
||||
|
||||
return res.Data.Results[0], nil
|
||||
return LookupOutput{
|
||||
App: res.Data.Results[0],
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *appstore) lookupRequest(bundleID, countryCode string) http.Request {
|
||||
func (t *appstore) lookupRequest(bundleID, countryCode string, platform Platform) (http.Request, error) {
|
||||
url, err := t.lookupURL(bundleID, countryCode, platform)
|
||||
if err != nil {
|
||||
return http.Request{}, err
|
||||
}
|
||||
|
||||
return http.Request{
|
||||
URL: a.lookupURL(bundleID, countryCode),
|
||||
URL: url,
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *appstore) lookupURL(bundleID, countryCode string) string {
|
||||
func (t *appstore) lookupURL(bundleID, countryCode string, platform Platform) (string, error) {
|
||||
entity, err := platform.lookupEntity()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("entity", "software,iPadSoftware")
|
||||
params.Add("entity", entity)
|
||||
params.Add("limit", "1")
|
||||
params.Add("media", "software")
|
||||
params.Add("bundleId", bundleID)
|
||||
params.Add("country", countryCode)
|
||||
|
||||
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode())
|
||||
return fmt.Sprintf("https://%s%s?%s", iTunesAPIDomain, iTunesAPIPathLookup, params.Encode()), nil
|
||||
}
|
||||
@@ -1,31 +1,27 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"errors"
|
||||
"net/url"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Lookup)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockClient *http.MockClient[SearchResult]
|
||||
mockLogger *log.MockLogger
|
||||
as *appstore
|
||||
mockClient *http.MockClient[searchResult]
|
||||
as AppStore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockClient = http.NewMockClient[SearchResult](ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
mockClient = http.NewMockClient[searchResult](ctrl)
|
||||
as = &appstore{
|
||||
searchClient: mockClient,
|
||||
ioReader: os.Stdin,
|
||||
logger: mockLogger,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -33,56 +29,14 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("country code is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "XYZ")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
var testErr = errors.New("test")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{}, testErr)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "US")
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns bad status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 400,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "US")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("request is successful", func() {
|
||||
When("does not find app", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Data: searchResult{
|
||||
Count: 0,
|
||||
Results: []App{},
|
||||
},
|
||||
@@ -90,8 +44,12 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.lookup("", "US")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrAppNotFound.Error())))
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -107,9 +65,9 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Data: searchResult{
|
||||
Count: 1,
|
||||
Results: []App{testApp},
|
||||
},
|
||||
@@ -117,10 +75,84 @@ var _ = Describe("AppStore (Lookup)", func() {
|
||||
})
|
||||
|
||||
It("returns app", func() {
|
||||
app, err := as.lookup("", "US")
|
||||
app, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(app).To(Equal(testApp))
|
||||
Expect(app).To(Equal(LookupOutput{App: testApp}))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
When("platform is AppleTV", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
parsedURL, err := url.Parse(req.URL)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(parsedURL.Query().Get("entity")).To(Equal("tvSoftware"))
|
||||
}).
|
||||
Return(http.Result[searchResult]{}, errors.New("request error"))
|
||||
})
|
||||
|
||||
It("uses the tvOS lookup entity", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
Platform: PlatformAppleTV,
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store front is invalid", func() {
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "xyz",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request returns bad status code", func() {
|
||||
BeforeEach(func() {
|
||||
mockClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[searchResult]{
|
||||
StatusCode: 400,
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
_, err := as.Lookup(LookupInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,318 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
apphttp "github.com/majd/ipatool/v2/pkg/http"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
var infoPlistReleaseDateKeys = []string{
|
||||
"releaseDate",
|
||||
"ReleaseDate",
|
||||
}
|
||||
|
||||
var infoPlistDisplayVersionKeys = []string{
|
||||
"CFBundleShortVersionString",
|
||||
"bundleShortVersionString",
|
||||
}
|
||||
|
||||
type versionMetadata struct {
|
||||
DisplayVersion string
|
||||
ReleaseDate time.Time
|
||||
}
|
||||
|
||||
type httpRangeReaderAt struct {
|
||||
client apphttp.Client[interface{}]
|
||||
url string
|
||||
size int64
|
||||
}
|
||||
|
||||
func newHTTPRangeReaderAt(client apphttp.Client[interface{}], url string) (*httpRangeReaderAt, int64, error) {
|
||||
if url == "" {
|
||||
return nil, 0, errors.New("url is empty")
|
||||
}
|
||||
|
||||
size, err := remoteFileSize(client, url)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("failed to read remote file size: %w", err)
|
||||
}
|
||||
|
||||
return &httpRangeReaderAt{
|
||||
client: client,
|
||||
url: url,
|
||||
size: size,
|
||||
}, size, nil
|
||||
}
|
||||
|
||||
func remoteFileSize(client apphttp.Client[interface{}], url string) (int64, error) {
|
||||
req, err := client.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Range", "bytes=0-0")
|
||||
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res != nil && res.Body != nil {
|
||||
defer res.Body.Close()
|
||||
}
|
||||
|
||||
if res.StatusCode != http.StatusPartialContent {
|
||||
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
size, err := parseContentRangeSize(res.Header.Get("Content-Range"))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func parseContentRangeSize(header string) (int64, error) {
|
||||
if header == "" {
|
||||
return 0, errors.New("content range is empty")
|
||||
}
|
||||
|
||||
slash := strings.LastIndex(header, "/")
|
||||
if slash == -1 || slash == len(header)-1 {
|
||||
return 0, fmt.Errorf("invalid content range: %s", header)
|
||||
}
|
||||
|
||||
sizeText := header[slash+1:]
|
||||
if sizeText == "*" {
|
||||
return 0, fmt.Errorf("invalid content range size: %s", sizeText)
|
||||
}
|
||||
|
||||
size, err := strconv.ParseInt(sizeText, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to parse content range size: %w", err)
|
||||
}
|
||||
|
||||
return size, nil
|
||||
}
|
||||
|
||||
func (r *httpRangeReaderAt) ReadAt(p []byte, off int64) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if off < 0 {
|
||||
return 0, errors.New("offset is negative")
|
||||
}
|
||||
|
||||
if off >= r.size {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
requestEnd := off + int64(len(p)) - 1
|
||||
rangeEnd := requestEnd
|
||||
|
||||
if rangeEnd >= r.size {
|
||||
rangeEnd = r.size - 1
|
||||
}
|
||||
|
||||
req, err := r.client.NewRequest("GET", r.url, nil)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Accept-Encoding", "identity")
|
||||
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", off, rangeEnd))
|
||||
|
||||
res, err := r.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res != nil && res.Body != nil {
|
||||
defer res.Body.Close()
|
||||
}
|
||||
|
||||
if res.StatusCode != http.StatusPartialContent {
|
||||
return 0, fmt.Errorf("expected partial content response, got status %d", res.StatusCode)
|
||||
}
|
||||
|
||||
readLength := int(rangeEnd-off) + 1
|
||||
|
||||
n, err := io.ReadFull(res.Body, p[:readLength])
|
||||
if err == io.ErrUnexpectedEOF || err == io.EOF {
|
||||
return n, io.EOF
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return n, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if requestEnd >= r.size {
|
||||
return n, io.EOF
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (t *appstore) readVersionMetadataFromIPA(url string) (versionMetadata, error) {
|
||||
reader, size, err := newHTTPRangeReaderAt(t.httpClient, url)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
zipReader, err := zip.NewReader(reader, size)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open zip reader: %w", err)
|
||||
}
|
||||
|
||||
for _, file := range zipReader.File {
|
||||
if !isMainAppInfoPlist(file.Name) {
|
||||
continue
|
||||
}
|
||||
|
||||
metadata, err := readVersionMetadataFromInfoPlist(file)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
return versionMetadata{}, errors.New("could not find Info.plist")
|
||||
}
|
||||
|
||||
func isMainAppInfoPlist(name string) bool {
|
||||
parts := strings.Split(name, "/")
|
||||
|
||||
return len(parts) == 3 && parts[0] == "Payload" && strings.HasSuffix(parts[1], ".app") && parts[2] == "Info.plist"
|
||||
}
|
||||
|
||||
func readVersionMetadataFromInfoPlist(file *zip.File) (versionMetadata, error) {
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to open Info.plist: %w", err)
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
data := new(bytes.Buffer)
|
||||
|
||||
_, err = io.Copy(data, src)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to read Info.plist: %w", err)
|
||||
}
|
||||
|
||||
metadata := map[string]interface{}{}
|
||||
|
||||
_, err = plist.Unmarshal(data.Bytes(), &metadata)
|
||||
if err != nil {
|
||||
return versionMetadata{}, fmt.Errorf("failed to unmarshal Info.plist: %w", err)
|
||||
}
|
||||
|
||||
displayVersion, err := readDisplayVersionFromMetadata(metadata)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
releaseDate, err := readReleaseDateFromInfoPlist(metadata, file.Modified)
|
||||
if err != nil {
|
||||
return versionMetadata{}, err
|
||||
}
|
||||
|
||||
return versionMetadata{
|
||||
DisplayVersion: displayVersion,
|
||||
ReleaseDate: releaseDate,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func readDisplayVersionFromMetadata(metadata map[string]interface{}) (string, error) {
|
||||
for _, key := range infoPlistDisplayVersionKeys {
|
||||
value, ok := metadata[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
displayVersion := strings.TrimSpace(fmt.Sprintf("%v", value))
|
||||
if displayVersion == "" || displayVersion == "<nil>" {
|
||||
return "", fmt.Errorf("%s is empty", key)
|
||||
}
|
||||
|
||||
return displayVersion, nil
|
||||
}
|
||||
|
||||
return "", errors.New("info plist does not contain a display version")
|
||||
}
|
||||
|
||||
func readReleaseDateFromInfoPlist(metadata map[string]interface{}, modified time.Time) (time.Time, error) {
|
||||
for _, key := range infoPlistReleaseDateKeys {
|
||||
value, ok := metadata[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
releaseDate, err := parseReleaseDateValue(value)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("failed to parse release date: %w", err)
|
||||
}
|
||||
|
||||
return releaseDate, nil
|
||||
}
|
||||
|
||||
if modified.IsZero() {
|
||||
return time.Time{}, errors.New("info plist does not contain a release date")
|
||||
}
|
||||
|
||||
return modified.UTC(), nil
|
||||
}
|
||||
|
||||
func parseReleaseDateValue(value interface{}) (time.Time, error) {
|
||||
switch val := value.(type) {
|
||||
case time.Time:
|
||||
return val.UTC(), nil
|
||||
case string:
|
||||
return parseReleaseDateString(val)
|
||||
case int:
|
||||
return time.Unix(int64(val), 0).UTC(), nil
|
||||
case int64:
|
||||
return time.Unix(val, 0).UTC(), nil
|
||||
case uint64:
|
||||
if val > math.MaxInt64 {
|
||||
return time.Time{}, fmt.Errorf("timestamp is too large: %d", val)
|
||||
}
|
||||
|
||||
return time.Unix(int64(val), 0).UTC(), nil
|
||||
case float64:
|
||||
return time.Unix(int64(val), 0).UTC(), nil
|
||||
default:
|
||||
return time.Time{}, fmt.Errorf("unsupported release date type %T", value)
|
||||
}
|
||||
}
|
||||
|
||||
func parseReleaseDateString(value string) (time.Time, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
for _, layout := range []string{
|
||||
time.RFC3339,
|
||||
time.RFC3339Nano,
|
||||
"Monday, January 2, 2006",
|
||||
"2006-01-02",
|
||||
} {
|
||||
parsed, err := time.Parse(layout, value)
|
||||
if err == nil {
|
||||
return parsed.UTC(), nil
|
||||
}
|
||||
}
|
||||
|
||||
return time.Time{}, fmt.Errorf("invalid release date: %s", value)
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
gohttp "net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type platformVersionLookupResult struct {
|
||||
Results map[string]platformVersionLookupItem `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupItem struct {
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Offers []platformVersionLookupOffer `json:"offers,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupOffer struct {
|
||||
BuyParams string `json:"buyParams,omitempty"`
|
||||
Version platformVersionLookupVersion `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionLookupVersion struct {
|
||||
Display string `json:"display,omitempty"`
|
||||
ExternalID platformVersionExternalID `json:"externalId,omitempty"`
|
||||
}
|
||||
|
||||
type platformVersionExternalID string
|
||||
|
||||
func (id *platformVersionExternalID) UnmarshalJSON(data []byte) error {
|
||||
if string(data) == "null" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var stringID string
|
||||
if err := json.Unmarshal(data, &stringID); err == nil {
|
||||
*id = platformVersionExternalID(stringID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var numberID json.Number
|
||||
if err := json.Unmarshal(data, &numberID); err == nil {
|
||||
*id = platformVersionExternalID(numberID.String())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("invalid external version id %s", string(data))
|
||||
}
|
||||
|
||||
func (t *appstore) lookupLatestExternalVersionID(acc Account, app App, platform Platform) (string, error) {
|
||||
if app.ID == 0 {
|
||||
return "", errors.New("app ID is required for platform version lookup")
|
||||
}
|
||||
|
||||
countryCode, err := countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve the country code: %w", err)
|
||||
}
|
||||
|
||||
request, err := t.platformVersionLookupRequest(app.ID, countryCode, platform)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create platform version lookup request: %w", err)
|
||||
}
|
||||
|
||||
res, err := t.platformClient.Send(request)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("platform version lookup request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.StatusCode != gohttp.StatusOK {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup request failed"), res)
|
||||
}
|
||||
|
||||
item, ok := res.Data.Results[strconv.FormatInt(app.ID, 10)]
|
||||
if !ok {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no app"), res)
|
||||
}
|
||||
|
||||
if len(item.Offers) == 0 {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no offers"), res)
|
||||
}
|
||||
|
||||
offer := item.Offers[0]
|
||||
externalVersionID := string(offer.Version.ExternalID)
|
||||
|
||||
if externalVersionID == "" {
|
||||
externalVersionID, err = externalVersionIDFromBuyParams(offer.BuyParams)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse buy params: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if externalVersionID == "" {
|
||||
return "", NewErrorWithMetadata(errors.New("platform version lookup returned no external version id"), res)
|
||||
}
|
||||
|
||||
return externalVersionID, nil
|
||||
}
|
||||
|
||||
func (*appstore) platformVersionLookupRequest(appID int64, countryCode string, platform Platform) (http.Request, error) {
|
||||
metadataPlatform, err := platform.metadataPlatform()
|
||||
if err != nil {
|
||||
return http.Request{}, err
|
||||
}
|
||||
|
||||
params := url.Values{}
|
||||
params.Add("version", "2")
|
||||
params.Add("id", strconv.FormatInt(appID, 10))
|
||||
params.Add("p", "mdm-lockup")
|
||||
params.Add("caller", "MDM")
|
||||
params.Add("platform", metadataPlatform)
|
||||
params.Add("cc", strings.ToLower(countryCode))
|
||||
params.Add("l", "en")
|
||||
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://uclient-api.itunes.apple.com/WebObjects/MZStorePlatform.woa/wa/lookup?%s", params.Encode()),
|
||||
Method: http.MethodGET,
|
||||
ResponseFormat: http.ResponseFormatJSON,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func externalVersionIDFromBuyParams(buyParams string) (string, error) {
|
||||
if buyParams == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
values, err := url.ParseQuery(buyParams)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to parse query: %w", err)
|
||||
}
|
||||
|
||||
return values.Get("appExtVrsId"), nil
|
||||
}
|
||||
@@ -1,77 +1,68 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/pkg/errors"
|
||||
gohttp "net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
)
|
||||
|
||||
type PurchaseResult struct {
|
||||
var (
|
||||
ErrPasswordTokenExpired = errors.New("password token is expired")
|
||||
ErrLicenseAlreadyExists = errors.New("license already exists")
|
||||
ErrSubscriptionRequired = errors.New("subscription required")
|
||||
ErrTemporarilyUnavailable = errors.New("item is temporarily unavailable")
|
||||
)
|
||||
|
||||
type PurchaseInput struct {
|
||||
Account Account
|
||||
App App
|
||||
}
|
||||
|
||||
func (t *appstore) Purchase(input PurchaseInput) error {
|
||||
macAddr, err := t.machine.MacAddress()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get mac address: %w", err)
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
|
||||
if input.App.Price > 0 {
|
||||
return errors.New("purchasing paid apps is not supported")
|
||||
}
|
||||
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppStore)
|
||||
if err != nil {
|
||||
if err == ErrTemporarilyUnavailable {
|
||||
err = t.purchaseWithParams(input.Account, input.App, guid, PricingParameterAppleArcade)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppleArcade, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("failed to purchase item with param '%s': %w", PricingParameterAppStore, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type purchaseResult struct {
|
||||
FailureType string `plist:"failureType,omitempty"`
|
||||
CustomerMessage string `plist:"customerMessage,omitempty"`
|
||||
JingleDocType string `plist:"jingleDocType,omitempty"`
|
||||
Status int `plist:"status,omitempty"`
|
||||
}
|
||||
|
||||
func (a *appstore) Purchase(bundleID string) error {
|
||||
macAddr, err := a.machine.MacAddress()
|
||||
func (t *appstore) purchaseWithParams(acc Account, app App, guid string, pricingParameters string) error {
|
||||
req := t.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
|
||||
res, err := t.purchaseClient.Send(req)
|
||||
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetMAC.Error())
|
||||
}
|
||||
|
||||
guid := strings.ReplaceAll(strings.ToUpper(macAddr), ":", "")
|
||||
a.logger.Verbose().Str("mac", macAddr).Str("guid", guid).Send()
|
||||
|
||||
err = a.purchase(bundleID, guid, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPurchase.Error())
|
||||
}
|
||||
|
||||
a.logger.Log().Bool("success", true).Send()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) purchase(bundleID string, guid string, attemptToRenewCredentials bool) error {
|
||||
acc, err := a.account()
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrGetAccount.Error())
|
||||
}
|
||||
|
||||
countryCode, err := a.countryCodeFromStoreFront(acc.StoreFront)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrInvalidCountryCode.Error())
|
||||
}
|
||||
|
||||
app, err := a.lookup(bundleID, countryCode)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrAppLookup.Error())
|
||||
}
|
||||
|
||||
if app.Price > 0 {
|
||||
return ErrPaidApp
|
||||
}
|
||||
|
||||
err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppStore)
|
||||
if err != nil {
|
||||
if err == ErrTemporarilyUnavailable {
|
||||
err = a.purchaseWithParams(acc, app, bundleID, guid, attemptToRenewCredentials, PricingParameterAppleArcade)
|
||||
if err != nil {
|
||||
return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppleArcade)
|
||||
}
|
||||
}
|
||||
|
||||
return errors.Wrapf(err, "failed to purchase item with param '%s'", PricingParameterAppStore)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, guid string, attemptToRenewCredentials bool, pricingParameters string) error {
|
||||
req := a.purchaseRequest(acc, app, acc.StoreFront, guid, pricingParameters)
|
||||
res, err := a.purchaseClient.Send(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRequest.Error())
|
||||
return fmt.Errorf("request failed: %w", err)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeTemporarilyUnavailable {
|
||||
@@ -79,61 +70,47 @@ func (a *appstore) purchaseWithParams(acc Account, app App, bundleID string, gui
|
||||
}
|
||||
|
||||
if res.Data.CustomerMessage == CustomerMessageSubscriptionRequired {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrSubscriptionRequired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired {
|
||||
if attemptToRenewCredentials {
|
||||
a.logger.Verbose().Msg("retrieving new password token")
|
||||
acc, err = a.login(acc.Email, acc.Password, "", guid, 0, true)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrPasswordTokenExpired.Error())
|
||||
}
|
||||
|
||||
return a.purchaseWithParams(acc, app, bundleID, guid, false, pricingParameters)
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypePasswordTokenExpired ||
|
||||
res.Data.FailureType == FailureTypeSignInRequired ||
|
||||
res.Data.FailureType == FailureTypeDeviceVerificationFailed ||
|
||||
res.Data.CustomerMessage == CustomerMessagePasswordChanged {
|
||||
return ErrPasswordTokenExpired
|
||||
}
|
||||
|
||||
if res.Data.FailureType == FailureTypeLicenseAlreadyExists {
|
||||
return ErrLicenseAlreadyExists
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" && res.Data.CustomerMessage != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return errors.New(res.Data.CustomerMessage)
|
||||
return NewErrorWithMetadata(errors.New(res.Data.CustomerMessage), res)
|
||||
}
|
||||
|
||||
if res.Data.FailureType != "" {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return ErrGeneric
|
||||
return NewErrorWithMetadata(errors.New("something went wrong"), res)
|
||||
}
|
||||
|
||||
if res.StatusCode == 500 {
|
||||
return ErrLicenseExists
|
||||
if res.StatusCode == gohttp.StatusInternalServerError {
|
||||
return ErrLicenseAlreadyExists
|
||||
}
|
||||
|
||||
if res.Data.JingleDocType != "purchaseSuccess" || res.Data.Status != 0 {
|
||||
a.logger.Verbose().Interface("response", res).Send()
|
||||
return errors.New(ErrPurchase.Error())
|
||||
return NewErrorWithMetadata(errors.New("failed to purchase app"), res)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) countryCodeFromStoreFront(storeFront string) (string, error) {
|
||||
for key, val := range StoreFronts {
|
||||
parts := strings.Split(storeFront, "-")
|
||||
|
||||
if len(parts) >= 1 && parts[0] == val {
|
||||
return key, nil
|
||||
}
|
||||
func (t *appstore) purchaseRequest(acc Account, app App, storeFront, guid string, pricingParameters string) http.Request {
|
||||
podPrefix := ""
|
||||
if acc.Pod != "" {
|
||||
podPrefix = "p" + acc.Pod + "-"
|
||||
}
|
||||
|
||||
return "", errors.New(ErrInvalidStoreFront.Error())
|
||||
}
|
||||
|
||||
func (a *appstore) purchaseRequest(acc Account, app App, storeFront, guid string, pricingParameters string) http.Request {
|
||||
return http.Request{
|
||||
URL: fmt.Sprintf("https://%s%s", PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathPurchase),
|
||||
URL: fmt.Sprintf("https://%s%s%s", podPrefix, PrivateAppStoreAPIDomain, PrivateAppStoreAPIPathPurchase),
|
||||
Method: http.MethodPOST,
|
||||
ResponseFormat: http.ResponseFormatXML,
|
||||
Headers: map[string]string{
|
||||
|
||||
@@ -1,42 +1,37 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/http"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"github.com/majd/ipatool/pkg/util"
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"github.com/majd/ipatool/v2/pkg/util/machine"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Purchase)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockMachine *util.MockMachine
|
||||
mockLogger *log.MockLogger
|
||||
mockPurchaseClient *http.MockClient[PurchaseResult]
|
||||
mockSearchClient *http.MockClient[SearchResult]
|
||||
mockLoginClient *http.MockClient[LoginResult]
|
||||
mockMachine *machine.MockMachine
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
as *appstore
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[PurchaseResult](ctrl)
|
||||
mockSearchClient = http.NewMockClient[SearchResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[LoginResult](ctrl)
|
||||
mockMachine = util.NewMockMachine(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
searchClient: mockSearchClient,
|
||||
loginClient: mockLoginClient,
|
||||
machine: mockMachine,
|
||||
logger: mockLogger,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -48,435 +43,306 @@ var _ = Describe("AppStore (Purchase)", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("", ErrGetMAC)
|
||||
Return("", errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetMAC.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("not logged in", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return(nil, ErrGetKeychainItem)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetKeychainItem.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGetAccount.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("country code is invalid", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{}"), nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrInvalidCountryCode.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("app lookup fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{}, ErrRequest)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrAppLookup.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
err := as.Purchase(PurchaseInput{})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("app is paid", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
Price: 0.99,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPaidApp.Error())))
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
App: App{
|
||||
Price: 0.99,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("purchase request fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{}, ErrRequest)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
Return(http.Result[purchaseResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRequest.Error())))
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("request uses a custom pod", func() {
|
||||
const (
|
||||
testPod = "42"
|
||||
testGUID = "001122334455"
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:11:22:33:44:55", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Do(func(req http.Request) {
|
||||
expectedURL := "https://p" + testPod + "-" + PrivateAppStoreAPIDomain + PrivateAppStoreAPIPathPurchase
|
||||
Expect(req.URL).To(Equal(expectedURL))
|
||||
Expect(req.Payload).To(BeAssignableToTypeOf(&http.XMLPayload{}))
|
||||
payload := req.Payload.(*http.XMLPayload)
|
||||
Expect(payload.Content["guid"]).To(Equal(testGUID))
|
||||
}).
|
||||
Return(http.Result[purchaseResult]{}, errors.New(""))
|
||||
})
|
||||
|
||||
It("sends the request to the pod-specific host", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
Pod: testPod,
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("password token is expired", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
When("renewing credentials fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockLoginClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{
|
||||
FailureType: "",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
|
||||
})
|
||||
When("Sign In to the iTunes Store", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeSignInRequired,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
When("renewing credentials succeeds", func() {
|
||||
BeforeEach(func() {
|
||||
mockLoginClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[LoginResult]{
|
||||
Data: LoginResult{},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Set("account", gomock.Any()).
|
||||
Return(nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
FailureType: FailureTypePasswordTokenExpired,
|
||||
},
|
||||
}, nil)
|
||||
It("returns error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
It("attempts to purchase app", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPasswordTokenExpired.Error())))
|
||||
When("customer message indicates password has changed", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: "some_other_failure",
|
||||
CustomerMessage: CustomerMessagePasswordChanged,
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns password token expired error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns customer error message", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: "failure",
|
||||
CustomerMessage: CustomerMessageBadLogin,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(CustomerMessageBadLogin)))
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("store API returns unknown error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Data: PurchaseResult{
|
||||
Return(http.Result[purchaseResult]{
|
||||
Data: purchaseResult{
|
||||
FailureType: "failure",
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrGeneric.Error())))
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("account already has a license for the app", func() {
|
||||
When("account already has a license for the app (failure type)", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
StatusCode: 500,
|
||||
Data: PurchaseResult{},
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeLicenseAlreadyExists,
|
||||
CustomerMessage: "An unknown error has occurred",
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrLicenseExists.Error())))
|
||||
It("returns license already exists error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrLicenseAlreadyExists))
|
||||
})
|
||||
})
|
||||
|
||||
When("account already has a license for the app (HTTP 500 legacy)", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 500,
|
||||
Data: purchaseResult{},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns license already exists error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrLicenseAlreadyExists))
|
||||
})
|
||||
})
|
||||
|
||||
When("device verification fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: purchaseResult{
|
||||
FailureType: FailureTypeDeviceVerificationFailed,
|
||||
CustomerMessage: "Your device or computer could not be verified. Contact support for assistance.",
|
||||
},
|
||||
}, nil)
|
||||
})
|
||||
|
||||
It("returns password token expired error", func() {
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(MatchError(ErrPasswordTokenExpired))
|
||||
})
|
||||
})
|
||||
|
||||
When("subscription is required", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"STDQ"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
Data: purchaseResult{
|
||||
CustomerMessage: "This item is temporarily unavailable.",
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
@@ -484,58 +350,35 @@ var _ = Describe("AppStore (Purchase)", func() {
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"GAME"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
Data: purchaseResult{
|
||||
CustomerMessage: CustomerMessageSubscriptionRequired,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrSubscriptionRequired.Error())))
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("successfully purchases the app", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"STDQ"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
Data: purchaseResult{
|
||||
CustomerMessage: "This item is temporarily unavailable.",
|
||||
FailureType: FailureTypeTemporarilyUnavailable,
|
||||
},
|
||||
@@ -543,76 +386,49 @@ var _ = Describe("AppStore (Purchase)", func() {
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(pricingParametersMatcher{"GAME"}).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
Data: purchaseResult{
|
||||
JingleDocType: "purchaseSuccess",
|
||||
Status: 0,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Purchase("")
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("purchasing the app fails", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Get("account").
|
||||
Return([]byte("{\"storeFront\":\"143441\"}"), nil)
|
||||
|
||||
mockSearchClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[SearchResult]{
|
||||
StatusCode: 200,
|
||||
Data: SearchResult{
|
||||
Count: 1,
|
||||
Results: []App{
|
||||
{
|
||||
ID: 0,
|
||||
BundleID: "",
|
||||
Name: "",
|
||||
Version: "",
|
||||
Price: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockMachine.EXPECT().
|
||||
MacAddress().
|
||||
Return("00:00:00:00:00:00", nil)
|
||||
|
||||
mockPurchaseClient.EXPECT().
|
||||
Send(gomock.Any()).
|
||||
Return(http.Result[PurchaseResult]{
|
||||
Return(http.Result[purchaseResult]{
|
||||
StatusCode: 200,
|
||||
Data: PurchaseResult{
|
||||
Data: purchaseResult{
|
||||
JingleDocType: "failure",
|
||||
Status: -1,
|
||||
},
|
||||
}, nil)
|
||||
|
||||
mockLogger.EXPECT().
|
||||
Verbose().
|
||||
Return(nil).
|
||||
Times(2)
|
||||
})
|
||||
|
||||
It("returns nil", func() {
|
||||
err := as.Purchase("")
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrPurchase.Error())))
|
||||
err := as.Purchase(PurchaseInput{
|
||||
Account: Account{
|
||||
StoreFront: "143441",
|
||||
},
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -622,8 +438,7 @@ type pricingParametersMatcher struct {
|
||||
}
|
||||
|
||||
func (p pricingParametersMatcher) Matches(in interface{}) bool {
|
||||
request := in.(http.Request)
|
||||
return request.Payload.(*http.XMLPayload).Content["pricingParameters"] == p.pricingParameters
|
||||
return in.(http.Request).Payload.(*http.XMLPayload).Content["pricingParameters"] == p.pricingParameters
|
||||
}
|
||||
|
||||
func (p pricingParametersMatcher) String() string {
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/util"
|
||||
"howett.net/plist"
|
||||
)
|
||||
|
||||
type Sinf struct {
|
||||
ID int64 `plist:"id,omitempty"`
|
||||
Data []byte `plist:"sinf,omitempty"`
|
||||
}
|
||||
|
||||
type ReplicateSinfInput struct {
|
||||
Sinfs []Sinf
|
||||
PackagePath string
|
||||
}
|
||||
|
||||
func (t *appstore) ReplicateSinf(input ReplicateSinfInput) error {
|
||||
tmpPath := fmt.Sprintf("%s.tmp", input.PackagePath)
|
||||
if err := t.writeReplicatedZip(input, tmpPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := t.os.Remove(input.PackagePath); err != nil {
|
||||
return fmt.Errorf("failed to remove original file: %w", err)
|
||||
}
|
||||
|
||||
if err := t.os.Rename(tmpPath, input.PackagePath); err != nil {
|
||||
return fmt.Errorf("failed to rename replicated file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint:nonamedreturns // Deferred cleanup must update the returned error.
|
||||
func (t *appstore) writeReplicatedZip(input ReplicateSinfInput, tmpPath string) (err error) {
|
||||
zipReader, err := zip.OpenReader(input.PackagePath)
|
||||
if err != nil {
|
||||
return errors.New("failed to open zip reader")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := zipReader.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close zip reader", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
tmpFile, err := t.os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if closeErr := tmpFile.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close replicated file", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
zipWriter := zip.NewWriter(tmpFile)
|
||||
defer func() {
|
||||
if closeErr := zipWriter.Close(); closeErr != nil {
|
||||
err = joinCleanupError(err, "failed to close zip writer", closeErr)
|
||||
}
|
||||
}()
|
||||
|
||||
err = t.replicateZip(zipReader, zipWriter)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate zip: %w", err)
|
||||
}
|
||||
|
||||
bundleName, err := t.readBundleName(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read bundle name: %w", err)
|
||||
}
|
||||
|
||||
manifest, err := t.readManifestPlist(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read manifest plist: %w", err)
|
||||
}
|
||||
|
||||
info, err := t.readInfoPlist(zipReader)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read info plist: %w", err)
|
||||
}
|
||||
|
||||
if manifest != nil {
|
||||
err = t.replicateSinfFromManifest(*manifest, zipWriter, input.Sinfs, bundleName)
|
||||
} else {
|
||||
err = t.replicateSinfFromInfo(*info, zipWriter, input.Sinfs, bundleName)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to replicate sinf: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func joinCleanupError(err error, message string, cleanupErr error) error {
|
||||
wrapped := fmt.Errorf("%s: %w", message, cleanupErr)
|
||||
if err == nil {
|
||||
return wrapped
|
||||
}
|
||||
|
||||
return errors.Join(err, wrapped)
|
||||
}
|
||||
|
||||
type packageManifest struct {
|
||||
SinfPaths []string `plist:"SinfPaths,omitempty"`
|
||||
}
|
||||
|
||||
type packageInfo struct {
|
||||
BundleExecutable string `plist:"CFBundleExecutable,omitempty"`
|
||||
}
|
||||
|
||||
func (*appstore) replicateSinfFromManifest(manifest packageManifest, zip *zip.Writer, sinfs []Sinf, bundleName string) error {
|
||||
zipped, err := util.Zip(sinfs, manifest.SinfPaths)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to zip sinfs: %w", err)
|
||||
}
|
||||
|
||||
for _, pair := range zipped {
|
||||
sp := fmt.Sprintf("Payload/%s.app/%s", bundleName, pair.Second)
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = file.Write(pair.First.Data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) replicateSinfFromInfo(info packageInfo, zip *zip.Writer, sinfs []Sinf, bundleName string) error {
|
||||
sp := fmt.Sprintf("Payload/%s.app/SC_Info/%s.sinf", bundleName, info.BundleExecutable)
|
||||
|
||||
file, err := zip.Create(sp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = file.Write(sinfs[0].Data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write data: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *appstore) replicateZip(src *zip.ReadCloser, dst *zip.Writer) error {
|
||||
for _, file := range src.File {
|
||||
err := func() error {
|
||||
srcFile, err := file.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
header := file.FileHeader
|
||||
dstFile, err := dst.CreateHeader(&header)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to copy file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*appstore) readInfoPlist(reader *zip.ReadCloser) (*packageInfo, error) {
|
||||
for _, file := range reader.File {
|
||||
if strings.Contains(file.Name, ".app/Info.plist") {
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
data := new(bytes.Buffer)
|
||||
_, err = io.Copy(data, src)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to copy data: %w", err)
|
||||
}
|
||||
|
||||
var info packageInfo
|
||||
_, err = plist.Unmarshal(data.Bytes(), &info)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (*appstore) readManifestPlist(reader *zip.ReadCloser) (*packageManifest, error) {
|
||||
for _, file := range reader.File {
|
||||
if strings.HasSuffix(file.Name, ".app/SC_Info/Manifest.plist") {
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
|
||||
data := new(bytes.Buffer)
|
||||
_, err = io.Copy(data, src)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to copy data: %w", err)
|
||||
}
|
||||
|
||||
var manifest packageManifest
|
||||
|
||||
_, err = plist.Unmarshal(data.Bytes(), &manifest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal data: %w", err)
|
||||
}
|
||||
|
||||
return &manifest, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (*appstore) readBundleName(reader *zip.ReadCloser) (string, error) {
|
||||
var bundleName string
|
||||
|
||||
for _, file := range reader.File {
|
||||
if strings.Contains(file.Name, ".app/Info.plist") && !strings.Contains(file.Name, "/Watch/") {
|
||||
bundleName = filepath.Base(strings.TrimSuffix(file.Name, ".app/Info.plist"))
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if bundleName == "" {
|
||||
return "", errors.New("could not read bundle name")
|
||||
}
|
||||
|
||||
return bundleName, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/http"
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
"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("AppStore (ReplicateSinf)", func() {
|
||||
var (
|
||||
ctrl *gomock.Controller
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockDownloadClient *http.MockClient[downloadResult]
|
||||
mockPurchaseClient *http.MockClient[purchaseResult]
|
||||
mockLoginClient *http.MockClient[loginResult]
|
||||
mockHTTPClient *http.MockClient[interface{}]
|
||||
mockOS *operatingsystem.MockOperatingSystem
|
||||
mockMachine *machine.MockMachine
|
||||
as AppStore
|
||||
testFile *os.File
|
||||
testZip *zip.Writer
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockDownloadClient = http.NewMockClient[downloadResult](ctrl)
|
||||
mockLoginClient = http.NewMockClient[loginResult](ctrl)
|
||||
mockPurchaseClient = http.NewMockClient[purchaseResult](ctrl)
|
||||
mockHTTPClient = http.NewMockClient[interface{}](ctrl)
|
||||
mockOS = operatingsystem.NewMockOperatingSystem(ctrl)
|
||||
mockMachine = machine.NewMockMachine(ctrl)
|
||||
as = &appstore{
|
||||
keychain: mockKeychain,
|
||||
loginClient: mockLoginClient,
|
||||
purchaseClient: mockPurchaseClient,
|
||||
downloadClient: mockDownloadClient,
|
||||
httpClient: mockHTTPClient,
|
||||
machine: mockMachine,
|
||||
os: mockOS,
|
||||
}
|
||||
|
||||
var err error
|
||||
testFile, err = os.CreateTemp("", "test_file")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
testZip = zip.NewWriter(testFile)
|
||||
})
|
||||
|
||||
JustBeforeEach(func() {
|
||||
Expect(testZip.Close()).To(Succeed())
|
||||
Expect(testFile.Close()).To(Succeed())
|
||||
})
|
||||
|
||||
AfterEach(func() {
|
||||
err := os.Remove(testFile.Name())
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("app includes codesign manifest", func() {
|
||||
BeforeEach(func() {
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
DoAndReturn(os.OpenFile)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Rename(fmt.Sprintf("%s.tmp", testFile.Name()), testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
manifest, err := plist.Marshal(packageManifest{
|
||||
SinfPaths: []string{
|
||||
"SC_Info/TestApp.sinf",
|
||||
},
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err := testZip.Create("Payload/Test.app/SC_Info/Manifest.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(manifest)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = testZip.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = testZip.Create("Payload/Test.app/Watch/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
watchInfo, err := plist.Marshal(map[string]interface{}{
|
||||
"WKWatchKitApp": true,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(watchInfo)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("replicates sinf from manifest plist", func() {
|
||||
err := as.ReplicateSinf(ReplicateSinfInput{
|
||||
PackagePath: testFile.Name(),
|
||||
Sinfs: []Sinf{
|
||||
{
|
||||
ID: 0,
|
||||
Data: []byte(""),
|
||||
},
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("app does not include codesign manifest", func() {
|
||||
BeforeEach(func() {
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
DoAndReturn(os.OpenFile)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Remove(testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
mockOS.EXPECT().
|
||||
Rename(fmt.Sprintf("%s.tmp", testFile.Name()), testFile.Name()).
|
||||
Return(nil)
|
||||
|
||||
w, err := testZip.Create("Payload/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
info, err := plist.Marshal(map[string]interface{}{
|
||||
"CFBundleExecutable": "Test",
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(info)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
w, err = testZip.Create("Payload/Test.app/Watch/Test.app/Info.plist")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
watchInfo, err := plist.Marshal(map[string]interface{}{
|
||||
"WKWatchKitApp": true,
|
||||
}, plist.BinaryFormat)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
_, err = w.Write(watchInfo)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("replicates sinf", func() {
|
||||
err := as.ReplicateSinf(ReplicateSinfInput{
|
||||
PackagePath: testFile.Name(),
|
||||
Sinfs: []Sinf{
|
||||
{
|
||||
ID: 0,
|
||||
Data: []byte(""),
|
||||
},
|
||||
},
|
||||
})
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("fails to open file", func() {
|
||||
BeforeEach(func() {
|
||||
mockOS.EXPECT().
|
||||
OpenFile(gomock.Any(), gomock.Any(), gomock.Any()).
|
||||
Return(nil, errors.New(""))
|
||||
})
|
||||
|
||||
It("returns error", func() {
|
||||
err := as.ReplicateSinf(ReplicateSinfInput{
|
||||
PackagePath: testFile.Name(),
|
||||
})
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,14 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (a *appstore) Revoke() error {
|
||||
err := a.keychain.Remove("account")
|
||||
func (t *appstore) Revoke() error {
|
||||
err := t.keychain.Remove("account")
|
||||
if err != nil {
|
||||
return errors.Wrap(err, ErrRemoveKeychainItem.Error())
|
||||
return fmt.Errorf("failed to remove account from keychain: %w", err)
|
||||
}
|
||||
|
||||
a.logger.Log().Bool("success", true).Send()
|
||||
return nil
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
package appstore
|
||||
|
||||
import (
|
||||
"github.com/golang/mock/gomock"
|
||||
"github.com/majd/ipatool/pkg/keychain"
|
||||
"github.com/majd/ipatool/pkg/log"
|
||||
"errors"
|
||||
|
||||
"github.com/majd/ipatool/v2/pkg/keychain"
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/mock/gomock"
|
||||
)
|
||||
|
||||
var _ = Describe("AppStore (Revoke)", func() {
|
||||
@@ -14,16 +14,13 @@ var _ = Describe("AppStore (Revoke)", func() {
|
||||
ctrl *gomock.Controller
|
||||
appstore AppStore
|
||||
mockKeychain *keychain.MockKeychain
|
||||
mockLogger *log.MockLogger
|
||||
)
|
||||
|
||||
BeforeEach(func() {
|
||||
ctrl = gomock.NewController(GinkgoT())
|
||||
mockKeychain = keychain.NewMockKeychain(ctrl)
|
||||
mockLogger = log.NewMockLogger(ctrl)
|
||||
appstore = NewAppStore(AppStoreArgs{
|
||||
appstore = NewAppStore(Args{
|
||||
Keychain: mockKeychain,
|
||||
Logger: mockLogger,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -31,28 +28,8 @@ var _ = Describe("AppStore (Revoke)", func() {
|
||||
ctrl.Finish()
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
var testErr = errors.New("test error")
|
||||
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(testErr)
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := appstore.Revoke()
|
||||
Expect(err).To(MatchError(ContainSubstring(testErr.Error())))
|
||||
Expect(err).To(MatchError(ContainSubstring(ErrRemoveKeychainItem.Error())))
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain removes item", func() {
|
||||
BeforeEach(func() {
|
||||
mockLogger.EXPECT().
|
||||
Log().
|
||||
Return(nil)
|
||||
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(nil)
|
||||
@@ -63,4 +40,17 @@ var _ = Describe("AppStore (Revoke)", func() {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
})
|
||||
|
||||
When("keychain returns error", func() {
|
||||
BeforeEach(func() {
|
||||
mockKeychain.EXPECT().
|
||||
Remove("account").
|
||||
Return(errors.New(""))
|
||||
})
|
||||
|
||||
It("returns wrapped error", func() {
|
||||
err := appstore.Revoke()
|
||||
Expect(err).To(HaveOccurred())
|
||||
})
|
||||
})
|
||||
})
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user