Compare commits

...
Sign in to create a new pull request.

25 commits

Author SHA1 Message Date
21c04ed179 Allow Actions to build from any branch 2025-06-17 07:57:19 -04:00
db4645b17f feat: sas accreditation number format check (#193)
Reviewed-on: PeterCxy/OpenEUICC#193
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-06-16 03:54:32 +02:00
149a19ca1c fix: build warning (#194)
Reviewed-on: PeterCxy/OpenEUICC#194
Co-authored-by: xqdoo00o <xqdoo00o@gmail.com>
Co-committed-by: xqdoo00o <xqdoo00o@gmail.com>
2025-06-16 03:54:02 +02:00
eaef00b88a Fixup README 2025-05-18 11:17:43 -04:00
023f6ded28 Update README.md to add a comparison matrix for Easy/OpenEUICC 2025-05-04 21:10:57 -04:00
a601ab7d72 fix: send euicc memory reset notification (#189)
```console
$ ./lpac profile list | jq
{
  "type": "lpa",
  "payload": {
    "code": 0,
    "message": "success",
    "data": [
      {
        "iccid": "8944476500001320600",
        "isdpAid": "a0000005591010ffffffff8900001100",
        "profileState": "enabled",
        "profileNickname": null,
        "serviceProviderName": "BetterRoaming",
        "profileName": "BetterRoaming",
        "iconType": null,
        "icon": null,
        "profileClass": "operational"
      },
      {
        "iccid": "89861234567891232113",
        "isdpAid": "a0000005591010ffffffff8900001200",
        "profileState": "disabled",
        "profileNickname": null,
        "serviceProviderName": "rspmanager_tester2",
        "profileName": "20230625_yysx",
        "iconType": null,
        "icon": null,
        "profileClass": "operational"
      }
    ]
  }
}
$ ./lpac notification list | jq
{
  "type": "lpa",
  "payload": {
    "code": 0,
    "message": "success",
    "data": [
      {
        "seqNumber": 48,
        "profileManagementOperation": "install",
        "notificationAddress": "smdp.io",
        "iccid": "8944476500001320600"
      },
      {
        "seqNumber": 49,
        "profileManagementOperation": "enable",
        "notificationAddress": "rsp.truphone.com",
        "iccid": "8944476500001320600"
      },
      {
        "seqNumber": 50,
        "profileManagementOperation": "install",
        "notificationAddress": "secsmsminiapp.eastcompeace.com",
        "iccid": "89861234567891232113"
      },
      {
        "seqNumber": 51,
        "profileManagementOperation": "install",
        "notificationAddress": "secsmsminiapp.eastcompeace.com",
        "iccid": "89861234567891232113"
      }
    ]
  }
}
$ ./lpac chip purge yes
{"type":"lpa","payload":{"code":0,"message":"success","data":null}}
$ ./lpac notification list | jq
{
  "type": "lpa",
  "payload": {
    "code": 0,
    "message": "success",
    "data": [
      {
        "seqNumber": 48,
        "profileManagementOperation": "install",
        "notificationAddress": "smdp.io",
        "iccid": "8944476500001320600"
      },
      {
        "seqNumber": 49,
        "profileManagementOperation": "enable",
        "notificationAddress": "rsp.truphone.com",
        "iccid": "8944476500001320600"
      },
      {
        "seqNumber": 50,
        "profileManagementOperation": "install",
        "notificationAddress": "secsmsminiapp.eastcompeace.com",
        "iccid": "89861234567891232113"
      },
      {
        "seqNumber": 51,
        "profileManagementOperation": "install",
        "notificationAddress": "secsmsminiapp.eastcompeace.com",
        "iccid": "89861234567891232113"
      },
      {
        "seqNumber": 52,
        "profileManagementOperation": "delete",
        "notificationAddress": "rsp.truphone.com",
        "iccid": "8944476500001320600"
      },
      {
        "seqNumber": 53,
        "profileManagementOperation": "delete",
        "notificationAddress": "secsmsminiapp.eastcompeace.com",
        "iccid": "89861234567891232113"
      }
    ]
  }
}
```

Reviewed-on: PeterCxy/OpenEUICC#189
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-14 03:36:38 +02:00
756c621d5e fix: stricted sm-dp+ address checking (#190)
Reviewed-on: PeterCxy/OpenEUICC#190
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-14 03:36:14 +02:00
68114fa863 Expose the current ISD-R AID in use 2025-04-05 20:50:10 -04:00
1fda120459 Avoid reconnecting to USB iface repeatedly while trying different AIDs 2025-04-05 20:44:15 -04:00
994324acb6 Fix up back button for IsdrAidListActivity 2025-04-05 17:58:56 -04:00
6c774450ec fix: usb isd-r aid fallback (#188)
Reviewed-on: PeterCxy/OpenEUICC#188
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-01 23:13:57 +02:00
00ddf09287 fix: improve lpa string parsing (#181)
Reviewed-on: PeterCxy/OpenEUICC#181
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-01 03:19:21 +02:00
3662f93760 fix: send terminal capabilities (#187)
fix 9eSIM v1 (G+D) on USB

Reviewed-on: PeterCxy/OpenEUICC#187
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-01 03:18:45 +02:00
05abed117a fix: click sn copy (#186)
Reviewed-on: PeterCxy/OpenEUICC#186
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-01 03:18:22 +02:00
92fbfc5229 chore: add more isd-r aids (#184)
Reviewed-on: PeterCxy/OpenEUICC#184
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-04-01 03:18:02 +02:00
d7bfd84de9 CompatibilityCheck: use the shared default AID constant 2025-03-23 11:00:28 -04:00
c6963feb17 feat: Customizable ISD-R AID list
This is stored base64-encoded in shared preferences (to avoid XML
encoding issues).

By default we have the standard AID plus the 5ber one. We may add more
going forward.
2025-03-23 10:35:07 -04:00
dc6b3a4810 feat: support disabling refresh after switch in settings
peter: Reworked strings and i18 translations. Also removed the ad-hoc
function in favor of a lambda.
2025-03-16 21:04:28 -04:00
e08f8beb45 feat: add iQOO stk launch support (#179)
![image](/attachments/b2aac119-c488-41e6-a39f-eab8559cd63b)

Reviewed-on: PeterCxy/OpenEUICC#179
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-03-17 00:01:22 +01:00
6b169c505d fix: crash (priv) (#177)
resolves #178

```
1741836445.585 10331 13748 13748 E AndroidRuntime: FATAL EXCEPTION: main
1741836445.585 10331 13748 13748 E AndroidRuntime: Process: im.angry.openeuicc, PID: 13748
1741836445.585 10331 13748 13748 E AndroidRuntime: java.lang.RuntimeException: PrivilegedEuiccContextMarker shall only be used on Fragments or UI types that derive from Context
1741836445.585 10331 13748 13748 E AndroidRuntime: 	at im.angry.openeuicc.util.PrivilegedEuiccContextMarker$DefaultImpls.getPrivilegedEuiccMarkerContext(PrivilegedUtils.kt:18)
```

Reviewed-on: PeterCxy/OpenEUICC#177
Co-authored-by: septs <github@septs.pw>
Co-committed-by: septs <github@septs.pw>
2025-03-17 00:01:06 +01:00
33d383a3ce ui: wizard: Keep screen on during the download process 2025-03-16 17:54:54 -04:00
291869207a We don't need a public wake lock 2025-03-16 17:35:46 -04:00
a6286ed097 feat: Acquire partial wake lock for all foreground tasks
All of our foreground tasks require the CPU to be at least awake to make
any progress. We could keep the screen on but we really only need the
partial wake lock to make sure progress is made.
2025-03-16 17:32:09 -04:00
360760b78f chore: Upgrade Android Studio and Gradle 2025-03-15 15:39:04 -04:00
b9849afe18 fix: Address multiple substitutions in string format error (#175)
Reviewed-on: PeterCxy/OpenEUICC#175
Co-authored-by: LuK1337 <priv.luk@gmail.com>
Co-committed-by: LuK1337 <priv.luk@gmail.com>
2025-03-12 01:00:10 +01:00
42 changed files with 830 additions and 313 deletions

View file

@ -1,7 +1,7 @@
on: on:
push: push:
branches: branches:
- 'master' - '*'
jobs: jobs:
build-debug: build-debug:

View file

@ -1,5 +1,8 @@
<component name="ProjectCodeStyleConfiguration"> <component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173"> <code_scheme name="Project" version="173">
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="XML"> <codeStyleSettings language="XML">
<option name="FORCE_REARRANGE_MODE" value="1" /> <option name="FORCE_REARRANGE_MODE" value="1" />
<indentOptions> <indentOptions>
@ -113,5 +116,8 @@
</rules> </rules>
</arrangement> </arrangement>
</codeStyleSettings> </codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</codeStyleSettings>
</code_scheme> </code_scheme>
</component> </component>

View file

@ -1,5 +1,6 @@
<component name="ProjectCodeStyleConfiguration"> <component name="ProjectCodeStyleConfiguration">
<state> <state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" /> <option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state> </state>
</component> </component>

View file

@ -8,6 +8,30 @@
<SelectionState runConfigName="app"> <SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" /> <option name="selectionMode" value="DROPDOWN" />
</SelectionState> </SelectionState>
<SelectionState runConfigName="app-unpriv.androidTest">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="app-unpriv.main">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="app-unpriv.unitTest">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="app.unitTest">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="app.androidTest">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="app.main">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="workspace.OpenEUICC.app-unpriv">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
<SelectionState runConfigName="workspace.OpenEUICC.app">
<option name="selectionMode" value="DROPDOWN" />
</SelectionState>
</selectionStates> </selectionStates>
</component> </component>
</project> </project>

2
.idea/kotlinc.xml generated
View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="KotlinJpsPluginSettings"> <component name="KotlinJpsPluginSettings">
<option name="version" value="1.9.20" /> <option name="version" value="1.9.24" />
</component> </component>
</project> </project>

View file

@ -2,18 +2,22 @@
A fully free and open-source Local Profile Assistant implementation for Android devices. A fully free and open-source Local Profile Assistant implementation for Android devices.
There are two variants of this project: There are two variants of this project, OpenEUICC and EasyEUICC:
- OpenEUICC: The full-fledged privileged variant. | | OpenEUICC | EasyEUICC |
- Due to its privilege requirement, OpenEUICC must be placed inside `/system/priv-app` and be signed with the platform certificate. |:------------------------------|:-----------------------------------------------:|:-----------------:|
- The preferred way to including OpenEUICC in a system image is to [build it along with AOSP](#building-aosp). | Privileged | Must be installed as system app | No |
- __Note__: When privileged, OpenEUICC supports any eUICC chip that implements the SGP.22 standard, internal or external. However, there is __no guarantee__ that external (removable) eSIMs actually follow the standard. Please __DO NOT__ submit bug reports for non-functioning removable eSIMs. They are __NOT__ officially supported unless they also support / are supported by EasyEUICC, the unprivileged variant. | Internal eSIM | Supported | Unsupported |
- EasyEUICC: Unprivileged version that can run as a user app. | External (Removable) eSIM | Supported | Supported |
- This version supports two modes of operation: | USB Readers | Supported | Supported |
1. Inserted, removable eSIMs: Due to obvious security requirements, EasyEUICC is only able to access eSIM chips whose [ARF/ARA](https://source.android.com/docs/core/connect/uicc#arf) contains the hash of EasyEUICC's signing certificate. | Requires allowlisting by eSIM | No | Yes -- except USB |
2. USB CCID Card Readers: Only `T=0` readers that use the standard [USB CCID protocol](https://en.wikipedia.org/wiki/CCID_(protocol)) are supported. In this mode, EasyEUICC can access any eSIM chip loaded in the card reader regardless of their ARF/ARA, as long as they implement the [SGP.22 standard](https://www.gsma.com/solutions-and-impact/technologies/esim/wp-content/uploads/2021/07/SGP.22-v2.3.pdf). | System Integration | Partial (carrier partner API unimplemented yet) | No |
- Prebuilt release-mode EasyEUICC apks can be downloaded [here](https://gitea.angry.im/PeterCxy/OpenEUICC/releases)
- For removable eSIM chip vendors: to have your chip supported by official builds of EasyEUICC when inserted, include the ARA-M hash `2A2FA878BC7C3354C2CF82935A5945A3EDAE4AFA` Some side notes:
1. When privileged, OpenEUICC supports any eUICC chip that implements the SGP.22 standard, internal or external. However, there is __no guarantee__ that external (removable) eSIMs actually follow the standard. Please __DO NOT__ submit bug reports for non-functioning removable eSIMs. They are __NOT__ officially supported unless they also support / are supported by EasyEUICC, the unprivileged variant.
2. Both variants support accessing eUICC chips through USB CCID readers, regardless of whether the chip contains the correct ARA-M hash to allow for unprivileged access. However, only `T=0` readers that use the standard [USB CCID protocol](https://en.wikipedia.org/wiki/CCID_(protocol)) are supported.
3. Prebuilt release-mode EasyEUICC apks can be downloaded [here](https://gitea.angry.im/PeterCxy/OpenEUICC/releases). For OpenEUICC, no official release is currently provided and only debug mode APKs can be found in the CI page.
4. For removable eSIM chip vendors: to have your chip supported by official builds of EasyEUICC when inserted, include the ARA-M hash `2A2FA878BC7C3354C2CF82935A5945A3EDAE4AFA`.
__This project is Free Software licensed under GNU GPL v3, WITHOUT the "or later" clause.__ Any modification and derivative work __MUST__ be released under the SAME license, which means, at the very least, that the source code __MUST__ be available upon request. __This project is Free Software licensed under GNU GPL v3, WITHOUT the "or later" clause.__ Any modification and derivative work __MUST__ be released under the SAME license, which means, at the very least, that the source code __MUST__ be available upon request.

View file

@ -7,6 +7,7 @@
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application <application
android:enableOnBackInvokedCallback="true" android:enableOnBackInvokedCallback="true"
@ -27,6 +28,10 @@
android:name="im.angry.openeuicc.ui.LogsActivity" android:name="im.angry.openeuicc.ui.LogsActivity"
android:label="@string/pref_advanced_logs" /> android:label="@string/pref_advanced_logs" />
<activity
android:name="im.angry.openeuicc.ui.IsdrAidListActivity"
android:label="@string/isdr_aid_list" />
<activity <activity
android:exported="true" android:exported="true"
android:name="im.angry.openeuicc.ui.wizard.DownloadWizardActivity" android:name="im.angry.openeuicc.ui.wizard.DownloadWizardActivity"

View file

@ -1,39 +1,40 @@
package im.angry.openeuicc.core package im.angry.openeuicc.core
import android.content.Context 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.se.omapi.SEService
import android.util.Log import android.util.Log
import im.angry.openeuicc.common.R import im.angry.openeuicc.common.R
import im.angry.openeuicc.core.usb.UsbApduInterface import im.angry.openeuicc.core.usb.UsbApduInterface
import im.angry.openeuicc.core.usb.bulkPair import im.angry.openeuicc.core.usb.UsbCcidContext
import im.angry.openeuicc.core.usb.endpoints
import im.angry.openeuicc.util.* import im.angry.openeuicc.util.*
import java.lang.IllegalArgumentException import java.lang.IllegalArgumentException
open class DefaultEuiccChannelFactory(protected val context: Context) : EuiccChannelFactory { open class DefaultEuiccChannelFactory(protected val context: Context) : EuiccChannelFactory {
private var seService: SEService? = null private var seService: SEService? = null
private val usbManager by lazy {
context.getSystemService(Context.USB_SERVICE) as UsbManager
}
private suspend fun ensureSEService() { private suspend fun ensureSEService() {
if (seService == null || !seService!!.isConnected) { if (seService == null || !seService!!.isConnected) {
seService = connectSEService(context) seService = connectSEService(context)
} }
} }
override suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? { override suspend fun tryOpenEuiccChannel(
port: UiccPortInfoCompat,
isdrAid: ByteArray
): EuiccChannel? {
if (port.portIndex != 0) { if (port.portIndex != 0) {
Log.w(DefaultEuiccChannelManager.TAG, "OMAPI channel attempted on non-zero portId, this may or may not work.") Log.w(
DefaultEuiccChannelManager.TAG,
"OMAPI channel attempted on non-zero portId, this may or may not work."
)
} }
ensureSEService() ensureSEService()
Log.i(DefaultEuiccChannelManager.TAG, "Trying OMAPI for physical slot ${port.card.physicalSlotIndex}") Log.i(
DefaultEuiccChannelManager.TAG,
"Trying OMAPI for physical slot ${port.card.physicalSlotIndex}"
)
try { try {
return EuiccChannelImpl( return EuiccChannelImpl(
context.getString(R.string.omapi), context.getString(R.string.omapi),
@ -44,41 +45,48 @@ open class DefaultEuiccChannelFactory(protected val context: Context) : EuiccCha
port, port,
context.preferenceRepository.verboseLoggingFlow context.preferenceRepository.verboseLoggingFlow
), ),
isdrAid,
context.preferenceRepository.verboseLoggingFlow, context.preferenceRepository.verboseLoggingFlow,
context.preferenceRepository.ignoreTLSCertificateFlow, context.preferenceRepository.ignoreTLSCertificateFlow,
).also { ).also {
Log.i(DefaultEuiccChannelManager.TAG, "Is OMAPI channel, setting MSS to 60") Log.i(DefaultEuiccChannelManager.TAG, "Is OMAPI channel, setting MSS to 60")
it.lpa.setEs10xMss(60) it.lpa.setEs10xMss(60)
} }
} catch (e: IllegalArgumentException) { } catch (_: IllegalArgumentException) {
// Failed // Failed
Log.w( Log.w(
DefaultEuiccChannelManager.TAG, DefaultEuiccChannelManager.TAG,
"OMAPI APDU interface unavailable for physical slot ${port.card.physicalSlotIndex}." "OMAPI APDU interface unavailable for physical slot ${port.card.physicalSlotIndex} with ISD-R AID: ${isdrAid.encodeHex()}."
) )
} }
return null return null
} }
override fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel? { override fun tryOpenUsbEuiccChannel(
val (bulkIn, bulkOut) = usbInterface.endpoints.bulkPair ccidCtx: UsbCcidContext,
if (bulkIn == null || bulkOut == null) return null isdrAid: ByteArray
val conn = usbManager.openDevice(usbDevice) ?: return null ): EuiccChannel? {
if (!conn.claimInterface(usbInterface, true)) return null try {
return EuiccChannelImpl( return EuiccChannelImpl(
context.getString(R.string.usb), context.getString(R.string.usb),
FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(EuiccChannelManager.USB_CHANNEL_ID)), FakeUiccPortInfoCompat(FakeUiccCardInfoCompat(EuiccChannelManager.USB_CHANNEL_ID)),
intrinsicChannelName = usbDevice.productName, intrinsicChannelName = ccidCtx.productName,
UsbApduInterface( UsbApduInterface(
conn, ccidCtx
bulkIn,
bulkOut,
context.preferenceRepository.verboseLoggingFlow
), ),
isdrAid,
context.preferenceRepository.verboseLoggingFlow, context.preferenceRepository.verboseLoggingFlow,
context.preferenceRepository.ignoreTLSCertificateFlow, context.preferenceRepository.ignoreTLSCertificateFlow,
) )
} catch (_: IllegalArgumentException) {
// Failed
Log.w(
DefaultEuiccChannelManager.TAG,
"USB APDU interface unavailable for ISD-R AID: ${isdrAid.encodeHex()}."
)
}
return null
} }
override fun cleanup() { override fun cleanup() {

View file

@ -5,6 +5,7 @@ import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager import android.hardware.usb.UsbManager
import android.telephony.SubscriptionManager import android.telephony.SubscriptionManager
import android.util.Log import android.util.Log
import im.angry.openeuicc.core.usb.UsbCcidContext
import im.angry.openeuicc.core.usb.smartCard import im.angry.openeuicc.core.usb.smartCard
import im.angry.openeuicc.core.usb.interfaces import im.angry.openeuicc.core.usb.interfaces
import im.angry.openeuicc.di.AppContainer import im.angry.openeuicc.di.AppContainer
@ -12,6 +13,7 @@ import im.angry.openeuicc.util.*
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.merge
@ -49,6 +51,24 @@ open class DefaultEuiccChannelManager(
protected open val uiccCards: Collection<UiccCardInfoCompat> protected open val uiccCards: Collection<UiccCardInfoCompat>
get() = (0..<tm.activeModemCountCompat).map { FakeUiccCardInfoCompat(it) } get() = (0..<tm.activeModemCountCompat).map { FakeUiccCardInfoCompat(it) }
private suspend inline fun tryOpenChannelFirstValidAid(openFn: (ByteArray) -> EuiccChannel?): EuiccChannel? {
val isdrAidList =
parseIsdrAidList(appContainer.preferenceRepository.isdrAidListFlow.first())
return isdrAidList.firstNotNullOfOrNull {
Log.i(TAG, "Opening channel, trying ISDR AID ${it.encodeHex()}")
openFn(it)?.let { channel ->
if (channel.valid) {
channel
} else {
channel.close()
null
}
}
}
}
private suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? { private suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? {
lock.withLock { lock.withLock {
if (port.card.physicalSlotIndex == EuiccChannelManager.USB_CHANNEL_ID) { if (port.card.physicalSlotIndex == EuiccChannelManager.USB_CHANNEL_ID) {
@ -76,9 +96,10 @@ open class DefaultEuiccChannelManager(
return null return null
} }
val channel = euiccChannelFactory.tryOpenEuiccChannel(port) ?: return null val channel =
tryOpenChannelFirstValidAid { euiccChannelFactory.tryOpenEuiccChannel(port, it) }
if (channel.valid) { if (channel != null) {
channelCache.add(channel) channelCache.add(channel)
return channel return channel
} else { } else {
@ -86,7 +107,6 @@ open class DefaultEuiccChannelManager(
TAG, 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." "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 return null
} }
} }
@ -212,7 +232,10 @@ open class DefaultEuiccChannelManager(
check(channel.valid) { "Invalid channel" } check(channel.valid) { "Invalid channel" }
break break
} catch (e: Exception) { } catch (e: Exception) {
Log.d(TAG, "Slot $physicalSlotId port $portId reconnect failure, retrying in 1000 ms") Log.d(
TAG,
"Slot $physicalSlotId port $portId reconnect failure, retrying in 1000 ms"
)
} }
delay(1000) delay(1000)
} }
@ -249,10 +272,19 @@ open class DefaultEuiccChannelManager(
// If we don't have permission, tell UI code that we found a candidate device, but we // 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 // need permission to be able to do anything with it
if (!usbManager.hasPermission(device)) return@withContext Pair(device, false) if (!usbManager.hasPermission(device)) return@withContext Pair(device, false)
Log.i(TAG, "Found CCID interface on ${device.deviceId}:${device.vendorId}, and has permission; trying to open channel") Log.i(
TAG,
"Found CCID interface on ${device.deviceId}:${device.vendorId}, and has permission; trying to open channel"
)
val ccidCtx = UsbCcidContext.createFromUsbDevice(context, device, iface) ?: return@forEach
try { try {
val channel = euiccChannelFactory.tryOpenUsbEuiccChannel(device, iface) val channel = tryOpenChannelFirstValidAid {
euiccChannelFactory.tryOpenUsbEuiccChannel(ccidCtx, it)
}
if (channel != null && channel.lpa.valid) { if (channel != null && channel.lpa.valid) {
ccidCtx.allowDisconnect = true
usbChannel = channel usbChannel = channel
return@withContext Pair(device, true) return@withContext Pair(device, true)
} }
@ -260,7 +292,14 @@ open class DefaultEuiccChannelManager(
// Ignored -- skip forward // Ignored -- skip forward
e.printStackTrace() e.printStackTrace()
} }
Log.i(TAG, "No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}")
ccidCtx.allowDisconnect = true
ccidCtx.disconnect()
Log.i(
TAG,
"No valid eUICC channel found on USB device ${device.deviceId}:${device.vendorId}"
)
} }
return@withContext Pair(null, false) return@withContext Pair(null, false)
} }

View file

@ -34,5 +34,10 @@ interface EuiccChannel {
*/ */
val apduInterface: ApduInterface val apduInterface: ApduInterface
/**
* The AID of the ISD-R channel currently in use
*/
val isdrAid: ByteArray
fun close() fun close()
} }

View file

@ -1,15 +1,17 @@
package im.angry.openeuicc.core package im.angry.openeuicc.core
import android.hardware.usb.UsbDevice import im.angry.openeuicc.core.usb.UsbCcidContext
import android.hardware.usb.UsbInterface
import im.angry.openeuicc.util.* import im.angry.openeuicc.util.*
// This class is here instead of inside DI because it contains a bit more logic than just // This class is here instead of inside DI because it contains a bit more logic than just
// "dumb" dependency injection. // "dumb" dependency injection.
interface EuiccChannelFactory { interface EuiccChannelFactory {
suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat, isdrAid: ByteArray): EuiccChannel?
fun tryOpenUsbEuiccChannel(usbDevice: UsbDevice, usbInterface: UsbInterface): EuiccChannel? fun tryOpenUsbEuiccChannel(
ccidCtx: UsbCcidContext,
isdrAid: ByteArray
): EuiccChannel?
/** /**
* Release all resources used by this EuiccChannelFactory * Release all resources used by this EuiccChannelFactory

View file

@ -13,21 +13,17 @@ class EuiccChannelImpl(
override val port: UiccPortInfoCompat, override val port: UiccPortInfoCompat,
override val intrinsicChannelName: String?, override val intrinsicChannelName: String?,
override val apduInterface: ApduInterface, override val apduInterface: ApduInterface,
override val isdrAid: ByteArray,
verboseLoggingFlow: Flow<Boolean>, verboseLoggingFlow: Flow<Boolean>,
ignoreTLSCertificateFlow: Flow<Boolean> ignoreTLSCertificateFlow: Flow<Boolean>
) : EuiccChannel { ) : EuiccChannel {
companion object {
// TODO: This needs to go somewhere else.
val ISDR_AID = "A0000005591010FFFFFFFF8900000100".decodeHex()
}
override val slotId = port.card.physicalSlotIndex override val slotId = port.card.physicalSlotIndex
override val logicalSlotId = port.logicalSlotIndex override val logicalSlotId = port.logicalSlotIndex
override val portId = port.portIndex override val portId = port.portIndex
override val lpa: LocalProfileAssistant = override val lpa: LocalProfileAssistant =
LocalProfileAssistantImpl( LocalProfileAssistantImpl(
ISDR_AID, isdrAid,
apduInterface, apduInterface,
HttpInterfaceImpl(verboseLoggingFlow, ignoreTLSCertificateFlow) HttpInterfaceImpl(verboseLoggingFlow, ignoreTLSCertificateFlow)
) )

View file

@ -38,6 +38,8 @@ class EuiccChannelWrapper(orig: EuiccChannel) : EuiccChannel {
get() = channel.apduInterface get() = channel.apduInterface
override val atr: ByteArray? override val atr: ByteArray?
get() = channel.atr get() = channel.atr
override val isdrAid: ByteArray
get() = channel.isdrAid
override fun close() = channel.close() override fun close() = channel.close()

View file

@ -1,27 +1,19 @@
package im.angry.openeuicc.core.usb package im.angry.openeuicc.core.usb
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.util.Log import android.util.Log
import im.angry.openeuicc.core.ApduInterfaceAtrProvider import im.angry.openeuicc.core.ApduInterfaceAtrProvider
import im.angry.openeuicc.util.* import im.angry.openeuicc.util.*
import kotlinx.coroutines.flow.Flow
import net.typeblog.lpac_jni.ApduInterface import net.typeblog.lpac_jni.ApduInterface
class UsbApduInterface( class UsbApduInterface(
private val conn: UsbDeviceConnection, private val ccidCtx: UsbCcidContext
private val bulkIn: UsbEndpoint,
private val bulkOut: UsbEndpoint,
private val verboseLoggingFlow: Flow<Boolean>
) : ApduInterface, ApduInterfaceAtrProvider { ) : ApduInterface, ApduInterfaceAtrProvider {
companion object { companion object {
private const val TAG = "UsbApduInterface" private const val TAG = "UsbApduInterface"
} }
private lateinit var ccidDescription: UsbCcidDescription override val atr: ByteArray?
private lateinit var transceiver: UsbCcidTransceiver get() = ccidCtx.atr
override var atr: ByteArray? = null
override val valid: Boolean override val valid: Boolean
get() = channels.isNotEmpty() get() = channels.isNotEmpty()
@ -29,29 +21,19 @@ class UsbApduInterface(
private var channels = mutableSetOf<Int>() private var channels = mutableSetOf<Int>()
override fun connect() { override fun connect() {
ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!! ccidCtx.connect()
if (!ccidDescription.hasT0Protocol) { // Send Terminal Capabilities
throw IllegalArgumentException("Unsupported card reader; T=0 support is required") // Specs: ETSI TS 102 221 v15.0.0 - 11.1.19 TERMINAL CAPABILITY
val terminalCapabilities = buildCmd(
0x80.toByte(), 0xaa.toByte(), 0x00, 0x00,
"A9088100820101830107".decodeHex(),
le = null,
)
transmitApduByChannel(terminalCapabilities, 0)
} }
transceiver = UsbCcidTransceiver(conn, bulkIn, bulkOut, ccidDescription, verboseLoggingFlow) override fun disconnect() = ccidCtx.disconnect()
try {
// 6.1.1.1 PC_to_RDR_IccPowerOn (Page 20 of 40)
// https://www.usb.org/sites/default/files/DWG_Smart-Card_USB-ICC_ICCD_rev10.pdf
atr = transceiver.iccPowerOn().data
} catch (e: Exception) {
e.printStackTrace()
throw e
}
}
override fun disconnect() {
conn.close()
atr = null
}
override fun logicalChannelOpen(aid: ByteArray): Int { override fun logicalChannelOpen(aid: ByteArray): Int {
// OPEN LOGICAL CHANNEL // OPEN LOGICAL CHANNEL
@ -140,7 +122,7 @@ class UsbApduInterface(
// OR the channel mask into the CLA byte // OR the channel mask into the CLA byte
realTx[0] = ((realTx[0].toInt() and 0xFC) or channel.toInt()).toByte() realTx[0] = ((realTx[0].toInt() and 0xFC) or channel.toInt()).toByte()
var resp = transceiver.sendXfrBlock(realTx).data!! var resp = ccidCtx.transceiver.sendXfrBlock(realTx).data!!
if (resp.size < 2) throw RuntimeException("APDU response smaller than 2 (sw1 + sw2)!") if (resp.size < 2) throw RuntimeException("APDU response smaller than 2 (sw1 + sw2)!")
@ -151,7 +133,7 @@ class UsbApduInterface(
// 0x6C = wrong le // 0x6C = wrong le
// so we fix the le field here // so we fix the le field here
realTx[realTx.size - 1] = resp[resp.size - 1] realTx[realTx.size - 1] = resp[resp.size - 1]
resp = transceiver.sendXfrBlock(realTx).data!! resp = ccidCtx.transceiver.sendXfrBlock(realTx).data!!
} else if (sw1 == 0x61) { } else if (sw1 == 0x61) {
// 0x61 = X bytes available // 0x61 = X bytes available
// continue reading by GET RESPONSE // continue reading by GET RESPONSE
@ -161,7 +143,7 @@ class UsbApduInterface(
realTx[0], 0xC0.toByte(), 0x00, 0x00, sw2.toByte() realTx[0], 0xC0.toByte(), 0x00, 0x00, sw2.toByte()
) )
val tmp = transceiver.sendXfrBlock(getResponseCmd).data!! val tmp = ccidCtx.transceiver.sendXfrBlock(getResponseCmd).data!!
resp = resp.sliceArray(0 until (resp.size - 2)) + tmp resp = resp.sliceArray(0 until (resp.size - 2)) + tmp

View file

@ -0,0 +1,87 @@
package im.angry.openeuicc.core.usb
import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbEndpoint
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import im.angry.openeuicc.util.preferenceRepository
import kotlinx.coroutines.flow.Flow
/**
* A wrapper over an usb device + interface, manages the lifecycle independent
* of the APDU interface exposed to lpac-jni.
*
* This allows us to try multiple AIDs on each interface without opening / closing
* the USB connection numerous times.
*/
class UsbCcidContext private constructor(
private val conn: UsbDeviceConnection,
private val bulkIn: UsbEndpoint,
private val bulkOut: UsbEndpoint,
val productName: String,
val verboseLoggingFlow: Flow<Boolean>
) {
companion object {
fun createFromUsbDevice(
context: Context,
usbDevice: UsbDevice,
usbInterface: UsbInterface
): UsbCcidContext? = runCatching {
val (bulkIn, bulkOut) = usbInterface.endpoints.bulkPair
if (bulkIn == null || bulkOut == null) return@runCatching null
val conn = context.getSystemService(UsbManager::class.java).openDevice(usbDevice)
?: return@runCatching null
if (!conn.claimInterface(usbInterface, true)) return@runCatching null
UsbCcidContext(
conn,
bulkIn,
bulkOut,
usbDevice.productName ?: "USB",
context.preferenceRepository.verboseLoggingFlow
)
}.getOrNull()
}
/**
* When set to false (the default), the disconnect() method does nothing.
* This allows the separation of device disconnection from lpac-jni's APDU interface.
*/
var allowDisconnect = false
private var initialized = false
lateinit var transceiver: UsbCcidTransceiver
var atr: ByteArray? = null
fun connect() {
if (initialized) {
return
}
val ccidDescription = UsbCcidDescription.fromRawDescriptors(conn.rawDescriptors)!!
if (!ccidDescription.hasT0Protocol) {
throw IllegalArgumentException("Unsupported card reader; T=0 support is required")
}
transceiver = UsbCcidTransceiver(conn, bulkIn, bulkOut, ccidDescription, verboseLoggingFlow)
try {
// 6.1.1.1 PC_to_RDR_IccPowerOn (Page 20 of 40)
// https://www.usb.org/sites/default/files/DWG_Smart-Card_USB-ICC_ICCD_rev10.pdf
atr = transceiver.iccPowerOn().data
} catch (e: Exception) {
e.printStackTrace()
throw e
}
initialized = true
}
fun disconnect() {
if (initialized && allowDisconnect) {
conn.close()
atr = null
}
}
}

View file

@ -4,6 +4,7 @@ import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Binder import android.os.Binder
import android.os.IBinder import android.os.IBinder
import android.os.PowerManager
import android.util.Log import android.util.Log
import androidx.core.app.NotificationChannelCompat import androidx.core.app.NotificationChannelCompat
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
@ -91,6 +92,12 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
} }
val euiccChannelManager: EuiccChannelManager by euiccChannelManagerDelegate val euiccChannelManager: EuiccChannelManager by euiccChannelManagerDelegate
private val wakeLock: PowerManager.WakeLock by lazy {
(getSystemService(POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this::class.simpleName)
}
}
/** /**
* The state of a "foreground" task (named so due to the need to startForeground()) * The state of a "foreground" task (named so due to the need to startForeground())
*/ */
@ -275,6 +282,8 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
updateForegroundNotification(title, iconRes) updateForegroundNotification(title, iconRes)
wakeLock.acquire(10 * 60 * 1000L /*10 minutes*/)
try { try {
withContext(Dispatchers.IO + NonCancellable) { // Any LPA-related task must always complete withContext(Dispatchers.IO + NonCancellable) { // Any LPA-related task must always complete
this@EuiccChannelManagerService.task() this@EuiccChannelManagerService.task()
@ -290,6 +299,7 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
postForegroundTaskFailureNotification(failureTitle) postForegroundTaskFailureNotification(failureTitle)
} }
} finally { } finally {
wakeLock.release()
if (isActive) { if (isActive) {
stopSelf() stopSelf()
} }
@ -446,30 +456,34 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
iccid: String, iccid: String,
enable: Boolean, // Enable or disable the profile indicated in iccid enable: Boolean, // Enable or disable the profile indicated in iccid
reconnectTimeoutMillis: Long = 0 // 0 = do not wait for reconnect reconnectTimeoutMillis: Long = 0 // 0 = do not wait for reconnect
): ForegroundTaskSubscriberFlow = ) =
launchForegroundTask( launchForegroundTask(
getString(R.string.task_profile_switch), getString(R.string.task_profile_switch),
getString(R.string.task_profile_switch_failure), getString(R.string.task_profile_switch_failure),
R.drawable.ic_task_switch R.drawable.ic_task_switch
) { ) {
euiccChannelManager.beginTrackedOperation(slotId, portId) { euiccChannelManager.beginTrackedOperation(slotId, portId) {
val (res, refreshed) = euiccChannelManager.withEuiccChannel( val (response, refreshed) =
slotId, euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
portId val refresh = preferenceRepository.refreshAfterSwitchFlow.first()
) { channel -> val response = channel.lpa.switchProfile(iccid, enable, refresh)
if (!channel.lpa.switchProfile(iccid, enable, refresh = true)) { if (response || !refresh) {
Pair(response, refresh)
} else {
// refresh failed, but refresh was requested
// Sometimes, we *can* enable or disable the profile, but we cannot // Sometimes, we *can* enable or disable the profile, but we cannot
// send the refresh command to the modem because the profile somehow // send the refresh command to the modem because the profile somehow
// makes the modem "busy". In this case, we can still switch by setting // 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 // refresh to false, but then the switch cannot take effect until the
// user resets the modem manually by toggling airplane mode or rebooting. // user resets the modem manually by toggling airplane mode or rebooting.
Pair(channel.lpa.switchProfile(iccid, enable, refresh = false), false) Pair(
} else { channel.lpa.switchProfile(iccid, enable, refresh = false),
Pair(true, true) false
)
} }
} }
if (!res) { if (!response) {
throw RuntimeException("Could not switch profile") throw RuntimeException("Could not switch profile")
} }
@ -502,8 +516,12 @@ class EuiccChannelManagerService : LifecycleService(), OpenEuiccContextMarker {
getString(R.string.task_euicc_memory_reset_failure), getString(R.string.task_euicc_memory_reset_failure),
R.drawable.ic_euicc_memory_reset R.drawable.ic_euicc_memory_reset
) { ) {
euiccChannelManager.beginTrackedOperation(slotId, portId) {
euiccChannelManager.withEuiccChannel(slotId, portId) { channel -> euiccChannelManager.withEuiccChannel(slotId, portId) { channel ->
channel.lpa.euiccMemoryReset() channel.lpa.euiccMemoryReset()
} }
preferenceRepository.notificationDeleteFlow.first()
}
} }
} }

View file

@ -27,6 +27,13 @@ import kotlinx.coroutines.launch
import net.typeblog.lpac_jni.impl.PKID_GSMA_LIVE_CI import net.typeblog.lpac_jni.impl.PKID_GSMA_LIVE_CI
import net.typeblog.lpac_jni.impl.PKID_GSMA_TEST_CI import net.typeblog.lpac_jni.impl.PKID_GSMA_TEST_CI
// https://euicc-manual.osmocom.org/docs/pki/eum/accredited.json
// ref: <https://regex101.com/r/5FFz8u>
private val RE_SAS = Regex(
"""^[A-Z]{2}-[A-Z]{2}(?:-UP)?-\d{4}T?(?:-\d+)?T?$""",
setOf(RegexOption.IGNORE_CASE),
)
class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker { class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
companion object { companion object {
private val YES_NO = Pair(R.string.yes, R.string.no) private val YES_NO = Pair(R.string.yes, R.string.no)
@ -102,19 +109,21 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
add(Item(R.string.euicc_info_access_mode, channel.type)) add(Item(R.string.euicc_info_access_mode, channel.type))
add(Item(R.string.euicc_info_removable, formatByBoolean(channel.port.card.isRemovable, YES_NO))) add(Item(R.string.euicc_info_removable, formatByBoolean(channel.port.card.isRemovable, YES_NO)))
add(Item(R.string.euicc_info_eid, channel.lpa.eID, copiedToastResId = R.string.toast_eid_copied)) add(Item(R.string.euicc_info_eid, channel.lpa.eID, copiedToastResId = R.string.toast_eid_copied))
add(Item(R.string.euicc_info_isdr_aid, channel.isdrAid.encodeHex()))
channel.tryParseEuiccVendorInfo()?.let { vendorInfo -> channel.tryParseEuiccVendorInfo()?.let { vendorInfo ->
vendorInfo.skuName?.let { add(Item(R.string.euicc_info_sku, it)) } vendorInfo.skuName?.let { add(Item(R.string.euicc_info_sku, it)) }
vendorInfo.serialNumber?.let { add(Item(R.string.euicc_info_sn, it)) } vendorInfo.serialNumber?.let { add(Item(R.string.euicc_info_sn, it, copiedToastResId = R.string.toast_sn_copied)) }
vendorInfo.firmwareVersion?.let { add(Item(R.string.euicc_info_fw_ver, it)) } vendorInfo.firmwareVersion?.let { add(Item(R.string.euicc_info_fw_ver, it)) }
vendorInfo.bootloaderVersion?.let { add(Item(R.string.euicc_info_bl_ver, it)) } vendorInfo.bootloaderVersion?.let { add(Item(R.string.euicc_info_bl_ver, it)) }
} }
channel.lpa.euiccInfo2.let { info -> channel.lpa.euiccInfo2?.let { info ->
add(Item(R.string.euicc_info_sgp22_version, info?.sgp22Version.toString())) add(Item(R.string.euicc_info_sgp22_version, info.sgp22Version.toString()))
add(Item(R.string.euicc_info_firmware_version, info?.euiccFirmwareVersion.toString())) add(Item(R.string.euicc_info_firmware_version, info.euiccFirmwareVersion.toString()))
add(Item(R.string.euicc_info_globalplatform_version, info?.globalPlatformVersion.toString())) add(Item(R.string.euicc_info_globalplatform_version, info.globalPlatformVersion.toString()))
add(Item(R.string.euicc_info_pp_version, info?.ppVersion.toString())) add(Item(R.string.euicc_info_pp_version, info.ppVersion.toString()))
add(Item(R.string.euicc_info_sas_accreditation_number, info?.sasAccreditationNumber)) info.sasAccreditationNumber.trim().takeIf(RE_SAS::matches)
add(Item(R.string.euicc_info_free_nvram, info?.freeNvram?.let(::formatFreeSpace))) ?.let { add(Item(R.string.euicc_info_sas_accreditation_number, it.uppercase())) }
add(Item(R.string.euicc_info_free_nvram, info.freeNvram.let(::formatFreeSpace)))
} }
channel.lpa.euiccInfo2?.euiccCiPKIdListForSigning.orEmpty().let { signers -> channel.lpa.euiccInfo2?.euiccCiPKIdListForSigning.orEmpty().let { signers ->
// SGP.28 v1.0, eSIM CI Registration Criteria (Page 5 of 9, 2019-10-24) // SGP.28 v1.0, eSIM CI Registration Criteria (Page 5 of 9, 2019-10-24)
@ -133,14 +142,9 @@ class EuiccInfoActivity : BaseEuiccAccessActivity(), OpenEuiccContextMarker {
add(Item(R.string.euicc_info_atr, atr, copiedToastResId = R.string.toast_atr_copied)) add(Item(R.string.euicc_info_atr, atr, copiedToastResId = R.string.toast_atr_copied))
} }
@Suppress("SameParameterValue")
private fun formatByBoolean(b: Boolean, res: Pair<Int, Int>): String = private fun formatByBoolean(b: Boolean, res: Pair<Int, Int>): String =
getString( getString(if (b) res.first else res.second)
if (b) {
res.first
} else {
res.second
}
)
inner class EuiccInfoViewHolder(root: View) : ViewHolder(root) { inner class EuiccInfoViewHolder(root: View) : ViewHolder(root) {
private val title: TextView = root.requireViewById(R.id.euicc_info_title) private val title: TextView = root.requireViewById(R.id.euicc_info_title)

View file

@ -0,0 +1,72 @@
package im.angry.openeuicc.ui
import android.os.Bundle
import android.text.Editable
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import im.angry.openeuicc.common.R
import im.angry.openeuicc.util.preferenceRepository
import im.angry.openeuicc.util.setupToolbarInsets
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
class IsdrAidListActivity : AppCompatActivity() {
private lateinit var isdrAidListEditor: EditText
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_isdr_aid_list)
setSupportActionBar(requireViewById(R.id.toolbar))
setupToolbarInsets()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
isdrAidListEditor = requireViewById(R.id.isdr_aid_list_editor)
lifecycleScope.launch {
preferenceRepository.isdrAidListFlow.onEach {
isdrAidListEditor.text = Editable.Factory.getInstance().newEditable(it)
}.collect()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.activity_isdr_aid_list, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.save -> {
lifecycleScope.launch {
preferenceRepository.isdrAidListFlow.updatePreference(isdrAidListEditor.text.toString())
Toast.makeText(
this@IsdrAidListActivity,
R.string.isdr_aid_list_saved,
Toast.LENGTH_SHORT
).show()
}
true
}
R.id.reset -> {
lifecycleScope.launch {
preferenceRepository.isdrAidListFlow.removePreference()
}
true
}
android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}

View file

@ -78,8 +78,15 @@ open class SettingsFragment: PreferenceFragmentCompat() {
requirePreference<CheckBoxPreference>("pref_developer_ignore_tls_certificate") requirePreference<CheckBoxPreference>("pref_developer_ignore_tls_certificate")
.bindBooleanFlow(preferenceRepository.ignoreTLSCertificateFlow) .bindBooleanFlow(preferenceRepository.ignoreTLSCertificateFlow)
requirePreference<CheckBoxPreference>("pref_developer_refresh_after_switch")
.bindBooleanFlow(preferenceRepository.refreshAfterSwitchFlow)
requirePreference<CheckBoxPreference>("pref_developer_euicc_memory_reset") requirePreference<CheckBoxPreference>("pref_developer_euicc_memory_reset")
.bindBooleanFlow(preferenceRepository.euiccMemoryResetFlow) .bindBooleanFlow(preferenceRepository.euiccMemoryResetFlow)
requirePreference<Preference>("pref_developer_isdr_aid_list").apply {
intent = Intent(requireContext(), IsdrAidListActivity::class.java)
}
} }
protected fun <T : Preference> requirePreference(key: CharSequence) = protected fun <T : Preference> requirePreference(key: CharSequence) =

View file

@ -3,6 +3,7 @@ package im.angry.openeuicc.ui.wizard
import android.app.assist.AssistContent import android.app.assist.AssistContent
import android.os.Bundle import android.os.Bundle
import android.view.View import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager
import android.widget.Button import android.widget.Button
import android.widget.ProgressBar import android.widget.ProgressBar
@ -251,6 +252,14 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
supportFragmentManager.beginTransaction().setCustomAnimations(enterAnim, exitAnim) supportFragmentManager.beginTransaction().setCustomAnimations(enterAnim, exitAnim)
.replace(R.id.step_fragment_container, nextFrag) .replace(R.id.step_fragment_container, nextFrag)
.commit() .commit()
// Sync screen on state
if (nextFrag.keepScreenOn) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
refreshButtons() refreshButtons()
} }
@ -280,6 +289,8 @@ class DownloadWizardActivity: BaseEuiccAccessActivity() {
protected val state: DownloadWizardState protected val state: DownloadWizardState
get() = (requireActivity() as DownloadWizardActivity).state get() = (requireActivity() as DownloadWizardActivity).state
open val keepScreenOn = false
abstract val hasNext: Boolean abstract val hasNext: Boolean
abstract val hasPrev: Boolean abstract val hasPrev: Boolean
abstract fun createNextFragment(): DownloadWizardStepFragment? abstract fun createNextFragment(): DownloadWizardStepFragment?

View file

@ -1,11 +1,9 @@
package im.angry.openeuicc.ui.wizard package im.angry.openeuicc.ui.wizard
import android.os.Bundle import android.os.Bundle
import android.util.Patterns
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.Toast
import androidx.core.widget.addTextChangedListener import androidx.core.widget.addTextChangedListener
import com.google.android.material.textfield.TextInputLayout import com.google.android.material.textfield.TextInputLayout
import im.angry.openeuicc.common.R import im.angry.openeuicc.common.R
@ -86,10 +84,34 @@ class DownloadWizardDetailsFragment : DownloadWizardActivity.DownloadWizardStepF
} }
private fun updateInputCompleteness() { private fun updateInputCompleteness() {
inputComplete = Patterns.DOMAIN_NAME.matcher(smdp.editText!!.text).matches() inputComplete = isValidAddress(smdp.editText!!.text)
if (state.confirmationCodeRequired) { if (state.confirmationCodeRequired) {
inputComplete = inputComplete && confirmationCode.editText!!.text.isNotEmpty() inputComplete = inputComplete && confirmationCode.editText!!.text.isNotEmpty()
} }
refreshButtons() refreshButtons()
} }
} }
private fun isValidAddress(input: CharSequence): Boolean {
if (!input.contains('.')) return false
var fqdn = input
var port = 443
if (input.contains(':')) {
val portIndex = input.lastIndexOf(':')
fqdn = input.substring(0, portIndex)
port = input.substring(portIndex + 1, input.length).toIntOrNull(10) ?: 0
}
// see https://en.wikipedia.org/wiki/Port_(computer_networking)
if (port < 1 || port > 0xffff) return false
// see https://en.wikipedia.org/wiki/Fully_qualified_domain_name
if (fqdn.isEmpty() || fqdn.length > 255) return false
for (part in fqdn.split('.')) {
if (part.isEmpty() || part.length > 64) return false
if (part.first() == '-' || part.last() == '-') return false
for (c in part) {
if (c.isLetterOrDigit() || c == '-') continue
return false
}
}
return true
}

View file

@ -59,6 +59,9 @@ class DownloadWizardProgressFragment : DownloadWizardActivity.DownloadWizardStep
private val adapter = ProgressItemAdapter() private val adapter = ProgressItemAdapter()
// We don't want to turn off the screen during a download
override val keepScreenOn = true
private var isDone = false private var isDone = false
override val hasNext: Boolean override val hasNext: Boolean

View file

@ -8,15 +8,15 @@ data class LPAString(
) { ) {
companion object { companion object {
fun parse(input: String): LPAString { fun parse(input: String): LPAString {
val components = input.removePrefix("LPA:").split('$') var token = input
if (components.size < 2 || components[0] != "1") { if (token.startsWith("LPA:", ignoreCase = true)) token = token.drop(4)
throw IllegalArgumentException("Invalid activation code format") val components = token.split('$').map { it.trim().ifBlank { null } }
} require(components.getOrNull(0) == "1") { "Invalid AC_Format" }
return LPAString( return LPAString(
address = components[1].trim(), requireNotNull(components.getOrNull(1)) { "SM-DP+ is required" },
matchingId = components.getOrNull(2)?.trim()?.ifBlank { null }, components.getOrNull(2),
oid = components.getOrNull(3)?.trim()?.ifBlank { null }, components.getOrNull(3),
confirmationCodeRequired = components.getOrNull(4)?.trim() == "1" components.getOrNull(4) == "1"
) )
} }
} }

View file

@ -5,11 +5,13 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore import androidx.datastore.preferences.preferencesDataStore
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import im.angry.openeuicc.OpenEuiccApplication import im.angry.openeuicc.OpenEuiccApplication
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import java.util.Base64
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "prefs") private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "prefs")
@ -31,9 +33,35 @@ internal object PreferenceKeys {
// ---- Developer Options ---- // ---- Developer Options ----
val DEVELOPER_OPTIONS_ENABLED = booleanPreferencesKey("developer_options_enabled") val DEVELOPER_OPTIONS_ENABLED = booleanPreferencesKey("developer_options_enabled")
val REFRESH_AFTER_SWITCH = booleanPreferencesKey("refresh_after_switch")
val UNFILTERED_PROFILE_LIST = booleanPreferencesKey("unfiltered_profile_list") val UNFILTERED_PROFILE_LIST = booleanPreferencesKey("unfiltered_profile_list")
val IGNORE_TLS_CERTIFICATE = booleanPreferencesKey("ignore_tls_certificate") val IGNORE_TLS_CERTIFICATE = booleanPreferencesKey("ignore_tls_certificate")
val EUICC_MEMORY_RESET = booleanPreferencesKey("euicc_memory_reset") val EUICC_MEMORY_RESET = booleanPreferencesKey("euicc_memory_reset")
val ISDR_AID_LIST = stringPreferencesKey("isdr_aid_list")
}
const val EUICC_DEFAULT_ISDR_AID = "A0000005591010FFFFFFFF8900000100"
internal object PreferenceConstants {
val DEFAULT_AID_LIST = """
# One AID per line. Comment lines start with #.
# Refs: <https://euicc-manual.osmocom.org/docs/lpa/applet-id-oem/>
# eUICC standard
$EUICC_DEFAULT_ISDR_AID
# eSTK.me
A06573746B6D65FFFFFFFF4953442D52
# eSIM.me
A0000005591010000000008900000300
# 5ber.eSIM
A0000005591010FFFFFFFF8900050500
# Xesim
A0000005591010FFFFFFFF8900000177
""".trimIndent()
} }
open class PreferenceRepository(private val context: Context) { open class PreferenceRepository(private val context: Context) {
@ -48,27 +76,50 @@ open class PreferenceRepository(private val context: Context) {
val verboseLoggingFlow = bindFlow(PreferenceKeys.VERBOSE_LOGGING, false) val verboseLoggingFlow = bindFlow(PreferenceKeys.VERBOSE_LOGGING, false)
// ---- Developer Options ---- // ---- Developer Options ----
val refreshAfterSwitchFlow = bindFlow(PreferenceKeys.REFRESH_AFTER_SWITCH, true)
val developerOptionsEnabledFlow = bindFlow(PreferenceKeys.DEVELOPER_OPTIONS_ENABLED, false) val developerOptionsEnabledFlow = bindFlow(PreferenceKeys.DEVELOPER_OPTIONS_ENABLED, false)
val unfilteredProfileListFlow = bindFlow(PreferenceKeys.UNFILTERED_PROFILE_LIST, false) val unfilteredProfileListFlow = bindFlow(PreferenceKeys.UNFILTERED_PROFILE_LIST, false)
val ignoreTLSCertificateFlow = bindFlow(PreferenceKeys.IGNORE_TLS_CERTIFICATE, false) val ignoreTLSCertificateFlow = bindFlow(PreferenceKeys.IGNORE_TLS_CERTIFICATE, false)
val euiccMemoryResetFlow = bindFlow(PreferenceKeys.EUICC_MEMORY_RESET, false) val euiccMemoryResetFlow = bindFlow(PreferenceKeys.EUICC_MEMORY_RESET, false)
val isdrAidListFlow = bindFlow(
PreferenceKeys.ISDR_AID_LIST,
PreferenceConstants.DEFAULT_AID_LIST,
{ Base64.getEncoder().encodeToString(it.encodeToByteArray()) },
{ Base64.getDecoder().decode(it).decodeToString() })
protected fun <T> bindFlow(key: Preferences.Key<T>, defaultValue: T): PreferenceFlowWrapper<T> = protected fun <T> bindFlow(
PreferenceFlowWrapper(context, key, defaultValue) key: Preferences.Key<T>,
defaultValue: T,
encoder: (T) -> T = { it },
decoder: (T) -> T = { it }
): PreferenceFlowWrapper<T> =
PreferenceFlowWrapper(context, key, defaultValue, encoder, decoder)
} }
class PreferenceFlowWrapper<T> private constructor( class PreferenceFlowWrapper<T> private constructor(
private val context: Context, private val context: Context,
private val key: Preferences.Key<T>, private val key: Preferences.Key<T>,
inner: Flow<T> inner: Flow<T>,
private val encoder: (T) -> T,
) : Flow<T> by inner { ) : Flow<T> by inner {
internal constructor(context: Context, key: Preferences.Key<T>, defaultValue: T) : this( internal constructor(
context: Context,
key: Preferences.Key<T>,
defaultValue: T,
encoder: (T) -> T,
decoder: (T) -> T
) : this(
context, context,
key, key,
context.dataStore.data.map { it[key] ?: defaultValue } context.dataStore.data.map { it[key]?.let(decoder) ?: defaultValue },
encoder
) )
suspend fun updatePreference(value: T) { suspend fun updatePreference(value: T) {
context.dataStore.edit { it[key] = value } context.dataStore.edit { it[key] = encoder(value) }
}
suspend fun removePreference() {
context.dataStore.edit { it.remove(key) }
} }
} }

View file

@ -1,7 +1,7 @@
package im.angry.openeuicc.util package im.angry.openeuicc.util
fun String.decodeHex(): ByteArray { fun String.decodeHex(): ByteArray {
check(length % 2 == 0) { "Must have an even length" } require(length % 2 == 0) { "Must have an even length" }
val decodedLength = length / 2 val decodedLength = length / 2
val out = ByteArray(decodedLength) val out = ByteArray(decodedLength)
@ -29,6 +29,19 @@ fun formatFreeSpace(size: Int): String =
"$size B" "$size B"
} }
/**
* Decode a list of potential ISDR AIDs, one per line. Lines starting with '#' are ignored.
* If none is found, at least EUICC_DEFAULT_ISDR_AID is returned
*/
fun parseIsdrAidList(s: String): List<ByteArray> =
s.split('\n')
.map(String::trim)
.filter { !it.startsWith('#') }
.map(String::trim)
.filter(String::isNotEmpty)
.mapNotNull { runCatching(it::decodeHex).getOrNull() }
.ifEmpty { listOf(EUICC_DEFAULT_ISDR_AID.decodeHex()) }
fun String.prettyPrintJson(): String { fun String.prettyPrintJson(): String {
val ret = StringBuilder() val ret = StringBuilder()
var inQuotes = false var inQuotes = false

View file

@ -54,6 +54,9 @@ interface OpenEuiccContextMarker {
val appContainer: AppContainer val appContainer: AppContainer
get() = openEuiccApplication.appContainer get() = openEuiccApplication.appContainer
val preferenceRepository: PreferenceRepository
get() = appContainer.preferenceRepository
val telephonyManager: TelephonyManager val telephonyManager: TelephonyManager
get() = appContainer.telephonyManager get() = appContainer.telephonyManager
} }

View file

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/toolbar_activity" />
<EditText
android:id="@+id/isdr_aid_list_editor"
android:layout_width="0dp"
android:layout_height="0dp"
android:fontFamily="monospace"
android:importantForAutofill="no"
android:inputType="textMultiLine"
android:gravity="top|start"
app:layout_constraintTop_toBottomOf="@id/toolbar"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
tools:ignore="LabelFor" />
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/save"
android:icon="@drawable/ic_save_as_black"
android:title="@string/logs_save"
app:showAsAction="always" />
<item
android:id="@+id/reset"
android:title="@string/reset"
android:icon="@drawable/ic_refresh_black"
app:showAsAction="ifRoom" />
</menu>

View file

@ -124,6 +124,7 @@
<string name="logs_filename_template">%s のログ</string> <string name="logs_filename_template">%s のログ</string>
<string name="developer_options_steps">開発者になるまであと %d ステップです。</string> <string name="developer_options_steps">開発者になるまであと %d ステップです。</string>
<string name="developer_options_enabled">あなたは開発者になりました!</string> <string name="developer_options_enabled">あなたは開発者になりました!</string>
<string name="isdr_aid_list_saved">カスタム ISD-R AID リストが保存されました</string>
<string name="pref_settings">設定</string> <string name="pref_settings">設定</string>
<string name="pref_notifications">通知</string> <string name="pref_notifications">通知</string>
<string name="pref_notifications_desc">eSIM のプロファイル操作により、通信事業者に通知が送信されます。必要に応じてこの動作を微調整できます。</string> <string name="pref_notifications_desc">eSIM のプロファイル操作により、通信事業者に通知が送信されます。必要に応じてこの動作を微調整できます。</string>
@ -143,10 +144,12 @@
<string name="pref_advanced_logs">ログ</string> <string name="pref_advanced_logs">ログ</string>
<string name="pref_advanced_logs_desc">アプリの最新デバッグログを表示します</string> <string name="pref_advanced_logs_desc">アプリの最新デバッグログを表示します</string>
<string name="pref_developer">開発者オプション</string> <string name="pref_developer">開発者オプション</string>
<string name="pref_developer_refresh_after_switch_desc">プロファイルを切り替えた後にモデムに更新コマンドを送信するかどうか。クラッシュが発生する場合は、これを無効にしてみてください。</string>
<string name="pref_developer_unfiltered_profile_list">フィルタリングされていないプロファイル一覧を表示</string> <string name="pref_developer_unfiltered_profile_list">フィルタリングされていないプロファイル一覧を表示</string>
<string name="pref_developer_unfiltered_profile_list_desc">非運用のプロファイルも含めます</string> <string name="pref_developer_unfiltered_profile_list_desc">非運用のプロファイルも含めます</string>
<string name="pref_developer_ignore_tls_certificate">SM-DP+ TLS 証明書を無視する</string> <string name="pref_developer_ignore_tls_certificate">SM-DP+ TLS 証明書を無視する</string>
<string name="pref_developer_ignore_tls_certificate_desc">RSP サーバーで使用される TLS 証明書を受け入れます</string> <string name="pref_developer_ignore_tls_certificate_desc">RSP サーバーで使用される TLS 証明書を受け入れます</string>
<string name="pref_developer_isdr_aid_list_desc">一部のブランドの取り外し可能な eUICC では、独自の非標準 ISD-R AID が使用されている場合があり、サードパーティ アプリからアクセスできなくなります。アプリはこのリストに追加された非標準の AID の使用を試みる可能性がありますが、動作することは保証されません。</string>
<string name="pref_info">情報</string> <string name="pref_info">情報</string>
<string name="pref_info_app_version">アプリバージョン</string> <string name="pref_info_app_version">アプリバージョン</string>
<string name="pref_info_source_code">ソースコード</string> <string name="pref_info_source_code">ソースコード</string>
@ -156,10 +159,14 @@
<string name="task_euicc_memory_reset_failure">eSIM チップの消去は失敗しました</string> <string name="task_euicc_memory_reset_failure">eSIM チップの消去は失敗しました</string>
<string name="euicc_memory_reset">eSIM を消去する</string> <string name="euicc_memory_reset">eSIM を消去する</string>
<string name="euicc_memory_reset_title">eSIM を消去する</string> <string name="euicc_memory_reset_title">eSIM を消去する</string>
<string name="euicc_memory_reset_message">このチップ内のすべてのプロファイルを削除することをご確認してください。この操作は元に戻せないことをご理解してください。\n\nEID: %s\n\n%s</string> <string name="euicc_memory_reset_message">このチップ内のすべてのプロファイルを削除することをご確認してください。この操作は元に戻せないことをご理解してください。\n\nEID: %1$s\n\n%2$s</string>
<string name="euicc_memory_reset_hint_text">確認のため、ここに「%s」を入力してください</string> <string name="euicc_memory_reset_hint_text">確認のため、ここに「%s」を入力してください</string>
<string name="euicc_memory_reset_confirm_text">EID が %s で終わるチップを消去することに同意します。これは元に戻せないことを理解しています。</string> <string name="euicc_memory_reset_confirm_text">EID が %s で終わるチップを消去することに同意します。これは元に戻せないことを理解しています。</string>
<string name="euicc_memory_reset_invoke_button">消去する</string> <string name="euicc_memory_reset_invoke_button">消去する</string>
<string name="pref_developer_euicc_memory_reset">eUICC の消去を可能にする</string> <string name="pref_developer_euicc_memory_reset">eUICC の消去を可能にする</string>
<string name="pref_developer_euicc_memory_reset_desc">この操作は、デフォルトでは非表示になっている危険な操作です。代わりに、すべての構成ファイルを手動で削除することもできます。</string> <string name="pref_developer_euicc_memory_reset_desc">この操作は、デフォルトでは非表示になっている危険な操作です。代わりに、すべての構成ファイルを手動で削除することもできます。</string>
<string name="pref_developer_refresh_after_switch">モデムに更新コマンドを送信</string>
<string name="pref_developer_isdr_aid_list">ISD-R AID リストのカスタマイズ</string>
<string name="reset">リセット</string>
<string name="isdr_aid_list">ISD-R AID リスト</string>
</resources> </resources>

View file

@ -65,6 +65,7 @@
<string name="profile_notification_delete">删除</string> <string name="profile_notification_delete">删除</string>
<string name="logs_save">保存日志</string> <string name="logs_save">保存日志</string>
<string name="logs_filename_template">%s 的日志</string> <string name="logs_filename_template">%s 的日志</string>
<string name="isdr_aid_list_saved">自定义 ISD-R AID 列表已保存</string>
<string name="pref_settings">设置</string> <string name="pref_settings">设置</string>
<string name="pref_notifications">通知</string> <string name="pref_notifications">通知</string>
<string name="pref_notifications_desc">操作 eSIM 配置文件会向运营商发送通知。根据需要在此处微调此行为。</string> <string name="pref_notifications_desc">操作 eSIM 配置文件会向运营商发送通知。根据需要在此处微调此行为。</string>
@ -81,6 +82,7 @@
<string name="pref_advanced_verbose_logging_desc">详细日志中包含敏感信息,开启此功能后请仅与你信任的人共享你的日志。</string> <string name="pref_advanced_verbose_logging_desc">详细日志中包含敏感信息,开启此功能后请仅与你信任的人共享你的日志。</string>
<string name="pref_advanced_logs">日志</string> <string name="pref_advanced_logs">日志</string>
<string name="pref_advanced_logs_desc">查看应用程序的最新调试日志</string> <string name="pref_advanced_logs_desc">查看应用程序的最新调试日志</string>
<string name="pref_developer_isdr_aid_list_desc">某些品牌的可移除 eUICC 可能会使用自己的非标准 ISD-R AID导致第三方应用无法访问。此 App 可以尝试使用此列表中添加的非标准 AID但不能保证它们一定有效。</string>
<string name="pref_info">信息</string> <string name="pref_info">信息</string>
<string name="pref_info_app_version">App 版本</string> <string name="pref_info_app_version">App 版本</string>
<string name="pref_info_source_code">源码</string> <string name="pref_info_source_code">源码</string>
@ -145,6 +147,7 @@
<string name="pref_advanced_language">语言</string> <string name="pref_advanced_language">语言</string>
<string name="pref_advanced_language_desc">选择 App 语言</string> <string name="pref_advanced_language_desc">选择 App 语言</string>
<string name="pref_developer">开发者选项</string> <string name="pref_developer">开发者选项</string>
<string name="pref_developer_refresh_after_switch_desc">切换配置文件后是否向基带发送刷新命令。如果发现崩溃,请尝试禁用此功能。</string>
<string name="pref_developer_unfiltered_profile_list">显示未经过滤的配置文件列表</string> <string name="pref_developer_unfiltered_profile_list">显示未经过滤的配置文件列表</string>
<string name="pref_developer_unfiltered_profile_list_desc">在配置文件列表中包括非生产环境的配置文件</string> <string name="pref_developer_unfiltered_profile_list_desc">在配置文件列表中包括非生产环境的配置文件</string>
<string name="pref_developer_ignore_tls_certificate">无视 SM-DP+ 的 TLS 证书</string> <string name="pref_developer_ignore_tls_certificate">无视 SM-DP+ 的 TLS 证书</string>
@ -156,10 +159,14 @@
<string name="task_euicc_memory_reset_failure">eSIM 芯片擦除失败</string> <string name="task_euicc_memory_reset_failure">eSIM 芯片擦除失败</string>
<string name="euicc_memory_reset">擦除 eSIM 芯片</string> <string name="euicc_memory_reset">擦除 eSIM 芯片</string>
<string name="euicc_memory_reset_title">擦除 eSIM 芯片</string> <string name="euicc_memory_reset_title">擦除 eSIM 芯片</string>
<string name="euicc_memory_reset_message">请确认删除此芯片上的所有配置文件,并了解此操作不可逆。\n\nEID: %s\n\n%s</string> <string name="euicc_memory_reset_message">请确认删除此芯片上的所有配置文件,并了解此操作不可逆。\n\nEID: %1$s\n\n%2$s</string>
<string name="euicc_memory_reset_hint_text">请在此处输入「%s」以确认</string> <string name="euicc_memory_reset_hint_text">请在此处输入「%s」以确认</string>
<string name="euicc_memory_reset_confirm_text">我确认擦除 EID 以 %s 结尾的芯片,并了解此操作不可逆</string> <string name="euicc_memory_reset_confirm_text">我确认擦除 EID 以 %s 结尾的芯片,并了解此操作不可逆</string>
<string name="euicc_memory_reset_invoke_button">擦除</string> <string name="euicc_memory_reset_invoke_button">擦除</string>
<string name="pref_developer_euicc_memory_reset">允许擦除 eUICC</string> <string name="pref_developer_euicc_memory_reset">允许擦除 eUICC</string>
<string name="pref_developer_euicc_memory_reset_desc">此操作是默认隐藏的危险操作。作为替代方案,您可以手动删除所有配置文件。</string> <string name="pref_developer_euicc_memory_reset_desc">此操作是默认隐藏的危险操作。作为替代方案,您可以手动删除所有配置文件。</string>
<string name="pref_developer_refresh_after_switch">向基带发送刷新命令</string>
<string name="pref_developer_isdr_aid_list">自定义 ISD-R AID 列表</string>
<string name="reset">重置</string>
<string name="isdr_aid_list">ISD-R AID 列表</string>
</resources> </resources>

View file

@ -65,6 +65,7 @@
<string name="profile_notification_delete">刪除</string> <string name="profile_notification_delete">刪除</string>
<string name="logs_save">儲存日誌</string> <string name="logs_save">儲存日誌</string>
<string name="logs_filename_template">%s 的日誌</string> <string name="logs_filename_template">%s 的日誌</string>
<string name="isdr_aid_list_saved">自訂 ISD-R AID 列表已儲存</string>
<string name="pref_settings">設定</string> <string name="pref_settings">設定</string>
<string name="pref_notifications">通知</string> <string name="pref_notifications">通知</string>
<string name="pref_notifications_desc">變更 eSIM 設定檔會向電信業者傳送通知。根據需要在此處微調此行為。</string> <string name="pref_notifications_desc">變更 eSIM 設定檔會向電信業者傳送通知。根據需要在此處微調此行為。</string>
@ -81,6 +82,7 @@
<string name="pref_advanced">進階</string> <string name="pref_advanced">進階</string>
<string name="pref_advanced_disable_safeguard_removable_esim">允許 停用/刪除 已啟用的設定檔</string> <string name="pref_advanced_disable_safeguard_removable_esim">允許 停用/刪除 已啟用的設定檔</string>
<string name="pref_advanced_disable_safeguard_removable_esim_desc">預設情況下,此應用程式會阻止您停用可插拔 eSIM 中已啟用的設定檔。\n因為這樣做 <i>有時</i> 會導致無法存取。\n勾選此框以 <i>移除</i> 此保護措施。</string> <string name="pref_advanced_disable_safeguard_removable_esim_desc">預設情況下,此應用程式會阻止您停用可插拔 eSIM 中已啟用的設定檔。\n因為這樣做 <i>有時</i> 會導致無法存取。\n勾選此框以 <i>移除</i> 此保護措施。</string>
<string name="pref_developer_isdr_aid_list_desc">某些品牌的可移除 eUICC 可能會使用自己的非標準 ISD-R AID導致第三方應用程式無法存取。此 App 可以嘗試使用此清單中新增的非標準 AID但不能保證它們一定有效。</string>
<string name="pref_info">資訊</string> <string name="pref_info">資訊</string>
<string name="pref_info_app_version">App 版本</string> <string name="pref_info_app_version">App 版本</string>
<string name="pref_info_source_code">原始碼</string> <string name="pref_info_source_code">原始碼</string>
@ -145,6 +147,7 @@
<string name="pref_advanced_language">語言</string> <string name="pref_advanced_language">語言</string>
<string name="pref_advanced_language_desc">選擇 App 語言</string> <string name="pref_advanced_language_desc">選擇 App 語言</string>
<string name="pref_developer">開發人員選項</string> <string name="pref_developer">開發人員選項</string>
<string name="pref_developer_refresh_after_switch_desc">切換設定檔後是否向基帶發送刷新命令。如果發現崩潰,請嘗試停用此功能。</string>
<string name="pref_developer_unfiltered_profile_list">顯示未經過濾的設定檔列表</string> <string name="pref_developer_unfiltered_profile_list">顯示未經過濾的設定檔列表</string>
<string name="pref_developer_unfiltered_profile_list_desc">在設定檔列表中包括非生產環境的設定檔</string> <string name="pref_developer_unfiltered_profile_list_desc">在設定檔列表中包括非生產環境的設定檔</string>
<string name="pref_developer_ignore_tls_certificate">忽略 SM-DP+ 的 TLS 證書</string> <string name="pref_developer_ignore_tls_certificate">忽略 SM-DP+ 的 TLS 證書</string>
@ -156,10 +159,14 @@
<string name="task_euicc_memory_reset_failure">eSIM 晶片擦除失敗</string> <string name="task_euicc_memory_reset_failure">eSIM 晶片擦除失敗</string>
<string name="euicc_memory_reset">擦除 eSIM 晶片</string> <string name="euicc_memory_reset">擦除 eSIM 晶片</string>
<string name="euicc_memory_reset_title">擦除 eSIM 晶片</string> <string name="euicc_memory_reset_title">擦除 eSIM 晶片</string>
<string name="euicc_memory_reset_message">請確認刪除此晶片上的所有配置文件,並了解此操作不可逆。\n\nEID: %s\n\n%s</string> <string name="euicc_memory_reset_message">請確認刪除此晶片上的所有配置文件,並了解此操作不可逆。\n\nEID: %1$s\n\n%2$s</string>
<string name="euicc_memory_reset_hint_text">請在此輸入「%s」以確認</string> <string name="euicc_memory_reset_hint_text">請在此輸入「%s」以確認</string>
<string name="euicc_memory_reset_confirm_text">我確認擦除 EID 以 %s 結尾的晶片,並了解此操作不可逆</string> <string name="euicc_memory_reset_confirm_text">我確認擦除 EID 以 %s 結尾的晶片,並了解此操作不可逆</string>
<string name="euicc_memory_reset_invoke_button">擦除</string> <string name="euicc_memory_reset_invoke_button">擦除</string>
<string name="pref_developer_euicc_memory_reset">允許擦除 eUICC</string> <string name="pref_developer_euicc_memory_reset">允許擦除 eUICC</string>
<string name="pref_developer_euicc_memory_reset_desc">此操作是預設隱藏的危險操作。作為替代方案,您可以手動刪除所有設定檔。</string> <string name="pref_developer_euicc_memory_reset_desc">此操作是預設隱藏的危險操作。作為替代方案,您可以手動刪除所有設定檔。</string>
<string name="pref_developer_refresh_after_switch">向基帶發送刷新命令</string>
<string name="pref_developer_isdr_aid_list">自訂 ISD-R AID 列表</string>
<string name="reset">重置</string>
<string name="isdr_aid_list">ISD-R AID 列表</string>
</resources> </resources>

View file

@ -134,6 +134,7 @@
<string name="euicc_info_bl_ver">Product Bootloader Version</string> <string name="euicc_info_bl_ver">Product Bootloader Version</string>
<string name="euicc_info_fw_ver">Product Firmware Version</string> <string name="euicc_info_fw_ver">Product Firmware Version</string>
<string name="euicc_info_eid" translatable="false">EID</string> <string name="euicc_info_eid" translatable="false">EID</string>
<string name="euicc_info_isdr_aid" translatable="false">ISD-R AID</string>
<string name="euicc_info_sgp22_version">SGP.22 Version</string> <string name="euicc_info_sgp22_version">SGP.22 Version</string>
<string name="euicc_info_firmware_version">eUICC OS Version</string> <string name="euicc_info_firmware_version">eUICC OS Version</string>
<string name="euicc_info_globalplatform_version">GlobalPlatform Version</string> <string name="euicc_info_globalplatform_version">GlobalPlatform Version</string>
@ -148,7 +149,7 @@
<string name="euicc_memory_reset">Erase eUICC</string> <string name="euicc_memory_reset">Erase eUICC</string>
<string name="euicc_memory_reset_title">Erase eUICC</string> <string name="euicc_memory_reset_title">Erase eUICC</string>
<string name="euicc_memory_reset_message">Please confirm to delete all profiles on this chip and understand that this operation is irreversible.\n\nEID: %s\n\n%s</string> <string name="euicc_memory_reset_message">Please confirm to delete all profiles on this chip and understand that this operation is irreversible.\n\nEID: %1$s\n\n%2$s</string>
<string name="euicc_memory_reset_hint_text">Type \'%s\' here to confirm</string> <string name="euicc_memory_reset_hint_text">Type \'%s\' here to confirm</string>
<string name="euicc_memory_reset_confirm_text">I CONFIRM TO ERASE THE CHIP WHOSE EID ENDS WITH %s AND UNDERSTAND THAT THIS IS IRREVERSIBLE</string> <string name="euicc_memory_reset_confirm_text">I CONFIRM TO ERASE THE CHIP WHOSE EID ENDS WITH %s AND UNDERSTAND THAT THIS IS IRREVERSIBLE</string>
<string name="euicc_memory_reset_invoke_button">Erase</string> <string name="euicc_memory_reset_invoke_button">Erase</string>
@ -162,6 +163,11 @@
<string name="developer_options_steps">You are %d steps away from being a developer.</string> <string name="developer_options_steps">You are %d steps away from being a developer.</string>
<string name="developer_options_enabled">You are now a developer!</string> <string name="developer_options_enabled">You are now a developer!</string>
<string name="reset">Reset</string>
<string name="isdr_aid_list">ISD-R AID List</string>
<string name="isdr_aid_list_saved">Saved custom ISD-R AID list.</string>
<string name="pref_settings">Settings</string> <string name="pref_settings">Settings</string>
<string name="pref_notifications">Notifications</string> <string name="pref_notifications">Notifications</string>
<string name="pref_notifications_desc">eSIM profile operations send notifications to the carrier. Fine-tune this behavior as needed here.</string> <string name="pref_notifications_desc">eSIM profile operations send notifications to the carrier. Fine-tune this behavior as needed here.</string>
@ -181,12 +187,16 @@
<string name="pref_advanced_logs">Logs</string> <string name="pref_advanced_logs">Logs</string>
<string name="pref_advanced_logs_desc">View recent debug logs of the application</string> <string name="pref_advanced_logs_desc">View recent debug logs of the application</string>
<string name="pref_developer">Developer Options</string> <string name="pref_developer">Developer Options</string>
<string name="pref_developer_refresh_after_switch">Send refresh command to modem</string>
<string name="pref_developer_refresh_after_switch_desc">Whether to send a refresh command to the modem after switching profiles. Try disabling this if you see crashes.</string>
<string name="pref_developer_unfiltered_profile_list">Show unfiltered profile list</string> <string name="pref_developer_unfiltered_profile_list">Show unfiltered profile list</string>
<string name="pref_developer_unfiltered_profile_list_desc">Include non-production profiles in the list</string> <string name="pref_developer_unfiltered_profile_list_desc">Include non-production profiles in the list</string>
<string name="pref_developer_ignore_tls_certificate">Ignore SM-DP+ TLS certificate</string> <string name="pref_developer_ignore_tls_certificate">Ignore SM-DP+ TLS certificate</string>
<string name="pref_developer_ignore_tls_certificate_desc">Accept any TLS certificate used by the RSP server</string> <string name="pref_developer_ignore_tls_certificate_desc">Accept any TLS certificate used by the RSP server</string>
<string name="pref_developer_euicc_memory_reset">Allow erasing eUICC</string> <string name="pref_developer_euicc_memory_reset">Allow erasing eUICC</string>
<string name="pref_developer_euicc_memory_reset_desc">This is a dangerous operation and hidden by default. As an alternative, you can delete all profiles manually.</string> <string name="pref_developer_euicc_memory_reset_desc">This is a dangerous operation and hidden by default. As an alternative, you can delete all profiles manually.</string>
<string name="pref_developer_isdr_aid_list">Customize ISD-R AID list</string>
<string name="pref_developer_isdr_aid_list_desc">Some brands of removable eUICCs may use their own non-standard ISD-R AID, rendering them inaccessible to third-party apps. We can attempt to use non-standard AIDs added in this list, but there is no guarantee that they will work.</string>
<string name="pref_info">Info</string> <string name="pref_info">Info</string>
<string name="pref_info_app_version">App Version</string> <string name="pref_info_app_version">App Version</string>
<string name="pref_info_source_code">Source Code</string> <string name="pref_info_source_code">Source Code</string>

View file

@ -57,6 +57,12 @@
app:title="@string/pref_developer" app:title="@string/pref_developer"
app:iconSpaceReserved="false"> app:iconSpaceReserved="false">
<CheckBoxPreference
app:iconSpaceReserved="false"
app:key="pref_developer_refresh_after_switch"
app:summary="@string/pref_developer_refresh_after_switch_desc"
app:title="@string/pref_developer_refresh_after_switch" />
<CheckBoxPreference <CheckBoxPreference
app:iconSpaceReserved="false" app:iconSpaceReserved="false"
app:key="pref_developer_unfiltered_profile_list" app:key="pref_developer_unfiltered_profile_list"
@ -75,6 +81,12 @@
app:summary="@string/pref_developer_euicc_memory_reset_desc" app:summary="@string/pref_developer_euicc_memory_reset_desc"
app:title="@string/pref_developer_euicc_memory_reset" /> app:title="@string/pref_developer_euicc_memory_reset" />
<Preference
app:iconSpaceReserved="false"
app:key="pref_developer_isdr_aid_list"
app:title="@string/pref_developer_isdr_aid_list"
app:summary="@string/pref_developer_isdr_aid_list_desc" />
</im.angry.openeuicc.ui.preference.LongSummaryPreferenceCategory> </im.angry.openeuicc.ui.preference.LongSummaryPreferenceCategory>
<PreferenceCategory <PreferenceCategory

View file

@ -128,10 +128,6 @@ internal class OmapiConnCheck(private val context: Context): CompatibilityCheck(
} }
internal class IsdrChannelAccessCheck(private val context: Context): CompatibilityCheck(context) { internal class IsdrChannelAccessCheck(private val context: Context): CompatibilityCheck(context) {
companion object {
val ISDR_AID = "A0000005591010FFFFFFFF8900000100".decodeHex()
}
override val title: String override val title: String
get() = context.getString(R.string.compatibility_check_isdr_channel) get() = context.getString(R.string.compatibility_check_isdr_channel)
override val defaultDescription: String override val defaultDescription: String
@ -147,7 +143,10 @@ internal class IsdrChannelAccessCheck(private val context: Context): Compatibili
val (validSlotIds, result) = readers.map { val (validSlotIds, result) = readers.map {
try { try {
it.openSession().openLogicalChannel(ISDR_AID)?.close() // Note: we ONLY check the default ISD-R AID, because this test is for the _device_,
// NOT the eUICC. We don't care what AID a potential eUICC might use, all we need to
// check is we can open _some_ AID.
it.openSession().openLogicalChannel(EUICC_DEFAULT_ISDR_AID.decodeHex())?.close()
Pair(it.slotIndex, State.SUCCESS) Pair(it.slotIndex, State.SUCCESS)
} catch (_: SecurityException) { } catch (_: SecurityException) {
// Ignore; this is expected when everything works // Ignore; this is expected when everything works

View file

@ -5,12 +5,14 @@
<item>com.android.stk/.StkMainHide</item> <item>com.android.stk/.StkMainHide</item>
<item>com.android.stk/.StkListActivity</item> <item>com.android.stk/.StkListActivity</item>
<item>com.android.stk/.StkLauncherListActivity</item> <item>com.android.stk/.StkLauncherListActivity</item>
<item>com.android.stk/.StkSelectionActivity</item>
</string-array> </string-array>
<string-array name="sim_toolkit_slot_1"> <string-array name="sim_toolkit_slot_1">
<item>com.android.stk/.StkMain1</item> <item>com.android.stk/.StkMain1</item>
<item>com.android.stk/.PrimaryStkMain</item> <item>com.android.stk/.PrimaryStkMain</item>
<item>com.android.stk/.StkLauncherActivity</item> <item>com.android.stk/.StkLauncherActivity</item>
<item>com.android.stk/.StkLauncherActivity_Chn</item> <item>com.android.stk/.StkLauncherActivity_Chn</item>
<item>com.android.stk/.StkLauncherActivity1</item>
<item>com.android.stk/.StkLauncherActivityI</item> <item>com.android.stk/.StkLauncherActivityI</item>
<item>com.android.stk/.OppoStkLauncherActivity1</item> <item>com.android.stk/.OppoStkLauncherActivity1</item>
<item>com.android.stk/.OplusStkLauncherActivity1</item> <item>com.android.stk/.OplusStkLauncherActivity1</item>

View file

@ -10,17 +10,19 @@ import java.lang.IllegalArgumentException
class PrivilegedEuiccChannelFactory(context: Context) : DefaultEuiccChannelFactory(context), class PrivilegedEuiccChannelFactory(context: Context) : DefaultEuiccChannelFactory(context),
PrivilegedEuiccContextMarker { PrivilegedEuiccContextMarker {
private val tm by lazy { override val openEuiccMarkerContext: Context
(context.applicationContext as OpenEuiccApplication).appContainer.telephonyManager get() = context
}
@Suppress("NAME_SHADOWING") @Suppress("NAME_SHADOWING")
override suspend fun tryOpenEuiccChannel(port: UiccPortInfoCompat): EuiccChannel? { override suspend fun tryOpenEuiccChannel(
port: UiccPortInfoCompat,
isdrAid: ByteArray
): EuiccChannel? {
val port = port as RealUiccPortInfoCompat val port = port as RealUiccPortInfoCompat
if (port.card.isRemovable) { if (port.card.isRemovable) {
// Attempt unprivileged (OMAPI) before TelephonyManager // Attempt unprivileged (OMAPI) before TelephonyManager
// but still try TelephonyManager in case OMAPI is broken // but still try TelephonyManager in case OMAPI is broken
super.tryOpenEuiccChannel(port)?.let { return it } super.tryOpenEuiccChannel(port, isdrAid)?.let { return it }
} }
if (port.card.isEuicc || preferenceRepository.removableTelephonyManagerFlow.first()) { if (port.card.isEuicc || preferenceRepository.removableTelephonyManagerFlow.first()) {
@ -35,21 +37,22 @@ class PrivilegedEuiccChannelFactory(context: Context) : DefaultEuiccChannelFacto
intrinsicChannelName = null, intrinsicChannelName = null,
TelephonyManagerApduInterface( TelephonyManagerApduInterface(
port, port,
tm, telephonyManager,
context.preferenceRepository.verboseLoggingFlow context.preferenceRepository.verboseLoggingFlow
), ),
isdrAid,
context.preferenceRepository.verboseLoggingFlow, context.preferenceRepository.verboseLoggingFlow,
context.preferenceRepository.ignoreTLSCertificateFlow, context.preferenceRepository.ignoreTLSCertificateFlow,
) )
} catch (e: IllegalArgumentException) { } catch (_: IllegalArgumentException) {
// Failed // Failed
Log.w( Log.w(
DefaultEuiccChannelManager.TAG, DefaultEuiccChannelManager.TAG,
"TelephonyManager APDU interface unavailable for slot ${port.card.physicalSlotIndex} port ${port.portIndex}, falling back" "TelephonyManager APDU interface unavailable for slot ${port.card.physicalSlotIndex} port ${port.portIndex} with ISD-R AID: ${isdrAid.encodeHex()}."
) )
} }
} }
return super.tryOpenEuiccChannel(port) return super.tryOpenEuiccChannel(port, isdrAid)
} }
} }

View file

@ -10,16 +10,9 @@ import java.util.concurrent.Executors
import kotlin.coroutines.resume import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine import kotlin.coroutines.suspendCoroutine
interface PrivilegedEuiccContextMarker { interface PrivilegedEuiccContextMarker : OpenEuiccContextMarker {
val privilegedEuiccMarkerContext: Context override val preferenceRepository: PrivilegedPreferenceRepository
get() = when (this) { get() = appContainer.preferenceRepository as PrivilegedPreferenceRepository
is Context -> this
is Fragment -> requireContext()
else -> throw RuntimeException("PrivilegedEuiccContextMarker shall only be used on Fragments or UI types that derive from Context")
}
val preferenceRepository: PrivilegedPreferenceRepository
get() = privilegedEuiccMarkerContext.preferenceRepository as PrivilegedPreferenceRepository
} }
suspend fun Context.bindServiceSuspended(intent: Intent, flags: Int): Pair<IBinder?, () -> Unit> = suspend fun Context.bindServiceSuspended(intent: Intent, flags: Int): Pair<IBinder?, () -> Unit> =

Binary file not shown.

View file

@ -1,6 +1,7 @@
#Wed Jun 08 13:28:20 EDT 2022
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

297
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -15,69 +15,104 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@ -87,9 +122,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -98,88 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC2039,SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC2039,SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

37
gradlew.bat vendored
View file

@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

View file

@ -80,7 +80,7 @@ apdu_interface_transmit(struct euicc_ctx *ctx, uint8_t **rx, uint32_t *rx_len, c
LPAC_JNI_EXCEPTION_RETURN; LPAC_JNI_EXCEPTION_RETURN;
*rx_len = (*env)->GetArrayLength(env, ret); *rx_len = (*env)->GetArrayLength(env, ret);
*rx = calloc(*rx_len, sizeof(uint8_t)); *rx = calloc(*rx_len, sizeof(uint8_t));
(*env)->GetByteArrayRegion(env, ret, 0, *rx_len, *rx); (*env)->GetByteArrayRegion(env, ret, 0, *rx_len, (jbyte *) *rx);
(*env)->DeleteLocalRef(env, txArr); (*env)->DeleteLocalRef(env, txArr);
(*env)->DeleteLocalRef(env, ret); (*env)->DeleteLocalRef(env, ret);
return 0; return 0;
@ -113,7 +113,7 @@ http_interface_transmit(struct euicc_ctx *ctx, const char *url, uint32_t *rcode,
jbyteArray rxArr = (jbyteArray) (*env)->GetObjectField(env, ret, field_resp_data); jbyteArray rxArr = (jbyteArray) (*env)->GetObjectField(env, ret, field_resp_data);
*rx_len = (*env)->GetArrayLength(env, rxArr); *rx_len = (*env)->GetArrayLength(env, rxArr);
*rx = calloc(*rx_len, sizeof(uint8_t)); *rx = calloc(*rx_len, sizeof(uint8_t));
(*env)->GetByteArrayRegion(env, rxArr, 0, *rx_len, *rx); (*env)->GetByteArrayRegion(env, rxArr, 0, *rx_len, (jbyte *) *rx);
(*env)->DeleteLocalRef(env, txArr); (*env)->DeleteLocalRef(env, txArr);
(*env)->DeleteLocalRef(env, rxArr); (*env)->DeleteLocalRef(env, rxArr);
(*env)->DeleteLocalRef(env, headersArr); (*env)->DeleteLocalRef(env, headersArr);