From 6e590cfd487fd39b681258c85957fea875f28b82 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Wed, 3 Apr 2024 20:53:48 -0400 Subject: [PATCH 01/81] OpenEuiccService: stop confusing AOSP with multiple eUICCs Unfortunately, AOSP is not really good at handling more than one eUICC chips per device, even though the EuiccService interface should technically allow for such a situation. Let's do the next best thing -- only ever report one eUICC chip to AOSP. If the device has an internal one, then only report that one; otherwise, select the first available eUICC chip to report to the system. We might make this more configurable in the future, but for now I think this should work for most of the situations. Note that this does NOT affect how the rest of OpenEUICC behaves. This does mean however OpenEUICC will keep hold of some APDU channels that it will never access via OpenEuiccService. A mitigation is to make EuiccChannelManager close unused channels automatically after some timeout. --- .../openeuicc/service/OpenEuiccService.kt | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index 65d7918..e635d21 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -16,6 +16,21 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { const val TAG = "OpenEuiccService" } + private val hasInternalEuicc by lazy { + telephonyManager.uiccCardsInfoCompat.any { it.isEuicc && !it.isRemovable } + } + + // TODO: Should this be configurable? + private fun shouldIgnoreSlot(physicalSlotId: Int) = + if (hasInternalEuicc) { + // For devices with an internal eUICC slot, ignore any removable UICC + telephonyManager.uiccCardsInfoCompat.find { it.physicalSlotIndex == physicalSlotId }!!.isRemovable + } 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 + } + private fun findChannel(physicalSlotId: Int): EuiccChannel? = euiccChannelManager.findEuiccChannelByPhysicalSlotBlocking(physicalSlotId) @@ -111,6 +126,11 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { override fun onGetEuiccProfileInfoList(slotId: Int): GetEuiccProfileInfoListResult { Log.i(TAG, "onGetEuiccProfileInfoList slotId=$slotId") + if (shouldIgnoreSlot(slotId)) { + Log.i(TAG, "ignoring slot $slotId") + return GetEuiccProfileInfoListResult(RESULT_FIRST_USER, arrayOf(), true) + } + val channel = findChannel(slotId)!! val profiles = channel.lpa.profiles.operational.map { EuiccProfileInfo.Builder(it.iccid).apply { @@ -142,6 +162,8 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { override fun onDeleteSubscription(slotId: Int, iccid: String): Int { Log.i(TAG, "onDeleteSubscription slotId=$slotId iccid=$iccid") + if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER + try { val channels = findAllChannels(slotId) ?: return RESULT_FIRST_USER @@ -187,6 +209,8 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { forceDeactivateSim: Boolean ): Int { Log.i(TAG,"onSwitchToSubscriptionWithPort slotId=$slotId portIndex=$portIndex iccid=$iccid forceDeactivateSim=$forceDeactivateSim") + if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER + try { // retryWithTimeout is needed here because this function may be called just after // AOSP has switched slot mappings, in which case the slots may not be ready yet. @@ -237,6 +261,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { override fun onUpdateSubscriptionNickname(slotId: Int, iccid: String, nickname: String?): Int { Log.i(TAG, "onUpdateSubscriptionNickname slotId=$slotId iccid=$iccid nickname=$nickname") + if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER val channel = findChannel(slotId) ?: return RESULT_FIRST_USER if (!channel.profileExists(iccid)) { return RESULT_FIRST_USER From 8b38a5a58d2b6cb276ad475a3289ca475f9ea0db Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 21 Apr 2024 22:31:03 -0400 Subject: [PATCH 02/81] OpenEuiccService: prevent crashing when AOSP queries an unmapped slot To properly fix this we need to temporarily enable disabled slots when they are requested by AOSP. For now let's just stop OpenEUICC from crashing. --- .../java/im/angry/openeuicc/service/OpenEuiccService.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index e635d21..7461298 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -131,7 +131,12 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { return GetEuiccProfileInfoListResult(RESULT_FIRST_USER, arrayOf(), true) } - val channel = findChannel(slotId)!! + // TODO: Temporarily enable the slot to access its profiles if it is currently unmapped + val channel = findChannel(slotId) ?: return GetEuiccProfileInfoListResult( + RESULT_FIRST_USER, + arrayOf(), + true + ) val profiles = channel.lpa.profiles.operational.map { EuiccProfileInfo.Builder(it.iccid).apply { setProfileName(it.name) From bf121e07a459783f163966434504afe827ee0009 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 13 Apr 2024 10:51:02 -0400 Subject: [PATCH 03/81] workflows: Correct build reproducibility - REPRODUCIBLE_BUILD needs to be a string - Fetch all history to generate versionCode correctly --- .forgejo/workflows/build-debug.yml | 1 + .forgejo/workflows/release.yml | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.forgejo/workflows/build-debug.yml b/.forgejo/workflows/build-debug.yml index 80b0d8e..1dcc692 100644 --- a/.forgejo/workflows/build-debug.yml +++ b/.forgejo/workflows/build-debug.yml @@ -14,6 +14,7 @@ jobs: uses: https://gitea.angry.im/actions/checkout@v3 with: submodules: recursive + fetch-depth: 0 - name: Decode Secret Signing Configuration uses: https://gitea.angry.im/actions/base64-to-file@v1 diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 529a6d8..e89323a 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -4,7 +4,7 @@ on: env: # Enable reproducibility-related build system workarounds - REPRODUCIBLE_BUILD: true + REPRODUCIBLE_BUILD: 'true' jobs: release: @@ -17,6 +17,7 @@ jobs: uses: https://gitea.angry.im/actions/checkout@v3 with: submodules: recursive + fetch-depth: 0 - name: Decode Secret Signing Configuration uses: https://gitea.angry.im/actions/base64-to-file@v1 From 03e63805704d728c29484d401ce0bbf423b243af Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 13 Apr 2024 11:33:00 -0400 Subject: [PATCH 04/81] Ditch REPRODUCIBLE_BUILD flag and set all prefix maps unconditionally --- .forgejo/workflows/release.yml | 4 ---- libs/lpac-jni/build.gradle.kts | 11 +++++------ 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index e89323a..650e95b 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -2,10 +2,6 @@ on: push: tags: '*' -env: - # Enable reproducibility-related build system workarounds - REPRODUCIBLE_BUILD: 'true' - jobs: release: runs-on: [docker, android-app-certs] diff --git a/libs/lpac-jni/build.gradle.kts b/libs/lpac-jni/build.gradle.kts index 313bf5b..b50a953 100644 --- a/libs/lpac-jni/build.gradle.kts +++ b/libs/lpac-jni/build.gradle.kts @@ -15,12 +15,11 @@ android { externalNativeBuild { ndkBuild { - if (System.getenv("REPRODUCIBLE_BUILD") != "true") { - arguments("-j4") - } else { - arguments("-j1") - cFlags("-fmacro-prefix-map=${project.projectDir.toString()}=/fake/path/") - } + cFlags( + "-fmacro-prefix-map=${project.projectDir.toString()}=/fake/path/", + "-fdebug-prefix-map=${project.projectDir.toString()}=/fake/path/", + "-ffile-prefix-map=${project.projectDir.toString()}=/fake/path/" + ) } } } From 1f6bad422274c48ec9ddcf7eaff905557244f95b Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 13 Apr 2024 15:05:34 -0400 Subject: [PATCH 05/81] app-unpriv: Set ndkVersion as well for stripping Otherwise, the stripping step always fails in CI builds. This breaks reproducibility as debug info contains path to NDK. --- app-unpriv/build.gradle.kts | 1 + 1 file changed, 1 insertion(+) diff --git a/app-unpriv/build.gradle.kts b/app-unpriv/build.gradle.kts index b664808..f1aa79d 100644 --- a/app-unpriv/build.gradle.kts +++ b/app-unpriv/build.gradle.kts @@ -18,6 +18,7 @@ apply { android { namespace = "im.angry.easyeuicc" compileSdk = 34 + ndkVersion = "26.1.10909125" defaultConfig { applicationId = "im.angry.easyeuicc" From 0f655f1f1fd4a722a52e5445f1fdffed1ed9744f Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 13 Apr 2024 15:15:20 -0400 Subject: [PATCH 06/81] workflows: Save debug symbols for releases --- .forgejo/workflows/release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index 650e95b..f35393d 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -34,6 +34,9 @@ jobs: - name: Build Release APK (Unprivileged / EasyEUICC only) run: ./gradlew --no-daemon :app-unpriv:assembleRelease + - name: Copy Debug Symbols to Release Path + run: cp app-unpriv/build/outputs/native-debug-symbols/jmpRelease/native-debug-symbols.zip app-unpriv/build/outputs/apk/jmp/release/ + - name: Create Release uses: https://gitea.angry.im/actions/forgejo-release@v1 with: From 59f359787412058d6c0d3e82e46eabadc03f0a78 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 4 May 2024 17:29:10 -0400 Subject: [PATCH 07/81] refactor: Wrap EuiccChannelManager in an Android Service instance This allows MUCH better lifecycle control over EuiccChannelManager. We no longer have to keep all opened APDU channels open until the application is destroyed. Instead, they can be closed as long as no component is bound to this Service instance. A catch is that other long-running services must bind to this service as-needed, otherwise a binding is going to keep the service always alive. This only affects the EuiccService implementation, and a suspending/blocking helper function is added to deal with this case. --- app-common/src/main/AndroidManifest.xml | 4 + .../core/DefaultEuiccChannelManagerFactory.kt | 10 ++ .../core/EuiccChannelManagerFactory.kt | 7 ++ .../im/angry/openeuicc/di/AppContainer.kt | 2 + .../angry/openeuicc/di/DefaultAppContainer.kt | 6 ++ .../service/EuiccChannelManagerService.kt | 41 +++++++++ .../openeuicc/ui/BaseEuiccAccessActivity.kt | 48 ++++++++++ .../ui/DirectProfileDownloadActivity.kt | 7 +- .../im/angry/openeuicc/ui/MainActivity.kt | 14 +-- .../openeuicc/ui/NotificationsActivity.kt | 5 +- .../angry/openeuicc/ui/SlotSelectFragment.kt | 3 +- .../util/EuiccChannelFragmentUtils.kt | 5 +- .../java/im/angry/openeuicc/util/Utils.kt | 6 +- .../core/PrivilegedEuiccChannelManager.kt | 5 +- .../PrivilegedEuiccChannelManagerFactory.kt | 10 ++ .../openeuicc/di/PrivilegedAppContainer.kt | 6 ++ .../openeuicc/service/OpenEuiccService.kt | 92 ++++++++++++++----- .../angry/openeuicc/ui/SlotMappingFragment.kt | 7 +- .../angry/openeuicc/util/PrivilegedUtils.kt | 27 ++++++ 19 files changed, 256 insertions(+), 49 deletions(-) create mode 100644 app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManagerFactory.kt create mode 100644 app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManagerFactory.kt create mode 100644 app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt create mode 100644 app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt create mode 100644 app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManagerFactory.kt create mode 100644 app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt diff --git a/app-common/src/main/AndroidManifest.xml b/app-common/src/main/AndroidManifest.xml index be37bf4..8163299 100644 --- a/app-common/src/main/AndroidManifest.xml +++ b/app-common/src/main/AndroidManifest.xml @@ -28,5 +28,9 @@ android:name="com.journeyapps.barcodescanner.CaptureActivity" android:screenOrientation="fullSensor" tools:replace="screenOrientation" /> + + diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManagerFactory.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManagerFactory.kt new file mode 100644 index 0000000..556a543 --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManagerFactory.kt @@ -0,0 +1,10 @@ +package im.angry.openeuicc.core + +import android.app.Service +import im.angry.openeuicc.di.AppContainer + +class DefaultEuiccChannelManagerFactory(private val appContainer: AppContainer) : + EuiccChannelManagerFactory { + override fun createEuiccChannelManager(serviceContext: Service) = + DefaultEuiccChannelManager(appContainer, serviceContext) +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManagerFactory.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManagerFactory.kt new file mode 100644 index 0000000..d39e6de --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManagerFactory.kt @@ -0,0 +1,7 @@ +package im.angry.openeuicc.core + +import android.app.Service + +interface EuiccChannelManagerFactory { + fun createEuiccChannelManager(serviceContext: Service): EuiccChannelManager +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt b/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt index 6ad6e0d..4b3c3cd 100644 --- a/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt +++ b/app-common/src/main/java/im/angry/openeuicc/di/AppContainer.kt @@ -4,11 +4,13 @@ import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import im.angry.openeuicc.core.EuiccChannelFactory import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.core.EuiccChannelManagerFactory import im.angry.openeuicc.util.* interface AppContainer { val telephonyManager: TelephonyManager val euiccChannelManager: EuiccChannelManager + val euiccChannelManagerFactory: EuiccChannelManagerFactory val subscriptionManager: SubscriptionManager val preferenceRepository: PreferenceRepository val uiComponentFactory: UiComponentFactory diff --git a/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt b/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt index 7a1a3fe..93fd8b8 100644 --- a/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt +++ b/app-common/src/main/java/im/angry/openeuicc/di/DefaultAppContainer.kt @@ -5,7 +5,9 @@ import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import im.angry.openeuicc.core.DefaultEuiccChannelFactory import im.angry.openeuicc.core.DefaultEuiccChannelManager +import im.angry.openeuicc.core.DefaultEuiccChannelManagerFactory import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.core.EuiccChannelManagerFactory import im.angry.openeuicc.util.* open class DefaultAppContainer(context: Context) : AppContainer { @@ -17,6 +19,10 @@ open class DefaultAppContainer(context: Context) : AppContainer { DefaultEuiccChannelManager(this, context) } + override val euiccChannelManagerFactory: EuiccChannelManagerFactory by lazy { + DefaultEuiccChannelManagerFactory(this) + } + override val subscriptionManager by lazy { context.getSystemService(SubscriptionManager::class.java)!! } diff --git a/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt b/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt new file mode 100644 index 0000000..75c58db --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/service/EuiccChannelManagerService.kt @@ -0,0 +1,41 @@ +package im.angry.openeuicc.service + +import android.app.Service +import android.content.Intent +import android.os.Binder +import android.os.IBinder +import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.util.* + +/** + * An Android Service wrapper for EuiccChannelManager. + * The purpose of this wrapper is mainly lifecycle-wise: having a Service allows the manager + * instance to have its own independent lifecycle. This way it can be created as requested and + * destroyed when no other components are bound to this service anymore. + * This behavior allows us to avoid keeping the APDU channels open at all times. For example, + * the EuiccService implementation should *only* bind to this service when it requires an + * instance of EuiccChannelManager. UI components can keep being bound to this service for + * their entire lifecycles, since the whole purpose of them is to expose the current state + * to the user. + */ +class EuiccChannelManagerService : Service(), OpenEuiccContextMarker { + inner class LocalBinder : Binder() { + val service = this@EuiccChannelManagerService + } + + private val euiccChannelManagerDelegate = lazy { + appContainer.euiccChannelManagerFactory.createEuiccChannelManager(this) + } + val euiccChannelManager: EuiccChannelManager by euiccChannelManagerDelegate + + override fun onBind(intent: Intent?): IBinder = LocalBinder() + + override fun onDestroy() { + super.onDestroy() + // This is the whole reason of the existence of this service: + // we can clean up opened channels when no one is using them + if (euiccChannelManagerDelegate.isInitialized()) { + euiccChannelManager.invalidate() + } + } +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt new file mode 100644 index 0000000..d760c76 --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/ui/BaseEuiccAccessActivity.kt @@ -0,0 +1,48 @@ +package im.angry.openeuicc.ui + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.Bundle +import android.os.IBinder +import androidx.appcompat.app.AppCompatActivity +import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.service.EuiccChannelManagerService + +abstract class BaseEuiccAccessActivity : AppCompatActivity() { + lateinit var euiccChannelManager: EuiccChannelManager + + private val euiccChannelManagerServiceConnection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, service: IBinder?) { + euiccChannelManager = + (service!! as EuiccChannelManagerService.LocalBinder).service.euiccChannelManager + onInit() + } + + override fun onServiceDisconnected(name: ComponentName?) { + // These activities should never lose the EuiccChannelManagerService connection + finish() + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + bindService( + Intent(this, EuiccChannelManagerService::class.java), + euiccChannelManagerServiceConnection, + Context.BIND_AUTO_CREATE + ) + } + + override fun onDestroy() { + super.onDestroy() + unbindService(euiccChannelManagerServiceConnection) + } + + /** + * When called, euiccChannelManager is guaranteed to have been initialized + */ + abstract fun onInit() +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt index 5414a67..dbdbe9d 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt @@ -1,16 +1,13 @@ package im.angry.openeuicc.ui -import android.os.Bundle -import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import im.angry.openeuicc.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -class DirectProfileDownloadActivity : AppCompatActivity(), SlotSelectFragment.SlotSelectedListener, OpenEuiccContextMarker { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) +class DirectProfileDownloadActivity : BaseEuiccAccessActivity(), SlotSelectFragment.SlotSelectedListener, OpenEuiccContextMarker { + override fun onInit() { lifecycleScope.launch { withContext(Dispatchers.IO) { euiccChannelManager.enumerateEuiccChannels() diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt index 2d80e33..ab89bab 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt @@ -10,16 +10,14 @@ import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner -import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import im.angry.openeuicc.common.R -import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -open class MainActivity : AppCompatActivity(), OpenEuiccContextMarker { +open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { companion object { const val TAG = "MainActivity" } @@ -45,10 +43,6 @@ open class MainActivity : AppCompatActivity(), OpenEuiccContextMarker { tm = telephonyManager spinnerAdapter = ArrayAdapter(this, R.layout.spinner_item) - - lifecycleScope.launch { - init() - } } override fun onCreateOptionsMenu(menu: Menu): Boolean { @@ -94,6 +88,12 @@ open class MainActivity : AppCompatActivity(), OpenEuiccContextMarker { else -> super.onOptionsItemSelected(item) } + override fun onInit() { + lifecycleScope.launch { + init() + } + } + private suspend fun init() { withContext(Dispatchers.IO) { euiccChannelManager.enumerateEuiccChannels() diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt index 925ed84..744a87d 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt @@ -12,7 +12,6 @@ import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.appcompat.app.AlertDialog -import androidx.appcompat.app.AppCompatActivity import androidx.core.view.forEach import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration @@ -27,7 +26,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import net.typeblog.lpac_jni.LocalProfileNotification -class NotificationsActivity: AppCompatActivity(), OpenEuiccContextMarker { +class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker { private lateinit var swipeRefresh: SwipeRefreshLayout private lateinit var notificationList: RecyclerView private val notificationAdapter = NotificationAdapter() @@ -39,7 +38,9 @@ class NotificationsActivity: AppCompatActivity(), OpenEuiccContextMarker { setContentView(R.layout.activity_notifications) setSupportActionBar(requireViewById(R.id.toolbar)) supportActionBar!!.setDisplayHomeAsUpEnabled(true) + } + override fun onInit() { euiccChannel = euiccChannelManager .findEuiccChannelBySlotBlocking(intent.getIntExtra("logicalSlotId", 0))!! diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt index 6288b0d..8fb36d9 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt @@ -29,7 +29,8 @@ class SlotSelectFragment : BaseMaterialDialogFragment(), OpenEuiccContextMarker private lateinit var toolbar: Toolbar private lateinit var spinner: Spinner private val channels: List by lazy { - euiccChannelManager.knownChannels.sortedBy { it.logicalSlotId } + (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager + .knownChannels.sortedBy { it.logicalSlotId } } override fun onCreateView( diff --git a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt index feee0cd..efe2326 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt @@ -4,9 +4,10 @@ import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import im.angry.openeuicc.core.EuiccChannel +import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.ui.BaseEuiccAccessActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import net.typeblog.lpac_jni.LocalProfileAssistant private const val TAG = "EuiccChannelFragmentUtils" @@ -30,6 +31,8 @@ val T.slotId: Int where T: Fragment, T: EuiccChannelFragmentMarker val T.portId: Int where T: Fragment, T: EuiccChannelFragmentMarker get() = requireArguments().getInt("portId") +val T.euiccChannelManager: EuiccChannelManager where T: Fragment, T: EuiccChannelFragmentMarker + get() = (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager val T.channel: EuiccChannel where T: Fragment, T: EuiccChannelFragmentMarker get() = euiccChannelManager.findEuiccChannelByPortBlocking(slotId, portId)!! diff --git a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt index 175e85f..6a43d00 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt @@ -7,7 +7,6 @@ import android.telephony.TelephonyManager import androidx.fragment.app.Fragment import im.angry.openeuicc.OpenEuiccApplication import im.angry.openeuicc.core.EuiccChannel -import im.angry.openeuicc.core.EuiccChannelManager import im.angry.openeuicc.di.AppContainer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking @@ -15,7 +14,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import net.typeblog.lpac_jni.LocalProfileInfo -import java.lang.RuntimeException +import kotlin.RuntimeException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine @@ -52,9 +51,6 @@ interface OpenEuiccContextMarker { val appContainer: AppContainer get() = openEuiccApplication.appContainer - val euiccChannelManager: EuiccChannelManager - get() = appContainer.euiccChannelManager - val telephonyManager: TelephonyManager get() = appContainer.telephonyManager } diff --git a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt index 1c5d132..923bbab 100644 --- a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt +++ b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManager.kt @@ -5,7 +5,10 @@ import im.angry.openeuicc.di.AppContainer import im.angry.openeuicc.util.* import java.lang.Exception -class PrivilegedEuiccChannelManager(appContainer: AppContainer, context: Context) : +class PrivilegedEuiccChannelManager( + appContainer: AppContainer, + context: Context +) : DefaultEuiccChannelManager(appContainer, context) { override val uiccCards: Collection get() = tm.uiccCardsInfoCompat diff --git a/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManagerFactory.kt b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManagerFactory.kt new file mode 100644 index 0000000..77dc5cd --- /dev/null +++ b/app/src/main/java/im/angry/openeuicc/core/PrivilegedEuiccChannelManagerFactory.kt @@ -0,0 +1,10 @@ +package im.angry.openeuicc.core + +import android.app.Service +import im.angry.openeuicc.di.AppContainer + +class PrivilegedEuiccChannelManagerFactory(private val appContainer: AppContainer) : + EuiccChannelManagerFactory { + override fun createEuiccChannelManager(serviceContext: Service): EuiccChannelManager = + PrivilegedEuiccChannelManager(appContainer, serviceContext) +} \ No newline at end of file diff --git a/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt b/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt index 5158352..c5896f2 100644 --- a/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt +++ b/app/src/main/java/im/angry/openeuicc/di/PrivilegedAppContainer.kt @@ -2,14 +2,20 @@ package im.angry.openeuicc.di import android.content.Context import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.core.EuiccChannelManagerFactory import im.angry.openeuicc.core.PrivilegedEuiccChannelFactory import im.angry.openeuicc.core.PrivilegedEuiccChannelManager +import im.angry.openeuicc.core.PrivilegedEuiccChannelManagerFactory class PrivilegedAppContainer(context: Context) : DefaultAppContainer(context) { override val euiccChannelManager: EuiccChannelManager by lazy { PrivilegedEuiccChannelManager(this, context) } + override val euiccChannelManagerFactory: EuiccChannelManagerFactory by lazy { + PrivilegedEuiccChannelManagerFactory(this) + } + override val uiComponentFactory by lazy { PrivilegedUiComponentFactory() } diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index 7461298..1aa9fc8 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -1,5 +1,7 @@ package im.angry.openeuicc.service +import android.content.Context +import android.content.Intent import android.os.Build import android.service.euicc.* import android.telephony.UiccSlotMapping @@ -8,7 +10,9 @@ import android.telephony.euicc.EuiccInfo import android.util.Log import net.typeblog.lpac_jni.LocalProfileInfo import im.angry.openeuicc.core.EuiccChannel +import im.angry.openeuicc.core.EuiccChannelManager import im.angry.openeuicc.util.* +import kotlinx.coroutines.runBlocking import java.lang.IllegalStateException class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { @@ -31,17 +35,51 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { telephonyManager.uiccCardsInfoCompat.firstOrNull { it.isEuicc }?.physicalSlotIndex == physicalSlotId } - private fun findChannel(physicalSlotId: Int): EuiccChannel? = - euiccChannelManager.findEuiccChannelByPhysicalSlotBlocking(physicalSlotId) + private data class EuiccChannelManagerContext( + val euiccChannelManager: EuiccChannelManager + ) { + fun findChannel(physicalSlotId: Int): EuiccChannel? = + euiccChannelManager.findEuiccChannelByPhysicalSlotBlocking(physicalSlotId) - private fun findChannel(slotId: Int, portId: Int): EuiccChannel? = - euiccChannelManager.findEuiccChannelByPortBlocking(slotId, portId) + fun findChannel(slotId: Int, portId: Int): EuiccChannel? = + euiccChannelManager.findEuiccChannelByPortBlocking(slotId, portId) - private fun findAllChannels(physicalSlotId: Int): List? = - euiccChannelManager.findAllEuiccChannelsByPhysicalSlotBlocking(physicalSlotId) + fun findAllChannels(physicalSlotId: Int): List? = + euiccChannelManager.findAllEuiccChannelsByPhysicalSlotBlocking(physicalSlotId) + } - override fun onGetEid(slotId: Int): String? = + /** + * Bind to EuiccChannelManagerService, run the callback with a EuiccChannelManager instance, + * and then unbind after the callback is finished. All methods in this class that require access + * to a EuiccChannelManager should be wrapped inside this call. + * + * 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. + */ + private inline fun withEuiccChannelManager(fn: EuiccChannelManagerContext.() -> T): T { + val (binder, unbind) = runBlocking { + bindServiceSuspended( + Intent( + this@OpenEuiccService, + EuiccChannelManagerService::class.java + ), Context.BIND_AUTO_CREATE + ) + } + + if (binder == null) { + throw RuntimeException("Unable to bind to EuiccChannelManagerService; aborting") + } + + val ret = + EuiccChannelManagerContext((binder as EuiccChannelManagerService.LocalBinder).service.euiccChannelManager).fn() + + unbind() + return ret + } + + override fun onGetEid(slotId: Int): String? = withEuiccChannelManager { findChannel(slotId)?.lpa?.eID + } // When two eSIM cards are present on one device, the Android settings UI // gets confused and sets the incorrect slotId for profiles from one of @@ -124,7 +162,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { return GetDefaultDownloadableSubscriptionListResult(RESULT_OK, arrayOf()) } - override fun onGetEuiccProfileInfoList(slotId: Int): GetEuiccProfileInfoListResult { + override fun onGetEuiccProfileInfoList(slotId: Int): GetEuiccProfileInfoListResult = withEuiccChannelManager { Log.i(TAG, "onGetEuiccProfileInfoList slotId=$slotId") if (shouldIgnoreSlot(slotId)) { Log.i(TAG, "ignoring slot $slotId") @@ -165,7 +203,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { return EuiccInfo("Unknown") // TODO: Can we actually implement this? } - override fun onDeleteSubscription(slotId: Int, iccid: String): Int { + override fun onDeleteSubscription(slotId: Int, iccid: String): Int = withEuiccChannelManager { Log.i(TAG, "onDeleteSubscription slotId=$slotId iccid=$iccid") if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER @@ -212,7 +250,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { portIndex: Int, iccid: String?, forceDeactivateSim: Boolean - ): Int { + ): Int = withEuiccChannelManager { Log.i(TAG,"onSwitchToSubscriptionWithPort slotId=$slotId portIndex=$portIndex iccid=$iccid forceDeactivateSim=$forceDeactivateSim") if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER @@ -264,22 +302,26 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { } } - override fun onUpdateSubscriptionNickname(slotId: Int, iccid: String, nickname: String?): Int { - Log.i(TAG, "onUpdateSubscriptionNickname slotId=$slotId iccid=$iccid nickname=$nickname") - if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER - val channel = findChannel(slotId) ?: return RESULT_FIRST_USER - if (!channel.profileExists(iccid)) { - return RESULT_FIRST_USER + override fun onUpdateSubscriptionNickname(slotId: Int, iccid: String, nickname: String?): Int = + withEuiccChannelManager { + Log.i( + TAG, + "onUpdateSubscriptionNickname slotId=$slotId iccid=$iccid nickname=$nickname" + ) + if (shouldIgnoreSlot(slotId)) return RESULT_FIRST_USER + val channel = findChannel(slotId) ?: return RESULT_FIRST_USER + if (!channel.profileExists(iccid)) { + return RESULT_FIRST_USER + } + val success = channel.lpa + .setNickname(iccid, nickname!!) + appContainer.subscriptionManager.tryRefreshCachedEuiccInfo(channel.cardId) + return if (success) { + RESULT_OK + } else { + RESULT_FIRST_USER + } } - val success = channel.lpa - .setNickname(iccid, nickname!!) - appContainer.subscriptionManager.tryRefreshCachedEuiccInfo(channel.cardId) - return if (success) { - RESULT_OK - } else { - RESULT_FIRST_USER - } - } @Deprecated("Deprecated in Java") override fun onEraseSubscriptions(slotId: Int): Int { diff --git a/app/src/main/java/im/angry/openeuicc/ui/SlotMappingFragment.kt b/app/src/main/java/im/angry/openeuicc/ui/SlotMappingFragment.kt index 1514fe9..e17f60e 100644 --- a/app/src/main/java/im/angry/openeuicc/ui/SlotMappingFragment.kt +++ b/app/src/main/java/im/angry/openeuicc/ui/SlotMappingFragment.kt @@ -96,14 +96,17 @@ class SlotMappingFragment: BaseMaterialDialogFragment(), withContext(Dispatchers.IO) { // Use the utility method from PrivilegedTelephonyUtils to ensure // unmapped ports have all profiles disabled - telephonyManager.updateSimSlotMapping(euiccChannelManager, adapter.mappings) + telephonyManager.updateSimSlotMapping( + (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager, + adapter.mappings + ) } } catch (e: Exception) { Toast.makeText(requireContext(), R.string.slot_mapping_failure, Toast.LENGTH_LONG).show() return@launch } Toast.makeText(requireContext(), R.string.slot_mapping_completed, Toast.LENGTH_LONG).show() - euiccChannelManager.invalidate() + (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager.invalidate() requireActivity().finish() } } diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt new file mode 100644 index 0000000..e295f26 --- /dev/null +++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedUtils.kt @@ -0,0 +1,27 @@ +package im.angry.openeuicc.util + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.IBinder +import java.util.concurrent.Executors +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine + +suspend fun Context.bindServiceSuspended(intent: Intent, flags: Int): Pair Unit> = + suspendCoroutine { cont -> + var binder: IBinder? + val conn = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, service: IBinder?) { + binder = service + cont.resume(Pair(binder) { unbindService(this) }) + } + + override fun onServiceDisconnected(name: ComponentName?) { + + } + } + + bindService(intent, flags, Executors.newSingleThreadExecutor(), conn) + } \ No newline at end of file From 043dff0f0a4e5f0378fb4b449af39f5cdfe72676 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 4 May 2024 22:02:11 -0400 Subject: [PATCH 08/81] lpac: bump upstream --- libs/lpac-jni/src/main/jni/lpac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/lpac-jni/src/main/jni/lpac b/libs/lpac-jni/src/main/jni/lpac index 0bb1969..d85537a 160000 --- a/libs/lpac-jni/src/main/jni/lpac +++ b/libs/lpac-jni/src/main/jni/lpac @@ -1 +1 @@ -Subproject commit 0bb196977e7f2e276a1076734897ad8c48d9d5ca +Subproject commit d85537a90922901638ca86c28ac6d5a0d494807c From 5785fe2e7c5ec9916ac661ec7704fad66b5659b5 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Tue, 7 May 2024 10:06:08 -0400 Subject: [PATCH 09/81] EuiccChannelManager: Check for channel validity before returning Related to #26. Sometimes we could open a channel but it somehow ends up being invalid, for example for a slot that's not actually an eUICC (???). This should be a bug somewhere else, but we should nevertheless prevent OpenEUICC from crashing. --- .../openeuicc/core/DefaultEuiccChannelManager.kt | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt index 811c56c..eb19c36 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt @@ -54,8 +54,18 @@ open class DefaultEuiccChannelManager( return null } - return euiccChannelFactory.tryOpenEuiccChannel(port)?.also { - channels.add(it) + val channel = euiccChannelFactory.tryOpenEuiccChannel(port) ?: return null + + if (channel.valid) { + channels.add(channel) + return channel + } else { + Log.i( + TAG, + "Was able to open channel for logical slot ${port.logicalSlotIndex}, but the channel is invalid (cannot get eID or profiles without errors). This slot might be broken, aborting." + ) + channel.close() + return null } } } From 1a22854d05d567be453fa2aadb839769fceaa9b7 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Thu, 9 May 2024 16:08:00 -0400 Subject: [PATCH 10/81] refactor: Remove all usage of knownChannels enumerateEuiccChannels() should return all discovered channels on its own. Outside classes should never access the cached open channels directly. --- .../core/DefaultEuiccChannelManager.kt | 28 ++++++------- .../openeuicc/core/EuiccChannelManager.kt | 20 ++++++--- .../ui/DirectProfileDownloadActivity.kt | 12 +++--- .../im/angry/openeuicc/ui/MainActivity.kt | 7 ++-- .../angry/openeuicc/ui/SlotSelectFragment.kt | 41 +++++++++++++------ .../util/PrivilegedTelephonyUtils.kt | 4 +- 6 files changed, 66 insertions(+), 46 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt index eb19c36..1d6627d 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt @@ -21,7 +21,7 @@ open class DefaultEuiccChannelManager( const val TAG = "EuiccChannelManager" } - private val channels = mutableListOf() + private val channelCache = mutableListOf() private val lock = Mutex() @@ -39,13 +39,13 @@ open class DefaultEuiccChannelManager( private suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? { lock.withLock { val existing = - channels.find { it.slotId == port.card.physicalSlotIndex && it.portId == port.portIndex } + channelCache.find { it.slotId == port.card.physicalSlotIndex && it.portId == port.portIndex } if (existing != null) { if (existing.valid && port.logicalSlotIndex == existing.logicalSlotId) { return existing } else { existing.close() - channels.remove(existing) + channelCache.remove(existing) } } @@ -57,7 +57,7 @@ open class DefaultEuiccChannelManager( val channel = euiccChannelFactory.tryOpenEuiccChannel(port) ?: return null if (channel.valid) { - channels.add(channel) + channelCache.add(channel) return channel } else { Log.i( @@ -128,7 +128,7 @@ open class DefaultEuiccChannelManager( override suspend fun waitForReconnect(physicalSlotId: Int, portId: Int, timeoutMillis: Long) { // If there is already a valid channel, we close it proactively // Sometimes the current channel can linger on for a bit even after it should have become invalid - channels.find { it.slotId == physicalSlotId && it.portId == portId }?.apply { + channelCache.find { it.slotId == physicalSlotId && it.portId == portId }?.apply { if (valid) close() } @@ -148,30 +148,26 @@ open class DefaultEuiccChannelManager( } } - override suspend fun enumerateEuiccChannels() { + override suspend fun enumerateEuiccChannels(): List = withContext(Dispatchers.IO) { - for (uiccInfo in uiccCards) { - for (port in uiccInfo.ports) { - if (tryOpenEuiccChannel(port) != null) { + uiccCards.flatMap { info -> + info.ports.mapNotNull { port -> + tryOpenEuiccChannel(port)?.also { Log.d( TAG, - "Found eUICC on slot ${uiccInfo.physicalSlotIndex} port ${port.portIndex}" + "Found eUICC on slot ${info.physicalSlotIndex} port ${port.portIndex}" ) } } } } - } - - override val knownChannels: List - get() = channels.toList() override fun invalidate() { - for (channel in channels) { + for (channel in channelCache) { channel.close() } - channels.clear() + channelCache.clear() euiccChannelFactory.cleanup() } } \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt index 9ec3030..5171779 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt @@ -1,12 +1,22 @@ package im.angry.openeuicc.core +/** + * EuiccChannelManager holds references to, and manages the lifecycles of, individual + * APDU channels to SIM cards. The find* methods will create channels when needed, and + * all opened channels will be held in an internal cache until invalidate() is called + * or when this instance is destroyed. + * + * To precisely control the lifecycle of this object itself (and thus its cached channels), + * all other compoents must access EuiccChannelManager objects through EuiccChannelManagerService. + * Holding references independent of EuiccChannelManagerService is unsupported. + */ interface EuiccChannelManager { - val knownChannels: List - /** - * Scan all possible sources for EuiccChannels and have them cached for future use + * Scan all possible sources for EuiccChannels, return them and have all + * scanned channels cached; these channels will remain open for the entire lifetime of + * this EuiccChannelManager object, unless disconnected externally or invalidate()'d */ - suspend fun enumerateEuiccChannels() + suspend fun enumerateEuiccChannels(): List /** * Wait for a slot + port to reconnect (i.e. become valid again) @@ -41,7 +51,7 @@ interface EuiccChannelManager { fun findEuiccChannelByPortBlocking(physicalSlotId: Int, portId: Int): EuiccChannel? /** - * Invalidate all EuiccChannels previously known by this Manager + * Invalidate all EuiccChannels previously cached by this Manager */ fun invalidate() diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt index dbdbe9d..9e79de6 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/DirectProfileDownloadActivity.kt @@ -9,23 +9,23 @@ import kotlinx.coroutines.withContext class DirectProfileDownloadActivity : BaseEuiccAccessActivity(), SlotSelectFragment.SlotSelectedListener, OpenEuiccContextMarker { override fun onInit() { lifecycleScope.launch { - withContext(Dispatchers.IO) { + val knownChannels = withContext(Dispatchers.IO) { euiccChannelManager.enumerateEuiccChannels() } when { - euiccChannelManager.knownChannels.isEmpty() -> { + knownChannels.isEmpty() -> { finish() } - euiccChannelManager.knownChannels.hasMultipleChips -> { - SlotSelectFragment.newInstance() + knownChannels.hasMultipleChips -> { + SlotSelectFragment.newInstance(knownChannels.sortedBy { it.logicalSlotId }) .show(supportFragmentManager, SlotSelectFragment.TAG) } else -> { // If the device has only one eSIM "chip" (but may be mapped to multiple slots), // we can skip the slot selection dialog since there is only one chip to save to. - onSlotSelected(euiccChannelManager.knownChannels[0].slotId, - euiccChannelManager.knownChannels[0].portId) + onSlotSelected(knownChannels[0].slotId, + knownChannels[0].portId) } } } diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt index ab89bab..9befe57 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt @@ -95,9 +95,8 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } private suspend fun init() { - withContext(Dispatchers.IO) { - euiccChannelManager.enumerateEuiccChannels() - euiccChannelManager.knownChannels.forEach { + val knownChannels = withContext(Dispatchers.IO) { + euiccChannelManager.enumerateEuiccChannels().onEach { Log.d(TAG, "slot ${it.slotId} port ${it.portId}") Log.d(TAG, it.lpa.eID) // Request the system to refresh the list of profiles every time we start @@ -108,7 +107,7 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } withContext(Dispatchers.Main) { - euiccChannelManager.knownChannels.sortedBy { it.logicalSlotId }.forEach { channel -> + knownChannels.sortedBy { it.logicalSlotId }.forEach { channel -> spinnerAdapter.add(getString(R.string.channel_name_format, channel.logicalSlotId)) fragments.add(appContainer.uiComponentFactory.createEuiccManagementFragment(channel)) } diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt index 8fb36d9..d1239c4 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/SlotSelectFragment.kt @@ -16,8 +16,14 @@ class SlotSelectFragment : BaseMaterialDialogFragment(), OpenEuiccContextMarker companion object { const val TAG = "SlotSelectFragment" - fun newInstance(): SlotSelectFragment { - return SlotSelectFragment() + fun newInstance(knownChannels: List): SlotSelectFragment { + return SlotSelectFragment().apply { + arguments = Bundle().apply { + putIntArray("slotIds", knownChannels.map { it.slotId }.toIntArray()) + putIntArray("logicalSlotIds", knownChannels.map { it.logicalSlotId }.toIntArray()) + putIntArray("portIds", knownChannels.map { it.portId }.toIntArray()) + } + } } } @@ -28,10 +34,10 @@ class SlotSelectFragment : BaseMaterialDialogFragment(), OpenEuiccContextMarker private lateinit var toolbar: Toolbar private lateinit var spinner: Spinner - private val channels: List by lazy { - (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager - .knownChannels.sortedBy { it.logicalSlotId } - } + private lateinit var adapter: ArrayAdapter + private lateinit var slotIds: IntArray + private lateinit var logicalSlotIds: IntArray + private lateinit var portIds: IntArray override fun onCreateView( inflater: LayoutInflater, @@ -44,26 +50,35 @@ class SlotSelectFragment : BaseMaterialDialogFragment(), OpenEuiccContextMarker toolbar.setTitle(R.string.slot_select) toolbar.inflateMenu(R.menu.fragment_slot_select) - val adapter = ArrayAdapter(inflater.context, R.layout.spinner_item) + adapter = ArrayAdapter(inflater.context, R.layout.spinner_item) spinner = view.requireViewById(R.id.spinner) spinner.adapter = adapter - channels.forEach { channel -> - adapter.add(getString(R.string.channel_name_format, channel.logicalSlotId)) + return view + } + + override fun onStart() { + super.onStart() + + slotIds = requireArguments().getIntArray("slotIds")!! + logicalSlotIds = requireArguments().getIntArray("logicalSlotIds")!! + portIds = requireArguments().getIntArray("portIds")!! + + logicalSlotIds.forEach { id -> + adapter.add(getString(R.string.channel_name_format, id)) } toolbar.setNavigationOnClickListener { (requireActivity() as SlotSelectedListener).onSlotSelectCancelled() } toolbar.setOnMenuItemClickListener { - val channel = channels[spinner.selectedItemPosition] - (requireActivity() as SlotSelectedListener).onSlotSelected(channel.slotId, channel.portId) + val slotId = slotIds[spinner.selectedItemPosition] + val portId = portIds[spinner.selectedItemPosition] + (requireActivity() as SlotSelectedListener).onSlotSelected(slotId, portId) dismiss() true } - - return view } override fun onResume() { diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt index 4675ab9..6a13c50 100644 --- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt +++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt @@ -15,12 +15,12 @@ val TelephonyManager.dsdsEnabled: Boolean get() = activeModemCount >= 2 fun TelephonyManager.setDsdsEnabled(euiccManager: EuiccChannelManager, enabled: Boolean) { - runBlocking { + val knownChannels = runBlocking { euiccManager.enumerateEuiccChannels() } // Disable all eSIM profiles before performing a DSDS switch (only for internal eSIMs) - euiccManager.knownChannels.forEach { + knownChannels.forEach { if (!it.removable) { it.lpa.disableActiveProfileWithUndo() } From 8eb36c77a826477faca8ce8a470113b437a74492 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Mon, 20 May 2024 10:10:55 -0400 Subject: [PATCH 11/81] workflows: Fix path This is not JMP SIM Manager :) --- .forgejo/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index f35393d..c8a7283 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -35,7 +35,7 @@ jobs: run: ./gradlew --no-daemon :app-unpriv:assembleRelease - name: Copy Debug Symbols to Release Path - run: cp app-unpriv/build/outputs/native-debug-symbols/jmpRelease/native-debug-symbols.zip app-unpriv/build/outputs/apk/jmp/release/ + run: cp app-unpriv/build/outputs/native-debug-symbols/release/native-debug-symbols.zip app-unpriv/build/outputs/apk/release/ - name: Create Release uses: https://gitea.angry.im/actions/forgejo-release@v1 From fc4e5739de11979226f4b80a0f79acbf9953c5c9 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Mon, 20 May 2024 18:09:00 -0400 Subject: [PATCH 12/81] feat: Scan QR code from gallery Close #6. --- .../openeuicc/ui/ProfileDownloadFragment.kt | 39 +++++++++++++++++-- .../java/im/angry/openeuicc/util/Utils.kt | 16 ++++++++ .../main/res/drawable/ic_gallery_black.xml | 5 +++ .../res/menu/fragment_profile_download.xml | 6 +++ app-common/src/main/res/values/strings.xml | 1 + 5 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 app-common/src/main/res/drawable/ic_gallery_black.xml diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt index feb0ab0..98237dc 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt @@ -3,6 +3,7 @@ package im.angry.openeuicc.ui import android.annotation.SuppressLint import android.app.Dialog import android.content.DialogInterface +import android.graphics.BitmapFactory import android.os.Bundle import android.text.Editable import android.util.Log @@ -10,6 +11,7 @@ import android.view.* import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.widget.Toolbar import androidx.lifecycle.lifecycleScope import com.google.android.material.textfield.TextInputLayout @@ -54,13 +56,38 @@ class ProfileDownloadFragment : BaseMaterialDialogFragment(), private val barcodeScannerLauncher = registerForActivityResult(ScanContract()) { result -> result.contents?.let { content -> Log.d(TAG, content) - val components = content.split("$") - if (components.size < 3 || components[0] != "LPA:1") return@registerForActivityResult - profileDownloadServer.editText?.setText(components[1]) - profileDownloadCode.editText?.setText(components[2]) + onScanResult(content) } } + private val gallerySelectorLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { result -> + if (result == null) return@registerForActivityResult + + lifecycleScope.launch(Dispatchers.IO) { + runCatching { + requireContext().contentResolver.openInputStream(result)?.let { input -> + val bmp = BitmapFactory.decodeStream(input) + input.close() + + decodeQrFromBitmap(bmp)?.let { + withContext(Dispatchers.Main) { + onScanResult(it) + } + } + + bmp.recycle() + } + } + } + } + + private fun onScanResult(result: String) { + val components = result.split("$") + if (components.size < 3 || components[0] != "LPA:1") return + profileDownloadServer.editText?.setText(components[1]) + profileDownloadCode.editText?.setText(components[2]) + } + override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, @@ -103,6 +130,10 @@ class ProfileDownloadFragment : BaseMaterialDialogFragment(), }) true } + R.id.scan_from_gallery -> { + gallerySelectorLauncher.launch("image/*") + true + } R.id.ok -> { startDownloadProfile() true diff --git a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt index 6a43d00..a93e7d2 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt @@ -2,9 +2,14 @@ package im.angry.openeuicc.util import android.content.Context import android.content.pm.PackageManager +import android.graphics.Bitmap import android.se.omapi.SEService import android.telephony.TelephonyManager import androidx.fragment.app.Fragment +import com.google.zxing.BinaryBitmap +import com.google.zxing.RGBLuminanceSource +import com.google.zxing.common.HybridBinarizer +import com.google.zxing.qrcode.QRCodeReader import im.angry.openeuicc.OpenEuiccApplication import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.di.AppContainer @@ -88,3 +93,14 @@ suspend fun connectSEService(context: Context): SEService = suspendCoroutine { c } } } + +fun decodeQrFromBitmap(bmp: Bitmap): String? = + runCatching { + val pixels = IntArray(bmp.width * bmp.height) + bmp.getPixels(pixels, 0, bmp.width, 0, 0, bmp.width, bmp.height) + + val luminanceSource = RGBLuminanceSource(bmp.width, bmp.height, pixels) + val binaryBmp = BinaryBitmap(HybridBinarizer(luminanceSource)) + + QRCodeReader().decode(binaryBmp).text + }.getOrNull() diff --git a/app-common/src/main/res/drawable/ic_gallery_black.xml b/app-common/src/main/res/drawable/ic_gallery_black.xml new file mode 100644 index 0000000..048f74a --- /dev/null +++ b/app-common/src/main/res/drawable/ic_gallery_black.xml @@ -0,0 +1,5 @@ + + + diff --git a/app-common/src/main/res/menu/fragment_profile_download.xml b/app-common/src/main/res/menu/fragment_profile_download.xml index d89c52c..b75822a 100644 --- a/app-common/src/main/res/menu/fragment_profile_download.xml +++ b/app-common/src/main/res/menu/fragment_profile_download.xml @@ -7,6 +7,12 @@ android:title="@string/profile_download_scan" app:showAsAction="ifRoom"/> + + IMEI (Optional) Space remaining: %s Scan QR Code + Scan QR Code from Gallery Download Failed to download eSIM. Check your activation / QR code. From 3869374140f6054aee3b7637485d1e4438f4ac5d Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Mon, 20 May 2024 18:09:49 -0400 Subject: [PATCH 13/81] ProfileDownloadFragment: make OK always appear as action --- app-common/src/main/res/menu/fragment_profile_download.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app-common/src/main/res/menu/fragment_profile_download.xml b/app-common/src/main/res/menu/fragment_profile_download.xml index b75822a..f93ae8d 100644 --- a/app-common/src/main/res/menu/fragment_profile_download.xml +++ b/app-common/src/main/res/menu/fragment_profile_download.xml @@ -17,5 +17,5 @@ android:id="@+id/ok" android:icon="@drawable/ic_check_black" android:title="@string/profile_download_ok" - app:showAsAction="ifRoom"/> + app:showAsAction="always"/> \ No newline at end of file From 2d312f2216a8a6d60815dba925ff6900320d9a82 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 2 Jun 2024 17:44:10 -0400 Subject: [PATCH 14/81] lpac-jni: Avoid reloading profiles from card every time Some cards may run at a low baud rate which causes issues --- .../impl/LocalProfileAssistantImpl.kt | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt index a76ba75..c0f81fb 100644 --- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt +++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt @@ -20,6 +20,7 @@ class LocalProfileAssistantImpl( private var finalized = false private var contextHandle: Long = LpacJni.createContext(apduInterface, httpInterface) + init { if (LpacJni.euiccInit(contextHandle) < 0) { throw IllegalArgumentException("Failed to initialize LPA") @@ -40,8 +41,11 @@ class LocalProfileAssistantImpl( false } + private var _profiles: List? = null override val profiles: List - get() = LpacJni.es10cGetProfilesInfo(contextHandle)!!.asList() + get() = (_profiles ?: LpacJni.es10cGetProfilesInfo(contextHandle)!!.asList()).also { + _profiles = it + } override val notifications: List get() = @@ -55,19 +59,26 @@ class LocalProfileAssistantImpl( get() = LpacJni.es10cexGetEuiccInfo2(contextHandle) override fun enableProfile(iccid: String): Boolean = - LpacJni.es10cEnableProfile(contextHandle, iccid) == 0 + (LpacJni.es10cEnableProfile(contextHandle, iccid) == 0).also { + _profiles = null + } override fun disableProfile(iccid: String): Boolean = - LpacJni.es10cDisableProfile(contextHandle, iccid) == 0 + (LpacJni.es10cDisableProfile(contextHandle, iccid) == 0).also { + _profiles = null + } - override fun deleteProfile(iccid: String): Boolean { - return LpacJni.es10cDeleteProfile(contextHandle, iccid) == 0 - } + override fun deleteProfile(iccid: String): Boolean = + (LpacJni.es10cDeleteProfile(contextHandle, iccid) == 0).also { + _profiles = null + } @Synchronized override fun downloadProfile(smdp: String, matchingId: String?, imei: String?, confirmationCode: String?, callback: ProfileDownloadCallback): Boolean { - return LpacJni.downloadProfile(contextHandle, smdp, matchingId, imei, confirmationCode, callback) == 0 + return (LpacJni.downloadProfile(contextHandle, smdp, matchingId, imei, confirmationCode, callback) == 0).also { + _profiles = null + } } override fun deleteNotification(seqNumber: Long): Boolean = @@ -79,9 +90,10 @@ class LocalProfileAssistantImpl( Log.d(TAG, "handleNotification $seqNumber = $it") } == 0 - override fun setNickname(iccid: String, nickname: String): Boolean { - return LpacJni.es10cSetNickname(contextHandle, iccid, nickname) == 0 - } + override fun setNickname(iccid: String, nickname: String): Boolean = + (LpacJni.es10cSetNickname(contextHandle, iccid, nickname) == 0).also { + _profiles = null + } @Synchronized override fun close() { From 5498186cf1f363dfbb189ce9cd5a92fcd5ede9f3 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 2 Jun 2024 20:12:28 -0400 Subject: [PATCH 15/81] ui: Stop refreshing profiles on every UI event --- .../main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt | 3 --- 1 file changed, 3 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index c1e5ba6..e4c667f 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -77,10 +77,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, ProfileDownloadFragment.newInstance(slotId, portId) .show(childFragmentManager, ProfileDownloadFragment.TAG) } - } - override fun onStart() { - super.onStart() refresh() } From 051bb9f1e385aabbff8064a700451343543f1705 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 2 Jun 2024 20:24:31 -0400 Subject: [PATCH 16/81] ui: Fix download errors, again Also improve comments so I don't keep forgetting what I did --- .../im/angry/openeuicc/ui/ProfileDownloadFragment.kt | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt index 98237dc..bb406e2 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/ProfileDownloadFragment.kt @@ -225,7 +225,7 @@ class ProfileDownloadFragment : BaseMaterialDialogFragment(), confirmationCode: String?, imei: String? ) = beginTrackedOperation { - channel.lpa.downloadProfile( + val res = channel.lpa.downloadProfile( server, code, imei, @@ -239,8 +239,14 @@ class ProfileDownloadFragment : BaseMaterialDialogFragment(), } }) + if (!res) { + // TODO: Provide more details on the error + throw RuntimeException("Failed to download profile; this is typically caused by another error happened before.") + } + // If we get here, we are successful - // Only send notifications if the user allowed us to + // This function is wrapped in beginTrackedOperation, so by returning the settings value, + // We only send notifications if the user allowed us to preferenceRepository.notificationDownloadFlow.first() } From 1536343b3f8bfe0018dbcd422928cb8c77db85f4 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Tue, 4 Jun 2024 22:05:29 -0400 Subject: [PATCH 17/81] fix: Add connection timeouts for notification handling ...and do not fail operations if notification handling fails -- notifications are best-effort. --- .../openeuicc/util/EuiccChannelFragmentUtils.kt | 15 ++++++++++----- .../typeblog/lpac_jni/impl/HttpInterfaceImpl.kt | 1 + 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt index efe2326..aff4154 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt @@ -48,11 +48,16 @@ suspend fun T.beginTrackedOperation(op: suspend () -> Boolean) where T : Fra Log.d(TAG, "Latest notification is $latestSeq before operation") if (op()) { Log.d(TAG, "Operation has requested notification handling") - // Note that the exact instance of "channel" might have changed here if reconnected; - // so we MUST use the automatic getter for "channel" - channel.lpa.notifications.filter { it.seqNumber > latestSeq }.forEach { - Log.d(TAG, "Handling notification $it") - channel.lpa.handleNotification(it.seqNumber) + try { + // Note that the exact instance of "channel" might have changed here if reconnected; + // so we MUST use the automatic getter for "channel" + channel.lpa.notifications.filter { it.seqNumber > latestSeq }.forEach { + Log.d(TAG, "Handling notification $it") + channel.lpa.handleNotification(it.seqNumber) + } + } catch (e: Exception) { + // Ignore any error during notification handling + e.printStackTrace() } } Log.d(TAG, "Operation complete") diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt index bfad50c..356ccb2 100644 --- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt +++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/HttpInterfaceImpl.kt @@ -33,6 +33,7 @@ class HttpInterfaceImpl: HttpInterface { sslContext.init(null, trustManagers, SecureRandom()) val conn = parsedUrl.openConnection() as HttpsURLConnection + conn.connectTimeout = 2000 conn.sslSocketFactory = sslContext.socketFactory conn.requestMethod = "POST" conn.doInput = true From 01e1b2b9a468fb164054921fe12d6daaa5c2c6bf Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Thu, 13 Jun 2024 20:24:42 -0400 Subject: [PATCH 18/81] fix: Show toasts from main thread --- .../im/angry/openeuicc/ui/EuiccManagementFragment.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index e4c667f..96c0949 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -137,8 +137,13 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, if (!res) { Log.d(TAG, "Failed to enable / disable profile $iccid") - Toast.makeText(context, R.string.toast_profile_enable_failed, Toast.LENGTH_LONG) - .show() + withContext(Dispatchers.Main) { + Toast.makeText( + context, + R.string.toast_profile_enable_failed, + Toast.LENGTH_LONG + ).show() + } return@beginTrackedOperation false } From 20cdb99a7b52f4c6ebc674f106fdeba4e56928e8 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 17:09:19 -0400 Subject: [PATCH 19/81] lpac-jni: Expose refresh flag to Kotlin --- .../java/net/typeblog/lpac_jni/LocalProfileAssistant.kt | 4 ++-- .../src/main/java/net/typeblog/lpac_jni/LpacJni.kt | 4 ++-- .../typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt | 8 ++++---- libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt index 16a91e7..89df38d 100644 --- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt +++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt @@ -10,8 +10,8 @@ interface LocalProfileAssistant { // All blocking functions in this class assume that they are executed on non-Main threads // The IO context in Kotlin's coroutine library is recommended. - fun enableProfile(iccid: String): Boolean - fun disableProfile(iccid: String): Boolean + fun enableProfile(iccid: String, refresh: Boolean = false): Boolean + fun disableProfile(iccid: String, refresh: Boolean = false): Boolean fun deleteProfile(iccid: String): Boolean fun downloadProfile(smdp: String, matchingId: String?, imei: String?, diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt index 836332e..5a706b9 100644 --- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt +++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LpacJni.kt @@ -15,8 +15,8 @@ internal object LpacJni { // null returns signify errors external fun es10cGetEid(handle: Long): String? external fun es10cGetProfilesInfo(handle: Long): Array? - external fun es10cEnableProfile(handle: Long, iccid: String): Int - external fun es10cDisableProfile(handle: Long, iccid: String): Int + external fun es10cEnableProfile(handle: Long, iccid: String, refresh: Boolean): Int + external fun es10cDisableProfile(handle: Long, iccid: String, refresh: Boolean): Int external fun es10cDeleteProfile(handle: Long, iccid: String): Int external fun es10cSetNickname(handle: Long, iccid: String, nick: String): Int diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt index c0f81fb..b5e4b5c 100644 --- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt +++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/impl/LocalProfileAssistantImpl.kt @@ -58,13 +58,13 @@ class LocalProfileAssistantImpl( override val euiccInfo2: EuiccInfo2? get() = LpacJni.es10cexGetEuiccInfo2(contextHandle) - override fun enableProfile(iccid: String): Boolean = - (LpacJni.es10cEnableProfile(contextHandle, iccid) == 0).also { + override fun enableProfile(iccid: String, refresh: Boolean): Boolean = + (LpacJni.es10cEnableProfile(contextHandle, iccid, refresh) == 0).also { _profiles = null } - override fun disableProfile(iccid: String): Boolean = - (LpacJni.es10cDisableProfile(contextHandle, iccid) == 0).also { + override fun disableProfile(iccid: String, refresh: Boolean): Boolean = + (LpacJni.es10cDisableProfile(contextHandle, iccid, refresh) == 0).also { _profiles = null } diff --git a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c index 503f816..6ba8ebf 100644 --- a/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c +++ b/libs/lpac-jni/src/main/jni/lpac-jni/lpac-jni.c @@ -242,26 +242,26 @@ Java_net_typeblog_lpac_1jni_LpacJni_es10cGetProfilesInfo(JNIEnv *env, jobject th JNIEXPORT jint JNICALL Java_net_typeblog_lpac_1jni_LpacJni_es10cEnableProfile(JNIEnv *env, jobject thiz, jlong handle, - jstring iccid) { + jstring iccid, jboolean refresh) { struct euicc_ctx *ctx = (struct euicc_ctx *) handle; const char *_iccid = NULL; int ret; _iccid = (*env)->GetStringUTFChars(env, iccid, NULL); - ret = es10c_enable_profile(ctx, _iccid, 1); + ret = es10c_enable_profile(ctx, _iccid, refresh ? 1 : 0); (*env)->ReleaseStringUTFChars(env, iccid, _iccid); return ret; } JNIEXPORT jint JNICALL Java_net_typeblog_lpac_1jni_LpacJni_es10cDisableProfile(JNIEnv *env, jobject thiz, jlong handle, - jstring iccid) { + jstring iccid, jboolean refresh) { struct euicc_ctx *ctx = (struct euicc_ctx *) handle; const char *_iccid = NULL; int ret; _iccid = (*env)->GetStringUTFChars(env, iccid, NULL); - ret = es10c_disable_profile(ctx, _iccid, 1); + ret = es10c_disable_profile(ctx, _iccid, refresh ? 1 : 0); (*env)->ReleaseStringUTFChars(env, iccid, _iccid); return ret; } From ff427759d780971e53c19395ce8d0e5a78aa83c5 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 17:27:00 -0400 Subject: [PATCH 20/81] fix: Try to disable the current profile before switching --- .../java/im/angry/openeuicc/ui/EuiccManagementFragment.kt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index 96c0949..999bafe 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -130,6 +130,12 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, lifecycleScope.launch { beginTrackedOperation { val res = if (enable) { + channel.lpa.profiles.find { it.isEnabled }?.let { + Log.i(TAG, "Profile ${it.iccid} is enabled; disabling before switching to new profile") + // Don't refresh -- we'll refresh later when enabling. + // Also ignore errors -- this is only a hard error if the enabling step fails. + channel.lpa.disableProfile(it.iccid, false) + } channel.lpa.enableProfile(iccid) } else { channel.lpa.disableProfile(iccid) From 2b3f042e39e88782b6ed42062108311572b01e5a Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 17:42:21 -0400 Subject: [PATCH 21/81] Move some functions to LPAUtils --- .../src/main/java/im/angry/openeuicc/util/LPAUtils.kt | 8 ++++++++ app-common/src/main/java/im/angry/openeuicc/util/Utils.kt | 8 -------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index e5c2f52..ee44028 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -1,16 +1,24 @@ package im.angry.openeuicc.util +import im.angry.openeuicc.core.EuiccChannel import net.typeblog.lpac_jni.LocalProfileAssistant import net.typeblog.lpac_jni.LocalProfileInfo val LocalProfileInfo.displayName: String get() = nickName.ifEmpty { name } + +val LocalProfileInfo.isEnabled: Boolean + get() = state == LocalProfileInfo.State.Enabled + val List.operational: List get() = filter { it.profileClass == LocalProfileInfo.Clazz.Operational } +val List.hasMultipleChips: Boolean + get() = distinctBy { it.slotId }.size > 1 + fun LocalProfileAssistant.disableActiveProfileWithUndo(): () -> Unit = profiles.find { it.state == LocalProfileInfo.State.Enabled }?.let { disableProfile(it.iccid) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt index a93e7d2..444c176 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/Utils.kt @@ -11,14 +11,12 @@ import com.google.zxing.RGBLuminanceSource import com.google.zxing.common.HybridBinarizer import com.google.zxing.qrcode.QRCodeReader import im.angry.openeuicc.OpenEuiccApplication -import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.di.AppContainer import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext -import net.typeblog.lpac_jni.LocalProfileInfo import kotlin.RuntimeException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @@ -60,12 +58,6 @@ interface OpenEuiccContextMarker { get() = appContainer.telephonyManager } -val LocalProfileInfo.isEnabled: Boolean - get() = state == LocalProfileInfo.State.Enabled - -val List.hasMultipleChips: Boolean - get() = distinctBy { it.slotId }.size > 1 - // Create an instance of OMAPI SEService in a manner that "makes sense" without unpredictable callbacks suspend fun connectSEService(context: Context): SEService = suspendCoroutine { cont -> // Use a Mutex to make sure the continuation is run *after* the "service" variable is assigned From 0e86a922d158547aeb69c4cc3f292425cee8b973 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 17:45:30 -0400 Subject: [PATCH 22/81] fix: do not refresh eUICC when switching port mapping This is entirely unnecessary and only causes problems --- .../main/java/im/angry/openeuicc/util/LPAUtils.kt | 12 +++++++++--- .../angry/openeuicc/util/PrivilegedTelephonyUtils.kt | 4 ++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index ee44028..f799f03 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -19,8 +19,14 @@ val List.operational: List val List.hasMultipleChips: Boolean get() = distinctBy { it.slotId }.size > 1 -fun LocalProfileAssistant.disableActiveProfileWithUndo(): () -> Unit = - profiles.find { it.state == LocalProfileInfo.State.Enabled }?.let { - disableProfile(it.iccid) +/** + * Disable the active profile, return a lambda that reverts this action when called. + * If refreshOnDisable is true, also cause a eUICC refresh command. Note that refreshing + * will disconnect the eUICC and might need some time before being operational again. + * See EuiccManager.waitForReconnect() + */ +fun LocalProfileAssistant.disableActiveProfileWithUndo(refreshOnDisable: Boolean): () -> Unit = + profiles.find { it.isEnabled }?.let { + disableProfile(it.iccid, refreshOnDisable) return { enableProfile(it.iccid) } } ?: { } \ No newline at end of file diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt index 6a13c50..3c30bce 100644 --- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt +++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt @@ -22,7 +22,7 @@ fun TelephonyManager.setDsdsEnabled(euiccManager: EuiccChannelManager, enabled: // Disable all eSIM profiles before performing a DSDS switch (only for internal eSIMs) knownChannels.forEach { if (!it.removable) { - it.lpa.disableActiveProfileWithUndo() + it.lpa.disableActiveProfileWithUndo(false) } } @@ -45,7 +45,7 @@ fun TelephonyManager.updateSimSlotMapping( val undo = unmapped.mapNotNull { mapping -> euiccManager.findEuiccChannelByPortBlocking(mapping.physicalSlotIndex, mapping.portIndex)?.let { channel -> if (!channel.removable) { - return@mapNotNull channel.lpa.disableActiveProfileWithUndo() + return@mapNotNull channel.lpa.disableActiveProfileWithUndo(false) } else { // Do not do anything for external eUICCs -- we can't really trust them to work properly // with no profile enabled. From df9cece94b6aa91c085b906a7361134bba745c27 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 17:53:26 -0400 Subject: [PATCH 23/81] refactor: Commonize logic for disabling the active profile --- .../im/angry/openeuicc/ui/EuiccManagementFragment.kt | 9 +++------ .../src/main/java/im/angry/openeuicc/util/LPAUtils.kt | 11 +++++++++++ .../im/angry/openeuicc/service/OpenEuiccService.kt | 6 +++--- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index 999bafe..954cb0f 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -130,12 +130,9 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, lifecycleScope.launch { beginTrackedOperation { val res = if (enable) { - channel.lpa.profiles.find { it.isEnabled }?.let { - Log.i(TAG, "Profile ${it.iccid} is enabled; disabling before switching to new profile") - // Don't refresh -- we'll refresh later when enabling. - // Also ignore errors -- this is only a hard error if the enabling step fails. - channel.lpa.disableProfile(it.iccid, false) - } + // Disable any active profile first, but don't do a refresh and ignore + // any errors -- we only error if the enabling action fails + channel.lpa.disableActiveProfile(false) channel.lpa.enableProfile(iccid) } else { channel.lpa.disableProfile(iccid) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index f799f03..556320f 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -1,5 +1,6 @@ package im.angry.openeuicc.util +import android.util.Log import im.angry.openeuicc.core.EuiccChannel import net.typeblog.lpac_jni.LocalProfileAssistant import net.typeblog.lpac_jni.LocalProfileInfo @@ -19,6 +20,16 @@ val List.operational: List val List.hasMultipleChips: Boolean get() = distinctBy { it.slotId }.size > 1 +/** + * Disable the current active profile if any. If refresh is true, also cause a refresh command. + * See EuiccManager.waitForReconnect() + */ +fun LocalProfileAssistant.disableActiveProfile(refresh: Boolean): Boolean = + profiles.find { it.isEnabled }?.let { + Log.i("LPAUtils", "Disabling active profile ${it.iccid}") + disableProfile(it.iccid, refresh) + } ?: true + /** * Disable the active profile, return a lambda that reverts this action when called. * If refreshOnDisable is true, also cause a eUICC refresh command. Note that refreshing diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index 1aa9fc8..74d2d75 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -284,9 +284,9 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { } // Disable any active profile first if present - channel.lpa.profiles.find { - it.state == LocalProfileInfo.State.Enabled - }?.let { if (!channel.lpa.disableProfile(it.iccid)) return RESULT_FIRST_USER } + if (!channel.lpa.disableActiveProfile(false)) { + return RESULT_FIRST_USER + } if (iccid != null) { if (!channel.lpa.enableProfile(iccid)) { From f73af48b5908ebc7197e7cb2b16b53f1bf8307fe Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 20:25:25 -0400 Subject: [PATCH 24/81] refactor: beginTrackedOperation should be a LPA extension --- .../util/EuiccChannelFragmentUtils.kt | 36 +++---------------- .../java/im/angry/openeuicc/util/LPAUtils.kt | 34 ++++++++++++++++-- 2 files changed, 36 insertions(+), 34 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt index aff4154..582f86c 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt @@ -1,15 +1,10 @@ package im.angry.openeuicc.util import android.os.Bundle -import android.util.Log import androidx.fragment.app.Fragment import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.core.EuiccChannelManager import im.angry.openeuicc.ui.BaseEuiccAccessActivity -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext - -private const val TAG = "EuiccChannelFragmentUtils" interface EuiccChannelFragmentMarker: OpenEuiccContextMarker @@ -37,32 +32,9 @@ val T.channel: EuiccChannel where T: Fragment, T: EuiccChannelFragmentMarker get() = euiccChannelManager.findEuiccChannelByPortBlocking(slotId, portId)!! -/* - * Begin a "tracked" operation where notifications may be generated by the eSIM - * Automatically handle any newly generated notification during the operation - * if the function "op" returns true. - */ -suspend fun T.beginTrackedOperation(op: suspend () -> Boolean) where T : Fragment, T : EuiccChannelFragmentMarker = - withContext(Dispatchers.IO) { - val latestSeq = channel.lpa.notifications.firstOrNull()?.seqNumber ?: 0 - Log.d(TAG, "Latest notification is $latestSeq before operation") - if (op()) { - Log.d(TAG, "Operation has requested notification handling") - try { - // Note that the exact instance of "channel" might have changed here if reconnected; - // so we MUST use the automatic getter for "channel" - channel.lpa.notifications.filter { it.seqNumber > latestSeq }.forEach { - Log.d(TAG, "Handling notification $it") - channel.lpa.handleNotification(it.seqNumber) - } - } catch (e: Exception) { - // Ignore any error during notification handling - e.printStackTrace() - } - } - Log.d(TAG, "Operation complete") - } - interface EuiccProfilesChangedListener { fun onEuiccProfilesChanged() -} \ No newline at end of file +} + +suspend fun T.beginTrackedOperation(op: suspend () -> Boolean) where T: Fragment, T: EuiccChannelFragmentMarker = + channel.lpa.beginTrackedOperation(op) \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index 556320f..1f68c46 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -2,9 +2,13 @@ package im.angry.openeuicc.util import android.util.Log import im.angry.openeuicc.core.EuiccChannel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import net.typeblog.lpac_jni.LocalProfileAssistant import net.typeblog.lpac_jni.LocalProfileInfo +private const val TAG = "LPAUtils" + val LocalProfileInfo.displayName: String get() = nickName.ifEmpty { name } @@ -26,7 +30,7 @@ val List.hasMultipleChips: Boolean */ fun LocalProfileAssistant.disableActiveProfile(refresh: Boolean): Boolean = profiles.find { it.isEnabled }?.let { - Log.i("LPAUtils", "Disabling active profile ${it.iccid}") + Log.i(TAG, "Disabling active profile ${it.iccid}") disableProfile(it.iccid, refresh) } ?: true @@ -40,4 +44,30 @@ fun LocalProfileAssistant.disableActiveProfileWithUndo(refreshOnDisable: Boolean profiles.find { it.isEnabled }?.let { disableProfile(it.iccid, refreshOnDisable) return { enableProfile(it.iccid) } - } ?: { } \ No newline at end of file + } ?: { } + +/** + * Begin a "tracked" operation where notifications may be generated by the eSIM + * Automatically handle any newly generated notification during the operation + * if the function "op" returns true. + */ +suspend fun LocalProfileAssistant.beginTrackedOperation(op: suspend () -> Boolean) = + withContext(Dispatchers.IO) { + val latestSeq = notifications.firstOrNull()?.seqNumber ?: 0 + Log.d(TAG, "Latest notification is $latestSeq before operation") + if (op()) { + Log.d(TAG, "Operation has requested notification handling") + try { + // Note that the exact instance of "channel" might have changed here if reconnected; + // so we MUST use the automatic getter for "channel" + notifications.filter { it.seqNumber > latestSeq }.forEach { + Log.d(TAG, "Handling notification $it") + handleNotification(it.seqNumber) + } + } catch (e: Exception) { + // Ignore any error during notification handling + e.printStackTrace() + } + } + Log.d(TAG, "Operation complete") + } \ No newline at end of file From 261ad6dbeb0617cf325761de4dd7e9ddb9b3afb8 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 20:53:25 -0400 Subject: [PATCH 25/81] OpenEuiccService: track LPA actions for notifications --- .../java/im/angry/openeuicc/util/LPAUtils.kt | 39 +++++++++++-------- .../openeuicc/service/OpenEuiccService.kt | 36 +++++++++++------ 2 files changed, 47 insertions(+), 28 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index 1f68c46..5d0c6ce 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -3,11 +3,12 @@ package im.angry.openeuicc.util import android.util.Log import im.angry.openeuicc.core.EuiccChannel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import net.typeblog.lpac_jni.LocalProfileAssistant import net.typeblog.lpac_jni.LocalProfileInfo -private const val TAG = "LPAUtils" +const val TAG = "LPAUtils" val LocalProfileInfo.displayName: String get() = nickName.ifEmpty { name } @@ -53,21 +54,25 @@ fun LocalProfileAssistant.disableActiveProfileWithUndo(refreshOnDisable: Boolean */ suspend fun LocalProfileAssistant.beginTrackedOperation(op: suspend () -> Boolean) = withContext(Dispatchers.IO) { - val latestSeq = notifications.firstOrNull()?.seqNumber ?: 0 - Log.d(TAG, "Latest notification is $latestSeq before operation") - if (op()) { - Log.d(TAG, "Operation has requested notification handling") - try { - // Note that the exact instance of "channel" might have changed here if reconnected; - // so we MUST use the automatic getter for "channel" - notifications.filter { it.seqNumber > latestSeq }.forEach { - Log.d(TAG, "Handling notification $it") - handleNotification(it.seqNumber) - } - } catch (e: Exception) { - // Ignore any error during notification handling - e.printStackTrace() + beginTrackedOperationBlocking { op() } + } + +inline fun LocalProfileAssistant.beginTrackedOperationBlocking(op: () -> Boolean) { + val latestSeq = notifications.firstOrNull()?.seqNumber ?: 0 + Log.d(TAG, "Latest notification is $latestSeq before operation") + if (op()) { + Log.d(TAG, "Operation has requested notification handling") + try { + // Note that the exact instance of "channel" might have changed here if reconnected; + // so we MUST use the automatic getter for "channel" + notifications.filter { it.seqNumber > latestSeq }.forEach { + Log.d(TAG, "Handling notification $it") + handleNotification(it.seqNumber) } + } catch (e: Exception) { + // Ignore any error during notification handling + e.printStackTrace() } - Log.d(TAG, "Operation complete") - } \ No newline at end of file + } + Log.d(TAG, "Operation complete") +} \ No newline at end of file diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index 74d2d75..dd7bc59 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -12,6 +12,8 @@ import net.typeblog.lpac_jni.LocalProfileInfo import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.core.EuiccChannelManager import im.angry.openeuicc.util.* +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.single import kotlinx.coroutines.runBlocking import java.lang.IllegalStateException @@ -226,11 +228,17 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { } } - return if (channels[0].lpa.deleteProfile(iccid)) { - RESULT_OK - } else { - RESULT_FIRST_USER + channels[0].lpa.beginTrackedOperationBlocking { + if (channels[0].lpa.deleteProfile(iccid)) { + return RESULT_OK + } + + runBlocking { + preferenceRepository.notificationDeleteFlow.first() + } } + + return RESULT_FIRST_USER } catch (e: Exception) { return RESULT_FIRST_USER } @@ -283,14 +291,20 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { return RESULT_FIRST_USER } - // Disable any active profile first if present - if (!channel.lpa.disableActiveProfile(false)) { - return RESULT_FIRST_USER - } + channel.lpa.beginTrackedOperationBlocking { + if (iccid != null) { + // Disable any active profile first if present + channel.lpa.disableActiveProfile(false) + if (!channel.lpa.enableProfile(iccid)) { + return RESULT_FIRST_USER + } + } else { + channel.lpa.disableActiveProfile(true) + } - if (iccid != null) { - if (!channel.lpa.enableProfile(iccid)) { - return RESULT_FIRST_USER + runBlocking { + // TODO: The enable / disable operations should really be one + preferenceRepository.notificationEnableFlow.first() } } From 790a5cf778ed88f8920f1c23330ad238bccf2863 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 16 Jun 2024 20:58:07 -0400 Subject: [PATCH 26/81] OpenEuiccService: handle errors in disabling active profiles --- .../main/java/im/angry/openeuicc/service/OpenEuiccService.kt | 4 +++- .../main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index dd7bc59..4b46164 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -299,7 +299,9 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { return RESULT_FIRST_USER } } else { - channel.lpa.disableActiveProfile(true) + if (!channel.lpa.disableActiveProfile(true)) { + return RESULT_FIRST_USER + } } runBlocking { diff --git a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt index 89df38d..7e0a31b 100644 --- a/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt +++ b/libs/lpac-jni/src/main/java/net/typeblog/lpac_jni/LocalProfileAssistant.kt @@ -10,8 +10,8 @@ interface LocalProfileAssistant { // All blocking functions in this class assume that they are executed on non-Main threads // The IO context in Kotlin's coroutine library is recommended. - fun enableProfile(iccid: String, refresh: Boolean = false): Boolean - fun disableProfile(iccid: String, refresh: Boolean = false): Boolean + fun enableProfile(iccid: String, refresh: Boolean = true): Boolean + fun disableProfile(iccid: String, refresh: Boolean = true): Boolean fun deleteProfile(iccid: String): Boolean fun downloadProfile(smdp: String, matchingId: String?, imei: String?, From c8d2269efb7d3d037f70e4c0140ee368fa2ad128 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 23 Jun 2024 21:40:14 -0400 Subject: [PATCH 27/81] fix: beginTrackedOperation() should work with channels that get invalidated --- .../util/EuiccChannelFragmentUtils.kt | 11 ++++-- .../java/im/angry/openeuicc/util/LPAUtils.kt | 35 ++++++++++++++----- .../openeuicc/service/OpenEuiccService.kt | 4 +-- 3 files changed, 37 insertions(+), 13 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt index 582f86c..8b2aadb 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/EuiccChannelFragmentUtils.kt @@ -5,6 +5,8 @@ import androidx.fragment.app.Fragment import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.core.EuiccChannelManager import im.angry.openeuicc.ui.BaseEuiccAccessActivity +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext interface EuiccChannelFragmentMarker: OpenEuiccContextMarker @@ -36,5 +38,10 @@ interface EuiccProfilesChangedListener { fun onEuiccProfilesChanged() } -suspend fun T.beginTrackedOperation(op: suspend () -> Boolean) where T: Fragment, T: EuiccChannelFragmentMarker = - channel.lpa.beginTrackedOperation(op) \ No newline at end of file +suspend fun T.beginTrackedOperation(op: suspend () -> Boolean) where T: Fragment, T: EuiccChannelFragmentMarker { + withContext(Dispatchers.IO) { + euiccChannelManager.beginTrackedOperationBlocking(slotId, portId) { + op() + } + } +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index 5d0c6ce..860abc9 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -2,6 +2,7 @@ package im.angry.openeuicc.util import android.util.Log import im.angry.openeuicc.core.EuiccChannel +import im.angry.openeuicc.core.EuiccChannelManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext @@ -51,23 +52,39 @@ fun LocalProfileAssistant.disableActiveProfileWithUndo(refreshOnDisable: Boolean * Begin a "tracked" operation where notifications may be generated by the eSIM * Automatically handle any newly generated notification during the operation * if the function "op" returns true. + * + * This requires the EuiccChannelManager object and a slotId / portId instead of + * just an LPA object, because a LPA might become invalid during an operation + * that generates notifications. As such, we will end up having to reconnect + * when this happens. + * + * Note that however, if reconnect is required and will not be instant, waiting + * should be the concern of op() itself, and this function assumes that when + * op() returns, the slotId and portId will correspond to a valid channel again. */ -suspend fun LocalProfileAssistant.beginTrackedOperation(op: suspend () -> Boolean) = - withContext(Dispatchers.IO) { - beginTrackedOperationBlocking { op() } - } - -inline fun LocalProfileAssistant.beginTrackedOperationBlocking(op: () -> Boolean) { - val latestSeq = notifications.firstOrNull()?.seqNumber ?: 0 +inline fun EuiccChannelManager.beginTrackedOperationBlocking( + slotId: Int, + portId: Int, + op: () -> Boolean +) { + val latestSeq = + findEuiccChannelByPortBlocking(slotId, portId)!!.lpa.notifications.firstOrNull()?.seqNumber + ?: 0 Log.d(TAG, "Latest notification is $latestSeq before operation") if (op()) { Log.d(TAG, "Operation has requested notification handling") try { // Note that the exact instance of "channel" might have changed here if reconnected; // so we MUST use the automatic getter for "channel" - notifications.filter { it.seqNumber > latestSeq }.forEach { + findEuiccChannelByPortBlocking( + slotId, + portId + )?.lpa?.notifications?.filter { it.seqNumber > latestSeq }?.forEach { Log.d(TAG, "Handling notification $it") - handleNotification(it.seqNumber) + findEuiccChannelByPortBlocking( + slotId, + portId + )?.lpa?.handleNotification(it.seqNumber) } } catch (e: Exception) { // Ignore any error during notification handling diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index 4b46164..219bcaf 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -228,7 +228,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { } } - channels[0].lpa.beginTrackedOperationBlocking { + euiccChannelManager.beginTrackedOperationBlocking(channels[0].slotId, channels[0].portId) { if (channels[0].lpa.deleteProfile(iccid)) { return RESULT_OK } @@ -291,7 +291,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { return RESULT_FIRST_USER } - channel.lpa.beginTrackedOperationBlocking { + euiccChannelManager.beginTrackedOperationBlocking(channel.slotId, channel.portId) { if (iccid != null) { // Disable any active profile first if present channel.lpa.disableActiveProfile(false) From 113cc1b4cfe9d6aa715e9e91d6646061abe7a572 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Mon, 24 Jun 2024 20:59:18 -0400 Subject: [PATCH 28/81] revert back to calling enableProfile directly Disabling without refreshing causes issues on eSTK.me --- .../main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt | 3 --- 1 file changed, 3 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index 954cb0f..96c0949 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -130,9 +130,6 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, lifecycleScope.launch { beginTrackedOperation { val res = if (enable) { - // Disable any active profile first, but don't do a refresh and ignore - // any errors -- we only error if the enabling action fails - channel.lpa.disableActiveProfile(false) channel.lpa.enableProfile(iccid) } else { channel.lpa.disableProfile(iccid) From 4914a35c3dbe7114fc095ca23dc6b997697f54f5 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Mon, 24 Jun 2024 21:02:13 -0400 Subject: [PATCH 29/81] fix: EuiccService should ignore negative slot IDs --- .../main/java/im/angry/openeuicc/service/OpenEuiccService.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt index 219bcaf..2910590 100644 --- a/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt +++ b/app/src/main/java/im/angry/openeuicc/service/OpenEuiccService.kt @@ -166,7 +166,7 @@ class OpenEuiccService : EuiccService(), OpenEuiccContextMarker { override fun onGetEuiccProfileInfoList(slotId: Int): GetEuiccProfileInfoListResult = withEuiccChannelManager { Log.i(TAG, "onGetEuiccProfileInfoList slotId=$slotId") - if (shouldIgnoreSlot(slotId)) { + if (slotId == -1 || shouldIgnoreSlot(slotId)) { Log.i(TAG, "ignoring slot $slotId") return GetEuiccProfileInfoListResult(RESULT_FIRST_USER, arrayOf(), true) } From f3391bb8ee6e2a099137598344b60b7d3c521c76 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Mon, 24 Jun 2024 21:07:50 -0400 Subject: [PATCH 30/81] lpac-jni: Bump --- libs/lpac-jni/src/main/jni/lpac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/lpac-jni/src/main/jni/lpac b/libs/lpac-jni/src/main/jni/lpac index d85537a..0011ea6 160000 --- a/libs/lpac-jni/src/main/jni/lpac +++ b/libs/lpac-jni/src/main/jni/lpac @@ -1 +1 @@ -Subproject commit d85537a90922901638ca86c28ac6d5a0d494807c +Subproject commit 0011ea6cc4c045c84f7aac839c1cce7804422355 From a29b06803572d56477ea33dec661b6a2911ea14e Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Wed, 26 Jun 2024 21:20:53 -0400 Subject: [PATCH 31/81] ui: Prevent crash after a profile switch that timed out ...and improve the prompt when this happens. --- .../java/im/angry/openeuicc/ui/EuiccManagementFragment.kt | 7 +++++++ app-common/src/main/res/values/strings.xml | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index 96c0949..551f0c2 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -47,6 +47,10 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, private val adapter = EuiccProfileAdapter() + // Marker for when this fragment might enter an invalid state + // e.g. after a failed enable / disable operation + private var invalid = false + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) @@ -106,6 +110,7 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, @SuppressLint("NotifyDataSetChanged") private fun refresh() { + if (invalid) return swipeRefresh.isRefreshing = true lifecycleScope.launch { @@ -151,6 +156,8 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, euiccChannelManager.waitForReconnect(slotId, portId, timeoutMillis = 30 * 1000) } catch (e: TimeoutCancellationException) { withContext(Dispatchers.Main) { + // Prevent this Fragment from being used again + invalid = true // Timed out waiting for SIM to come back online, we can no longer assume that the LPA is still valid AlertDialog.Builder(requireContext()).apply { setMessage(R.string.enable_disable_timeout) diff --git a/app-common/src/main/res/values/strings.xml b/app-common/src/main/res/values/strings.xml index a2424e5..2920bfa 100644 --- a/app-common/src/main/res/values/strings.xml +++ b/app-common/src/main/res/values/strings.xml @@ -16,7 +16,7 @@ Delete Rename - Timed out waiting for the eSIM chip to switch profiles. You might want to restart the application or even the phone. + Timed out waiting for the eSIM chip to switch profiles. This may be a bug in your phone\'s modem firmware. Try toggling airplane mode, restarting the application, or rebooting the phone. Cannot switch to new eSIM profile. Nickname cannot be longer than 64 characters From 4790f87b65c3b5c70b20b8b6a10767d9bcf877a7 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Wed, 26 Jun 2024 21:23:10 -0400 Subject: [PATCH 32/81] ui: Prevent users from doing multiple things at once --- .../main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index 551f0c2..cff6e89 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -254,6 +254,9 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, } private fun showOptionsMenu() { + // Prevent users from doing multiple things at once + if (invalid || swipeRefresh.isRefreshing) return + PopupMenu(root.context, profileMenu).apply { setOnMenuItemClickListener(::onMenuItemClicked) populatePopupWithProfileActions(this, profile) From 6396f170128f6950562339b3d089fd86a3744eda Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Thu, 27 Jun 2024 20:01:44 -0400 Subject: [PATCH 33/81] Retry profile switching with refresh = false if refresh = true failed --- .../openeuicc/ui/EuiccManagementFragment.kt | 33 ++++++++++++++++--- .../java/im/angry/openeuicc/util/LPAUtils.kt | 11 +++++++ app-common/src/main/res/values/strings.xml | 1 + 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt index cff6e89..6aa1ace 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/EuiccManagementFragment.kt @@ -134,11 +134,17 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, lifecycleScope.launch { beginTrackedOperation { - val res = if (enable) { - channel.lpa.enableProfile(iccid) - } else { - channel.lpa.disableProfile(iccid) - } + val (res, refreshed) = + if (!channel.lpa.switchProfile(iccid, enable, refresh = true)) { + // Sometimes, we *can* enable or disable the profile, but we cannot + // send the refresh command to the modem because the profile somehow + // makes the modem "busy". In this case, we can still switch by setting + // refresh to false, but then the switch cannot take effect until the + // user resets the modem manually by toggling airplane mode or rebooting. + Pair(channel.lpa.switchProfile(iccid, enable, refresh = false), false) + } else { + Pair(true, true) + } if (!res) { Log.d(TAG, "Failed to enable / disable profile $iccid") @@ -152,6 +158,23 @@ open class EuiccManagementFragment : Fragment(), EuiccProfilesChangedListener, return@beginTrackedOperation false } + if (!refreshed) { + withContext(Dispatchers.Main) { + AlertDialog.Builder(requireContext()).apply { + setMessage(R.string.switch_did_not_refresh) + setPositiveButton(android.R.string.ok) { dialog, _ -> + dialog.dismiss() + requireActivity().finish() + } + setOnDismissListener { _ -> + requireActivity().finish() + } + show() + } + } + return@beginTrackedOperation true + } + try { euiccChannelManager.waitForReconnect(slotId, portId, timeoutMillis = 30 * 1000) } catch (e: TimeoutCancellationException) { diff --git a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt index 860abc9..50b2077 100644 --- a/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/util/LPAUtils.kt @@ -26,6 +26,17 @@ val List.operational: List val List.hasMultipleChips: Boolean get() = distinctBy { it.slotId }.size > 1 +fun LocalProfileAssistant.switchProfile( + iccid: String, + enable: Boolean = false, + refresh: Boolean = false +): Boolean = + if (enable) { + enableProfile(iccid, refresh) + } else { + disableProfile(iccid, refresh) + } + /** * Disable the current active profile if any. If refresh is true, also cause a refresh command. * See EuiccManager.waitForReconnect() diff --git a/app-common/src/main/res/values/strings.xml b/app-common/src/main/res/values/strings.xml index 2920bfa..c42e5da 100644 --- a/app-common/src/main/res/values/strings.xml +++ b/app-common/src/main/res/values/strings.xml @@ -17,6 +17,7 @@ Rename Timed out waiting for the eSIM chip to switch profiles. This may be a bug in your phone\'s modem firmware. Try toggling airplane mode, restarting the application, or rebooting the phone. + The operation was successful, but your phone\'s modem refused to refresh. You might need to toggle airplane mode or reboot in order to use the new profile. Cannot switch to new eSIM profile. Nickname cannot be longer than 64 characters From 803b88f74ed7c8f519b68a3b40baa82dec0fabb3 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sat, 29 Jun 2024 20:02:48 -0400 Subject: [PATCH 34/81] feat: USB CCID reader support [1/n] --- .../core/DefaultEuiccChannelFactory.kt | 20 ++++ .../core/DefaultEuiccChannelManager.kt | 44 ++++++++ .../openeuicc/core/EuiccChannelFactory.kt | 4 + .../openeuicc/core/EuiccChannelManager.kt | 16 ++- .../openeuicc/core/usb/UsbApduInterface.kt | 37 ++++++ .../openeuicc/core/usb/UsbCcidDescription.kt | 106 ++++++++++++++++++ .../angry/openeuicc/core/usb/UsbCcidUtils.kt | 34 ++++++ .../im/angry/openeuicc/ui/MainActivity.kt | 85 +++++++++++++- 8 files changed, 343 insertions(+), 3 deletions(-) create mode 100644 app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt create mode 100644 app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt create mode 100644 app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt index 1cb3650..e653a07 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelFactory.kt @@ -1,14 +1,23 @@ package im.angry.openeuicc.core import android.content.Context +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbInterface +import android.hardware.usb.UsbManager import android.se.omapi.SEService import android.util.Log +import im.angry.openeuicc.core.usb.UsbApduInterface +import im.angry.openeuicc.core.usb.getIoEndpoints import im.angry.openeuicc.util.* import java.lang.IllegalArgumentException open class DefaultEuiccChannelFactory(protected val context: Context) : EuiccChannelFactory { private var seService: SEService? = null + private val usbManager by lazy { + context.getSystemService(Context.USB_SERVICE) as UsbManager + } + private suspend fun ensureSEService() { if (seService == null || !seService!!.isConnected) { seService = connectSEService(context) @@ -36,6 +45,17 @@ open class DefaultEuiccChannelFactory(protected val context: Context) : EuiccCha return null } + override fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel? { + val (bulkIn, bulkOut) = usbInterface.getIoEndpoints() + if (bulkIn == null || bulkOut == null) return null + val conn = usbManager.openDevice(usbDevice) ?: return null + if (!conn.claimInterface(usbInterface, true)) return null + return EuiccChannel( + FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(EuiccChannelManager.USB_CHANNEL_ID)), + UsbApduInterface(conn, bulkIn, bulkOut) + ) + } + override fun cleanup() { seService?.shutdown() seService = null diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt index 1d6627d..81d86ee 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt @@ -1,8 +1,11 @@ package im.angry.openeuicc.core import android.content.Context +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbManager import android.telephony.SubscriptionManager import android.util.Log +import im.angry.openeuicc.core.usb.getSmartCardInterface import im.angry.openeuicc.di.AppContainer import im.angry.openeuicc.util.* import kotlinx.coroutines.Dispatchers @@ -23,12 +26,18 @@ open class DefaultEuiccChannelManager( private val channelCache = mutableListOf() + private var usbChannel: EuiccChannel? = null + private val lock = Mutex() protected val tm by lazy { appContainer.telephonyManager } + private val usbManager by lazy { + context.getSystemService(Context.USB_SERVICE) as UsbManager + } + private val euiccChannelFactory by lazy { appContainer.euiccChannelFactory } @@ -38,6 +47,15 @@ open class DefaultEuiccChannelManager( private suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? { lock.withLock { + if (port.card.physicalSlotIndex == EuiccChannelManager.USB_CHANNEL_ID) { + return if (usbChannel != null && usbChannel!!.valid) { + usbChannel + } else { + usbChannel = null + null + } + } + val existing = channelCache.find { it.slotId == port.card.physicalSlotIndex && it.portId == port.portIndex } if (existing != null) { @@ -162,11 +180,37 @@ open class DefaultEuiccChannelManager( } } + override suspend fun enumerateUsbEuiccChannel(): Pair = + withContext(Dispatchers.IO) { + usbManager.deviceList.values.forEach { device -> + Log.i(TAG, "Scanning USB device ${device.deviceId}:${device.vendorId}") + val iface = device.getSmartCardInterface() ?: return@forEach + // If we don't have permission, tell UI code that we found a candidate device, but we + // need permission to be able to do anything with it + if (!usbManager.hasPermission(device)) return@withContext Pair(device, null) + Log.i(TAG, "Found CCID interface on ${device.deviceId}:${device.vendorId}, and has permission; trying to open channel") + try { + val channel = euiccChannelFactory.tryOpenUsbEuiccChannel(device, iface) + if (channel != null && channel.lpa.valid) { + usbChannel = channel + return@withContext Pair(device, channel) + } + } catch (e: Exception) { + // Ignored -- skip forward + e.printStackTrace() + } + Log.i(TAG, "No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}") + } + return@withContext Pair(null, null) + } + override fun invalidate() { for (channel in channelCache) { channel.close() } + usbChannel?.close() + usbChannel = null channelCache.clear() euiccChannelFactory.cleanup() } diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt index c8435dc..fb5d95d 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelFactory.kt @@ -1,5 +1,7 @@ package im.angry.openeuicc.core +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbInterface import im.angry.openeuicc.util.* // This class is here instead of inside DI because it contains a bit more logic than just @@ -7,6 +9,8 @@ import im.angry.openeuicc.util.* interface EuiccChannelFactory { suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? + fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel? + /** * Release all resources used by this EuiccChannelFactory * Note that the same instance may be reused; any resources allocated must be automatically diff --git a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt index 5171779..b21ccf6 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/EuiccChannelManager.kt @@ -1,5 +1,7 @@ package im.angry.openeuicc.core +import android.hardware.usb.UsbDevice + /** * EuiccChannelManager holds references to, and manages the lifecycles of, individual * APDU channels to SIM cards. The find* methods will create channels when needed, and @@ -11,13 +13,25 @@ package im.angry.openeuicc.core * Holding references independent of EuiccChannelManagerService is unsupported. */ interface EuiccChannelManager { + companion object { + const val USB_CHANNEL_ID = 99 + } + /** - * Scan all possible sources for EuiccChannels, return them and have all + * Scan all possible _device internal_ sources for EuiccChannels, return them and have all * scanned channels cached; these channels will remain open for the entire lifetime of * this EuiccChannelManager object, unless disconnected externally or invalidate()'d */ suspend fun enumerateEuiccChannels(): List + /** + * Scan all possible USB devices for CCID readers that may contain eUICC cards. + * If found, try to open it for access, and add it to the internal EuiccChannel cache + * as a "port" with id 99. When user interaction is required to obtain permission + * to interact with the device, the second return value (EuiccChannel) will be null. + */ + suspend fun enumerateUsbEuiccChannel(): Pair + /** * Wait for a slot + port to reconnect (i.e. become valid again) * If the port is currently valid, this function will return immediately. diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt new file mode 100644 index 0000000..86efc24 --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt @@ -0,0 +1,37 @@ +package im.angry.openeuicc.core.usb + +import android.hardware.usb.UsbDeviceConnection +import android.hardware.usb.UsbEndpoint +import net.typeblog.lpac_jni.ApduInterface + +class UsbApduInterface( + private val conn: UsbDeviceConnection, + private val bulkIn: UsbEndpoint, + private val bulkOut: UsbEndpoint +): ApduInterface { + private lateinit var ccidDescription: UsbCcidDescription + + override fun connect() { + ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!! + ccidDescription.checkTransportProtocol() + } + + override fun disconnect() { + conn.close() + } + + override fun logicalChannelOpen(aid: ByteArray): Int { + return 0 + } + + override fun logicalChannelClose(handle: Int) { + + } + + override fun transmit(tx: ByteArray): ByteArray { + return byteArrayOf() + } + + override val valid: Boolean + get() = true +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt new file mode 100644 index 0000000..a9fa394 --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt @@ -0,0 +1,106 @@ +package im.angry.openeuicc.core.usb + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +data class UsbCcidDescription( + private val bMaxSlotIndex: Byte, + private val bVoltageSupport: Byte, + private val dwProtocols: Int, + private val dwFeatures: Int +) { + companion object { + private const val DESCRIPTOR_LENGTH: Byte = 0x36 + private const val DESCRIPTOR_TYPE: Byte = 0x21 + + // dwFeatures Masks + private const val FEATURE_AUTOMATIC_VOLTAGE = 0x00008 + private const val FEATURE_AUTOMATIC_PPS = 0x00080 + + private const val FEATURE_EXCHANGE_LEVEL_TPDU = 0x10000 + private const val FEATURE_EXCHANGE_LEVEL_SHORT_APDU = 0x20000 + private const val FEATURE_EXCHAGE_LEVEL_EXTENDED_APDU = 0x40000 + + // bVoltageSupport Masks + private const val VOLTAGE_5V: Byte = 1 + private const val VOLTAGE_3V: Byte = 2 + private const val VOLTAGE_1_8V: Byte = 4 + + private const val SLOT_OFFSET = 4 + private const val FEATURES_OFFSET = 40 + private const val MASK_T0_PROTO = 1 + private const val MASK_T1_PROTO = 2 + + fun fromRawDescriptors(desc: ByteArray): UsbCcidDescription? { + var dwProtocols = 0 + var dwFeatures = 0 + var bMaxSlotIndex: Byte = 0 + var bVoltageSupport: Byte = 0 + + var hasCcidDescriptor = false + + val byteBuffer = ByteBuffer.wrap(desc).order(ByteOrder.LITTLE_ENDIAN) + + while (byteBuffer.hasRemaining()) { + byteBuffer.mark() + val len = byteBuffer.get() + val type = byteBuffer.get() + if (type == DESCRIPTOR_TYPE && len == DESCRIPTOR_LENGTH) { + byteBuffer.reset() + byteBuffer.position(byteBuffer.position() + SLOT_OFFSET) + bMaxSlotIndex = byteBuffer.get() + bVoltageSupport = byteBuffer.get() + dwProtocols = byteBuffer.int + byteBuffer.reset() + byteBuffer.position(byteBuffer.position() + FEATURES_OFFSET) + dwFeatures = byteBuffer.int + hasCcidDescriptor = true + break + } else { + byteBuffer.position(byteBuffer.position() + len - 2) + } + } + + return if (hasCcidDescriptor) { + UsbCcidDescription(bMaxSlotIndex, bVoltageSupport, dwProtocols, dwFeatures) + } else { + null + } + } + } + + enum class Voltage(powerOnValue: Int, mask: Int) { + AUTO(0, 0), _5V(1, VOLTAGE_5V.toInt()), _3V(2, VOLTAGE_3V.toInt()), _1_8V( + 3, + VOLTAGE_1_8V.toInt() + ); + + val mask = powerOnValue.toByte() + val powerOnValue = mask.toByte() + } + + private fun hasFeature(feature: Int): Boolean = + (dwFeatures and feature) != 0 + + val voltages: Array + get() = + if (hasFeature(FEATURE_AUTOMATIC_VOLTAGE)) { + arrayOf(Voltage.AUTO) + } else { + Voltage.values().mapNotNull { + if ((it.mask.toInt() and bVoltageSupport.toInt()) != 0) { + it + } else { + null + } + }.toTypedArray() + } + + val hasAutomaticPps: Boolean = hasFeature(FEATURE_AUTOMATIC_PPS) + + fun checkTransportProtocol() { + val hasT1Protocol = dwProtocols and MASK_T1_PROTO != 0 + val hasT0Protocol = dwProtocols and MASK_T0_PROTO != 0 + android.util.Log.d("CcidDescription", "hasT1Protocol = $hasT1Protocol, hasT0Protocol = $hasT0Protocol") + } +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt new file mode 100644 index 0000000..f4e9a87 --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt @@ -0,0 +1,34 @@ +// Adapted from +package im.angry.openeuicc.core.usb + +import android.hardware.usb.UsbConstants +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbEndpoint +import android.hardware.usb.UsbInterface + +fun UsbInterface.getIoEndpoints(): Pair { + var bulkIn: UsbEndpoint? = null + var bulkOut: UsbEndpoint? = null + for (i in 0 until endpointCount) { + val endpoint = getEndpoint(i) + if (endpoint.type != UsbConstants.USB_ENDPOINT_XFER_BULK) { + continue + } + if (endpoint.direction == UsbConstants.USB_DIR_IN) { + bulkIn = endpoint + } else if (endpoint.direction == UsbConstants.USB_DIR_OUT) { + bulkOut = endpoint + } + } + return Pair(bulkIn, bulkOut) +} + +fun UsbDevice.getSmartCardInterface(): UsbInterface? { + for (i in 0 until interfaceCount) { + val anInterface = getInterface(i) + if (anInterface.interfaceClass == UsbConstants.USB_CLASS_CSCID) { + return anInterface + } + } + return null +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt index 9befe57..485d87f 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt @@ -1,6 +1,14 @@ package im.angry.openeuicc.ui +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context import android.content.Intent +import android.content.IntentFilter +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbManager +import android.os.Build import android.os.Bundle import android.telephony.TelephonyManager import android.util.Log @@ -12,6 +20,7 @@ import android.widget.ArrayAdapter import android.widget.Spinner import androidx.lifecycle.lifecycleScope import im.angry.openeuicc.common.R +import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -20,6 +29,7 @@ import kotlinx.coroutines.withContext open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { companion object { const val TAG = "MainActivity" + const val ACTION_USB_PERMISSION = "im.angry.openeuicc.USB_PERMISSION" } private lateinit var spinnerAdapter: ArrayAdapter @@ -30,6 +40,28 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { protected lateinit var tm: TelephonyManager + private val usbManager: UsbManager by lazy { + getSystemService(USB_SERVICE) as UsbManager + } + + private var usbDevice: UsbDevice? = null + private var usbChannel: EuiccChannel? = null + + private lateinit var usbPendingIntent: PendingIntent + + private val usbPermissionReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action == ACTION_USB_PERMISSION) { + if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { + lifecycleScope.launch(Dispatchers.Main) { + switchToUsbFragmentIfPossible() + } + } + } + } + } + + @SuppressLint("WrongConstant", "UnspecifiedRegisterReceiverFlag") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) @@ -43,6 +75,15 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { tm = telephonyManager spinnerAdapter = ArrayAdapter(this, R.layout.spinner_item) + + usbPendingIntent = PendingIntent.getBroadcast(this, 0, + Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE) + val filter = IntentFilter(ACTION_USB_PERMISSION) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + registerReceiver(usbPermissionReceiver, filter, Context.RECEIVER_EXPORTED) + } else { + registerReceiver(usbPermissionReceiver, filter) + } } override fun onCreateOptionsMenu(menu: Menu): Boolean { @@ -62,8 +103,15 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { position: Int, id: Long ) { - supportFragmentManager.beginTransaction() - .replace(R.id.fragment_root, fragments[position]).commit() + if (position < fragments.size) { + supportFragmentManager.beginTransaction() + .replace(R.id.fragment_root, fragments[position]).commit() + } else if (position == fragments.size) { + // If we are at the last position, this is the USB device + lifecycleScope.launch(Dispatchers.Main) { + switchToUsbFragmentIfPossible() + } + } } override fun onNothingSelected(parent: AdapterView<*>?) { @@ -106,12 +154,22 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } } + withContext(Dispatchers.IO) { + val res = euiccChannelManager.enumerateUsbEuiccChannel() + usbDevice = res.first + usbChannel = res.second + } + withContext(Dispatchers.Main) { knownChannels.sortedBy { it.logicalSlotId }.forEach { channel -> spinnerAdapter.add(getString(R.string.channel_name_format, channel.logicalSlotId)) fragments.add(appContainer.uiComponentFactory.createEuiccManagementFragment(channel)) } + // If USB readers exist, add them at the very last + // The adapter logic depends on this assumption + usbDevice?.let { spinnerAdapter.add(it.productName) } + if (fragments.isNotEmpty()) { if (this@MainActivity::spinner.isInitialized) { spinnerItem.isVisible = true @@ -120,4 +178,27 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } } } + + private suspend fun switchToUsbFragmentIfPossible() { + if (usbDevice != null && usbChannel == null) { + if (!usbManager.hasPermission(usbDevice)) { + usbManager.requestPermission(usbDevice, usbPendingIntent) + return + } else { + val (device, channel) = withContext(Dispatchers.IO) { + euiccChannelManager.enumerateUsbEuiccChannel() + } + + if (device != null && channel != null) { + usbDevice = device + usbChannel = channel + } + } + } + + if (usbChannel != null) { + supportFragmentManager.beginTransaction().replace(R.id.fragment_root, + appContainer.uiComponentFactory.createEuiccManagementFragment(usbChannel!!)).commit() + } + } } \ No newline at end of file From 3667f578d7d33dbb2bba2047e0a5de74ae344442 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 30 Jun 2024 16:51:59 -0400 Subject: [PATCH 35/81] [2/n] USB CCID Reader support *cough* copied CCID driver from OpenKeychains --- .../core/DefaultEuiccChannelManager.kt | 16 + .../openeuicc/core/usb/UsbApduInterface.kt | 128 ++++++- .../openeuicc/core/usb/UsbCcidDescription.kt | 10 +- .../openeuicc/core/usb/UsbCcidTransceiver.kt | 348 ++++++++++++++++++ .../angry/openeuicc/core/usb/UsbCcidUtils.kt | 2 + .../util/PrivilegedTelephonyUtils.kt | 7 +- 6 files changed, 499 insertions(+), 12 deletions(-) create mode 100644 app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt diff --git a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt index 81d86ee..0955959 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/DefaultEuiccChannelManager.kt @@ -91,6 +91,10 @@ open class DefaultEuiccChannelManager( override fun findEuiccChannelBySlotBlocking(logicalSlotId: Int): EuiccChannel? = runBlocking { withContext(Dispatchers.IO) { + if (logicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) { + return@withContext usbChannel + } + for (card in uiccCards) { for (port in card.ports) { if (port.logicalSlotIndex == logicalSlotId) { @@ -106,6 +110,10 @@ open class DefaultEuiccChannelManager( override fun findEuiccChannelByPhysicalSlotBlocking(physicalSlotId: Int): EuiccChannel? = runBlocking { withContext(Dispatchers.IO) { + if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) { + return@withContext usbChannel + } + for (card in uiccCards) { if (card.physicalSlotIndex != physicalSlotId) continue for (port in card.ports) { @@ -118,6 +126,10 @@ open class DefaultEuiccChannelManager( } override suspend fun findAllEuiccChannelsByPhysicalSlot(physicalSlotId: Int): List? { + if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) { + return usbChannel?.let { listOf(it) } + } + for (card in uiccCards) { if (card.physicalSlotIndex != physicalSlotId) continue return card.ports.mapNotNull { tryOpenEuiccChannel(it) } @@ -133,6 +145,10 @@ open class DefaultEuiccChannelManager( override suspend fun findEuiccChannelByPort(physicalSlotId: Int, portId: Int): EuiccChannel? = withContext(Dispatchers.IO) { + if (physicalSlotId == EuiccChannelManager.USB_CHANNEL_ID) { + return@withContext usbChannel + } + uiccCards.find { it.physicalSlotIndex == physicalSlotId }?.let { card -> card.ports.find { it.portIndex == portId }?.let { tryOpenEuiccChannel(it) } } diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt index 86efc24..d181e53 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbApduInterface.kt @@ -2,6 +2,8 @@ package im.angry.openeuicc.core.usb import android.hardware.usb.UsbDeviceConnection import android.hardware.usb.UsbEndpoint +import android.util.Log +import im.angry.openeuicc.util.* import net.typeblog.lpac_jni.ApduInterface class UsbApduInterface( @@ -9,11 +11,30 @@ class UsbApduInterface( private val bulkIn: UsbEndpoint, private val bulkOut: UsbEndpoint ): ApduInterface { + companion object { + private const val TAG = "UsbApduInterface" + } + private lateinit var ccidDescription: UsbCcidDescription + private lateinit var transceiver: UsbCcidTransceiver + + private var channelId = -1 override fun connect() { ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!! - ccidDescription.checkTransportProtocol() + + if (!ccidDescription.hasT0Protocol) { + throw IllegalArgumentException("Unsupported card reader; T=0 support is required") + } + + transceiver = UsbCcidTransceiver(conn, bulkIn, bulkOut, ccidDescription) + + try { + transceiver.iccPowerOn() + } catch (e: Exception) { + e.printStackTrace() + throw e + } } override fun disconnect() { @@ -21,17 +42,118 @@ class UsbApduInterface( } override fun logicalChannelOpen(aid: ByteArray): Int { - return 0 + check(channelId == -1) { "Logical channel already opened" } + + // OPEN LOGICAL CHANNEL + val req = manageChannelCmd(true, 0) + Log.d(TAG, "OPEN LOGICAL CHANNEL: ${req.encodeHex()}") + + val resp = try { + transmitApduByChannel(req, 0) + } catch (e: Exception) { + e.printStackTrace() + return -1 + } + Log.d(TAG, "OPEN LOGICAL CHANNEL response: ${resp.encodeHex()}") + + return if (resp.size >= 2 && resp.sliceArray((resp.size - 2) until resp.size).contentEquals( + byteArrayOf(0x90.toByte(), 0x00) + ) + ) { + channelId = resp[0].toInt() + Log.d(TAG, "channelId = $channelId") + + // Then, select AID + val selectAid = selectByDfCmd(aid, channelId.toByte()) + Log.d(TAG, "Select DF command: ${selectAid.encodeHex()}") + val selectAidResp = transmitApduByChannel(selectAid, channelId.toByte()) + Log.d(TAG, "Select DF resp: ${selectAidResp.encodeHex()}") + channelId + } else { + -1 + } } override fun logicalChannelClose(handle: Int) { + check(handle == channelId) { "Logical channel ID mismatch" } + check(channelId != -1) { "Logical channel is not opened" } + // CLOSE LOGICAL CHANNEL + val req = manageChannelCmd(false, channelId.toByte()) + Log.d(TAG, "CLOSE LOGICAL CHANNEL: ${req.encodeHex()}") + + val resp = transmitApduByChannel(req, channelId.toByte()) + Log.d(TAG, "CLOSE LOGICAL CHANNEL response: ${resp.encodeHex()}") + + channelId = -1 } override fun transmit(tx: ByteArray): ByteArray { - return byteArrayOf() + check(channelId != -1) { "Logical channel is not opened" } + Log.d(TAG, "USB APDU command: ${tx.encodeHex()}") + val resp = transmitApduByChannel(tx, channelId.toByte()) + Log.d(TAG, "USB APDU response: ${resp.encodeHex()}") + return resp } override val valid: Boolean get() = true + + private fun buildCmd(cla: Byte, ins: Byte, p1: Byte, p2: Byte, data: ByteArray?, le: Byte?) = + byteArrayOf(cla, ins, p1, p2).let { + if (data != null) { + it + data.size.toByte() + data + } else { + it + } + }.let { + if (le != null) { + it + byteArrayOf(le) + } else { + it + } + } + + private fun manageChannelCmd(open: Boolean, channel: Byte) = + if (open) { + buildCmd(0x00, 0x70, 0x00, 0x00, null, 0x01) + } else { + buildCmd(channel, 0x70, 0x80.toByte(), channel, null, null) + } + + private fun selectByDfCmd(aid: ByteArray, channel: Byte) = + buildCmd(channel, 0xA4.toByte(), 0x04, 0x00, aid, null) + + private fun transmitApduByChannel(tx: ByteArray, channel: Byte): ByteArray { + val realTx = tx.copyOf() + // OR the channel mask into the CLA byte + realTx[0] = ((realTx[0].toInt() and 0xFC) or channel.toInt()).toByte() + + var resp = transceiver.sendXfrBlock(realTx)!!.data!! + + if (resp.size >= 2) { + var sw1 = resp[resp.size - 2].toInt() and 0xFF + var sw2 = resp[resp.size - 1].toInt() and 0xFF + + if (sw1 == 0x6C) { + realTx[realTx.size - 1] = resp[resp.size - 1] + resp = transceiver.sendXfrBlock(realTx)!!.data!! + } else if (sw1 == 0x61) { + do { + val getResponseCmd = byteArrayOf( + realTx[0], 0xC0.toByte(), 0x00, 0x00, sw2.toByte() + ) + + val tmp = transceiver.sendXfrBlock(getResponseCmd)!!.data!! + + resp = resp.sliceArray(0 until (resp.size - 2)) + tmp + + sw1 = resp[resp.size - 2].toInt() and 0xFF + sw2 = resp[resp.size - 1].toInt() and 0xFF + } while (sw1 == 0x61) + } + } + + return resp + } } \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt index a9fa394..8a2ed39 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidDescription.kt @@ -96,11 +96,9 @@ data class UsbCcidDescription( }.toTypedArray() } - val hasAutomaticPps: Boolean = hasFeature(FEATURE_AUTOMATIC_PPS) + val hasAutomaticPps: Boolean + get() = hasFeature(FEATURE_AUTOMATIC_PPS) - fun checkTransportProtocol() { - val hasT1Protocol = dwProtocols and MASK_T1_PROTO != 0 - val hasT0Protocol = dwProtocols and MASK_T0_PROTO != 0 - android.util.Log.d("CcidDescription", "hasT1Protocol = $hasT1Protocol, hasT0Protocol = $hasT0Protocol") - } + val hasT0Protocol: Boolean + get() = (dwProtocols and MASK_T0_PROTO) != 0 } \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt new file mode 100644 index 0000000..ac2e1dc --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidTransceiver.kt @@ -0,0 +1,348 @@ +package im.angry.openeuicc.core.usb + +import android.hardware.usb.UsbDeviceConnection +import android.hardware.usb.UsbEndpoint +import android.os.SystemClock +import android.util.Log +import im.angry.openeuicc.util.* +import java.nio.ByteBuffer +import java.nio.ByteOrder + + +/** + * Provides raw, APDU-agnostic transmission to the CCID reader + * Adapted from + */ +class UsbCcidTransceiver( + private val usbConnection: UsbDeviceConnection, + private val usbBulkIn: UsbEndpoint, + private val usbBulkOut: UsbEndpoint, + private val usbCcidDescription: UsbCcidDescription +) { + companion object { + private const val TAG = "UsbCcidTransceiver" + + private const val CCID_HEADER_LENGTH = 10 + + private const val MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK = 0x80 + private const val MESSAGE_TYPE_PC_TO_RDR_ICC_POWER_ON = 0x62 + private const val MESSAGE_TYPE_PC_TO_RDR_ICC_POWER_OFF = 0x63 + private const val MESSAGE_TYPE_PC_TO_RDR_XFR_BLOCK = 0x6f + + private const val COMMAND_STATUS_SUCCESS: Byte = 0 + private const val COMMAND_STATUS_TIME_EXTENSION_RQUESTED: Byte = 2 + + /** + * Level Parameter: APDU is a single command. + * + * "the command APDU begins and ends with this command" + * -- DWG Smart-Card USB Integrated Circuit(s) Card Devices rev 1.0 + * § 6.1.1.3 + */ + const val LEVEL_PARAM_START_SINGLE_CMD_APDU: Short = 0x0000 + + /** + * Level Parameter: First APDU in a multi-command APDU. + * + * "the command APDU begins with this command, and continue in the + * next PC_to_RDR_XfrBlock" + * -- DWG Smart-Card USB Integrated Circuit(s) Card Devices rev 1.0 + * § 6.1.1.3 + */ + const val LEVEL_PARAM_START_MULTI_CMD_APDU: Short = 0x0001 + + /** + * Level Parameter: Final APDU in a multi-command APDU. + * + * "this abData field continues a command APDU and ends the command APDU" + * -- DWG Smart-Card USB Integrated Circuit(s) Card Devices rev 1.0 + * § 6.1.1.3 + */ + const val LEVEL_PARAM_END_MULTI_CMD_APDU: Short = 0x0002 + + /** + * Level Parameter: Next command in a multi-command APDU. + * + * "the abData field continues a command APDU and another block is to follow" + * -- DWG Smart-Card USB Integrated Circuit(s) Card Devices rev 1.0 + * § 6.1.1.3 + */ + const val LEVEL_PARAM_CONTINUE_MULTI_CMD_APDU: Short = 0x0003 + + /** + * Level Parameter: Request the device continue sending APDU. + * + * "empty abData field, continuation of response APDU is expected in the next + * RDR_to_PC_DataBlock" + * -- DWG Smart-Card USB Integrated Circuit(s) Card Devices rev 1.0 + * § 6.1.1.3 + */ + const val LEVEL_PARAM_CONTINUE_RESPONSE: Short = 0x0010 + + private const val SLOT_NUMBER = 0x00 + + private const val ICC_STATUS_SUCCESS: Byte = 0 + + private const val DEVICE_COMMUNICATE_TIMEOUT_MILLIS = 5000 + private const val DEVICE_SKIP_TIMEOUT_MILLIS = 100 + } + + data class UsbCcidErrorException(val msg: String, val errorResponse: CcidDataBlock) : + Exception(msg) + + data class CcidDataBlock( + val dwLength: Int, + val bSlot: Byte, + val bSeq: Byte, + val bStatus: Byte, + val bError: Byte, + val bChainParameter: Byte, + val data: ByteArray? + ) { + companion object { + fun parseHeaderFromBytes(headerBytes: ByteArray): CcidDataBlock { + val buf = ByteBuffer.wrap(headerBytes) + buf.order(ByteOrder.LITTLE_ENDIAN) + + val type = buf.get() + require(type == MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK.toByte()) { "Header has incorrect type value!" } + val dwLength = buf.int + val bSlot = buf.get() + val bSeq = buf.get() + val bStatus = buf.get() + val bError = buf.get() + val bChainParameter = buf.get() + + return CcidDataBlock(dwLength, bSlot, bSeq, bStatus, bError, bChainParameter, null) + } + } + + fun withData(d: ByteArray): CcidDataBlock { + require(data == null) { "Cannot add data twice" } + return CcidDataBlock(dwLength, bSlot, bSeq, bStatus, bError, bChainParameter, d) + } + + val iccStatus: Byte + get() = (bStatus.toInt() and 0x03).toByte() + + val commandStatus: Byte + get() = ((bStatus.toInt() shr 6) and 0x03).toByte() + + val isStatusTimeoutExtensionRequest: Boolean + get() = commandStatus == COMMAND_STATUS_TIME_EXTENSION_RQUESTED + + val isStatusSuccess: Boolean + get() = iccStatus == ICC_STATUS_SUCCESS && commandStatus == COMMAND_STATUS_SUCCESS + } + + val hasAutomaticPps = usbCcidDescription.hasAutomaticPps + + private val inputBuffer = ByteArray(usbBulkIn.maxPacketSize) + + private var currentSequenceNumber: Byte = 0 + + private fun sendRaw(data: ByteArray, offset: Int, length: Int) { + val tr1 = usbConnection.bulkTransfer( + usbBulkOut, data, offset, length, DEVICE_COMMUNICATE_TIMEOUT_MILLIS + ) + if (tr1 != length) { + throw UsbTransportException( + "USB error - failed to transmit data ($tr1/$length)" + ) + } + } + + private fun receiveDataBlock(expectedSequenceNumber: Byte): CcidDataBlock? { + var response: CcidDataBlock? + do { + response = receiveDataBlockImmediate(expectedSequenceNumber) + } while (response!!.isStatusTimeoutExtensionRequest) + if (!response.isStatusSuccess) { + throw UsbCcidErrorException("USB-CCID error!", response) + } + return response + } + + private fun receiveDataBlockImmediate(expectedSequenceNumber: Byte): CcidDataBlock? { + /* + * Some USB CCID devices (notably NitroKey 3) may time-out and need a subsequent poke to + * carry on communications. No particular reason why the number 3 was chosen. If we get a + * zero-sized reply (or a time-out), we try again. Clamped retries prevent an infinite loop + * if things really turn sour. + */ + var attempts = 3 + Log.d(TAG, "Receive data block immediate seq=$expectedSequenceNumber") + var readBytes: Int + do { + readBytes = usbConnection.bulkTransfer( + usbBulkIn, inputBuffer, inputBuffer.size, DEVICE_COMMUNICATE_TIMEOUT_MILLIS + ) + Log.d(TAG, "Received " + readBytes + " bytes: " + inputBuffer.encodeHex()) + } while (readBytes <= 0 && attempts-- > 0) + if (readBytes < CCID_HEADER_LENGTH) { + throw UsbTransportException("USB-CCID error - failed to receive CCID header") + } + if (inputBuffer[0] != MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK.toByte()) { + if (expectedSequenceNumber != inputBuffer[6]) { + throw UsbTransportException( + ((("USB-CCID error - bad CCID header, type " + inputBuffer[0]) + " (expected " + + MESSAGE_TYPE_RDR_TO_PC_DATA_BLOCK) + "), sequence number " + inputBuffer[6] + ) + " (expected " + + expectedSequenceNumber + ")" + ) + } + throw UsbTransportException( + "USB-CCID error - bad CCID header type " + inputBuffer[0] + ) + } + var result = CcidDataBlock.parseHeaderFromBytes(inputBuffer) + if (expectedSequenceNumber != result.bSeq) { + throw UsbTransportException( + ("USB-CCID error - expected sequence number " + + expectedSequenceNumber + ", got " + result) + ) + } + + val dataBuffer = ByteArray(result.dwLength) + var bufferedBytes = readBytes - CCID_HEADER_LENGTH + System.arraycopy(inputBuffer, CCID_HEADER_LENGTH, dataBuffer, 0, bufferedBytes) + while (bufferedBytes < dataBuffer.size) { + readBytes = usbConnection.bulkTransfer( + usbBulkIn, inputBuffer, inputBuffer.size, DEVICE_COMMUNICATE_TIMEOUT_MILLIS + ) + if (readBytes < 0) { + throw UsbTransportException( + "USB error - failed reading response data! Header: $result" + ) + } + System.arraycopy(inputBuffer, 0, dataBuffer, bufferedBytes, readBytes) + bufferedBytes += readBytes + } + result = result.withData(dataBuffer) + return result + } + + + private fun skipAvailableInput() { + var ignoredBytes: Int + do { + ignoredBytes = usbConnection.bulkTransfer( + usbBulkIn, inputBuffer, inputBuffer.size, DEVICE_SKIP_TIMEOUT_MILLIS + ) + if (ignoredBytes > 0) { + Log.e(TAG, "Skipped $ignoredBytes bytes") + } + } while (ignoredBytes > 0) + } + + /** + * Transmits XfrBlock + * 6.1.4 PC_to_RDR_XfrBlock + * + * @param payload payload to transmit + */ + fun sendXfrBlock(payload: ByteArray): CcidDataBlock? { + return sendXfrBlock(payload, LEVEL_PARAM_START_SINGLE_CMD_APDU) + } + + /** + * Receives a continued XfrBlock. Should be called when a multiblock response is indicated + * 6.1.4 PC_to_RDR_XfrBlock + */ + fun receiveContinuedResponse(): CcidDataBlock? { + return sendXfrBlock(ByteArray(0), LEVEL_PARAM_CONTINUE_RESPONSE) + } + + /** + * Transmits XfrBlock + * 6.1.4 PC_to_RDR_XfrBlock + * + * @param payload payload to transmit + * @param levelParam Level parameter + */ + private fun sendXfrBlock(payload: ByteArray, levelParam: Short): CcidDataBlock? { + val startTime = SystemClock.elapsedRealtime() + val l = payload.size + val sequenceNumber: Byte = currentSequenceNumber++ + val headerData = byteArrayOf( + MESSAGE_TYPE_PC_TO_RDR_XFR_BLOCK.toByte(), + l.toByte(), + (l shr 8).toByte(), + (l shr 16).toByte(), + (l shr 24).toByte(), + SLOT_NUMBER.toByte(), + sequenceNumber, + 0x00.toByte(), + (levelParam.toInt() and 0x00ff).toByte(), + (levelParam.toInt() shr 8).toByte() + ) + val data: ByteArray = headerData + payload + var sentBytes = 0 + while (sentBytes < data.size) { + val bytesToSend = Math.min(usbBulkOut.maxPacketSize, data.size - sentBytes) + sendRaw(data, sentBytes, bytesToSend) + sentBytes += bytesToSend + } + val ccidDataBlock = receiveDataBlock(sequenceNumber) + val elapsedTime = SystemClock.elapsedRealtime() - startTime + Log.d(TAG, "USB XferBlock call took " + elapsedTime + "ms") + return ccidDataBlock + } + + fun iccPowerOn(): CcidDataBlock { + val startTime = SystemClock.elapsedRealtime() + skipAvailableInput() + var response: CcidDataBlock? = null + for (v in usbCcidDescription.voltages) { + Log.v(TAG, "CCID: attempting to power on with voltage $v") + response = try { + iccPowerOnVoltage(v.powerOnValue) + } catch (e: UsbCcidErrorException) { + if (e.errorResponse.bError.toInt() == 7) { // Power select error + Log.v(TAG, "CCID: failed to power on with voltage $v") + iccPowerOff() + Log.v(TAG, "CCID: powered off") + continue + } + throw e + } + break + } + if (response == null) { + throw UsbTransportException("Couldn't power up ICC2") + } + val elapsedTime = SystemClock.elapsedRealtime() - startTime + Log.d( + TAG, + "Usb transport connected, took " + elapsedTime + "ms, ATR=" + + response.data?.encodeHex() + ) + return response + } + + private fun iccPowerOnVoltage(voltage: Byte): CcidDataBlock? { + val sequenceNumber = currentSequenceNumber++ + val iccPowerCommand = byteArrayOf( + MESSAGE_TYPE_PC_TO_RDR_ICC_POWER_ON.toByte(), + 0x00, 0x00, 0x00, 0x00, + SLOT_NUMBER.toByte(), + sequenceNumber, + voltage, + 0x00, 0x00 // reserved for future use + ) + sendRaw(iccPowerCommand, 0, iccPowerCommand.size) + return receiveDataBlock(sequenceNumber) + } + + private fun iccPowerOff() { + val sequenceNumber = currentSequenceNumber++ + val iccPowerCommand = byteArrayOf( + MESSAGE_TYPE_PC_TO_RDR_ICC_POWER_OFF.toByte(), + 0x00, 0x00, 0x00, 0x00, + 0x00, + sequenceNumber, + 0x00 + ) + sendRaw(iccPowerCommand, 0, iccPowerCommand.size) + } +} \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt index f4e9a87..edca7a0 100644 --- a/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt +++ b/app-common/src/main/java/im/angry/openeuicc/core/usb/UsbCcidUtils.kt @@ -6,6 +6,8 @@ import android.hardware.usb.UsbDevice import android.hardware.usb.UsbEndpoint import android.hardware.usb.UsbInterface +class UsbTransportException(msg: String) : Exception(msg) + fun UsbInterface.getIoEndpoints(): Pair { var bulkIn: UsbEndpoint? = null var bulkOut: UsbEndpoint? = null diff --git a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt index 3c30bce..ae7294a 100644 --- a/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt +++ b/app/src/main/java/im/angry/openeuicc/util/PrivilegedTelephonyUtils.kt @@ -74,11 +74,12 @@ fun SubscriptionManager.tryRefreshCachedEuiccInfo(cardId: Int) { } // Every EuiccChannel we use here should be backed by a RealUiccPortInfoCompat +// except when it is from a USB card reader val EuiccChannel.removable - get() = (port as RealUiccPortInfoCompat).card.isRemovable + get() = (port as? RealUiccPortInfoCompat)?.card?.isRemovable ?: true val EuiccChannel.cardId - get() = (port as RealUiccPortInfoCompat).card.cardId + get() = (port as? RealUiccPortInfoCompat)?.card?.cardId ?: -1 val EuiccChannel.isMEP - get() = (port as RealUiccPortInfoCompat).card.isMultipleEnabledProfilesSupported \ No newline at end of file + get() = (port as? RealUiccPortInfoCompat)?.card?.isMultipleEnabledProfilesSupported ?: false \ No newline at end of file From 87fc1cd2f87dc7fb9b6c2119b261870031f30790 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 30 Jun 2024 16:55:55 -0400 Subject: [PATCH 36/81] NotificationsActivity: Prevent simulatenous handleNotification + refresh --- .../java/im/angry/openeuicc/ui/NotificationsActivity.kt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt index 744a87d..9758d18 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/NotificationsActivity.kt @@ -180,8 +180,9 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker { withContext(Dispatchers.IO) { euiccChannel.lpa.handleNotification(notification.inner.seqNumber) } + + refresh() } - refresh() true } R.id.notification_delete -> { @@ -189,8 +190,9 @@ class NotificationsActivity: BaseEuiccAccessActivity(), OpenEuiccContextMarker { withContext(Dispatchers.IO) { euiccChannel.lpa.deleteNotification(notification.inner.seqNumber) } + + refresh() } - refresh() true } else -> false From ccf21675d64bd989e853b6e2fd7db6e5a572cf9c Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 30 Jun 2024 17:06:58 -0400 Subject: [PATCH 37/81] [3/n] Handle USB permission responses properly --- app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt index 485d87f..4641732 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt @@ -52,7 +52,7 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { private val usbPermissionReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == ACTION_USB_PERMISSION) { - if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { + if (usbDevice != null && usbManager.hasPermission(usbDevice)) { lifecycleScope.launch(Dispatchers.Main) { switchToUsbFragmentIfPossible() } From 70f20f9de83a29eb5d2d305920aad1c6e43e528c Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 30 Jun 2024 20:08:01 -0400 Subject: [PATCH 38/81] OpenEUICC is now GPLv3 only We have included code originating from OpenKeychains. Our current downstreams should all be okay with GPLv3. If not, contact me and we might be able to figure something out (e.g. isolating GPLv3 code) --- LICENSE | 833 ++++++++++++++++++++++++++++++++++++++---------------- README.md | 2 +- 2 files changed, 585 insertions(+), 250 deletions(-) diff --git a/LICENSE b/LICENSE index d159169..f288702 100644 --- a/LICENSE +++ b/LICENSE @@ -1,281 +1,622 @@ GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + TERMS AND CONDITIONS - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". + 0. Definitions. -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. + "This License" refers to version 3 of the GNU General Public License. - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. + A "covered work" means either the unmodified Program or a work based +on the Program. - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. + 1. Source Code. -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. + The Corresponding Source for a work in source code form is that +same work. -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. + 2. Basic Permissions. - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. + 13. Use with the GNU Affero General Public License. -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. + 14. Revised Versions of this License. - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. - NO WARRANTY + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. + 15. Disclaimer of Warranty. - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS @@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -303,37 +644,31 @@ the "copyright" line and a pointer to where the full notice is found. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index a90df38..7ec6c7b 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ Copyright 2022-2024 OpenEUICC contributors This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License -as published by the Free Software Foundation, version 2. +as published by the Free Software Foundation, version 3. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of From 3960a2d9d8578223eab0469ff6b449a6a0039104 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Sun, 30 Jun 2024 20:20:32 -0400 Subject: [PATCH 39/81] ui: Add progress spinner when MainActivity is loading --- .../im/angry/openeuicc/ui/MainActivity.kt | 28 +++++++++++++++---- .../src/main/res/layout/activity_main.xml | 10 +++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt index 4641732..274a8ec 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt @@ -17,6 +17,7 @@ import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter +import android.widget.ProgressBar import android.widget.Spinner import androidx.lifecycle.lifecycleScope import im.angry.openeuicc.common.R @@ -35,6 +36,17 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { private lateinit var spinnerAdapter: ArrayAdapter private lateinit var spinnerItem: MenuItem private lateinit var spinner: Spinner + private lateinit var loadingProgress: ProgressBar + + var loading: Boolean + get() = loadingProgress.visibility == View.VISIBLE + set(value) { + loadingProgress.visibility = if (value) { + View.VISIBLE + } else { + View.GONE + } + } private val fragments = arrayListOf() @@ -66,11 +78,7 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(requireViewById(R.id.toolbar)) - - supportFragmentManager.beginTransaction().replace( - R.id.fragment_root, - appContainer.uiComponentFactory.createNoEuiccPlaceholderFragment() - ).commit() + loadingProgress = requireViewById(R.id.loading) tm = telephonyManager @@ -143,6 +151,8 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } private suspend fun init() { + loading = true + val knownChannels = withContext(Dispatchers.IO) { euiccChannelManager.enumerateEuiccChannels().onEach { Log.d(TAG, "slot ${it.slotId} port ${it.portId}") @@ -161,6 +171,8 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } withContext(Dispatchers.Main) { + loading = false + knownChannels.sortedBy { it.logicalSlotId }.forEach { channel -> spinnerAdapter.add(getString(R.string.channel_name_format, channel.logicalSlotId)) fragments.add(appContainer.uiComponentFactory.createEuiccManagementFragment(channel)) @@ -175,6 +187,12 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { spinnerItem.isVisible = true } supportFragmentManager.beginTransaction().replace(R.id.fragment_root, fragments.first()).commit() + } else { + // TODO: Handle cases where there is _only_ a USB reader + supportFragmentManager.beginTransaction().replace( + R.id.fragment_root, + appContainer.uiComponentFactory.createNoEuiccPlaceholderFragment() + ).commit() } } } diff --git a/app-common/src/main/res/layout/activity_main.xml b/app-common/src/main/res/layout/activity_main.xml index 4f1020d..89b9d7e 100644 --- a/app-common/src/main/res/layout/activity_main.xml +++ b/app-common/src/main/res/layout/activity_main.xml @@ -14,6 +14,16 @@ app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintWidth_percent="1" /> + + Date: Sun, 30 Jun 2024 21:00:30 -0400 Subject: [PATCH 40/81] ui: Decouple USB-specific logic from MainActivity into a dedicated fragment --- .../im/angry/openeuicc/ui/MainActivity.kt | 87 ++-------- .../openeuicc/ui/UsbCcidReaderFragment.kt | 159 ++++++++++++++++++ .../res/layout/fragment_usb_ccid_reader.xml | 37 ++++ app-common/src/main/res/values/strings.xml | 4 + 4 files changed, 211 insertions(+), 76 deletions(-) create mode 100644 app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt create mode 100644 app-common/src/main/res/layout/fragment_usb_ccid_reader.xml diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt index 274a8ec..f8a1915 100644 --- a/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt +++ b/app-common/src/main/java/im/angry/openeuicc/ui/MainActivity.kt @@ -1,14 +1,7 @@ package im.angry.openeuicc.ui import android.annotation.SuppressLint -import android.app.PendingIntent -import android.content.BroadcastReceiver -import android.content.Context import android.content.Intent -import android.content.IntentFilter -import android.hardware.usb.UsbDevice -import android.hardware.usb.UsbManager -import android.os.Build import android.os.Bundle import android.telephony.TelephonyManager import android.util.Log @@ -19,9 +12,9 @@ import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ProgressBar import android.widget.Spinner +import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import im.angry.openeuicc.common.R -import im.angry.openeuicc.core.EuiccChannel import im.angry.openeuicc.util.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -30,7 +23,6 @@ import kotlinx.coroutines.withContext open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { companion object { const val TAG = "MainActivity" - const val ACTION_USB_PERMISSION = "im.angry.openeuicc.USB_PERMISSION" } private lateinit var spinnerAdapter: ArrayAdapter @@ -48,31 +40,10 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } } - private val fragments = arrayListOf() + private val fragments = arrayListOf() protected lateinit var tm: TelephonyManager - private val usbManager: UsbManager by lazy { - getSystemService(USB_SERVICE) as UsbManager - } - - private var usbDevice: UsbDevice? = null - private var usbChannel: EuiccChannel? = null - - private lateinit var usbPendingIntent: PendingIntent - - private val usbPermissionReceiver = object : BroadcastReceiver() { - override fun onReceive(context: Context?, intent: Intent?) { - if (intent?.action == ACTION_USB_PERMISSION) { - if (usbDevice != null && usbManager.hasPermission(usbDevice)) { - lifecycleScope.launch(Dispatchers.Main) { - switchToUsbFragmentIfPossible() - } - } - } - } - } - @SuppressLint("WrongConstant", "UnspecifiedRegisterReceiverFlag") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -83,15 +54,6 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { tm = telephonyManager spinnerAdapter = ArrayAdapter(this, R.layout.spinner_item) - - usbPendingIntent = PendingIntent.getBroadcast(this, 0, - Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE) - val filter = IntentFilter(ACTION_USB_PERMISSION) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - registerReceiver(usbPermissionReceiver, filter, Context.RECEIVER_EXPORTED) - } else { - registerReceiver(usbPermissionReceiver, filter) - } } override fun onCreateOptionsMenu(menu: Menu): Boolean { @@ -114,11 +76,6 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { if (position < fragments.size) { supportFragmentManager.beginTransaction() .replace(R.id.fragment_root, fragments[position]).commit() - } else if (position == fragments.size) { - // If we are at the last position, this is the USB device - lifecycleScope.launch(Dispatchers.Main) { - switchToUsbFragmentIfPossible() - } } } @@ -164,10 +121,8 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } } - withContext(Dispatchers.IO) { - val res = euiccChannelManager.enumerateUsbEuiccChannel() - usbDevice = res.first - usbChannel = res.second + val (usbDevice, _) = withContext(Dispatchers.IO) { + euiccChannelManager.enumerateUsbEuiccChannel() } withContext(Dispatchers.Main) { @@ -179,16 +134,19 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } // If USB readers exist, add them at the very last - // The adapter logic depends on this assumption - usbDevice?.let { spinnerAdapter.add(it.productName) } + // We use a wrapper fragment to handle logic specific to USB readers + usbDevice?.let { + spinnerAdapter.add(it.productName) + fragments.add(UsbCcidReaderFragment()) + } if (fragments.isNotEmpty()) { if (this@MainActivity::spinner.isInitialized) { spinnerItem.isVisible = true } - supportFragmentManager.beginTransaction().replace(R.id.fragment_root, fragments.first()).commit() + supportFragmentManager.beginTransaction() + .replace(R.id.fragment_root, fragments.first()).commit() } else { - // TODO: Handle cases where there is _only_ a USB reader supportFragmentManager.beginTransaction().replace( R.id.fragment_root, appContainer.uiComponentFactory.createNoEuiccPlaceholderFragment() @@ -196,27 +154,4 @@ open class MainActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { } } } - - private suspend fun switchToUsbFragmentIfPossible() { - if (usbDevice != null && usbChannel == null) { - if (!usbManager.hasPermission(usbDevice)) { - usbManager.requestPermission(usbDevice, usbPendingIntent) - return - } else { - val (device, channel) = withContext(Dispatchers.IO) { - euiccChannelManager.enumerateUsbEuiccChannel() - } - - if (device != null && channel != null) { - usbDevice = device - usbChannel = channel - } - } - } - - if (usbChannel != null) { - supportFragmentManager.beginTransaction().replace(R.id.fragment_root, - appContainer.uiComponentFactory.createEuiccManagementFragment(usbChannel!!)).commit() - } - } } \ No newline at end of file diff --git a/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt b/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt new file mode 100644 index 0000000..4660d97 --- /dev/null +++ b/app-common/src/main/java/im/angry/openeuicc/ui/UsbCcidReaderFragment.kt @@ -0,0 +1,159 @@ +package im.angry.openeuicc.ui + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbManager +import android.os.Build +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import android.widget.TextView +import androidx.fragment.app.Fragment +import androidx.fragment.app.commit +import androidx.lifecycle.lifecycleScope +import im.angry.openeuicc.common.R +import im.angry.openeuicc.core.EuiccChannel +import im.angry.openeuicc.core.EuiccChannelManager +import im.angry.openeuicc.util.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * A wrapper fragment over EuiccManagementFragment where we handle + * logic specific to USB devices. This is mainly USB permission + * requests, and the fact that USB devices may or may not be + * available by the time the user selects it from MainActivity. + * + * Having this fragment allows MainActivity to be (mostly) agnostic + * of the underlying implementation of different types of channels. + * When permission is granted, this fragment will simply load + * EuiccManagementFragment using its own childFragmentManager. + * + * Note that for now we assume there will only be one USB card reader + * device. This is also an implicit assumption in EuiccChannelManager. + */ +class UsbCcidReaderFragment : Fragment(), OpenEuiccContextMarker { + companion object { + const val ACTION_USB_PERMISSION = "im.angry.openeuicc.USB_PERMISSION" + } + + private val euiccChannelManager: EuiccChannelManager by lazy { + (requireActivity() as MainActivity).euiccChannelManager + } + + private val usbManager: UsbManager by lazy { + requireContext().getSystemService(Context.USB_SERVICE) as UsbManager + } + + private val usbPermissionReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action == ACTION_USB_PERMISSION) { + if (usbDevice != null && usbManager.hasPermission(usbDevice)) { + lifecycleScope.launch(Dispatchers.Main) { + tryLoadUsbChannel() + } + } + } + } + } + + private lateinit var usbPendingIntent: PendingIntent + + private lateinit var text: TextView + private lateinit var permissionButton: Button + + private var usbDevice: UsbDevice? = null + private var usbChannel: EuiccChannel? = null + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + val view = inflater.inflate(R.layout.fragment_usb_ccid_reader, container, false) + + text = view.requireViewById(R.id.usb_reader_text) + permissionButton = view.requireViewById(R.id.usb_grant_permission) + + permissionButton.setOnClickListener { + usbManager.requestPermission(usbDevice, usbPendingIntent) + } + + return view + } + + @SuppressLint("UnspecifiedRegisterReceiverFlag", "WrongConstant") + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + usbPendingIntent = PendingIntent.getBroadcast( + requireContext(), 0, + Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE + ) + val filter = IntentFilter(ACTION_USB_PERMISSION) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + requireContext().registerReceiver( + usbPermissionReceiver, + filter, + Context.RECEIVER_EXPORTED + ) + } else { + requireContext().registerReceiver(usbPermissionReceiver, filter) + } + + lifecycleScope.launch(Dispatchers.Main) { + tryLoadUsbChannel() + } + } + + override fun onDetach() { + super.onDetach() + requireContext().unregisterReceiver(usbPermissionReceiver) + } + + override fun onDestroy() { + super.onDestroy() + requireContext().unregisterReceiver(usbPermissionReceiver) + } + + private suspend fun tryLoadUsbChannel() { + text.visibility = View.GONE + permissionButton.visibility = View.GONE + + (requireActivity() as MainActivity).loading = true + + val (device, channel) = withContext(Dispatchers.IO) { + euiccChannelManager.enumerateUsbEuiccChannel() + } + + (requireActivity() as MainActivity).loading = false + + usbDevice = device + usbChannel = channel + + if (device != null && channel == null && !usbManager.hasPermission(device)) { + text.text = getString(R.string.usb_permission_needed) + text.visibility = View.VISIBLE + permissionButton.visibility = View.VISIBLE + } else if (device != null && channel != null) { + childFragmentManager.commit { + replace( + R.id.child_container, + appContainer.uiComponentFactory.createEuiccManagementFragment(channel) + ) + } + } else { + text.text = getString(R.string.usb_failed) + text.visibility = View.VISIBLE + permissionButton.visibility = View.GONE + } + } +} \ No newline at end of file diff --git a/app-common/src/main/res/layout/fragment_usb_ccid_reader.xml b/app-common/src/main/res/layout/fragment_usb_ccid_reader.xml new file mode 100644 index 0000000..1207990 --- /dev/null +++ b/app-common/src/main/res/layout/fragment_usb_ccid_reader.xml @@ -0,0 +1,37 @@ + + + + + +