diff --git a/AGENTS.md b/AGENTS.md index e058c94e..34ebedfa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -755,6 +755,14 @@ Unicorn, in `libmacadi.so` (`app/src/main/cpp/macadi/`, ported from sacca97/os-f `scripts/locate_mac_coreadi.py` re-derives and checks every constant, reading them from the Java sources. Both the payload and the library are pinned by SHA-256, and the dispatcher offset (`0x979A0`) is only valid for that one build. +- **A CoreADI that cannot be downloaded must not fall back to a server quietly.** Since the + 2026-10-12 change a server signs in and then every fetch answers 401, so the fallback is a trap. + A failed fetch marks `unavailableReason` with `EmulatedMacAnisette.NO_COREADI_REASON`, + `AnisetteStatus` makes that `NEEDS_COREADI`, and the sign-in screen stops on the Anisette step, + **even when a stored server answers** (that used to skip straight to the account form), offering + Apple's link, **Choose a file** and **Retry**. `MacCoreAdiFetcher.importFrom` takes the iTunes + disk image or the library and checks both against the download's own pins. + `SuppliedCoreAdiFlowTest` fails if the screen skips the offer again. - **One identity, kept forever** - rule 11, with more at stake. `files/anisette/mac/identity.json` and `store/` belong together: the library hashes the host UUID into the machine id, Apple binds the provisioning to the device id, and the Find My token only works alongside Anisette from the diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 387834a8..639fce3f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -171,6 +171,7 @@ wizard). | Anisette tests | `app/src/androidTest/java/.../anisette/` | as above, **opt-in** except `ApplesRealLibraryOnThisDeviceTest` | yes, and network | | UI tests | `AppleLoginFlowTest`, `app/src/androidTest/java/.../ui/` | Espresso, on the managed device | provisioned for you | | Wiki screenshots | `app/src/androidTest/java/.../ui/WikiScreenshots*Test` | as above, **opt-in** | a windowed emulator | +| CoreADI from the real disk image | `MacCoreAdiRealImageTest` (JVM) | Gradle / JUnit, **opt-in**: set `COREADI_DMG` | no, but the 291 MB image | | Chaquopy bridge tests | `app/src/test/python/` | pytest | no | | Desktop exporter tests | `python/test/` | pytest | no | | Shared export package | `python/opentagviewer_export/tests/` | pytest | no | @@ -664,6 +665,16 @@ it works and what it measured. ### The emulated Mac, on the host +**A CoreADI supplied by hand** (the sign-in screen offers this when the download fails) goes +through `MacCoreAdiFetcher.importFrom`. Its JVM tests use miniature fakes; to put Apple's real +image through it against the real pins, download `MacCoreAdiFetcher.DMG_URL` and run: + +```bash +COREADI_DMG=/path/to/iTunes12.8.3.dmg ./gradlew :app:testDebugUnitTest --tests '*MacCoreAdiRealImageTest' +``` + +Passed on 2026-11-21 in 0.3 s (it seeks to the payload instead of reading 291 MB). + ```bash python scripts/locate_mac_coreadi.py --remote --out /tmp/CoreADI.x86_64 cmake -S app/src/test/macadi-host -B build/macadi && cmake --build build/macadi --parallel diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/SuppliedCoreAdiFlowTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/SuppliedCoreAdiFlowTest.java new file mode 100644 index 00000000..52f360a9 --- /dev/null +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/SuppliedCoreAdiFlowTest.java @@ -0,0 +1,236 @@ +package dev.wander.android.opentagviewer; + +import static androidx.test.espresso.Espresso.onView; +import static androidx.test.espresso.action.ViewActions.click; +import static androidx.test.espresso.action.ViewActions.scrollTo; +import static androidx.test.espresso.assertion.ViewAssertions.matches; +import static androidx.test.espresso.intent.Intents.intended; +import static androidx.test.espresso.intent.Intents.intending; +import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; +import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; +import static androidx.test.espresso.matcher.ViewMatchers.withId; +import static androidx.test.espresso.matcher.ViewMatchers.withText; +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertFalse; + +import android.app.Activity; +import android.app.Instrumentation.ActivityResult; +import android.content.Intent; +import android.net.Uri; +import android.os.SystemClock; + +import androidx.appcompat.app.AppCompatDelegate; +import androidx.test.core.app.ActivityScenario; +import androidx.test.espresso.intent.Intents; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.filters.LargeTest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.File; +import java.io.FileOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicInteger; + +import dev.wander.android.opentagviewer.anisette.EmulatedMacAnisette; +import dev.wander.android.opentagviewer.anisette.FakeAnisetteSource; +import dev.wander.android.opentagviewer.db.datastore.UserAuthDataStore; +import dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore; +import dev.wander.android.opentagviewer.db.repo.UserAuthRepository; +import dev.wander.android.opentagviewer.db.repo.UserSettingsRepository; +import dev.wander.android.opentagviewer.db.repo.model.UserSettings; +import dev.wander.android.opentagviewer.python.AppDependencies; +import dev.wander.android.opentagviewer.python.FakeAppleAuthService; +import dev.wander.android.opentagviewer.service.web.FakeAnisetteServerTester; +import dev.wander.android.opentagviewer.util.android.AppCryptographyUtil; + +/** + * Signing in on a phone that could not download CoreADI. + * + *

The trap this guards against: a working server signs in, and then every location fetch + * answers 401. So the screen has to stop on the Anisette step and offer the file, even when a + * stored server answers, which used to send it straight to the account form. + * + *

