Compare commits

...

14 commits

Author SHA1 Message Date
b79e03bbf4 CONTRIBUTING: Stress expectation for committers
All checks were successful
Build Debug APKs / build-debug (push) Successful in 4m45s
2026-11-08 22:57:10 -05:00
a2fe586441 CONTRIBUTING: Clarify when LLM use for capturing hardware / carrier
All checks were successful
Build Debug APKs / build-debug (push) Successful in 4m55s
behavior is allowable
2026-11-08 19:34:16 -05:00
6b5fe5d28c Update CONTRIBUTING.md again
Some checks are pending
Build Debug APKs / build-debug (push) Waiting to run
2026-11-08 19:33:34 -05:00
8bb3652b31 More explanation on LLM policy
Some checks are pending
Build Debug APKs / build-debug (push) Waiting to run
2026-11-08 19:26:35 -05:00
2ff540bc52 Fix typo
Some checks are pending
Build Debug APKs / build-debug (push) Waiting to run
2026-11-08 19:18:01 -05:00
5804aa5d17 Add contributing guidelines and LLM policy
Some checks are pending
Build Debug APKs / build-debug (push) Waiting to run
2026-11-08 19:16:27 -05:00
412a4649e4 docs: add application notes (#368)
Some checks are pending
Build Debug APKs / build-debug (push) Waiting to run
Reviewed-on: #368
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2026-11-09 00:42:52 +01:00
2cbd7a1b3f fix AOSP build
All checks were successful
Build Debug APKs / build-debug (push) Successful in 4m47s
Closes #367
2026-10-27 17:24:44 -04:00
055d1e2cac feat: Profile download API via EuiccService (#366)
All checks were successful
Build Debug APKs / build-debug (push) Successful in 5m36s
Closes #99. Closes #360 (supersedes that PR).

Profile metadata fetch and profile download APIs now implemented. Fetching metadata initiates a download session, which gets preserved until profile download is called.

This still contains some horrible code that we probably will have to deal with more systematically later. Some of these aren't really fixable without reworking entirely how EuiccChannelManagerService works. For example the section of code in OpenEuiccService that serializes all OpenEuiccService methods against themselves and EuiccChannelManagerService tasks -- because it needs to serialize against 2 separate things, the code is extremely complicated and likely fragile. Android also asks for confirmation code much later in the process, which means we need to be able to supply that to the download process. Currently this is done by adding a field on top of the confirmation state shared with lpac-jni, but this really should be done better.

Much of the code assumes that the Android platform only initiates one download at a time. If it does two at a time a bunch of things may break. We try to be defensive and do the sensitive thing even if it happens, but we can't be perfect here.

Assisted-by: claude-opus-5.5, deepseek-v4-flash, qwen3.8-flash-next
Co-authored-by: Macktherealonereally <macdev@mackthessd.org>
Reviewed-on: #366
2026-10-26 04:55:22 +01:00
89d677e07d OpenEuiccService: Don't ignore the only removable eUICC (#358)
All checks were successful
Build Debug APKs / build-debug (push) Successful in 6m58s
`shouldIgnoreSlot()` returns **true for slots to ignore**. On devices without an internal eUICC, its own comment says it should *expose* the first removable eUICC to the system:

```kotlin
// Otherwise, we can report at least one removable eUICC to the system without confusing it too much.
telephonyManager.uiccCardsInfoCompat.firstOrNull { it.isEuicc }?.physicalSlotIndex == physicalSlotId
```

The comparison is inverted, so exactly that slot is ignored. Every `EuiccService` call on it (`onGetEid`, `onGetDownloadableSubscriptionMetadata`, `onDownloadSubscription`, `onSwitchToSubscription…`) returns `RESULT_FIRST_USER` within a few milliseconds.

**How it showed up:** on a Samsung Galaxy S21 (SM-G991B, LineageOS 23.2, OpenEUICC as system LPA), the Samsung RIL reports the built-in eUICC as *removable* (`isRemovable=true`), so `hasInternalEuicc` is false. `EuiccManager` downloads from carrier apps failed immediately. The log showed `OpenEuiccService: onGetDownloadableSubscriptionMetadata slotId=1 portIndex=0 ...`, and 11 ms later the call returned an error to EuiccController without a single APDU being sent (the app showed its generic install error). Meanwhile the same eUICC worked fine inside the OpenEUICC UI, which doesn't go through `shouldIgnoreSlot()`.

**Fix:** `==` → `!=`.

**Testing:** with the fix, the platform download flow reaches the eUICC (metadata → carrier-privilege check → download). On 2026-09-27 a travel-eSIM provider's app installed its profile end to end through `EuiccManager` on that phone (the app-side changes are in a separate PR).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #358
Co-authored-by: Macktherealonereally <macdev@mackthessd.org>
Co-committed-by: Macktherealonereally <macdev@mackthessd.org>
2026-09-28 15:43:01 +02:00
7c05c06d14 feat: Make default ES10x MSS overlayable (#357)
All checks were successful
Build Debug APKs / build-debug (push) Successful in 7m11s
Expose config_es10x_mss_default so device trees can raise MSS where small LoadBPP STORE DATA chains fail.

Change-Id: I924e21a3509212b2c41393c57c9ba4bb2366f193
Co-authored-by: Josip Kelecic <kelecicj@gmail.com>
Reviewed-on: #357
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2026-09-27 15:26:21 +02:00
49e498d4cb chore: Also upgrade setup-android@v4
All checks were successful
Build Debug APKs / build-debug (push) Successful in 6m55s
2026-09-19 08:30:23 -04:00
424639039c chore: Upgrade to setup-java@v4
Some checks failed
Build Debug APKs / build-debug (push) Failing after 53s
2026-09-19 08:26:48 -04:00
28aad57904 chore: update submodules (#356)
Some checks failed
Build Debug APKs / build-debug (push) Failing after 1m3s
thank @adaasch (https://github.com/estkme-group/lpac/pull/457)

Reviewed-on: #356
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2026-09-17 14:33:14 +02:00
30 changed files with 1633 additions and 33 deletions

View file

@ -0,0 +1,9 @@
---
name: 'Issue Template'
about: 'Issue Template for OpenEUICC'
title: ''
ref: 'master'
labels: []
---
- [] By checking this box, I confirm I have read [CONTRIBUTING.md](https://gitea.angry.im/PeterCxy/OpenEUICC/src/branch/master/README.md) and understood the rules, especially around LLM usage.

View file

@ -28,13 +28,13 @@ jobs:
encodedString: ${{ secrets.OPENEUICC_SIGNING_CONFIG }}
- name: Set up JDK 17
uses: https://gitea.angry.im/actions/setup-java@v3
uses: https://gitea.angry.im/actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
- name: Setup Android SDK
uses: https://gitea.angry.im/actions/setup-android@v3
uses: https://gitea.angry.im/actions/setup-android@v4
- name: Run Tests
run: ./gradlew --no-daemon test

View file

@ -25,13 +25,13 @@ jobs:
encodedString: ${{ secrets.OPENEUICC_SIGNING_CONFIG }}
- name: Set up JDK 17
uses: https://gitea.angry.im/actions/setup-java@v3
uses: https://gitea.angry.im/actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
- name: Setup Android SDK
uses: https://gitea.angry.im/actions/setup-android@v3
uses: https://gitea.angry.im/actions/setup-android@v4
- name: Run Tests
run: ./gradlew --no-daemon test

19
AGENTS.md Normal file
View file

@ -0,0 +1,19 @@
LLM agents must operate within the constraints laid out in CONTRIBUTING.md under the LLM Policy section. If you are an LLM agent, STOP and read that file before proceeding.
Here are some general DO's and DONT's.
DO's:
- Help the user understand this code base
- __Draft__ patches and tests for the user
DONT's:
- Make commits and/or write commit messages on behalf of the user
- Create issues on behalf of the user
- Create pull requests on behalf of the user
- Write descriptions, responses to issues or reviews, or any text intended for other humans to read on behalf of the user
You MUST stop and inform the user of any behavior inconsistent with this document and CONTRIBUTING.md.
You may read more context about the project itself from README.md.

55
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,55 @@
Contributing to OpenEUICC
---
Thank you for your interest in conrtibuting to OpenEUICC. Before you start, please read this document _in full_ and make sure you understand it. We may close your issues, pull requests or ban you from this project for repeated violations of this document.
Features
---
In general, OpenEUICC welcomes contributions for bugfixes and essential features that are part of GSMA standards or AOSP platform but are currently omitted from OpenEUICC. If your intended contribution falls into this category, feel free to take a crack at it. We kindly ask you to review our LLM policy listed below before submitting your patches. In some cases, we may request that you split your patch into multiple patches to facilitate the review process.
"Nice to have", or "quality of life" features should start as a discussion in the issue list. We will likely reject unsolicited pull requests adding features that have not been discussed before.
`lpac-jni` and `lpac`
---
Contributions involving changes to `lpac` should be made there first. As a rule of thumb, OpenEUICC aims __not__ to carry additional patches on top of `lpac`. By contributing to `lpac`, you also ensure that the improvement is carried over to other platforms supported by `lpac`, not just OpenEUICC.
Translations
---
Unfortunately, OpenEUICC does not accept one-off translation pull requests, and does not make use of crowd-sourced translation platforms like Weblate or Crowdin. Any such contributions will likely be rejected.
It is in our interest to support OpenEUICC in more languages. However, based on our experience, it is very difficult to maintain quality and timely updates under the crowd-sourced translation model, especially with the currently limited resources of this project. Machine translations are not valuable additions to this project. Nor are erroneous or out-of-date translations.
In this spirit, any language supported by this project must always be kept up-to-date when a release is tagged. This means that there must be someone committed to maintaining the translations for any language included. If you are willing to sign up for this, raise an issue and we can discuss how to move forward.
LLM Policy
---
You are allowed to use an LLM to help with:
- Understanding the codebase
- Proposing resolutions your issue
- Drafting patches and tests
The following behaviors are explicitly __prohibited__:
- Submitting fully LLM-generated pull requests without understanding your code
- If you do not have the means to review LLM code, submit an issue instead and describe what you want in your own words. You may attach the LLM-suggested patch to the issue. __Do not submit a pull request that you do not understand__.
- Handling pull request review comments purely through LLMs
- We do not need meat proxies to address review comments. That is pure waste of time.
- __We expect the committer to be able to explain design decisions in their own words.__ Unexplanable and undefensible design will not be accepted. Discuss in the issue list if unsure.
- Posting LLM-generated text in the issue list, pull requests, commit messages, or in responses to issues or pull request reviews
- If you find it valuable, it is okay to, for example, attach a LLM transcript for _your attempt at diagnosing the issue_. It cannot be the main bulk of your submission. You must describe what you understand of the issue and/or fix in your own words.
- Unsolicited, automated issue or pull request creation with the help of LLM tools (or really any automation in general)
Before submitting pull requests, we kindly ask you to understand that most of the maintainers also have access to the same tools as you do, and a purely LLM generated pull request offers no value without your expertise and input. If your contribution boils down to only token costs, it probably belongs to a discussion in the issue list instead.
If you have the ability to test against some unique hardware configurations or carriers, but you could not code or review code yourself, it may be more effective to:
- Capture that behavior in tests, possibly with an initial draft implementation (for which you _may_ ask LLM for assistance)
- Start a discussion in the issue list, submit your expected behavior, the test suite that captures it, and possibly a draft implementation if your tests cannot be produced standalone (e.g. to proceed to a certain point you need to implement part of the feature you desire). Submit them __cleanly separated__ and describe what you want __in your own words__.
See an example of how this could be done in [this pull request](https://gitea.angry.im/PeterCxy/OpenEUICC/pulls/360) and how it was resolved.

View file

@ -403,9 +403,14 @@ open class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMark
.collect()
}
/**
* The download waits at ProfileDownloadState.ConfirmingDownload for a Boolean on the
* backChannel, for at most confirmationTimeoutMillis. The backChannel is closed after that.
*/
open fun launchProfileDownloadTask(
slotId: Int, portId: Int, seId: EuiccChannel.SecureElementId,
input: ProfileDownloadInput,
confirmationTimeoutMillis: Long = 60 * 1000,
): ForegroundTaskHandle =
launchForegroundTask(
getString(R.string.task_profile_download),
@ -435,13 +440,16 @@ open class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMark
// because we don't run download on the main thread; see withEuiccChannel.
return@downloadProfile runBlocking {
try {
// We can't wait indefinitely; just time out after 1 minute.
withTimeout(60 * 1000) {
// We can't wait indefinitely; just time out.
withTimeout(confirmationTimeoutMillis) {
backChannel.receive() as Boolean
}
} catch (_: TimeoutCancellationException) {
// Default to cancelling / aborting here if we didn't receive a confirmation signal
false
} finally {
// Late confirmations fail to send instead of getting lost
backChannel.close()
}
}
}

View file

@ -89,7 +89,7 @@ open class SettingsFragment : PreferenceFragmentCompat(), OpenEuiccContextMarker
.bindBooleanFlow(preferenceRepository.refreshAfterSwitchFlow)
requirePreference<ListPreference>("pref_developer_es10x_mss")
.bindIntFlow(preferenceRepository.es10xMssFlow, 63)
.bindIntFlow(preferenceRepository.es10xMssFlow, defaultEs10xMss(requireContext()))
requirePreference<Preference>("pref_developer_isdr_aid_list").apply {
intent = Intent(requireContext(), IsdrAidListActivity::class.java)

View file

@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.fragment.app.Fragment
import im.angry.openeuicc.OpenEuiccApplication
import im.angry.openeuicc.common.R
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.Base64
@ -79,6 +80,9 @@ internal object PreferenceConstants {
""".trimIndent()
}
fun defaultEs10xMss(context: Context): Int =
context.resources.getInteger(R.integer.config_es10x_mss_default)
open class PreferenceRepository(private val context: Context) {
// Expose flows so that we can also handle default values
// ---- Profile Notifications ----
@ -101,7 +105,7 @@ open class PreferenceRepository(private val context: Context) {
PreferenceConstants.DEFAULT_AID_LIST,
{ Base64.getEncoder().encodeToString(it.encodeToByteArray()) },
{ Base64.getDecoder().decode(it).decodeToString() })
val es10xMssFlow = bindFlow(PreferenceKeys.ES10X_MSS, 63)
val es10xMssFlow = bindFlow(PreferenceKeys.ES10X_MSS, defaultEs10xMss(context))
val httpProxyFlow = bindFlow(PreferenceKeys.HTTP_PROXY, "")
protected fun <T> bindFlow(

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--
Default ES10x maximum segment size (MSS) when the user has not set
pref_developer_es10x_mss. Device overlays may raise this (e.g. to 255)
for eUICCs that mishandle small LoadBPP STORE DATA chains.
-->
<integer name="config_es10x_mss_default">63</integer>
</resources>

View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<overlayable name="OpenEUICC">
<policy type="system|product|vendor">
<item type="integer" name="config_es10x_mss_default" />
</policy>
</overlayable>
</resources>

View file

@ -75,7 +75,8 @@ class EuiccChannelManagerServiceTest {
private suspend fun awaitTaskDone(
handle: EuiccChannelManagerService.ForegroundTaskHandle
): ForegroundTaskState.Done = coroutineScope {
val states = mutableListOf<ForegroundTaskState>()
// Written by the collector on Dispatchers.Default while awaitMainLooper() reads it
val states = java.util.concurrent.CopyOnWriteArrayList<ForegroundTaskState>()
val collector = async(Dispatchers.Default) { handle.stateFlow.collect { states += it } }
try {
awaitMainLooper {
@ -132,4 +133,21 @@ class EuiccChannelManagerServiceTest {
val done = awaitTaskDone(handle)
assertNull(done.error)
}
@Test
fun `download task cancels when no confirmation arrives within the timeout`() = runBlocking {
val handle = service.launchProfileDownloadTask(
1, 2, seId, input,
confirmationTimeoutMillis = 100
)
startService()
awaitMainLooper { lpa.downloadStarted.isCompleted }
// Nothing is sent on the back channel.
assertEquals(false, lpa.awaitDownloadResult())
// A late confirmation is refused
assertFalse(handle.backChannel.trySend(true).isSuccess)
assertNull(awaitTaskDone(handle).error)
}
}

View file

@ -20,7 +20,7 @@ android {
defaultConfig {
applicationId = "im.angry.openeuicc"
minSdk = 30
minSdk = 31
targetSdk = 37
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@ -35,6 +35,18 @@ android {
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
testOptions {
unitTests {
// Robolectric needs real resources (task titles, dialog themes)
isIncludeAndroidResources = true
}
}
sourceSets {
// Reuse app-common's Robolectric mocks (EuiccChannel / EuiccChannelManager / test application)
getByName("test").java.srcDir("../app-common/src/test/java/im/angry/openeuicc/testutil")
}
}
kotlin {
@ -48,7 +60,13 @@ dependencies {
implementation(project(":libs:hidden-apis-shim"))
implementation(project(":libs:lpac-jni"))
implementation(project(":app-common"))
// This is a massiave hack. We need testImplementation because the test classes
// need to be loadable against only public android.jar. However, once Robolectic
// starts running tests, the real classes from android-all.jar take precedence.
// FIXME: Probably make it so that this is not utterly fragile...
testImplementation(project(":libs:hidden-apis-stub"))
testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.17-beta-4")
androidTestImplementation("androidx.test.ext:junit:1.3.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
}

View file

@ -56,6 +56,27 @@
</intent-filter>
</activity>
<!--
LUI resolution activity, started by com.android.phone's
EuiccResolutionUiDispatcherActivity. Like all LUI components, it must require
BIND_EUICC_SERVICE and declare a non-zero priority (EuiccConnector.findBestActivity).
-->
<activity
android:name=".ui.EuiccResolutionActivity"
android:excludeFromRecents="true"
android:exported="true"
android:permission="android.permission.BIND_EUICC_SERVICE"
android:theme="@style/Theme.App.DeepLinkTransparent">
<intent-filter android:priority="100">
<action android:name="android.service.euicc.action.RESOLVE_NO_PRIVILEGES" />
<action android:name="android.service.euicc.action.RESOLVE_DEACTIVATE_SIM" />
<action android:name="android.service.euicc.action.RESOLVE_RESOLVABLE_ERRORS" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.service.euicc.category.EUICC_UI" />
</intent-filter>
</activity>
<service
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
android:enabled="false"

View file

@ -2,11 +2,15 @@ package im.angry.openeuicc.service
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.service.euicc.DownloadSubscriptionResult
import android.service.euicc.EuiccProfileInfo
import android.service.euicc.EuiccService
import android.service.euicc.GetDefaultDownloadableSubscriptionListResult
import android.service.euicc.GetDownloadableSubscriptionMetadataResult
import android.service.euicc.GetEuiccProfileInfoListResult
import android.telephony.TelephonyManager
import android.telephony.UiccAccessRule
import android.telephony.UiccSlotMapping
import android.telephony.euicc.DownloadableSubscription
import android.telephony.euicc.EuiccInfo
@ -14,18 +18,62 @@ import android.util.Log
import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.service.EuiccChannelManagerService.Companion.waitDone
import im.angry.openeuicc.service.EuiccChannelManagerService.ForegroundTaskHandle
import im.angry.openeuicc.service.EuiccChannelManagerService.ForegroundTaskState
import im.angry.openeuicc.util.*
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import net.typeblog.lpac_jni.LocalProfileInfo
import net.typeblog.lpac_jni.ProfileClass
import net.typeblog.lpac_jni.ProfileDownloadInput
import net.typeblog.lpac_jni.ProfileDownloadState
import kotlin.time.Duration.Companion.milliseconds
class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
companion object {
const val TAG = "OpenEuiccService"
/**
* The profile download that OpenEuiccService left waiting for confirmation in
* EuiccChannelManagerService, if any, together with the activation code it was started
* for. See pendingDownloadTask.
*/
@Volatile
private var pendingDownload: PendingDownload? = null
/**
* This lock is used in withEuiccManager() to serialize access to EuiccManager in this class.
* See that method for details.
*/
private val euiccLock = Mutex()
/**
* Cancel the download left waiting for confirmation, if there is one.
*
* It is assumed that the pending download is the one just declined; the platform is
* unlikely to have started another order this quickly.
*/
suspend fun cancelPendingDownload(euiccChannelManagerService: EuiccChannelManagerService) {
euiccLock.withLock {
pendingDownload?.let { pending ->
euiccChannelManagerService.recoverForegroundTaskSubscriber(pending.taskId)
?.backChannel?.trySend(false)
}
pendingDownload = null
}
}
}
// A download task left in EuiccChannelManagerService waiting for confirmation.
// LPAString is remembered to prevent reuse across different download sessions however unlikely.
// Confirmation code is not included here since it does not change the identity of the profile being downloaded,
// and could be supplied later.
private data class PendingDownload(val taskId: Long, val lpaString: LPAString)
private val seId = EuiccChannel.SecureElementId.DEFAULT
private val hasInternalEuicc by lazy {
@ -40,7 +88,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
} else {
// Otherwise, we can report at least one removable eUICC to the system without confusing
// it too much.
telephonyManager.uiccCardsInfoCompat.firstOrNull { it.isEuicc }?.physicalSlotIndex == physicalSlotId
telephonyManager.uiccCardsInfoCompat.firstOrNull { it.isEuicc }?.physicalSlotIndex != physicalSlotId
}
private data class EuiccChannelManagerContext(
@ -58,9 +106,18 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
* This ensures that we only spawn and connect to APDU channels when we absolutely need to,
* instead of keeping them open unnecessarily in the background at all times.
*
* This function also serializes all access to EuiccChannelManager from this class with a mutex,
* and it also ensures that when it calls fn(), no other foreground tasks managed by EuiccChannelManagerService
* are running. This is currently a massive hack and requires fragile interaction between the two systems,
* and is EXTREMELY hacky. THIS SHALL BE REPLACED AS SOON AS POSSIBLE.
*
* This function cannot be inline because non-local returns may bypass to unbind
*/
private fun <T> withEuiccChannelManager(fn: suspend EuiccChannelManagerContext.() -> T): T {
@OptIn(DelicateCoroutinesApi::class)
private fun <T> withEuiccChannelManager(
waitForDownload: Boolean = true,
fn: suspend EuiccChannelManagerContext.() -> T
): T {
val (binder, unbind) = runBlocking {
bindServiceSuspended(
Intent(this@OpenEuiccService, EuiccChannelManagerService::class.java),
@ -74,11 +131,50 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
val localBinder = binder as EuiccChannelManagerService.LocalBinder
val ret = runBlocking {
EuiccChannelManagerContext(localBinder.service).fn()
val ret = try {
runBlocking {
// Wrapped in Result so that a legitimate null returned by fn() (e.g. onGetEid on
// an unmapped slot) is not confused with "fn() has not run yet".
var result: kotlin.Result<T>? = null
// THIS IS WHERE I GO TO HELL FOR KEEPING THIS HORRIBLE SECTION OF CODE.
// The main complexity here is that we need to serialize on both the mutex _in this class_,
// and also on the foreground task system managed by EuiccChannelManagerService.
// If any other method is currently accessing EuiccChannelManager, OR if any foreground task
// is running, even if they're not launched from this service, we must not allow the callback
// to run.
while (true) {
val task = euiccLock.withLock {
if (waitForDownload) {
val pending = pendingDownload
val task = pending?.taskId?.let {
localBinder.service.recoverForegroundTaskSubscriber(it)?.takeIf { handle ->
// This is okay for a similar reason as pendingDownloadTask().
!handle.backChannel.isClosedForSend
}
}
if (task == null) {
// The task is gone or has already finished
if (pending != null) pendingDownload = null
result =
runCatching { EuiccChannelManagerContext(localBinder.service).fn() }
}
task
} else {
result =
runCatching { EuiccChannelManagerContext(localBinder.service).fn() }
null
}
}
if (task == null) break
task.stateFlow.waitDone()
}
// Always assigned by the time the loop breaks
checkNotNull(result).getOrThrow()
}
} finally {
unbind()
}
unbind()
return ret
}
@ -133,7 +229,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
} catch (_: Exception) {
// Ignore
} finally {
delay(backoff.toLong())
delay(backoff.toLong().milliseconds)
}
} while (System.currentTimeMillis() - startTimeMillis < timeoutMillis)
return null
@ -151,14 +247,271 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
// Not implemented
}
private fun DownloadableSubscription.parseActivationCode(): LPAString? =
encodedActivationCode?.let { runCatching { LPAString.parse(it) }.getOrNull() }
// Wait for a download task to reach ConfirmingDownload; null if it failed before
private suspend fun ForegroundTaskHandle.awaitConfirmingDownload() =
// FIXME: This only awaits for ConfirmingDownload, but not later states. What happens if we happen to
// race against the task in a way that makes it go past that state when we get here?
// It should probably not happen normally since Android should not launch another download task
// before it learns about teh completion of a previous one, but we probably need to address this.
stateFlow.first {
it is ForegroundTaskState.Done ||
(it as? ForegroundTaskState.InProgress)?.context is ProfileDownloadState.ConfirmingDownload
}.let { (it as? ForegroundTaskState.InProgress)?.context as? ProfileDownloadState.ConfirmingDownload }
// Returns the download task left pending by the metadata fetch call waiting for confirmation to
// finish, but only if it was started for the same activation code.
// Call sites should probably not expect a pending download task to always exist.
// If it does not, you should probably just launch a new one via launchAndRememberDownloadTask,
// which also cancels any pending download task for other sessions.
@OptIn(DelicateCoroutinesApi::class)
private fun EuiccChannelManagerContext.pendingDownloadTask(lpaString: LPAString): ForegroundTaskHandle? {
val pending = pendingDownload ?: return null
if (pending.lpaString != lpaString) {
// A task is pending, but for another activation code. Leave it remembered so that
// launchAndRememberDownloadTask cancels it; just do not reuse it here.
return null
}
return euiccChannelManagerService.recoverForegroundTaskSubscriber(pending.taskId)?.takeIf {
// Technically this is racy because the backChannel could be closed as we are
// checking this status, but that is unlikely, and even if it happened, we would
// just return a task handle that will emit an error (or Done). The user may see
// a transient error and be asked to try again.
!it.backChannel.isClosedForSend
} ?: run {
// Lazily clear the remembered task now that we know it is gone (or no longer waiting).
// As its name suggests this variable and this function only cares about tasks left over by the
// metadata fetch function.
pendingDownload = null
null
}
}
/**
* Launch a profile download task based on an existing bound EuiccChannelManager,
* and remember it as pending for future confirmation.
*
* This function is almost entirely for the purpose of onGetDownloadableSubscriptionMetadata.
* To acquire profile metadata, we must start a downlaod session, but onGetDownloadableSubscriptionMetadata
* also must return once metadata is fetched. So it leaves two options: you either cancel the session
* at that point, which, on many SM-DP+ servers, will also invalidate the matching code; or, you
* keep the session around somehow and reuse it when the user finally proceeds to download.
*
* We keep the download task running in background for up to 5 minutes. This should be more than enough
* for "normal" download sessions.
*
* Of course, it is also possible to launch a download task directly as part of onDownloadSubscription.
* That probably does not happen except for privileged caller apps (system privileged)/
*
* Returns null if the caller should return RESULT_MUST_DEACTIVATE_SIM.
*/
private suspend fun EuiccChannelManagerContext.launchAndRememberDownloadTask(
slotId: Int,
portIndex: Int,
lpaString: LPAString,
confirmationCode: String?,
forceDeactivateSim: Boolean
): ForegroundTaskHandle? {
// Only one task can run at a time; don't wait until another waiting download times out.
pendingDownload?.let { pending ->
euiccChannelManagerService.recoverForegroundTaskSubscriber(pending.taskId)
?.backChannel?.trySend(false)
}
pendingDownload = null
val port = euiccChannelManager.findFirstAvailablePort(slotId).takeIf { it >= 0 } ?: run {
if (!forceDeactivateSim) return null
val port = if (portIndex >= 0) portIndex else 0
ensurePortIsMapped(slotId, port)
retryWithTimeout(5000) {
euiccChannelManager.withEuiccChannel(slotId, port, seId) { channel ->
if (!channel.valid) {
throw IllegalStateException("Slot $slotId port $port is unavailable; may need to try again")
}
port
}
} ?: throw IllegalStateException("Slot $slotId port $port did not become available")
}
val imei = euiccChannelManager.withEuiccChannel(slotId, port, seId) { channel ->
runCatching { telephonyManager.getImei(channel.logicalSlotId) }.getOrNull()
}
euiccChannelManagerService.waitForForegroundTask()
val handle = euiccChannelManagerService.launchProfileDownloadTask(
slotId,
port,
seId,
ProfileDownloadInput(
lpaString.address,
lpaString.matchingId,
imei,
confirmationCode
),
// Leaves time for the user to consent or enter a confirmation code in between
5 * 60 * 1000
)
pendingDownload = PendingDownload(handle.taskId, lpaString)
return handle
}
override fun onGetDownloadableSubscriptionMetadata(
slotId: Int,
subscription: DownloadableSubscription?,
forceDeactivateSim: Boolean
): GetDownloadableSubscriptionMetadataResult {
// Stub: return as-is and do not fetch anything
// This is incompatible with carrier eSIM apps; should we make it compatible?
return GetDownloadableSubscriptionMetadataResult(RESULT_OK, subscription)
): GetDownloadableSubscriptionMetadataResult =
if (subscription == null) {
GetDownloadableSubscriptionMetadataResult(RESULT_FIRST_USER, null)
} else {
// -1 = any port
onGetDownloadableSubscriptionMetadata(slotId, -1, subscription, forceDeactivateSim)
}
override fun onGetDownloadableSubscriptionMetadata(
slotId: Int,
portIndex: Int,
subscription: DownloadableSubscription,
forceDeactivateSim: Boolean
): GetDownloadableSubscriptionMetadataResult = withEuiccChannelManager(waitForDownload = false) {
Log.i(
TAG,
"onGetDownloadableSubscriptionMetadata slotId=$slotId portIndex=$portIndex forceDeactivateSim=$forceDeactivateSim"
)
val lpaString = subscription.parseActivationCode()
if (shouldIgnoreSlot(slotId) || lpaString == null) {
return@withEuiccChannelManager GetDownloadableSubscriptionMetadataResult(
RESULT_FIRST_USER,
null
)
}
val confirming = try {
// Either reuse a pending download task we launched before or create a new one.
// As described in launchAndRememberDownloadTask, we must start to download in order to fetch metadata,
// and we can't safely cancel the task in the general case for arbitrary SM-DP+ servers, so we need
// to memorize the task to continue later.
// It's possible that the system may call this function again for the same profile, so
// we do need to check pendingDownloadTask.
(pendingDownloadTask(lpaString)
?: launchAndRememberDownloadTask(
slotId,
portIndex,
lpaString,
subscription.confirmationCode?.ifEmpty { null },
forceDeactivateSim
)
?: return@withEuiccChannelManager GetDownloadableSubscriptionMetadataResult(
RESULT_MUST_DEACTIVATE_SIM,
null
)).awaitConfirmingDownload()
} catch (e: Exception) {
Log.e(TAG, "Failed to fetch profile metadata", e)
null
} ?: return@withEuiccChannelManager GetDownloadableSubscriptionMetadataResult(
RESULT_FIRST_USER,
null
)
val builder = DownloadableSubscription.Builder(subscription)
confirming.metadata?.let { metadata ->
if (metadata.providerName.isNotBlank()) {
builder.setCarrierName(metadata.providerName)
}
if (metadata.accessRules.isNotEmpty()) {
builder.setAccessRules(metadata.accessRules.map {
UiccAccessRule(it.certificateHash.decodeHex(), it.packageName, 0)
})
}
}
GetDownloadableSubscriptionMetadataResult(RESULT_OK, builder.build())
}
override fun onDownloadSubscription(
slotIndex: Int,
portIndex: Int,
subscription: DownloadableSubscription,
switchAfterDownload: Boolean,
forceDeactivateSim: Boolean,
resolvedBundle: Bundle
): DownloadSubscriptionResult {
val (downloadResult, iccid) = withEuiccChannelManager(waitForDownload = false) {
Log.i(
TAG,
"onDownloadSubscription slotIndex=$slotIndex portIndex=$portIndex switchAfterDownload=$switchAfterDownload forceDeactivateSim=$forceDeactivateSim " +
"callingPackage=${resolvedBundle.getString("android.service.euicc.extra.PACKAGE_NAME")}"
)
val lpaString = subscription.parseActivationCode()
if (shouldIgnoreSlot(slotIndex) || lpaString == null) {
return@withEuiccChannelManager Pair(
DownloadSubscriptionResult(RESULT_FIRST_USER, 0, TelephonyManager.UNSUPPORTED_CARD_ID),
null
)
}
// FIXME: I'm not sure this is entirely correct since it is possible that we only knew about
// the confirmation code when the server returned an error. We need to handle that case
// as well.
if (lpaString.confirmationCodeRequired && subscription.confirmationCode.isNullOrEmpty()) {
return@withEuiccChannelManager Pair(
DownloadSubscriptionResult(
RESULT_RESOLVABLE_ERRORS,
RESOLVABLE_ERROR_CONFIRMATION_CODE,
TelephonyManager.UNSUPPORTED_CARD_ID
), null
)
}
val cardId = telephonyManager.uiccCardsInfoCompat.find { it.physicalSlotIndex == slotIndex }
?.cardId ?: TelephonyManager.UNSUPPORTED_CARD_ID
suspend fun confirm(handle: ForegroundTaskHandle) =
handle.awaitConfirmingDownload()?.takeIf {
it.confirmationCode = subscription.confirmationCode?.ifEmpty { null }
// Fails if the download is not waiting anymore, e.g. timed out
handle.backChannel.trySend(true).isSuccess
}
// Confirm the download onGetDownloadableSubscriptionMetadata() left waiting, or a new
// one (it's possible to skip the get metadata step depending on caller privilege)
val waiting = pendingDownloadTask(lpaString)
val (handle, confirming) = waiting?.let { h -> confirm(h)?.let { Pair(h, it) } } ?: try {
launchAndRememberDownloadTask(
slotIndex, portIndex, lpaString,
subscription.confirmationCode?.ifEmpty { null }, forceDeactivateSim
)
?.let { Pair(it, confirm(it)) }
?: return@withEuiccChannelManager Pair(
DownloadSubscriptionResult(RESULT_MUST_DEACTIVATE_SIM, 0, cardId), null
)
} catch (e: Exception) {
Log.e(TAG, "Could not start the profile download", e)
return@withEuiccChannelManager Pair(DownloadSubscriptionResult(RESULT_FIRST_USER, 0, cardId), null)
}
val error = handle.stateFlow.waitDone()
pendingDownload = null
if (error != null) {
Log.e(TAG, "Profile download failed", error)
Pair(DownloadSubscriptionResult(RESULT_FIRST_USER, 0, cardId), null)
} else {
Pair(DownloadSubscriptionResult(RESULT_OK, 0, cardId), confirming?.metadata?.iccid)
}
}
if (downloadResult.result != RESULT_OK || !switchAfterDownload) return downloadResult
// Calling onSwitchToSubscriptionWithPort must happen outside of withEuiccChannelManager because
// of the lock inside of that function.
if (iccid.isNullOrEmpty() ||
onSwitchToSubscriptionWithPort(slotIndex, portIndex, iccid, true) != RESULT_OK
) {
Log.e(TAG, "Profile $iccid downloaded but not enabled; it has to be enabled manually")
// The platform only refreshes its list after the switch
appContainer.subscriptionManager.tryRefreshCachedEuiccInfo(downloadResult.cardId)
}
return downloadResult
}
override fun onGetDefaultDownloadableSubscriptionList(
@ -181,7 +534,6 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
)
}
// TODO: Temporarily enable the slot to access its profiles if it is currently unmapped
val port = euiccChannelManager.findFirstAvailablePort(slotId)
if (port == -1) {
return@withEuiccChannelManager GetEuiccProfileInfoListResult(
@ -376,10 +728,14 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker {
30 * 1000
).stateFlow.waitDone()
if (res != null) return@withEuiccChannelManager RESULT_FIRST_USER
if (res != null) {
Log.e(TAG, "Profile switch task failed (iccid=$foundIccid enable=$enable)", res)
return@withEuiccChannelManager RESULT_FIRST_USER
}
return@withEuiccChannelManager RESULT_OK
} catch (_: Exception) {
} catch (e: Exception) {
Log.e(TAG, "onSwitchToSubscriptionWithPort failed", e)
return@withEuiccChannelManager RESULT_FIRST_USER
} finally {
euiccChannelManager.invalidate()

View file

@ -0,0 +1,224 @@
package im.angry.openeuicc.ui
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.service.euicc.EuiccService
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.telephony.euicc.EuiccManager
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import com.google.android.material.textfield.TextInputLayout
import im.angry.openeuicc.R
import im.angry.openeuicc.service.OpenEuiccService
import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* LUI resolution activity, started by com.android.phone's EuiccResolutionUiDispatcherActivity when
* the platform needs the user's consent (or a confirmation code) for an EuiccManager operation
* requested by an app. The answer goes back through EuiccManager.continueOperation(), with the
* intent's extras untouched; declining (or leaving) the dialog fails the operation.
*/
class EuiccResolutionActivity : BaseEuiccAccessActivity() {
companion object {
private const val TAG = "EuiccResolutionActivity"
}
private var resolved = false
private val resolutionCallingPackage: String? by lazy {
intent.getStringExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE)
}
private val callingAppLabel: CharSequence by lazy {
// Without QUERY_ALL_PACKAGES, the calling app may not be visible to us
resolutionCallingPackage?.let {
runCatching {
packageManager.getApplicationLabel(packageManager.getApplicationInfo(it, 0))
}.getOrDefault(it)
} ?: getString(R.string.euicc_resolution_unknown_app)
}
// Downloads (and metadata lookups) come with INVALID_SUBSCRIPTION_ID
private val isSwitch: Boolean by lazy {
intent.getIntExtra(
EuiccService.EXTRA_RESOLUTION_SUBSCRIPTION_ID,
SubscriptionManager.INVALID_SUBSCRIPTION_ID
) != SubscriptionManager.INVALID_SUBSCRIPTION_ID
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setBackgroundDrawableResource(android.R.color.transparent)
}
override fun onInit() {
val builder = AlertDialog.Builder(this, im.angry.openeuicc.common.R.style.AlertDialogTheme)
val dialog = when (intent.action) {
EuiccService.ACTION_RESOLVE_NO_PRIVILEGES -> builder
.setTitle(
getString(
if (isSwitch) R.string.euicc_resolution_no_privileges_switch_title
else R.string.euicc_resolution_no_privileges_title,
callingAppLabel
)
)
.setMessage(
getString(
if (isSwitch) R.string.euicc_resolution_no_privileges_switch_message
else R.string.euicc_resolution_no_privileges_message,
callingAppLabel
)
)
.setNegativeButton(R.string.euicc_resolution_deny) { _, _ -> resolve(false) }
.setPositiveButton(R.string.euicc_resolution_allow) { _, _ -> resolve(true) }
.apply {
if (resolutionCallingPackage != null) {
setNeutralButton(R.string.euicc_resolution_app_info, null)
}
}
.create()
.apply {
// Set here so that the button doesn't dismiss the dialog
setOnShowListener {
getButton(AlertDialog.BUTTON_NEUTRAL)?.setOnClickListener {
startActivity(
Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", resolutionCallingPackage, null)
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
}
}
}
EuiccService.ACTION_RESOLVE_DEACTIVATE_SIM -> builder
.setTitle(R.string.euicc_resolution_deactivate_sim_title)
.setMessage(getString(R.string.euicc_resolution_deactivate_sim_message, callingAppLabel))
.setNegativeButton(R.string.euicc_resolution_cancel) { _, _ -> resolve(false) }
.setPositiveButton(R.string.euicc_resolution_continue) { _, _ -> resolve(true) }
.create()
EuiccService.ACTION_RESOLVE_RESOLVABLE_ERRORS -> {
val errors = intent.getIntExtra(EuiccService.EXTRA_RESOLVABLE_ERRORS, 0)
val needsCode = errors and EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE != 0
val needsPolicyRules = errors and EuiccService.RESOLVABLE_ERROR_POLICY_RULES != 0
val codeView = if (needsCode) {
layoutInflater.inflate(R.layout.dialog_euicc_resolution_code, null)
} else {
null
}
val codeInput = codeView?.requireViewById<EditText>(R.id.euicc_resolution_code)
if (intent.getBooleanExtra(EuiccService.EXTRA_RESOLUTION_CONFIRMATION_CODE_RETRIED, false)) {
codeView?.requireViewById<TextInputLayout>(R.id.euicc_resolution_code_layout)?.error =
getString(R.string.euicc_resolution_confirmation_code_retry)
}
builder
.setTitle(R.string.euicc_resolution_resolvable_errors_title)
.setMessage(
listOfNotNull(
if (needsCode) {
getString(R.string.euicc_resolution_confirmation_code_message, callingAppLabel)
} else null,
if (needsPolicyRules) getString(R.string.euicc_resolution_policy_rules_message) else null,
).joinToString("\n\n")
)
.setView(codeView)
.setNegativeButton(R.string.euicc_resolution_cancel) { _, _ -> resolve(false) }
.setPositiveButton(R.string.euicc_resolution_continue) { _, _ ->
resolve(true, Bundle().apply {
if (needsCode) {
putString(
EuiccService.EXTRA_RESOLUTION_CONFIRMATION_CODE,
codeInput?.text?.toString()?.trim()
)
}
if (needsPolicyRules) {
putBoolean(EuiccService.EXTRA_RESOLUTION_ALLOW_POLICY_RULES, true)
}
})
}
.create()
.apply {
// The platform fails the operation with an empty confirmation code
if (codeInput != null) {
setOnShowListener {
val positive = getButton(DialogInterface.BUTTON_POSITIVE)
positive.isEnabled = !codeInput.text.isNullOrBlank()
codeInput.doAfterTextChanged { positive.isEnabled = !it.isNullOrBlank() }
}
}
}
}
else -> {
Log.w(TAG, "Unsupported resolution action ${intent.action}")
finish()
return
}
}
// Back declines, but a stray tap outside the dialog doesn't
dialog.setCanceledOnTouchOutside(false)
dialog.setOnCancelListener { resolve(false) }
dialog.show()
}
override fun onDestroy() {
// Never leave the operation (and the calling app) hanging
if (isFinishing && !resolved) {
resolve(false)
}
super.onDestroy()
}
private fun resolve(consent: Boolean, extras: Bundle = Bundle()) {
if (resolved) return
resolved = true
Log.i(TAG, "Resolution ${intent.action} for $resolutionCallingPackage: consent=$consent")
if (!consent && !isSwitch && euiccChannelManagerLoaded.isCompleted) {
// The platform doesn't tell OpenEuiccService; cancel the download it may have left
// waiting for confirmation.
lifecycleScope.launch(Dispatchers.IO) {
OpenEuiccService.cancelPendingDownload(euiccChannelManagerService)
}
}
val resolutionExtras = Bundle(extras).apply {
putBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT, consent)
// For RESOLVE_NO_PRIVILEGES, the platform may leave the choice of the port to us
val defaultPortIndex = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
TelephonyManager.DEFAULT_PORT_INDEX
} else {
0
}
if (intent.action == EuiccService.ACTION_RESOLVE_NO_PRIVILEGES &&
intent.getIntExtra(EuiccService.EXTRA_RESOLUTION_PORT_INDEX, defaultPortIndex) < 0
) {
putInt(EuiccService.EXTRA_RESOLUTION_PORT_INDEX, defaultPortIndex)
}
}
try {
val cardId = intent.getIntExtra(EuiccService.EXTRA_RESOLUTION_CARD_ID, TelephonyManager.UNSUPPORTED_CARD_ID)
getSystemService(EuiccManager::class.java)!!
.let { if (cardId >= 0) it.createForCardId(cardId) else it }
.continueOperation(intent, resolutionExtras)
} catch (e: Exception) {
Log.e(TAG, "Unable to continue eUICC operation", e)
}
setResult(if (consent) RESULT_OK else RESULT_CANCELED)
finish()
}
}

View file

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingStart="24dp"
android:paddingTop="8dp"
android:paddingEnd="24dp">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/euicc_resolution_code_layout"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/euicc_resolution_confirmation_code_hint">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/euicc_resolution_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:importantForAutofill="no"
android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

View file

@ -23,6 +23,25 @@
<string name="lui_skip">Skip</string>
<string name="lui_download">Download eSIM</string>
<!-- eUICC resolution (user consent) dialogs, shown on behalf of apps using EuiccManager -->
<string name="euicc_resolution_unknown_app">Unknown app</string>
<string name="euicc_resolution_no_privileges_title">Allow \"%1$s\" to download an eSIM?</string>
<string name="euicc_resolution_no_privileges_message">\"%1$s\" wants to download a mobile network profile (eSIM) to this device and turn it on. This may turn off the profile currently in use on the eSIM.\n\nOnly allow this if you trust this app.</string>
<string name="euicc_resolution_no_privileges_switch_title">Allow \"%1$s\" to switch your eSIM?</string>
<string name="euicc_resolution_no_privileges_switch_message">\"%1$s\" wants to turn on another mobile network profile on your eSIM. The profile currently in use on the eSIM will be turned off.</string>
<string name="euicc_resolution_allow">Allow</string>
<string name="euicc_resolution_deny">Don\'t allow</string>
<string name="euicc_resolution_app_info">App info</string>
<string name="euicc_resolution_deactivate_sim_title">Turn off current mobile network?</string>
<string name="euicc_resolution_deactivate_sim_message">To continue, \"%1$s\" needs to turn off the mobile network profile currently in use on this SIM. You can turn it back on later.</string>
<string name="euicc_resolution_continue">Continue</string>
<string name="euicc_resolution_cancel">Cancel</string>
<string name="euicc_resolution_resolvable_errors_title">Additional confirmation needed</string>
<string name="euicc_resolution_confirmation_code_message">Enter the confirmation code provided by your carrier to download the eSIM requested by \"%1$s\".</string>
<string name="euicc_resolution_confirmation_code_retry">The confirmation code was incorrect. Please try again.</string>
<string name="euicc_resolution_confirmation_code_hint">Confirmation code</string>
<string name="euicc_resolution_policy_rules_message">This eSIM profile contains carrier policy rules, which may for example prevent turning it off or deleting it. Continue only if you agree.</string>
<!-- Preference -->
<string name="pref_advanced_telephony_manager_removable">Use TelephonyManager everywhere</string>
<string name="pref_advanced_telephony_manager_removable_desc">By default, only OMAPI is attempted for removable eSIMs to match what is done in unprivileged mode (i.e. EasyEUICC). This may not work well on some devices. Select this option to force the use of TelephonyManager even for removable eSIMs.</string>

View file

@ -0,0 +1,619 @@
package im.angry.openeuicc.service
import android.content.ComponentName
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.service.euicc.EuiccService
import android.service.euicc.GetEuiccProfileInfoListResult
import android.telephony.TelephonyManager
import android.telephony.UiccAccessRule
import android.telephony.euicc.DownloadableSubscription
import android.telephony.euicc.EuiccManager
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import im.angry.openeuicc.R
import im.angry.openeuicc.core.EuiccChannel
import im.angry.openeuicc.core.EuiccChannelManager
import im.angry.openeuicc.testutil.MockEuiccChannel
import im.angry.openeuicc.testutil.MockEuiccChannelManager
import im.angry.openeuicc.testutil.TestOpenEuiccApplication
import im.angry.openeuicc.testutil.awaitMainLooper
import im.angry.openeuicc.ui.EuiccResolutionActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import net.typeblog.lpac_jni.EuiccInfo2
import net.typeblog.lpac_jni.HttpInterface
import net.typeblog.lpac_jni.LocalProfileAssistant
import net.typeblog.lpac_jni.LocalProfileInfo
import net.typeblog.lpac_jni.LocalProfileNotification
import net.typeblog.lpac_jni.ProfileClass
import net.typeblog.lpac_jni.ProfileDownloadCallback
import net.typeblog.lpac_jni.ProfileDownloadInput
import net.typeblog.lpac_jni.ProfileDownloadState
import net.typeblog.lpac_jni.RemoteProfileAccessRule
import net.typeblog.lpac_jni.RemoteProfileInfo
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.shadows.ShadowDialog
import org.robolectric.shadows.ShadowEuiccManager
import org.robolectric.shadows.UiccCardInfoBuilder
import org.robolectric.shadows.UiccPortInfoBuilder
import org.robolectric.util.ReflectionHelpers
import java.time.Duration
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* Carrier-app eSIM downloads through the platform (EuiccManager.downloadSubscription() →
* EuiccController → OpenEuiccService), tested only through the public EuiccService entry points
* and the contract of EuiccResolutionActivity (the user's answer → continueOperation()).
*
* Everything in OpenEUICC runs for real (OpenEuiccService, EuiccChannelManagerService and its
* foreground tasks); only the LPA is faked. [CarrierLpa] replays what lpac reported against real
* SM-DP+ servers on a Galaxy S21 (LineageOS 23.2 / Android 16, September 2026), with made-up
* ICCIDs, activation codes and certificate hashes.
*
* The platform called the service in this order for an unprivileged carrier app:
* downloadSubscription() → RESOLVE_NO_PRIVILEGES → continueOperation(consent)
* → onGetDownloadableSubscriptionMetadata(forceDeactivateSim = true)
* → "Calling package has carrier privilege to this profile" (access rules match)
* → onDownloadSubscription(forceDeactivateSim = true)
*/
@RunWith(RobolectricTestRunner::class)
@Config(
application = TestOpenEuiccApplication::class,
shadows = [ContinueOperationRecorder::class]
)
class OpenEuiccServiceDownloadTest {
companion object {
const val SLOT = 1 // physical slot of the S21's built-in eUICC
const val PORT = 0
const val CARRIER_APP = "com.example.carrierapp"
const val EID = "89000000000000000000000000000000"
val activationCode: DownloadableSubscription =
DownloadableSubscription.forActivationCode("LPA:1\$smdp.example.com\$TEST-MATCHING-ID")
// SGP.22 StoreMetadataRequest as received from the Simyo SM-DP+: provider "simyo",
// one REF-AR-DO (certificate hash, here a fake SHA-256, plus package name)
val operatorProfile = RemoteProfileInfo(
iccid = "89000000000000000011",
name = "Simyo Android eSIM",
providerName = "simyo",
profileClass = ProfileClass.Operational,
accessRules = listOf(RemoteProfileAccessRule("AB".repeat(32), CARRIER_APP)),
)
// Nomad (travel eSIM, Thales SM-DP+): provider and name "NOMAD", one access rule
val travelProfile = RemoteProfileInfo(
iccid = "89000000000000000022",
name = "NOMAD",
providerName = "NOMAD",
profileClass = ProfileClass.Operational,
accessRules = listOf(RemoteProfileAccessRule("CD".repeat(32), null)),
)
}
private val app = RuntimeEnvironment.getApplication()
private lateinit var lpa: CarrierLpa
private lateinit var channelManager: CarrierChannelManager
private lateinit var channelManagerService: VirtualClockEuiccChannelManagerService
private lateinit var service: OpenEuiccService
@Before
fun setUp() {
lpa = CarrierLpa()
channelManager = CarrierChannelManager(lpa)
TestOpenEuiccApplication.mockEuiccChannelManager = channelManager
channelManagerService =
Robolectric.buildService(VirtualClockEuiccChannelManagerService::class.java).create().get()
shadowOf(app).setComponentNameAndServiceForBindService(
ComponentName(app, EuiccChannelManagerService::class.java),
channelManagerService.onBind(Intent())
)
shadowOf(app.getSystemService(TelephonyManager::class.java)).setUiccCardsInfo(
listOf(
UiccCardInfoBuilder.newBuilder()
.setIsEuicc(true)
.setIsRemovable(false)
.setPhysicalSlotIndex(SLOT)
.setPorts(listOf(UiccPortInfoBuilder.newBuilder().setPortIndex(PORT).build()))
.build()
)
)
service = Robolectric.buildService(OpenEuiccService::class.java).create().get()
ContinueOperationRecorder.extras.clear()
}
/**
* The platform calls EuiccService methods on a binder thread and waits for the result. Do the
* same, while this (main) thread runs the main looper and delivers EuiccChannelManagerService's
* self-start (startForegroundService()) like the system would. A call that blocks fails the
* test after 30 s (its thread is left behind).
*/
private fun <T> platformCall(call: OpenEuiccService.() -> T): T = runBlocking {
val result = CoroutineScope(Dispatchers.IO).async { service.call() }
awaitMainLooper(30_000) {
shadowOf(app).nextStartedService?.let {
// Let the task subscribe to the start command first (it's not replayed)
shadowOf(Looper.getMainLooper()).idle()
channelManagerService.onStartCommand(it, 0, 1)
}
result.isCompleted
}
result.await()
}
/**
* Start EuiccResolutionActivity as com.android.phone does, press [button] (after typing
* [confirmationCode], if given) and return the extras it passed to continueOperation().
*/
private fun userAnswers(intent: Intent, button: Int, confirmationCode: String? = null): Bundle {
Robolectric.buildActivity(EuiccResolutionActivity::class.java, intent).setup()
val dialog = ShadowDialog.getLatestDialog() as AlertDialog
confirmationCode?.let { dialog.findViewById<EditText>(R.id.euicc_resolution_code)!!.setText(it) }
dialog.getButton(button).performClick()
shadowOf(Looper.getMainLooper()).idle()
return ContinueOperationRecorder.extras.single()
}
// Mijn Simyo app, "Allow", switchAfterDownload = true
@Test
fun `operator app - one ES9+ session from metadata to download, then enable with refresh`() {
val consent = userAnswers(
Intent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES)
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP),
DialogInterface.BUTTON_POSITIVE
)
assertTrue(consent.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT))
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
assertEquals(EuiccService.RESULT_OK, metadata.result)
// The platform matches the calling package against these rules
val subscription = metadata.downloadableSubscription
assertEquals("simyo", ReflectionHelpers.callInstanceMethod<String>(subscription, "getCarrierName"))
val rule = ReflectionHelpers.callInstanceMethod<List<UiccAccessRule>>(subscription, "getAccessRules").single()
assertEquals("AB".repeat(32), rule.certificateHexString)
assertEquals(CARRIER_APP, rule.packageName)
// The session waits at the metadata step
assertEquals(1, lpa.sessions.get())
assertEquals(emptyList<Boolean>(), lpa.metadataStepAnswers)
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
}
assertEquals(EuiccService.RESULT_OK, download.result)
// The same session continued: many SM-DP+ servers refuse a second one for the same order
assertEquals(1, lpa.sessions.get())
assertEquals(listOf(true), lpa.metadataStepAnswers)
assertEquals(listOf(operatorProfile.iccid to true), lpa.enableCalls)
}
// The SIM refresh of the switch makes the platform ask for the profiles
// (SubscriptionManagerService.updateEmbeddedSubscriptions) while the switch waits for the eUICC
// to come back. Without the new profile, it stores the new subscription as a physical SIM.
@Test
fun `profile list requested during the switch after a download has the new profile`() {
lateinit var query: Deferred<GetEuiccProfileInfoListResult>
channelManager.onRefresh = {
query = CoroutineScope(Dispatchers.IO).async { service.onGetEuiccProfileInfoList(SLOT) }
}
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
}
assertEquals(EuiccService.RESULT_OK, download.result)
assertEquals(listOf(operatorProfile.iccid to true), lpa.enableCalls)
val profiles = runBlocking {
awaitMainLooper(30_000) { query.isCompleted }
query.await()
}
assertEquals(EuiccService.RESULT_OK, profiles.result)
assertEquals(listOf(operatorProfile.iccid), profiles.profiles.map { it.iccid })
}
// The order where the metadata is fetched before the user declines (Mijn Simyo asked for
// consent first, see the next test); the waiting session must not be left behind
@Test
fun `don't allow after the metadata step cancels the waiting session`() = runBlocking {
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, false) }
assertEquals(EuiccService.RESULT_OK, metadata.result)
val consent = userAnswers(
Intent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES)
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP),
DialogInterface.BUTTON_NEGATIVE
)
// The platform reports the error to the carrier app upon consent = false
assertEquals(false, consent.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT, true))
awaitMainLooper { lpa.metadataStepAnswers.isNotEmpty() }
assertEquals(listOf(false), lpa.metadataStepAnswers)
assertEquals(emptyList<LocalProfileInfo>(), lpa.profiles)
}
// Mijn Simyo app, "Don't allow" (consent is asked before the metadata step)
@Test
fun `don't allow before the metadata step starts no ES9+ session`() {
val consent = userAnswers(
Intent(EuiccService.ACTION_RESOLVE_NO_PRIVILEGES)
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP),
DialogInterface.BUTTON_NEGATIVE
)
assertEquals(false, consent.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT, true))
assertEquals(0, lpa.sessions.get())
}
// Nomad app, switchAfterDownload = false, enabled later in Settings
@Test
fun `travel eSIM app - download without switching`() {
lpa.metadata = travelProfile
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, -1, activationCode, true) }
assertEquals(EuiccService.RESULT_OK, metadata.result)
assertEquals(
"NOMAD",
ReflectionHelpers.callInstanceMethod<String>(metadata.downloadableSubscription, "getCarrierName")
)
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, false, true, Bundle())
}
assertEquals(EuiccService.RESULT_OK, download.result)
assertEquals(1, lpa.sessions.get())
assertEquals(listOf(travelProfile.iccid), lpa.profiles.map { it.iccid })
assertEquals(emptyList<Pair<String, Boolean>>(), lpa.enableCalls)
}
// Not observed with a real carrier (Simyo and Nomad need no confirmation code)
@Test
fun `confirmation code requested after the metadata step continues the same session`() {
val subscription =
DownloadableSubscription.forActivationCode("LPA:1\$smdp.example.com\$TEST-MATCHING-ID\$\$1")
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, subscription, true) }
assertEquals(EuiccService.RESULT_OK, metadata.result)
val needsCode = platformCall {
onDownloadSubscription(SLOT, PORT, subscription, false, true, Bundle())
}
assertEquals(EuiccService.RESULT_RESOLVABLE_ERRORS, needsCode.result)
assertEquals(
EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE,
needsCode.resolvableErrors and EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE
)
val answer = userAnswers(
Intent(EuiccService.ACTION_RESOLVE_RESOLVABLE_ERRORS)
.putExtra(EuiccService.EXTRA_RESOLUTION_CALLING_PACKAGE, CARRIER_APP)
.putExtra(EuiccService.EXTRA_RESOLVABLE_ERRORS, EuiccService.RESOLVABLE_ERROR_CONFIRMATION_CODE),
DialogInterface.BUTTON_POSITIVE,
confirmationCode = "1234"
)
assertTrue(answer.getBoolean(EuiccService.EXTRA_RESOLUTION_CONSENT))
assertEquals("1234", answer.getString(EuiccService.EXTRA_RESOLUTION_CONFIRMATION_CODE))
// EuiccController then runs the operation again, with the code
val withCode = DownloadableSubscription.Builder(subscription).setConfirmationCode("1234").build()
assertEquals(
EuiccService.RESULT_OK,
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, withCode, true) }.result
)
val download = platformCall {
onDownloadSubscription(SLOT, PORT, withCode, false, true, Bundle())
}
assertEquals(EuiccService.RESULT_OK, download.result)
assertEquals(1, lpa.sessions.get())
assertEquals("1234", lpa.prepareDownloadConfirmationCode)
}
// Not observed like this with a real carrier: a modem that rejects EnableProfile with refresh
// (e.g. catBusy), so it only works without refresh and the switch task reports
// SwitchingProfilesRefreshException after the profile has already been installed
@Test
fun `failed enable after a finished download still reports success`() {
lpa.refreshWorks = false
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
}
// An error would make the carrier app request a new activation code for a profile
// that is already installed
assertEquals(EuiccService.RESULT_OK, download.result)
assertEquals(listOf(operatorProfile.iccid), lpa.profiles.map { it.iccid })
assertEquals(
listOf(operatorProfile.iccid to true, operatorProfile.iccid to false),
lpa.enableCalls
)
}
@Test
fun `session waiting at the metadata step survives a slow user`() {
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
// E.g. a consent or confirmation code dialog in between
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMinutes(1))
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, false, true, Bundle())
}
assertEquals(EuiccService.RESULT_OK, download.result)
assertEquals(1, lpa.sessions.get())
assertEquals(listOf(true), lpa.metadataStepAnswers)
}
// The timeout itself runs on the virtual clock (VirtualClockEuiccChannelManagerService); this
// checks that the service asks for one and cancels the session when it fires
@Test
fun `session waiting at the metadata step is cancelled after the timeout`() = runBlocking {
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMinutes(6))
awaitMainLooper { lpa.metadataStepAnswers.isNotEmpty() }
assertEquals(listOf(false), lpa.metadataStepAnswers)
// A late download request starts a new session
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, false, true, Bundle())
}
assertEquals(EuiccService.RESULT_OK, download.result)
assertEquals(2, lpa.sessions.get())
assertEquals(listOf(false, true), lpa.metadataStepAnswers)
}
// The waiting session holds the eUICC (the LPA lock). The platform calls these synchronously,
// e.g. on the telephony worker thread; they block until the session is over and only then
// touch the eUICC. Nothing confirms the session here, so the confirmation timeout cancels it.
@Test
fun `EID and profile list requests block until the waiting session is over`() = runBlocking {
platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
assertEquals(1, lpa.sessions.get())
// Both block until the waiting session is over; nothing confirms it, so the confirmation
// timeout cancels it while they wait (idleFor() advances the virtual clock)
val eid = CoroutineScope(Dispatchers.IO).async { service.onGetEid(SLOT) }
val profiles = CoroutineScope(Dispatchers.IO).async { service.onGetEuiccProfileInfoList(SLOT) }
awaitMainLooper(30_000) {
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMinutes(1))
eid.isCompleted && profiles.isCompleted
}
assertEquals(EID, eid.await())
assertEquals(EuiccService.RESULT_OK, profiles.await().result)
assertEquals(1, lpa.sessions.get())
assertEquals(listOf(false), lpa.metadataStepAnswers)
}
// An invalid matching ID, refused by the SM-DP+ in
// ES9+.AuthenticateClient with subjectCode 8.2.6, reasonCode 3.8
@Test
fun `server rejection is reported and leaves no waiting session`() {
lpa.rejection = LocalProfileAssistant.ProfileDownloadException(
lpaErrorReason = "ES10B_ERROR_REASON_UNDEFINED",
lastHttpResponse = HttpInterface.HttpResponse(
200,
"""{"header":{"functionExecutionStatus":{"status":"Failed","statusCodeData":{"subjectCode":"8.2.6","reasonCode":"3.8","subjectIdentifier":"Matching ID","message":"Refused"}}}}""".toByteArray()
),
lastHttpException = null,
lastApduResponse = null,
lastApduException = null,
)
val metadata = platformCall { onGetDownloadableSubscriptionMetadata(SLOT, PORT, activationCode, true) }
assertNotEquals(EuiccService.RESULT_OK, metadata.result)
assertNull(metadata.downloadableSubscription)
val download = platformCall {
onDownloadSubscription(SLOT, PORT, activationCode, true, true, Bundle())
}
assertNotEquals(EuiccService.RESULT_OK, download.result)
assertEquals(2, lpa.sessions.get())
assertEquals(emptyList<Boolean>(), lpa.metadataStepAnswers)
assertEquals(emptyList<Pair<String, Boolean>>(), lpa.enableCalls)
}
}
/**
* A LocalProfileAssistant replaying lpac against a real SM-DP+. Each downloadProfile() call is
* one ES9+ session: ES9+.InitiateAuthentication and AuthenticateClient (Preparing, Connecting,
* Authenticating), then the metadata step (ConfirmingDownload with the StoreMetadataRequest
* content) and, only if confirmed there, PrepareDownload, GetBoundProfilePackage and
* LoadBoundProfilePackage (Downloading, Finalizing). Like LocalProfileAssistantImpl, it throws a
* ProfileDownloadException when the session is declined at the metadata step or fails.
*/
class CarrierLpa : LocalProfileAssistant {
/** Profile metadata sent by the SM-DP+ */
@Volatile
var metadata = OpenEuiccServiceDownloadTest.operatorProfile
/** If set, the SM-DP+ refuses the order during authentication with this error */
@Volatile
var rejection: LocalProfileAssistant.ProfileDownloadException? = null
/** Whether EnableProfile with refresh works; if not, it only works without refresh */
@Volatile
var refreshWorks = true
/** Number of ES9+ sessions (downloadProfile() calls) */
val sessions = AtomicInteger()
/** What the callback answered at the metadata step, per session (false = cancelled) */
val metadataStepAnswers = CopyOnWriteArrayList<Boolean>()
/** The confirmation code the last ES10b.PrepareDownload was called with */
@Volatile
var prepareDownloadConfirmationCode: String? = null
/** (ICCID, refresh) of every EnableProfile */
val enableCalls = CopyOnWriteArrayList<Pair<String, Boolean>>()
private val installed = CopyOnWriteArrayList<LocalProfileInfo>()
// Like LocalProfileAssistantImpl: a download holds the eUICC for all other operations
val lock = ReentrantLock()
override fun downloadProfile(input: ProfileDownloadInput, callback: ProfileDownloadCallback) = lock.withLock {
sessions.incrementAndGet()
callback.onStatusUpdate(ProfileDownloadState.Preparing())
callback.onStatusUpdate(ProfileDownloadState.Connecting())
callback.onStatusUpdate(ProfileDownloadState.Authenticating())
rejection?.let { throw it }
val confirming = ProfileDownloadState.ConfirmingDownload(metadata)
val confirmed = callback.onStatusUpdate(confirming)
metadataStepAnswers += confirmed
if (!confirmed) {
throw LocalProfileAssistant.ProfileDownloadException(
"ES10B_ERROR_REASON_UNDEFINED", null, null, null, null
)
}
prepareDownloadConfirmationCode = confirming.confirmationCode ?: input.confirmationCode
callback.onStatusUpdate(ProfileDownloadState.Downloading())
callback.onStatusUpdate(ProfileDownloadState.Finalizing())
installed += LocalProfileInfo(
metadata.iccid,
LocalProfileInfo.State.Disabled,
metadata.name,
"",
metadata.providerName,
"",
metadata.profileClass
)
}
override fun enableProfile(iccid: String, refresh: Boolean): Boolean {
enableCalls += iccid to refresh
return refreshWorks || !refresh
}
override val profiles: List<LocalProfileInfo>
get() = lock.withLock { installed.toList() }
override val valid = true
override val notifications = emptyList<LocalProfileNotification>()
override val eID: String
get() = lock.withLock { OpenEuiccServiceDownloadTest.EID }
override val euiccInfo2: EuiccInfo2? = null
override fun setEs10xMss(mss: Byte) {}
override fun disableProfile(iccid: String, refresh: Boolean): Boolean = true
override fun deleteProfile(iccid: String): Boolean = true
override fun deleteNotification(seqNumber: Long): Boolean = true
override fun handleNotification(seqNumber: Long): Boolean = true
override fun euiccMemoryReset() {}
override fun setNickname(iccid: String, nickname: String) {}
override fun close() {}
}
/**
* Like DefaultEuiccChannelManager: waitForReconnect() and invalidate() close the channel, even while
* someone else uses it, and the next withEuiccChannel() opens a new one. Using a closed channel
* throws here; lpac itself uses its freed context.
*/
class CarrierChannelManager(private val lpa: CarrierLpa) : EuiccChannelManager by MockEuiccChannelManager(
MockEuiccChannel(OpenEuiccServiceDownloadTest.SLOT, OpenEuiccServiceDownloadTest.PORT, lpa)
) {
/** How the platform reacts to the SIM refresh of a profile switch */
@Volatile
var onRefresh: (() -> Unit)? = null
private var channel = ChannelLpa(lpa)
override suspend fun <R> withEuiccChannel(
physicalSlotId: Int,
portId: Int,
seId: EuiccChannel.SecureElementId,
fn: suspend (EuiccChannel) -> R
): R {
val channelLpa = synchronized(this) {
channel.takeIf { !it.closed } ?: ChannelLpa(lpa).also { channel = it }
}
return fn(MockEuiccChannel(physicalSlotId, portId, channelLpa))
}
override suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long) {
onRefresh?.invoke()
invalidate()
}
override fun invalidate() = lpa.lock.withLock {
// Like LocalProfileAssistantImpl.close(), with the eUICC held; with the platform around,
// let whoever got the channel before wait for the eUICC meanwhile (up to 1 s)
val deadline = System.currentTimeMillis() + if (onRefresh != null) 1000 else 0
while (!lpa.lock.hasQueuedThreads() && System.currentTimeMillis() < deadline) {
Thread.sleep(10)
}
synchronized(this) { channel.close() }
}
}
/** The LPA of one channel */
class ChannelLpa(private val lpa: CarrierLpa) : LocalProfileAssistant by lpa {
@Volatile
var closed = false
override val profiles: List<LocalProfileInfo>
get() = lpa.lock.withLock {
check(!closed) { "Channel closed" }
lpa.profiles
}
override fun close() {
closed = true
}
}
/**
* EuiccChannelManagerService with the download confirmation timeout on Robolectric's clock (the
* main looper) instead of the wall clock, so that tests can let minutes pass instantly.
*/
class VirtualClockEuiccChannelManagerService : EuiccChannelManagerService() {
override fun launchProfileDownloadTask(
slotId: Int,
portId: Int,
seId: EuiccChannel.SecureElementId,
input: ProfileDownloadInput,
confirmationTimeoutMillis: Long,
): ForegroundTaskHandle =
super.launchProfileDownloadTask(slotId, portId, seId, input, Long.MAX_VALUE).also {
Handler(Looper.getMainLooper()).postDelayed(
{ it.backChannel.trySend(false) },
confirmationTimeoutMillis
)
}
}
/** Records EuiccManager.continueOperation() (a system API that talks to EuiccController) */
@Implements(EuiccManager::class)
class ContinueOperationRecorder : ShadowEuiccManager() {
companion object {
val extras = CopyOnWriteArrayList<Bundle>()
}
@Implementation
protected fun continueOperation(resolutionIntent: Intent, resolutionExtras: Bundle) {
extras += resolutionExtras
}
}

View file

@ -0,0 +1,2 @@
# EuiccService APIs used by OpenEuiccService need a recent platform
sdk=35

22
docs/ARA-M.md Normal file
View file

@ -0,0 +1,22 @@
# ARA-M Applet Configuration
Audience: SAS-UP FAE
This configuration affects only EasyEUICC and is unrelated to OpenEUICC.
The ARA-M applet configuration is **REQUIRED** for EasyEUICC to communicate with the card in the device.
The current EasyEUICC signing key is valid until 24 Dec 2043 and is represented by the following fingerprints:
- `2A2FA878BC7C3354C2CF82935A5945A3EDAE4AFA` (SHA-1, **PREFERRED**)
- `57BECC26B373A6475D093D33B0EA1C5E2BF2738EC0233680094CCBBCB500A13E` (SHA-256)
## Signing key rotation policy
There is currently no formal rotation plan or contingency. The design prioritizes maximum compatibility while a rotation strategy is selected in 2038 and implemented no later than 24 Dec 2038.
This approach provides a five-year migration window before the current signing key expires on 24 Dec 2043.
## References
- [UICC carrier privileges](https://source.android.com/docs/core/connect/uicc#rules_on_uicc)

22
docs/ATR.md Normal file
View file

@ -0,0 +1,22 @@
# Answer To Reset
Audience: SAS-UP FAE
## `T = 15` and interface byte
After `T = 15`, the first `tBi` byte is not arbitrary; it indicates interface byte.
For ETSI TS 102 221, the key values are:
- `0x82` (`0b1000_0010`): eUICC-related functions supported
- `0x81` (`0b1000_0001`): LSIs (Logical Secure Element Interfaces) supported
These are defined in [ETSI TS 102 221, clause 6.3.3, Table 6.7](https://www.etsi.org/deliver/etsi_ts/102200_102299/102221/18.02.00_60/ts_102221v180200p.pdf#page=36).
## Why it matters
- `T = 15` + first `tBi = 0x82`: the card is advertising **eUICC-related functions supported**. \
On Android, removable eUICC with this flag is often treated as non-removable. \
Result: the modem/Telephony stack may refuse to re-enable it as a normal SIM
- `T = 15` + first `tBi = 0x81`: the card is advertising **LSIs supported**. \
This is not a strong compatibility signal for removable eUICC behavior. \
Modem implementations vary; support is not consistently reliable.

View file

@ -2,7 +2,7 @@
Since: OpenEUICC v1.3.0 or EasyEUICC v1.3.0
## Web Intent
## Web intent
HTML example:
@ -10,7 +10,7 @@ HTML example:
<a href="lpa:1$rsp.example.com$matching-id">Open {Open/Easy}EUICC</a>
```
## Android Intent
## Android intent
Kotlin example:
@ -19,8 +19,7 @@ val lpaUri = Uri.parse("lpa:1\$rsp.example.com\$matching-id")
startActivity(Intent(Intent.ACTION_VIEW, lpaUri))
```
To check whether any installed app can handle this deep link, call [PackageManager#queryIntentActivities] before calling
`startActivity`.
Before calling `startActivity`, check whether any installed app can handle this deep link by calling [PackageManager#queryIntentActivities].
[PackageManager#queryIntentActivities]: https://developer.android.com/reference/android/content/pm/PackageManager#queryIntentActivities(android.content.Intent,%20int)

8
docs/README.md Normal file
View file

@ -0,0 +1,8 @@
# Application Notes
- [Deep Link](DEEP-LINK.md)
## EasyEUICC
- [Answer To Reset](ATR.md)
- [ARA-M Applet Configuration](ARA-M.md)

View file

@ -0,0 +1,40 @@
package im.angry.openeuicc.util
import android.content.Intent
import android.os.Bundle
import android.telephony.UiccAccessRule
import android.telephony.euicc.DownloadableSubscription
import android.telephony.euicc.EuiccManager
import java.lang.reflect.Method
// System APIs of android.telephony.euicc via reflection to enable building without AOSP source
// tree (see TelephonyManagerHiddenApi.kt). When building against AOSP, the real member
// functions take precedence and this file is not compiled at all.
private val continueOperation: Method by lazy {
EuiccManager::class.java.getMethod(
"continueOperation",
Intent::class.java, Bundle::class.java
)
}
private val builderSetCarrierName: Method by lazy {
DownloadableSubscription.Builder::class.java.getMethod(
"setCarrierName",
String::class.java
)
}
private val builderSetAccessRules: Method by lazy {
DownloadableSubscription.Builder::class.java.getMethod(
"setAccessRules",
List::class.java
)
}
fun EuiccManager.continueOperation(resolutionIntent: Intent, resolutionExtras: Bundle) {
continueOperation.invoke(this, resolutionIntent, resolutionExtras)
}
fun DownloadableSubscription.Builder.setCarrierName(value: String): DownloadableSubscription.Builder =
builderSetCarrierName.invoke(this, value) as DownloadableSubscription.Builder
fun DownloadableSubscription.Builder.setAccessRules(value: List<UiccAccessRule>): DownloadableSubscription.Builder =
builderSetAccessRules.invoke(this, value) as DownloadableSubscription.Builder

View file

@ -151,6 +151,12 @@ public abstract class EuiccService extends Service {
*/
public static final String EXTRA_RESOLUTION_CARD_ID =
"android.service.euicc.extra.RESOLUTION_CARD_ID";
/**
* Intent extra set for resolution requests containing an int indicating the subscription id
* to be enabled.
*/
public static final String EXTRA_RESOLUTION_SUBSCRIPTION_ID =
"android.service.euicc.extra.RESOLUTION_SUBSCRIPTION_ID";
/**
* Intent extra set for resolution requests containing an int indicating the current port index.
*/
@ -288,6 +294,14 @@ public abstract class EuiccService extends Service {
public abstract GetDownloadableSubscriptionMetadataResult onGetDownloadableSubscriptionMetadata(
int slotId, DownloadableSubscription subscription, boolean forceDeactivateSim);
public GetDownloadableSubscriptionMetadataResult onGetDownloadableSubscriptionMetadata(
int slotId, int portIndex, DownloadableSubscription subscription,
boolean forceDeactivateSim) {
// stub implementation, LPA needs to implement this
throw new UnsupportedOperationException(
"LPA must override onGetDownloadableSubscriptionMetadata");
}
/**
* Return metadata for subscriptions which are available for download for this device.
*
@ -328,6 +342,13 @@ public abstract class EuiccService extends Service {
return null;
}
public DownloadSubscriptionResult onDownloadSubscription(int slotIndex, int portIndex,
DownloadableSubscription subscription, boolean switchAfterDownload,
boolean forceDeactivateSim, Bundle resolvedBundle) {
// stub implementation, LPA needs to implement this
throw new UnsupportedOperationException("LPA must override onDownloadSubscription");
}
/**
* Download the given subscription.
*

View file

@ -4,7 +4,10 @@ sealed class ProfileDownloadState {
class Preparing : ProfileDownloadState()
class Connecting : ProfileDownloadState()
class Authenticating : ProfileDownloadState()
class ConfirmingDownload(val metadata: RemoteProfileInfo?) : ProfileDownloadState()
class ConfirmingDownload(val metadata: RemoteProfileInfo?) : ProfileDownloadState() {
// FIXME: Pass this back to JNI better. Something that's not a random property.
var confirmationCode: String? = null
}
class Downloading : ProfileDownloadState()
class Finalizing : ProfileDownloadState()
}

View file

@ -6,4 +6,22 @@ data class RemoteProfileInfo(
val name: String,
val providerName: String,
val profileClass: ProfileClass,
// Carrier privilege access rules (REF-AR-DO) from the profile metadata
val accessRules: List<RemoteProfileAccessRule>,
) {
// Used by JNI (see lpac-download.c)
@Suppress("unused")
constructor(
iccid: String,
name: String,
providerName: String,
profileClass: ProfileClass,
accessRules: Array<RemoteProfileAccessRule>,
) : this(iccid, name, providerName, profileClass, accessRules.toList())
}
// packageName is null if the rule applies to any app signed with the certificate
data class RemoteProfileAccessRule(
val certificateHash: String,
val packageName: String?,
)

@ -1 +1 @@
Subproject commit c859b25da02955fef659d658b8f324b5cde87be3
Subproject commit 6d9f2443ab071f86e5d9b43025a40929ec41c46c

@ -1 +1 @@
Subproject commit d214738fa0bdb23faf5833d3d798963079a00468
Subproject commit 50cdf15ab40942b00f8819a1c2ca19997f1a6d34

View file

@ -15,8 +15,11 @@ jobject download_state_finalizing;
jmethodID on_state_update;
jclass confirming_download_class;
jmethodID confirming_download_constructor;
jmethodID confirming_download_get_confirmation_code;
jclass remote_profile_info_class;
jmethodID remote_profile_info_constructor;
jclass remote_profile_access_rule_class;
jmethodID remote_profile_access_rule_constructor;
jobject profile_class_testing;
jobject profile_class_provisioning;
jobject profile_class_operational;
@ -86,6 +89,10 @@ void lpac_download_init() {
confirming_download_class,
"<init>",
"(Lnet/typeblog/lpac_jni/RemoteProfileInfo;)V");
confirming_download_get_confirmation_code = (*env)->GetMethodID(env,
confirming_download_class,
"getConfirmationCode",
"()Ljava/lang/String;");
jclass profile_class_class = (*env)->FindClass(env, "net/typeblog/lpac_jni/ProfileClass");
jfieldID profile_class_testing_field = (*env)->GetStaticFieldID(env, profile_class_class,
@ -111,7 +118,15 @@ void lpac_download_init() {
"net/typeblog/lpac_jni/RemoteProfileInfo");
remote_profile_info_class = (*env)->NewGlobalRef(env, _remote_profile_info_class);
remote_profile_info_constructor = (*env)->GetMethodID(env, remote_profile_info_class, "<init>",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/typeblog/lpac_jni/ProfileClass;)V");
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lnet/typeblog/lpac_jni/ProfileClass;[Lnet/typeblog/lpac_jni/RemoteProfileAccessRule;)V");
jclass _remote_profile_access_rule_class = (*env)->FindClass(env,
"net/typeblog/lpac_jni/RemoteProfileAccessRule");
remote_profile_access_rule_class = (*env)->NewGlobalRef(env, _remote_profile_access_rule_class);
remote_profile_access_rule_constructor = (*env)->GetMethodID(env,
remote_profile_access_rule_class,
"<init>",
"(Ljava/lang/String;Ljava/lang/String;)V");
}
static jobject profile_class_from_es10c_profile_class(enum es10c_profile_class profile_class) {
@ -133,7 +148,27 @@ static jobject create_remote_profile_info(JNIEnv *env,
jstring metadata_iccid = NULL;
jstring metadata_profile_name = NULL;
jstring metadata_provider_name = NULL;
jobjectArray metadata_access_rules = NULL;
jobject remote_profile_info = NULL;
struct es8p_metadata_access_rule *rule;
jsize i = 0;
for (rule = profile_metadata->accessRules; rule != NULL; rule = rule->next)
i++;
metadata_access_rules = (*env)->NewObjectArray(env, i, remote_profile_access_rule_class, NULL);
for (i = 0, rule = profile_metadata->accessRules; rule != NULL; i++, rule = rule->next) {
jstring cert_hash = toJString(env, rule->certificateHash);
// toJString() would turn a missing package name into ""
jstring package_name = rule->packageName != NULL ? toJString(env, rule->packageName) : NULL;
jobject access_rule = (*env)->NewObject(env, remote_profile_access_rule_class,
remote_profile_access_rule_constructor,
cert_hash, package_name);
(*env)->SetObjectArrayElement(env, metadata_access_rules, i, access_rule);
(*env)->DeleteLocalRef(env, access_rule);
(*env)->DeleteLocalRef(env, cert_hash);
if (package_name != NULL)
(*env)->DeleteLocalRef(env, package_name);
}
metadata_iccid = toJString(env, profile_metadata->iccid);
metadata_profile_name = toJString(env, profile_metadata->profileName);
@ -145,8 +180,10 @@ static jobject create_remote_profile_info(JNIEnv *env,
metadata_iccid,
metadata_profile_name,
metadata_provider_name,
profile_class);
profile_class,
metadata_access_rules);
(*env)->DeleteLocalRef(env, metadata_access_rules);
if (metadata_iccid != NULL)
(*env)->DeleteLocalRef(env, metadata_iccid);
if (metadata_profile_name != NULL)
@ -166,11 +203,13 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
struct es8p_metadata *profile_metadata = NULL;
struct es10b_load_bound_profile_package_result es10b_load_bound_profile_package_result;
const char *_confirmation_code = NULL;
const char *_late_confirmation_code = NULL;
const char *_matching_id = NULL;
const char *_smdp = NULL;
const char *_imei = NULL;
jobject remote_profile_info = NULL;
jobject confirming_download_state = NULL;
jstring late_confirmation_code = NULL;
jboolean confirmed = JNI_TRUE;
int ret;
@ -256,6 +295,15 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
confirmed = (*env)->CallBooleanMethod(env, callback, on_state_update, confirming_download_state);
if (confirmed) {
// The callback may have set the confirmation code only now (EuiccService case)
// FIXME: This should probably be passed in through something that's not just a property.
late_confirmation_code = (*env)->CallObjectMethod(env, confirming_download_state,
confirming_download_get_confirmation_code);
if (late_confirmation_code != NULL)
_late_confirmation_code = (*env)->GetStringUTFChars(env, late_confirmation_code, NULL);
}
if (remote_profile_info != NULL) {
(*env)->DeleteLocalRef(env, remote_profile_info);
remote_profile_info = NULL;
@ -276,7 +324,8 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
goto out;
}
ret = es10b_prepare_download(ctx, _confirmation_code);
ret = es10b_prepare_download(ctx, _late_confirmation_code != NULL ? _late_confirmation_code
: _confirmation_code);
syslog(LOG_INFO, "es10b_prepare_download %d", ret);
if (ret < 0) {
ret = -ES10B_ERROR_REASON_UNDEFINED;
@ -307,6 +356,10 @@ Java_net_typeblog_lpac_1jni_LpacJni_downloadProfile(JNIEnv *env, jobject thiz, j
// This is so that Java side can access the last HTTP and/or APDU errors when we return.
if (_confirmation_code != NULL)
(*env)->ReleaseStringUTFChars(env, confirmation_code, _confirmation_code);
if (_late_confirmation_code != NULL)
(*env)->ReleaseStringUTFChars(env, late_confirmation_code, _late_confirmation_code);
if (late_confirmation_code != NULL)
(*env)->DeleteLocalRef(env, late_confirmation_code);
if (_matching_id != NULL)
(*env)->ReleaseStringUTFChars(env, matching_id, _matching_id);
(*env)->ReleaseStringUTFChars(env, smdp, _smdp);