A file that passes cannot be driven here: only Apple's real disk image matches the pins. + * {@code MacCoreAdiFetcherTest} covers that on the JVM. What this covers is the screen. + */ +@LargeTest +@RunWith(AndroidJUnit4.class) +public class SuppliedCoreAdiFlowTest { + + private static final String SERVER = "https://ani.example.com"; + + private ActivityScenario scenario; + private DeviceStateGuard deviceState; + private int nightModeBefore; + private final AtomicInteger sourcesMade = new AtomicInteger(); + + private static FakeAnisetteSource noCoreAdi() { + return FakeAnisetteSource.unavailable(EmulatedMacAnisette.NO_COREADI_REASON + + ": could not download the library from Apple: UnknownHostException"); + } + + @Before + public void aPhoneThatCannotDownloadCoreAdi() { + this.deviceState = DeviceStateGuard.capture(getInstrumentation().getTargetContext()); + this.nightModeBefore = AppCompatDelegate.getDefaultNightMode(); + + signEverybodyOut(); + // A stored server that answers: the case that used to skip straight past the offer. + new UserSettingsRepository( + UserSettingsDataStore.getInstance(getInstrumentation().getTargetContext())) + .storeUserSettings(UserSettings.builder().anisetteServerUrl(SERVER).build()) + .blockingAwait(); + + AppDependencies.replaceAuthService(FakeAppleAuthService.signsInImmediately()); + AppDependencies.replaceServerTester(FakeAnisetteServerTester.thatIsUp()); + AppDependencies.replaceAnisette(settings -> { + this.sourcesMade.incrementAndGet(); + return noCoreAdi(); + }); + + Intents.init(); + } + + @After + public void putTheRealOnesBack() { + if (this.scenario != null) { + this.scenario.close(); + } + Intents.release(); + AppDependencies.reset(); + getInstrumentation().runOnMainSync( + () -> AppCompatDelegate.setDefaultNightMode(this.nightModeBefore)); + + getInstrumentation().waitForIdleSync(); + signEverybodyOut(); + this.deviceState.restore(); + } + + private void launch() { + this.scenario = ActivityScenario.launch(AppleLoginActivity.class); + TestPace.afterAStep(); + } + + private void shot(final String name) { + final AppleLoginActivity[] activity = {null}; + this.scenario.onActivity(a -> activity[0] = a); + Shot.of(activity[0], name); + } + + @Test + public void aStoredServerThatAnswersDoesNotSkipTheOffer() { + launch(); + + Eventually.check(() -> onView(withId(R.id.anisetteCoreAdiContainer)) + .perform(scrollTo()).check(matches(isDisplayed()))); + onView(withId(R.id.email_or_phone_input_field)).check(matches(not(isDisplayed()))); + onView(withId(R.id.anisetteLoginFallbackReason)) + .check(matches(withText(R.string.anisette_login_needs_coreadi))); + + this.shot("coreadi_1_offer_light"); + } + + @Test + public void theOfferInDarkMode() { + getInstrumentation().runOnMainSync( + () -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)); + launch(); + + Eventually.check(() -> onView(withId(R.id.anisetteCoreAdiContainer)) + .perform(scrollTo()).check(matches(isDisplayed()))); + + this.shot("coreadi_2_offer_dark"); + } + + @Test + public void choosingAFileAsksTheSystemForOne() { + stubThePickerWith(null); + launch(); + + Eventually.check(() -> onView(withId(R.id.anisetteChooseCoreAdiButton)) + .perform(scrollTo(), click())); + + Eventually.check(() -> intended(hasAction(Intent.ACTION_OPEN_DOCUMENT))); + } + + @Test + public void aFileThatIsNotCoreAdiIsRefusedWithTheReason() throws Exception { + stubThePickerWith(aHolidayPhoto()); + launch(); + + Eventually.check(() -> onView(withId(R.id.anisetteChooseCoreAdiButton)) + .perform(scrollTo(), click())); + + Eventually.check(() -> onView(withId(R.id.anisetteCoreAdiRejection)) + .perform(scrollTo()) + .check(matches(allOf(isDisplayed(), withText(containsString("too small")))))); + assertFalse("nothing may be stored from a refused file", + EmulatedMacAnisette.libraryFile(getInstrumentation().getTargetContext()).exists()); + + this.shot("coreadi_3_refused"); + } + + /** Retry after the file arrived (or the network came back) moves on to the account form. */ + @Test + public void retryingOnceItWorksMovesOn() { + launch(); + Eventually.check(() -> onView(withId(R.id.anisetteRetryCoreAdiButton)) + .perform(scrollTo()).check(matches(isDisplayed()))); + + AppDependencies.replaceAnisette(settings -> FakeAnisetteSource.ready()); + Eventually.perform("retry", + () -> isShown(R.id.login_maininfo_container), + () -> onView(withId(R.id.anisetteRetryCoreAdiButton)).perform(scrollTo(), click())); + + Eventually.check(() -> onView(withId(R.id.email_or_phone_input_field)) + .perform(scrollTo()).check(matches(isDisplayed()))); + } + + private boolean isShown(final int id) { + final boolean[] shown = {false}; + this.scenario.onActivity(a -> shown[0] = a.findViewById(id).isShown()); + return shown[0]; + } + + private void stubThePickerWith(final Uri chosen) { + final Intent data = chosen == null ? null : new Intent().setData(chosen); + intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(new ActivityResult( + chosen == null ? Activity.RESULT_CANCELED : Activity.RESULT_OK, data)); + } + + private static Uri aHolidayPhoto() throws Exception { + final File photo = new File(getInstrumentation().getTargetContext().getCacheDir(), + "holiday.jpg"); + try (FileOutputStream out = new FileOutputStream(photo)) { + out.write("not a disk image".getBytes(StandardCharsets.US_ASCII)); + } + return Uri.fromFile(photo); + } + + private static void signEverybodyOut() { + final UserAuthRepository auth = new UserAuthRepository( + UserAuthDataStore.getInstance(getInstrumentation().getTargetContext()), + new AppCryptographyUtil()); + + int consecutivelyEmpty = 0; + for (int attempt = 0; attempt < 40 && consecutivelyEmpty < 3; attempt++) { + if (auth.getUserAuth().blockingFirst().isEmpty()) { + consecutivelyEmpty++; + } else { + consecutivelyEmpty = 0; + auth.clearUser().blockingAwait(); + } + SystemClock.sleep(50); + } + if (consecutivelyEmpty < 3) { + throw new IllegalStateException("a stored session kept coming back"); + } + } +} diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/anisette/AnisetteStatusTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/anisette/AnisetteStatusTest.java index 982b9233..35c399df 100644 --- a/app/src/androidTest/java/dev/wander/android/opentagviewer/anisette/AnisetteStatusTest.java +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/anisette/AnisetteStatusTest.java @@ -86,6 +86,40 @@ public void aLibraryThatCrashesThisPhoneIsItsOwnState() { assertFalse("a copy of the same library crashes the same way", status.needsOwnApk()); } + /** The emulated Mac crashing is a crash too. Its sentence differs, and it used to read as UNAVAILABLE. */ + @Test + public void theEmulatedMacCrashingIsACrashToo() { + final AnisetteStatus status = AnisetteStatus.of( + FakeAnisetteSource.unavailable(EmulatedMacAnisette.CRASHES_HERE_REASON)); + + assertEquals(AnisetteStatus.State.CRASHES_HERE, status.state()); + } + + /** + * No CoreADI is its own state, offering the file and never the APK. A server would sign in and + * then fail every fetch, so it is not an answer here. + */ + @Test + public void noCoreAdiAsksForCoreAdiAndNotTheApk() { + final AnisetteStatus status = AnisetteStatus.of(FakeAnisetteSource.unavailable( + EmulatedMacAnisette.NO_COREADI_REASON + + ": could not download the library from Apple: UnknownHostException")); + + assertEquals(AnisetteStatus.State.NEEDS_COREADI, status.state()); + assertTrue(status.failed()); + assertTrue(status.needsCoreAdi()); + assertFalse(status.needsOwnApk()); + } + + /** An ordinary network failure elsewhere does not ask for CoreADI. */ + @Test + public void anOrdinaryFailureDoesNotAskForCoreAdi() { + final AnisetteStatus status = AnisetteStatus.of( + FakeAnisetteSource.unavailable("Unable to resolve host gsa.apple.com")); + + assertFalse(status.needsCoreAdi()); + } + /** No source at all is "nothing has happened yet", not "something went wrong". */ @Test public void noSourceIsPendingRatherThanBroken() { diff --git a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/LoginAnisetteFallbackLayoutTest.java b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/LoginAnisetteFallbackLayoutTest.java index f745bfe2..f443ab42 100644 --- a/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/LoginAnisetteFallbackLayoutTest.java +++ b/app/src/androidTest/java/dev/wander/android/opentagviewer/ui/settings/LoginAnisetteFallbackLayoutTest.java @@ -21,7 +21,9 @@ import dev.wander.android.opentagviewer.R; import dev.wander.android.opentagviewer.anisette.AnisetteStatus; import dev.wander.android.opentagviewer.anisette.AppleLibraryCrashReport; +import dev.wander.android.opentagviewer.anisette.EmulatedMacAnisette; import dev.wander.android.opentagviewer.anisette.LocalAnisette; +import dev.wander.android.opentagviewer.anisette.MacCoreAdiFetcher; import dev.wander.android.opentagviewer.anisette.FakeAnisetteSource; /** @@ -186,6 +188,70 @@ public void anOrdinaryFailureAfterACrashGoesBackToTheGeneralSentence() { View.GONE, view(R.id.anisetteReportCrashButton).getVisibility()); } + private static AnisetteStatus noCoreAdi() { + return AnisetteStatus.of(FakeAnisetteSource.unavailable( + EmulatedMacAnisette.NO_COREADI_REASON + ": Apple answered HTTP 403")); + } + + /** + * Without CoreADI, the file is offered first: the link to Apple's image, choose and retry. + * The server stays reachable, but the sentence says locations will not load through it. + */ + @Test + public void noCoreAdiOffersTheFileAndWarnsAboutTheServer() { + apply(noCoreAdi()); + + assertEquals(View.VISIBLE, view(R.id.anisetteCoreAdiContainer).getVisibility()); + assertEquals(MacCoreAdiFetcher.DMG_URL, + ((TextView) view(R.id.anisetteCoreAdiLink)).getText().toString()); + assertEquals(this.screen.getContext().getString(R.string.anisette_login_needs_coreadi), + ((TextView) view(R.id.anisetteLoginFallbackReason)).getText().toString()); + assertEquals(View.VISIBLE, view(R.id.anisetteChooseCoreAdiButton).getVisibility()); + assertEquals(View.VISIBLE, view(R.id.anisetteRetryCoreAdiButton).getVisibility()); + assertEquals("the server is still a way to sign in", + View.VISIBLE, view(R.id.anisetteRemoteSection).getVisibility()); + assertEquals(View.GONE, view(R.id.anisetteReportCrashButton).getVisibility()); + assertEquals("nothing was refused yet", + View.GONE, view(R.id.anisetteCoreAdiRejection).getVisibility()); + } + + /** Any other failure, or recovering, takes the offer away again. */ + @Test + public void theFileIsOfferedOnlyWhileItIsMissing() { + apply(noCoreAdi()); + apply(AnisetteStatus.of(FakeAnisetteSource.unavailable("Unable to resolve host"))); + assertEquals(View.GONE, view(R.id.anisetteCoreAdiContainer).getVisibility()); + + apply(noCoreAdi()); + apply(AnisetteStatus.of(FakeAnisetteSource.ready())); + assertEquals(View.GONE, view(R.id.anisetteCoreAdiContainer).getVisibility()); + } + + /** Somebody who chose a server is not offered a file for a machine they are not using. */ + @Test + public void choosingAServerIsNotAnsweredWithTheFile() { + apply(noCoreAdi(), true); + + assertEquals(View.GONE, view(R.id.anisetteCoreAdiContainer).getVisibility()); + } + + /** A refused file says why, and a fresh attempt clears it. */ + @Test + public void aRefusedFileSaysWhyUntilTheNextTry() { + apply(noCoreAdi()); + getInstrumentation().runOnMainSync(() -> SharedMainSettingsManager.applyCoreAdiRejection( + this.screen, "the library is not the expected build")); + + final TextView rejection = (TextView) view(R.id.anisetteCoreAdiRejection); + assertEquals(View.VISIBLE, rejection.getVisibility()); + assertTrue(rejection.getText().toString(), + rejection.getText().toString().contains("not the expected build")); + + getInstrumentation().runOnMainSync( + () -> SharedMainSettingsManager.applyCoreAdiRejection(this.screen, null)); + assertEquals(View.GONE, rejection.getVisibility()); + } + /** The report is only worth sending if it names the phone. */ @Test public void theReportNamesThePhone() { diff --git a/app/src/main/java/dev/wander/android/opentagviewer/AppleLoginActivity.java b/app/src/main/java/dev/wander/android/opentagviewer/AppleLoginActivity.java index 05be9d41..aff06eff 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/AppleLoginActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/AppleLoginActivity.java @@ -11,8 +11,11 @@ import static dev.wander.android.opentagviewer.ui.settings.SharedMainSettingsManager.ANISETTE_TEST_STATUS.OK; import static dev.wander.android.opentagviewer.util.android.TextChangedWatcherFactory.justWatchOnChanged; +import android.content.ClipData; +import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; +import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; @@ -28,6 +31,8 @@ import android.widget.Toast; import androidx.activity.OnBackPressedCallback; +import androidx.activity.result.ActivityResultLauncher; +import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.core.os.LocaleListCompat; @@ -43,6 +48,7 @@ import com.google.android.material.textfield.MaterialAutoCompleteTextView; import com.google.android.material.textfield.TextInputEditText; +import java.io.InputStream; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -64,6 +70,8 @@ import dev.wander.android.opentagviewer.python.TermsDocument; import dev.wander.android.opentagviewer.anisette.AnisetteSource; import dev.wander.android.opentagviewer.anisette.AnisetteStatus; +import dev.wander.android.opentagviewer.anisette.EmulatedMacAnisette; +import dev.wander.android.opentagviewer.anisette.MacCoreAdiFetcher; import dev.wander.android.opentagviewer.service.web.AnisetteServerTesterService; import dev.wander.android.opentagviewer.service.web.CronetProvider; import dev.wander.android.opentagviewer.service.web.GitHubService; @@ -282,6 +290,16 @@ public void handleOnBackPressed() { this.findViewById(R.id.login_error_try_remote_anisette) .setOnClickListener(v -> this.onClickTryRemoteAnisette()); + // Supplying CoreADI by hand, offered only in AnisetteStatus.State.NEEDS_COREADI. + // Not the DMG's mime type: a download arrives as octet-stream, x-apple-diskimage or + // nothing at all, and filtering would hide the very file the user was sent to fetch. + this.findViewById(R.id.anisetteChooseCoreAdiButton) + .setOnClickListener(v -> this.pickCoreAdiLauncher.launch(new String[] {"*/*"})); + this.findViewById(R.id.anisetteRetryCoreAdiButton) + .setOnClickListener(v -> this.checkAnisetteAgain()); + this.findViewById(R.id.anisetteCopyCoreAdiLinkButton) + .setOnClickListener(v -> this.copyCoreAdiLink()); + this.findViewById(R.id.login_terms_agree_button) .setOnClickListener(v -> this.onAgreeToTerms()); @@ -1002,7 +1020,8 @@ private void showInitialWelcomeConfOptions(SETUP_STATUS setupStatus, Direction d this.testAndSaveAnisetteUrl(currentAnisetteServerSelection); - if (setupStatus == SETUP_STATUS.NO_SERVER_CONFIGURED) { + if (setupStatus == SETUP_STATUS.NO_SERVER_CONFIGURED + || setupStatus == SETUP_STATUS.NEEDS_COREADI) { this.setCurrentStepText(R.string.welcome, direction); } else { this.setCurrentStepText(R.string.choose_your_server, direction); @@ -1366,6 +1385,12 @@ private Observable getAnisetteSetupStatus() { if (status.state() == AnisetteStatus.State.READY) { return Observable.just(SETUP_STATUS.OK); } + // Not OK even when a stored server answers. That server would sign in + // and then fail every fetch, and OK skips this step, so nobody would ever + // see the offer of the file that would actually fix it. + if (status.needsCoreAdi()) { + return Observable.just(SETUP_STATUS.NEEDS_COREADI); + } return this.getAnisetteServerSetupStatus(); }); } @@ -1518,9 +1543,84 @@ private LoginActivityState getUiState() { return Objects.requireNonNull(this.model.getUiState().getValue()); } + /** + * Picks the iTunes 12.8.3 disk image, or CoreADI itself, for a phone that could not download + * it. {@code OpenDocument}, so a 291 MB file is read where it lies rather than copied first. + */ + private final ActivityResultLauncher pickCoreAdiLauncher = + registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> { + if (uri != null) { + this.importCoreAdi(uri); + } + }); + + /** + * Store a CoreADI the user chose, then check Anisette again. + * + *

Off the main thread: a disk image is skipped through to its payload, then unpacked and + * hashed. Checked against the same pins as the download, so nothing chosen here can run code + * the download would have refused. + */ + private void importCoreAdi(final Uri chosen) { + final View root = this.findViewById(android.R.id.content); + SharedMainSettingsManager.applyCoreAdiRejection(root, null); + this.showLoading(null); + + var async = Observable.fromCallable(() -> { + try (InputStream in = this.getContentResolver().openInputStream(chosen)) { + if (in == null) { + return Optional.of("the file could not be opened"); + } + MacCoreAdiFetcher.importFrom(in, EmulatedMacAnisette.libraryFile(this)); + return Optional.empty(); + } catch (final MacCoreAdiFetcher.FetchException e) { + Log.w(TAG, "the chosen file is not CoreADI", e); + return Optional.of(String.valueOf(e.getMessage())); + } + }) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(problem -> { + this.hideLoading(); + if (problem.isPresent()) { + SharedMainSettingsManager.applyCoreAdiRejection(root, problem.get()); + return; + } + this.checkAnisetteAgain(); + }, error -> { + this.hideLoading(); + Log.e(TAG, "could not import the chosen CoreADI", error); + SharedMainSettingsManager.applyCoreAdiRejection(root, + String.valueOf(error.getMessage())); + }); + } + + /** Ask local Anisette again from scratch: after a supplied file, or a network that recovered. */ + private void checkAnisetteAgain() { + // A fresh source, so nothing it remembered about the failure carries over. + this.localAnisette = AppDependencies.anisette(this, this.getUserSettings(), false); + // Aimed at the account form, as a phone that worked from the start would be. handleAuth + // only goes there for LOGIN or no page, and this screen's page is still the welcome + // step; when the answer is still no, it comes back here anyway. + this.getUiState().setCurrentPage(PAGE.LOGIN); + this.handleAuth(this.getUiState()); + } + + private void copyCoreAdiLink() { + final ClipboardManager clipboard = + (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE); + if (clipboard != null) { + clipboard.setPrimaryClip(ClipData.newPlainText("iTunes 12.8.3", + MacCoreAdiFetcher.DMG_URL)); + Toast.makeText(this, R.string.exported_tags_code_copied, Toast.LENGTH_SHORT).show(); + } + } + enum SETUP_STATUS { NO_SERVER_CONFIGURED, SERVER_UNAVAILABLE, + /** The emulated Mac has no CoreADI. Stops on this step, with the file offered. */ + NEEDS_COREADI, OK; } } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java index 9c3f2daf..8cdbfc7a 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/SettingsActivity.java @@ -9,6 +9,9 @@ import static android.view.View.inflate; import static dev.wander.android.opentagviewer.util.android.TextChangedWatcherFactory.justWatchOnChanged; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; @@ -50,6 +53,7 @@ import com.google.android.material.textfield.TextInputLayout; import java.io.File; +import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -65,7 +69,9 @@ import dev.wander.android.opentagviewer.anisette.AdiLibraryManifest; import dev.wander.android.opentagviewer.anisette.AnisetteSource; import dev.wander.android.opentagviewer.anisette.AnisetteStatus; +import dev.wander.android.opentagviewer.anisette.EmulatedMacAnisette; import dev.wander.android.opentagviewer.anisette.LocalAnisette; +import dev.wander.android.opentagviewer.anisette.MacCoreAdiFetcher; import dev.wander.android.opentagviewer.databinding.ActivitySettingsBinding; import dev.wander.android.opentagviewer.db.datastore.UserAuthDataStore; import dev.wander.android.opentagviewer.db.datastore.UserCacheDataStore; @@ -806,9 +812,17 @@ private void setupAnisetteModeControls(final View view) { learnMore.setOnClickListener(v -> this.openConfiguredLink("anisetteWikiPage")); } + // Both buttons serve whichever file is missing: CoreADI for the emulated Mac, or the + // Apple Music APK for the Android libraries. See applyLocalAnisetteStatus. final View whereToGetApk = view.findViewById(R.id.anisetteWhereToGetApkButton); if (whereToGetApk != null) { - whereToGetApk.setOnClickListener(v -> this.openConfiguredLink("anisetteApkWikiPage")); + whereToGetApk.setOnClickListener(v -> { + if (this.lastLocalAnisetteStatus.needsCoreAdi()) { + this.copyCoreAdiLink(); + } else { + this.openConfiguredLink("anisetteApkWikiPage"); + } + }); } final View chooseApk = view.findViewById(R.id.anisetteChooseApkButton); @@ -819,7 +833,11 @@ private void setupAnisetteModeControls(final View view) { // Not the APK mime type: files downloaded from a browser or a file host // routinely arrive as octet-stream or with no type at all, and filtering them // out would hide the very file people were told to go and find. - this.pickAnisetteApkLauncher.launch(new String[] {"*/*"}); + if (this.lastLocalAnisetteStatus.needsCoreAdi()) { + this.pickCoreAdiLauncher.launch(new String[] {"*/*"}); + } else { + this.pickAnisetteApkLauncher.launch(new String[] {"*/*"}); + } }); } @@ -832,6 +850,59 @@ private void setupAnisetteModeControls(final View view) { /** The Anisette dialog currently on screen, so a file-picker result can update it. */ private View anisetteDialogView; + /** What local Anisette said last, which decides which file the dialog's buttons ask for. */ + private AnisetteStatus lastLocalAnisetteStatus = AnisetteStatus.pending(); + + /** Picks the iTunes 12.8.3 disk image, or CoreADI itself. See AppleLoginActivity's twin. */ + private final ActivityResultLauncher pickCoreAdiLauncher = + registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> { + if (uri != null) { + this.importCoreAdi(uri); + } + }); + + /** Store a CoreADI chosen by hand, checked against the download's own pins, then re-check. */ + private void importCoreAdi(final Uri chosen) { + final View view = this.anisetteDialogView; + if (view != null) { + SharedMainSettingsManager.applyApkRejection(view, null); + SharedMainSettingsManager.applyLocalAnisetteStatus( + view, AnisetteStatus.checking(), "", this.currentSettings.hasOwnAnisetteApk()); + } + + var async = Observable.fromCallable(() -> { + try (InputStream in = this.getContentResolver().openInputStream(chosen)) { + if (in == null) { + return Optional.of("the file could not be opened"); + } + MacCoreAdiFetcher.importFrom(in, EmulatedMacAnisette.libraryFile(this)); + return Optional.empty(); + } catch (final MacCoreAdiFetcher.FetchException e) { + Log.w(TAG, "the chosen file is not CoreADI", e); + return Optional.of(String.valueOf(e.getMessage())); + } + }) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(problem -> { + if (view == null) { + return; + } + problem.ifPresent(p -> SharedMainSettingsManager.applyApkRejection(view, p)); + this.loadLocalAnisetteStatus(view); + }, error -> Log.e(TAG, "failed to import the chosen CoreADI", error)); + } + + private void copyCoreAdiLink() { + final ClipboardManager clipboard = + (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE); + if (clipboard != null) { + clipboard.setPrimaryClip(ClipData.newPlainText("iTunes 12.8.3", + MacCoreAdiFetcher.DMG_URL)); + Toast.makeText(this, R.string.exported_tags_code_copied, Toast.LENGTH_SHORT).show(); + } + } + /** * Picks an Apple Music APK to take the ADI libraries from. * @@ -972,9 +1043,12 @@ private void loadLocalAnisetteStatus(final View view) { .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( - result -> SharedMainSettingsManager.applyLocalAnisetteStatus( - view, result.first, result.second, - this.currentSettings.hasOwnAnisetteApk()), + result -> { + this.lastLocalAnisetteStatus = result.first; + SharedMainSettingsManager.applyLocalAnisetteStatus( + view, result.first, result.second, + this.currentSettings.hasOwnAnisetteApk()); + }, error -> Log.w(TAG, "could not determine the local Anisette status", error)); } diff --git a/app/src/main/java/dev/wander/android/opentagviewer/anisette/AnisetteStatus.java b/app/src/main/java/dev/wander/android/opentagviewer/anisette/AnisetteStatus.java index db57ecd1..c3af6121 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/anisette/AnisetteStatus.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/anisette/AnisetteStatus.java @@ -33,6 +33,16 @@ public enum State { * where doing so would help. Everything else is either fine or fixed by other means. */ APPLE_CHANGED, + /** + * The emulated Mac could not get Apple's macOS CoreADI: the download was blocked, failed, + * or came back as something other than the pinned build. + * + *

Its own state because the usual way out is a trap. A remote server signs in fine but, + * since Apple's 2026-10-12 change, gets no Find My token, so every report fetch afterwards + * answers 401. What does help is the file itself, downloaded on a computer and chosen + * here, which is what the sign-in screen offers in this state. + */ + NEEDS_COREADI, /** * Apple's library kills the process that loads it, on this device (issue #232). * @@ -74,9 +84,15 @@ public static AnisetteStatus of(final AnisetteSource source) { } final String reason = source.unavailableReason(); - if (reason != null && reason.contains(LocalAnisette.CRASHES_HERE_REASON)) { + // Either source's sentence. The emulated Mac's used to fall through to UNAVAILABLE, so a + // phone it crashed on was told to try a server rather than asked for a report. + if (reason != null && (reason.contains(LocalAnisette.CRASHES_HERE_REASON) + || reason.contains(EmulatedMacAnisette.CRASHES_HERE_REASON))) { return new AnisetteStatus(State.CRASHES_HERE, reason); } + if (reason != null && reason.contains(EmulatedMacAnisette.NO_COREADI_REASON)) { + return new AnisetteStatus(State.NEEDS_COREADI, reason); + } return new AnisetteStatus( looksLikeAppleChangedTheLibraries(reason) ? State.APPLE_CHANGED : State.UNAVAILABLE, @@ -109,9 +125,15 @@ public String detail() { public boolean failed() { return this.state == State.UNAVAILABLE || this.state == State.APPLE_CHANGED + || this.state == State.NEEDS_COREADI || this.state == State.CRASHES_HERE; } + /** Whether supplying Apple's macOS CoreADI (or the iTunes disk image) by hand would help. */ + public boolean needsCoreAdi() { + return this.state == State.NEEDS_COREADI; + } + /** Whether supplying an Apple Music APK by hand would help. */ public boolean needsOwnApk() { return this.state == State.APPLE_CHANGED; diff --git a/app/src/main/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisette.java b/app/src/main/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisette.java index 1785c5ce..668273d7 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisette.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisette.java @@ -74,6 +74,20 @@ public enum Purpose { "The emulated Mac crashed its process on this device, so a remote Anisette server is" + " used instead"; + /** + * Starts {@link #unavailableReason()} when CoreADI could not be got onto the phone: the + * download failed, or what came back was not the pinned build. {@link AnisetteStatus} matches + * on it to offer supplying the file by hand, which is the one thing that helps then. + */ + public static final String NO_COREADI_REASON = "Apple's macOS CoreADI could not be fetched"; + + private static final String LIBRARY_NAME = "CoreADI-4.19-x86_64"; + + /** Where CoreADI is kept, for {@link MacCoreAdiFetcher#importFrom} to put one supplied by hand. */ + public static File libraryFile(Context context) { + return new File(directoryFor(context), LIBRARY_NAME); + } + /** How long one generated set is reused. See {@code LocalAnisette.CACHE_FOR_MS}. */ private static final long CACHE_FOR_MS = 5_000; @@ -197,7 +211,7 @@ private static File directoryFor(Context context) { private static Library libraryIn(File directory) { return () -> { - final File target = new File(directory, "CoreADI-4.19-x86_64"); + final File target = new File(directory, LIBRARY_NAME); MacCoreAdiFetcher.ensure(target); return target; }; @@ -328,7 +342,10 @@ public boolean ensureReady() { if (opened != null) { opened.close(); } - this.unavailableReason = e.getMessage() == null ? e.toString() : e.getMessage(); + final String message = e.getMessage() == null ? e.toString() : e.getMessage(); + // Only the library step throws this, so it is a CoreADI that never arrived. + this.unavailableReason = e instanceof MacCoreAdiFetcher.FetchException + ? NO_COREADI_REASON + ": " + message : message; Log.w(TAG, "the emulated Mac is unavailable, falling back to a remote server: " + this.unavailableReason, e); return false; diff --git a/app/src/main/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcher.java b/app/src/main/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcher.java index 84893284..55832d6b 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcher.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcher.java @@ -2,6 +2,7 @@ import android.util.Log; +import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -51,6 +52,33 @@ public final class MacCoreAdiFetcher { private static final int CPU_TYPE_X86_64 = 0x01000007; + private static final int FAT_MAGIC = 0xCAFEBABE; + /** A thin 64-bit Mach-O, as its first four bytes read big-endian. */ + private static final int MH_CIGAM_64 = 0xCFFAEDFE; + + /** + * What a file has to hash to, and where the payload sits in the disk image. + * + *

A value rather than constants used directly, so a test can build a small disk image and + * library of its own: Apple's bytes cannot be checked into this repository. + */ + static final class Pins { + final long payloadOffset; + final int payloadLength; + final String payloadSha256; + final String librarySha256; + + Pins(long payloadOffset, int payloadLength, String payloadSha256, String librarySha256) { + this.payloadOffset = payloadOffset; + this.payloadLength = payloadLength; + this.payloadSha256 = payloadSha256; + this.librarySha256 = librarySha256; + } + } + + static final Pins APPLES = new Pins(PAYLOAD_OFFSET, PAYLOAD_LENGTH, PAYLOAD_SHA256, + MacCoreAdi.BUILD_SHA256); + private MacCoreAdiFetcher() { } @@ -135,8 +163,12 @@ private static byte[] fetchPayload(String url) throws FetchException { * @throws FetchException if either the payload or the library is not the pinned one */ static byte[] extract(byte[] payload) throws FetchException { + return extract(payload, APPLES); + } + + static byte[] extract(byte[] payload, Pins pins) throws FetchException { final String payloadHash = sha256(payload); - if (!PAYLOAD_SHA256.equals(payloadHash)) { + if (!pins.payloadSha256.equals(payloadHash)) { throw new FetchException("the installer bytes are not the expected ones (sha256 " + payloadHash + ")"); } @@ -149,16 +181,102 @@ static byte[] extract(byte[] payload) throws FetchException { } final byte[] framework = fileFromCpio(cpio, FRAMEWORK_PATH); - final byte[] library = slice(framework, CPU_TYPE_X86_64); + return checkedLibrary(slice(framework, CPU_TYPE_X86_64), pins); + } + private static byte[] checkedLibrary(byte[] library, Pins pins) throws FetchException { final String libraryHash = sha256(library); - if (!MacCoreAdi.BUILD_SHA256.equals(libraryHash)) { + if (!pins.librarySha256.equals(libraryHash)) { throw new FetchException("the library is not the expected build (sha256 " + libraryHash + ")"); } return library; } + /** + * Store a library the user supplied, for a phone that cannot download it from Apple. + * + *

Takes either of two files, told apart by their first four bytes: + *

+ * Both are checked against exactly the pins the download is, so a file supplied by hand can + * never run code the download would have refused. + * + * @return the library's bytes, once stored at {@code target} + * @throws FetchException with a reason worth showing, for any other file + */ + public static byte[] importFrom(InputStream in, File target) throws FetchException { + return importFrom(in, target, APPLES); + } + + static byte[] importFrom(InputStream in, File target, Pins pins) throws FetchException { + final byte[] library; + try (BufferedInputStream buffered = new BufferedInputStream(in)) { + buffered.mark(4); + final byte[] head = new byte[4]; + final int got = readUpTo(buffered, head); + buffered.reset(); + + final int magic = got == 4 ? be32(head, 0) : 0; + if (magic == FAT_MAGIC || magic == MH_CIGAM_64) { + final byte[] file = readAtMost(buffered, 64 << 20); + library = checkedLibrary( + magic == FAT_MAGIC ? slice(file, CPU_TYPE_X86_64) : file, pins); + } else { + if (!skipExactly(buffered, pins.payloadOffset)) { + throw new FetchException("the file is too small to be the iTunes 12.8.3" + + " disk image, and is not a CoreADI library either"); + } + final byte[] payload = new byte[pins.payloadLength]; + if (readUpTo(buffered, payload) != payload.length) { + throw new FetchException("the file is too small to be the iTunes 12.8.3" + + " disk image, and is not a CoreADI library either"); + } + library = extract(payload, pins); + } + } catch (final IOException e) { + throw new FetchException("could not read the file: " + + e.getClass().getSimpleName() + ": " + e.getMessage(), e); + } + + write(target, library); + Log.i(TAG, "stored a CoreADI library supplied by hand"); + return library; + } + + /** Fills as much of {@code into} as the stream has; returns how much that was. */ + private static int readUpTo(InputStream in, byte[] into) throws IOException { + int total = 0; + while (total < into.length) { + final int read = in.read(into, total, into.length - total); + if (read == -1) { + break; + } + total += read; + } + return total; + } + + /** False when the stream ends first. {@code skip} may stop short without being at the end. */ + private static boolean skipExactly(InputStream in, long count) throws IOException { + long left = count; + while (left > 0) { + final long skipped = in.skip(left); + if (skipped > 0) { + left -= skipped; + } else if (in.read() == -1) { + return false; + } else { + left--; + } + } + return true; + } + /** * One file's contents from an "odc" (old ASCII) cpio archive, which is what Apple's package * payloads are. diff --git a/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/SharedMainSettingsManager.java b/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/SharedMainSettingsManager.java index 74280254..99b5f911 100644 --- a/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/SharedMainSettingsManager.java +++ b/app/src/main/java/dev/wander/android/opentagviewer/ui/settings/SharedMainSettingsManager.java @@ -40,6 +40,7 @@ import dev.wander.android.opentagviewer.R; import dev.wander.android.opentagviewer.anisette.AnisetteStatus; import dev.wander.android.opentagviewer.anisette.AppleLibraryCrashReport; +import dev.wander.android.opentagviewer.anisette.MacCoreAdiFetcher; import dev.wander.android.opentagviewer.ui.error.ErrorReportActivity; import dev.wander.android.opentagviewer.db.repo.model.UserSettings; import dev.wander.android.opentagviewer.service.web.GithubRawUtilityFilesService; @@ -349,16 +350,32 @@ public static void applyLoginAnisetteFallback(final View root, final AnisetteSta // again - and there is nothing to try. What helps is knowing which phone it is. final boolean crashes = explain && state == AnisetteStatus.State.CRASHES_HERE; + // **Without CoreADI, the server is the trap, not the way out.** It signs in, and then + // every location fetch answers 401 (no Find My token since 2026-10-12). So the screen + // offers the file first and says what the server will not do. + final boolean needsCoreAdi = explain && status.needsCoreAdi(); + final View reason = root.findViewById(R.id.anisetteLoginFallbackReason); if (reason != null) { reason.setVisibility(explain ? VISIBLE : GONE); if (reason instanceof TextView) { ((TextView) reason).setText(crashes ? R.string.anisette_login_crashes_here + : needsCoreAdi + ? R.string.anisette_login_needs_coreadi : R.string.anisette_login_needs_server); } } + final View coreAdi = root.findViewById(R.id.anisetteCoreAdiContainer); + if (coreAdi != null) { + coreAdi.setVisibility(needsCoreAdi ? VISIBLE : GONE); + } + final TextView coreAdiLink = root.findViewById(R.id.anisetteCoreAdiLink); + if (coreAdiLink != null) { + coreAdiLink.setText(MacCoreAdiFetcher.DMG_URL); + } + final View report = root.findViewById(R.id.anisetteReportCrashButton); if (report != null) { report.setVisibility(crashes ? VISIBLE : GONE); @@ -367,6 +384,27 @@ public static void applyLoginAnisetteFallback(final View root, final AnisetteSta } } + /** + * Say why a file chosen as CoreADI was refused, or clear it with {@code null}. + * + * @param problem the importer's reason, shown inside the existing "not the version" sentence + */ + public static void applyCoreAdiRejection(final View root, final String problem) { + if (root == null) { + return; + } + final TextView rejection = root.findViewById(R.id.anisetteCoreAdiRejection); + if (rejection == null) { + return; + } + if (problem == null) { + rejection.setVisibility(GONE); + return; + } + rejection.setText(root.getContext().getString(R.string.anisette_apk_rejected, problem)); + rejection.setVisibility(VISIBLE); + } + private static void openTheCrashReport(final Context context, final AnisetteStatus status) { final Intent intent = ErrorReportActivity.intentFor(context, AppleLibraryCrashReport.describe(context, status), @@ -490,12 +528,24 @@ public static void applyLocalAnisetteStatus(final View root, final AnisetteStatu if (ownApk == null) { return; } - ownApk.setVisibility(status.needsOwnApk() ? VISIBLE : GONE); + // The same block serves both files: the Apple Music APK for the Android libraries, and + // CoreADI for the emulated Mac. Only one of them can be what is missing. + ownApk.setVisibility(status.needsOwnApk() || status.needsCoreAdi() ? VISIBLE : GONE); final TextView explanation = root.findViewById(R.id.anisetteOwnApkExplanation); - if (status.needsOwnApk() && explanation != null) { - explanation.setText(root.getContext().getString( - R.string.anisette_local_needs_own_file, apkVersion)); + if (explanation != null) { + if (status.needsCoreAdi()) { + explanation.setText(R.string.anisette_local_needs_coreadi); + } else if (status.needsOwnApk()) { + explanation.setText(root.getContext().getString( + R.string.anisette_local_needs_own_file, apkVersion)); + } + } + + final TextView whereToGet = root.findViewById(R.id.anisetteWhereToGetApkButton); + if (whereToGet != null) { + whereToGet.setText(status.needsCoreAdi() + ? R.string.anisette_coreadi_copy_link : R.string.anisette_where_to_get_apk); } final View clear = root.findViewById(R.id.anisetteClearApkButton); diff --git a/app/src/main/res/layout/main_app_settings.xml b/app/src/main/res/layout/main_app_settings.xml index ab5d4c75..e4029ed8 100644 --- a/app/src/main/res/layout/main_app_settings.xml +++ b/app/src/main/res/layout/main_app_settings.xml @@ -96,6 +96,66 @@ android:text="@string/anisette_report_crash" android:visibility="gone" /> + + + + + + + + + + + + + + + + + Kein https: Das API-Token wird unverschlüsselt gesendet. So richtest du das ein Akku %1$s + Dieses Telefon konnte eine benötigte Datei nicht von Apple herunterladen (macOS CoreADI). Lade das iTunes-12.8.3-Image über den Link unten herunter, am Computer oder im Browser, lege es auf dieses Telefon und wähle es hier aus. Ein Server kann dich zwar anmelden, aber die Standorte deiner Tags werden darüber nicht geladen. + Dieses Telefon konnte eine benötigte Datei nicht von Apple herunterladen (macOS CoreADI). Lade das iTunes-12.8.3-Image am Computer oder im Browser herunter, lege es auf dieses Telefon und wähle es hier aus. + Download-Link kopieren \ No newline at end of file diff --git a/app/src/main/res/values-en/strings.xml b/app/src/main/res/values-en/strings.xml index fdfa5fbb..4164b527 100644 --- a/app/src/main/res/values-en/strings.xml +++ b/app/src/main/res/values-en/strings.xml @@ -422,4 +422,7 @@ If Apple simply refused the request, waiting and trying again is worth doing fir Not https: the API token will be sent unencrypted. How to set this up Battery %1$s + This phone couldn\'t download a file it needs from Apple (macOS CoreADI). Download the iTunes 12.8.3 disk image from the link below, on a computer or in your browser, put it on this phone and choose it here. A server can still sign you in, but your tags\' locations won\'t load through one. + This phone couldn\'t download a file it needs from Apple (macOS CoreADI). Download the iTunes 12.8.3 disk image on a computer or in your browser, put it on this phone and choose it here. + Copy download link \ No newline at end of file diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index c3eb1870..c846714e 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -422,4 +422,7 @@ Si Apple a simplement refusé la requête, il vaut mieux attendre et réessayer. Pas en https : le jeton d\'API sera envoyé sans chiffrement. Comment le configurer Batterie %1$s + Ce téléphone n\'a pas pu télécharger un fichier nécessaire depuis Apple (macOS CoreADI). Téléchargez l\'image disque d\'iTunes 12.8.3 via le lien ci-dessous, sur un ordinateur ou dans votre navigateur, placez-la sur ce téléphone et choisissez-la ici. Un serveur peut toujours vous connecter, mais la position de vos balises ne se chargera pas par son intermédiaire. + Ce téléphone n\'a pas pu télécharger un fichier nécessaire depuis Apple (macOS CoreADI). Téléchargez l\'image disque d\'iTunes 12.8.3 sur un ordinateur ou dans votre navigateur, placez-la sur ce téléphone et choisissez-la ici. + Copier le lien de téléchargement \ No newline at end of file diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 1cd87e06..aa048a9d 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -422,4 +422,7 @@ Appleが要求を拒否しただけなら、少し待ってからもう一度お https ではありません。API トークンは暗号化されずに送信されます。 設定方法 電池 %1$s + この端末は Apple から必要なファイル(macOS CoreADI)をダウンロードできませんでした。下のリンクから iTunes 12.8.3 のディスクイメージをパソコンまたはブラウザでダウンロードし、この端末に置いてここで選択してください。サーバーでもサインインはできますが、タグの位置情報は読み込まれません。 + この端末は Apple から必要なファイル(macOS CoreADI)をダウンロードできませんでした。iTunes 12.8.3 のディスクイメージをパソコンまたはブラウザでダウンロードし、この端末に置いてここで選択してください。 + ダウンロードリンクをコピー \ No newline at end of file diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 762d013c..a29f68e5 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -422,4 +422,7 @@ Apple이 요청을 거부한 것뿐이라면 잠시 기다렸다가 다시 시 https가 아닙니다. API 토큰이 암호화되지 않은 채 전송됩니다. 설정 방법 배터리 %1$s + 이 휴대폰에서 Apple로부터 필요한 파일(macOS CoreADI)을 다운로드하지 못했습니다. 아래 링크에서 iTunes 12.8.3 디스크 이미지를 컴퓨터나 브라우저로 다운로드해 이 휴대폰에 넣은 뒤 여기서 선택하세요. 서버로도 로그인은 할 수 있지만 태그 위치는 불러오지 못합니다. + 이 휴대폰에서 Apple로부터 필요한 파일(macOS CoreADI)을 다운로드하지 못했습니다. iTunes 12.8.3 디스크 이미지를 컴퓨터나 브라우저로 다운로드해 이 휴대폰에 넣은 뒤 여기서 선택하세요. + 다운로드 링크 복사 \ No newline at end of file diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index fd0f2ab6..e89a66dc 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -422,4 +422,7 @@ Als Apple het verzoek simpelweg weigerde, is even wachten en opnieuw proberen he Geen https: het API-token wordt onversleuteld verstuurd. Zo stel je dit in Batterij %1$s + Deze telefoon kon een benodigd bestand niet van Apple downloaden (macOS CoreADI). Download de iTunes 12.8.3-schijfkopie via de link hieronder, op een computer of in je browser, zet hem op deze telefoon en kies hem hier. Een server kan je nog steeds aanmelden, maar de locaties van je tags laden daar niet mee. + Deze telefoon kon een benodigd bestand niet van Apple downloaden (macOS CoreADI). Download de iTunes 12.8.3-schijfkopie op een computer of in je browser, zet hem op deze telefoon en kies hem hier. + Downloadlink kopiëren \ No newline at end of file diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c3570d21..4a4372a5 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -422,4 +422,7 @@ Не https: токен API будет передан без шифрования. Как это настроить Батарея %1$s + Телефону не удалось скачать у Apple нужный файл (macOS CoreADI). Скачайте образ диска iTunes 12.8.3 по ссылке ниже — на компьютере или в браузере, — перенесите его на этот телефон и выберите здесь. Сервер по-прежнему может выполнить вход, но местоположения ваших меток через него не загрузятся. + Телефону не удалось скачать у Apple нужный файл (macOS CoreADI). Скачайте образ диска iTunes 12.8.3 на компьютере или в браузере, перенесите его на этот телефон и выберите здесь. + Скопировать ссылку для загрузки \ No newline at end of file diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index c5a35e6e..9ebbc6e4 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -422,4 +422,7 @@ 不是 https:API 令牌将以未加密方式发送。 如何设置 电量%1$s + 此手机无法从 Apple 下载所需的文件(macOS CoreADI)。请通过下方链接在电脑或浏览器中下载 iTunes 12.8.3 磁盘映像,放到此手机上并在此处选择。服务器仍可让你登录,但无法通过它加载标签的位置。 + 此手机无法从 Apple 下载所需的文件(macOS CoreADI)。请在电脑或浏览器中下载 iTunes 12.8.3 磁盘映像,放到此手机上并在此处选择。 + 复制下载链接 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index a4af8d0e..8bd30689 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -422,4 +422,7 @@ 不是 https:API 權杖將以未加密方式傳送。 如何設定 電量%1$s + 此手機無法從 Apple 下載所需的檔案(macOS CoreADI)。請透過下方連結在電腦或瀏覽器中下載 iTunes 12.8.3 磁碟映像,放到此手機上並在此處選擇。伺服器仍可讓你登入,但無法透過它載入標籤的位置。 + 此手機無法從 Apple 下載所需的檔案(macOS CoreADI)。請在電腦或瀏覽器中下載 iTunes 12.8.3 磁碟映像,放到此手機上並在此處選擇。 + 複製下載連結 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1e12e195..f8158ed4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -457,4 +457,7 @@ If Apple simply refused the request, waiting and trying again is worth doing fir Not https: the API token will be sent unencrypted. How to set this up Battery %1$s + This phone couldn\'t download a file it needs from Apple (macOS CoreADI). Download the iTunes 12.8.3 disk image from the link below, on a computer or in your browser, put it on this phone and choose it here. A server can still sign you in, but your tags\' locations won\'t load through one. + This phone couldn\'t download a file it needs from Apple (macOS CoreADI). Download the iTunes 12.8.3 disk image on a computer or in your browser, put it on this phone and choose it here. + Copy download link diff --git a/app/src/test/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisetteTest.java b/app/src/test/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisetteTest.java index b40f8043..1aef3c3b 100644 --- a/app/src/test/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisetteTest.java +++ b/app/src/test/java/dev/wander/android/opentagviewer/anisette/EmulatedMacAnisetteTest.java @@ -51,6 +51,8 @@ public class EmulatedMacAnisetteTest { /** Device ids Apple has provisioned already, and answers HTTP 433 for. */ private Set appleHasProvisioned; private int libraryFetches; + /** When set, getting CoreADI fails with this, as a blocked download would. */ + private Exception libraryFails; /** {@link NativeLoadGuard.Store} in memory. */ private static final class MemoryDeaths implements NativeLoadGuard.Store { @@ -99,6 +101,9 @@ private EmulatedMacAnisette in(final EmulatedMacAnisette.Shared shared, return new EmulatedMacAnisette(this.directory, settings, purpose, this.provenanceFile.provenance(), this.opener, () -> { this.libraryFetches++; + if (this.libraryFails != null) { + throw this.libraryFails; + } return this.library; }, (identity, adi) -> { @@ -313,6 +318,32 @@ public void aRemoteServerChosenInSettingsTouchesNothing() { assertEquals("", mac.otp()); } + /** + * A CoreADI that never arrived is marked as such, which is what makes the sign-in screen + * offer the file instead of a server that would fail every fetch. + */ + @Test + public void aCoreAdiThatCouldNotBeFetchedSaysSo() { + this.libraryFails = new MacCoreAdiFetcher.FetchException( + "Apple answered HTTP 403 to a range request for the library; expected 206"); + final EmulatedMacAnisette mac = inANewProcess(EmulatedMacAnisette.Purpose.SIGN_IN); + + assertFalse(mac.ensureReady()); + assertTrue(mac.unavailableReason(), + mac.unavailableReason().startsWith(EmulatedMacAnisette.NO_COREADI_REASON)); + assertTrue("the cause is kept for the log", mac.unavailableReason().contains("HTTP 403")); + } + + /** Any other failure is not mistaken for a missing CoreADI. */ + @Test + public void otherFailuresAreNotCalledAMissingCoreAdi() { + this.opener.failWith = new IOException("could not start the emulated Mac's process"); + final EmulatedMacAnisette mac = inANewProcess(EmulatedMacAnisette.Purpose.SIGN_IN); + + assertFalse(mac.ensureReady()); + assertFalse(mac.unavailableReason().contains(EmulatedMacAnisette.NO_COREADI_REASON)); + } + @Test public void anEmulatorThatWillNotStartFallsBack() { this.opener.failWith = new IOException("could not start the emulated Mac's process"); diff --git a/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcherTest.java b/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcherTest.java index 6856e268..916b2cbc 100644 --- a/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcherTest.java +++ b/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiFetcherTest.java @@ -1,6 +1,7 @@ package dev.wander.android.opentagviewer.anisette; import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -8,11 +9,13 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.zip.GZIPOutputStream; /** * Getting Apple's macOS CoreADI out of the iTunes installer, without Apple's bytes. @@ -171,4 +174,106 @@ public void aStoredFileOfTheWrongBuildIsFetchedAgainRatherThanUsed() throws Exce assertArrayEquals(bytes("some other build"), MacCoreAdiFetcher.readFile(target)); } } + + // --- Supplied by hand, for a phone that cannot download it --- + + /** A thin x86_64 Mach-O, as far as the first four bytes go. */ + private static final byte[] LIBRARY = concat( + new byte[]{(byte) 0xCF, (byte) 0xFA, (byte) 0xED, (byte) 0xFE}, + bytes("the x86_64 CoreADI")); + + private static final int OFFSET = 1000; + + private static byte[] concat(byte[]... parts) { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (final byte[] part : parts) { + out.write(part, 0, part.length); + } + return out.toByteArray(); + } + + private static byte[] gzip(byte[] data) throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (GZIPOutputStream zipped = new GZIPOutputStream(out)) { + zipped.write(data); + } + return out.toByteArray(); + } + + /** The installer payload: a gzipped cpio holding the universal framework binary. */ + private static byte[] payload() throws Exception { + return gzip(cpio("./" + MacCoreAdiFetcher.FRAMEWORK_PATH, + fat(bytes("thirty-two bit"), LIBRARY))); + } + + /** A disk image in miniature: the payload at a fixed offset, with other bytes either side. */ + private static byte[] diskImage() throws Exception { + final byte[] before = new byte[OFFSET]; + Arrays.fill(before, (byte) 'x'); + return concat(before, payload(), bytes("the rest of the image")); + } + + private static MacCoreAdiFetcher.Pins pins() throws Exception { + final byte[] payload = payload(); + return new MacCoreAdiFetcher.Pins(OFFSET, payload.length, + MacCoreAdiFetcher.sha256(payload), MacCoreAdiFetcher.sha256(LIBRARY)); + } + + private File target() { + return new File(this.folder.getRoot(), "CoreADI-4.19-x86_64"); + } + + private byte[] importing(byte[] file) throws Exception { + return MacCoreAdiFetcher.importFrom(new ByteArrayInputStream(file), target(), pins()); + } + + @Test + public void theDiskImageGivesTheSameLibraryTheDownloadWould() throws Exception { + assertArrayEquals(LIBRARY, importing(diskImage())); + assertArrayEquals(LIBRARY, MacCoreAdiFetcher.readFile(target())); + } + + @Test + public void theUniversalLibraryIsSlicedToX8664() throws Exception { + assertArrayEquals(LIBRARY, importing(fat(bytes("thirty-two bit"), LIBRARY))); + } + + @Test + public void theAlreadySlicedLibraryIsTakenAsItIs() throws Exception { + assertArrayEquals(LIBRARY, importing(LIBRARY)); + assertArrayEquals(LIBRARY, MacCoreAdiFetcher.readFile(target())); + } + + @Test + public void aLibraryOfAnotherBuildIsRefusedAndNothingIsStored() { + final byte[] other = concat(Arrays.copyOf(LIBRARY, 4), bytes("a newer CoreADI")); + + final MacCoreAdiFetcher.FetchException thrown = assertThrows( + MacCoreAdiFetcher.FetchException.class, () -> importing(other)); + + assertTrue(thrown.getMessage(), thrown.getMessage().contains("not the expected build")); + assertFalse(target().exists()); + } + + @Test + public void aDiskImageOfAnotherVersionIsRefused() throws Exception { + final byte[] image = diskImage(); + image[OFFSET + 20] ^= 1; + + final MacCoreAdiFetcher.FetchException thrown = assertThrows( + MacCoreAdiFetcher.FetchException.class, () -> importing(image)); + + assertTrue(thrown.getMessage(), thrown.getMessage().contains("not the expected ones")); + assertFalse(target().exists()); + } + + @Test + public void aFileThatIsNeitherSaysSo() { + final MacCoreAdiFetcher.FetchException thrown = assertThrows( + MacCoreAdiFetcher.FetchException.class, + () -> importing(bytes("a holiday photo"))); + + assertTrue(thrown.getMessage(), thrown.getMessage().contains("too small")); + assertFalse(target().exists()); + } } diff --git a/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiRealImageTest.java b/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiRealImageTest.java new file mode 100644 index 00000000..c6afb7d6 --- /dev/null +++ b/app/src/test/java/dev/wander/android/opentagviewer/anisette/MacCoreAdiRealImageTest.java @@ -0,0 +1,47 @@ +package dev.wander.android.opentagviewer.anisette; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assume.assumeTrue; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +/** + * Apple's real iTunes 12.8.3 disk image through {@link MacCoreAdiFetcher#importFrom}, against the + * real pins. Everything else here uses miniature fakes, because Apple's bytes cannot be checked + * in; this is the one place the constants meet the actual file. + * + *

Opt-in. Skipped unless {@code COREADI_DMG} names the image (291 MB, from + * {@link MacCoreAdiFetcher#DMG_URL}): + * + *

+ * COREADI_DMG=/path/to/iTunes12.8.3.dmg ./gradlew :app:testDebugUnitTest --tests '*MacCoreAdiRealImageTest'
+ * 
+ */ +public class MacCoreAdiRealImageTest { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + @Test + public void theRealDiskImageGivesThePinnedLibrary() throws Exception { + final String path = System.getenv("COREADI_DMG"); + assumeTrue("set COREADI_DMG to the iTunes 12.8.3 disk image to run this", + path != null && new File(path).isFile()); + + final File target = new File(this.folder.getRoot(), "CoreADI-4.19-x86_64"); + final byte[] library; + try (InputStream in = new FileInputStream(path)) { + library = MacCoreAdiFetcher.importFrom(in, target); + } + + assertEquals(MacCoreAdi.BUILD_SHA256, MacCoreAdiFetcher.sha256(library)); + assertEquals(MacCoreAdi.BUILD_SHA256, + MacCoreAdiFetcher.sha256(MacCoreAdiFetcher.readFile(target))); + } +}