euicc: add profile management and notifications (ES10)
- Commit
f13ce74d470ec9457d89512bd7c0e7777835e684- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-12 16:26 UTC (3 months ago)
- Parents
b493ca4
Diff
euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.ktindex bc9cee2b91..d72f624878 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/EuiccNative.kt@@ -41,4 +41,25 @@ object EuiccNative { /** Returns the EUICCInfo1 subset as a JSON string, or null on error. */ external fun nativeGetEuiccInfo(): String?++ /** Returns the installed profiles as a JSON array string, or null on error. */+ external fun nativeGetProfiles(): String?++ /** Enables the profile with [iccid] (raw hex). 0 = success, else error code / -1. */+ external fun nativeEnableProfile(iccid: String): Int++ /** Disables the profile with [iccid] (raw hex). 0 = success, else error code / -1. */+ external fun nativeDisableProfile(iccid: String): Int++ /** Deletes the profile with [iccid] (raw hex). 0 = success, else error code / -1. */+ external fun nativeDeleteProfile(iccid: String): Int++ /** Sets the nickname of the profile with [iccid] (raw hex). 0 = success, else error / -1. */+ external fun nativeSetNickname(iccid: String, nickname: String): Int++ /** Returns pending notifications as a JSON array string, or null on error. */+ external fun nativeListNotifications(): String?++ /** Removes the notification with sequence number [seq]. 0 = success, else error / -1. */+ external fun nativeRemoveNotification(seq: Int): Int }
euicc/src/main/java/com/vayunmathur/euicc/data/Notification.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/data/Notification.kt b/euicc/src/main/java/com/vayunmathur/euicc/data/Notification.ktnew file mode 100644index 0000000000..44f953a6de--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/data/Notification.kt@@ -0,0 +1,14 @@+package com.vayunmathur.euicc.data++import kotlinx.serialization.Serializable++/** One pending eUICC notification, deserialized from the native ListNotification JSON. */+@Serializable+data class Notification(+ val seqNumber: Int = -1,+ /** "install", "enable", "disable", "delete", or "unknown". */+ val operation: String = "unknown",+ /** SM-DP+ / SM-DS address the notification is destined for. */+ val address: String = "",+ val iccidDisplay: String = "",+)
euicc/src/main/java/com/vayunmathur/euicc/data/Profile.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/data/Profile.kt b/euicc/src/main/java/com/vayunmathur/euicc/data/Profile.ktnew file mode 100644index 0000000000..d7ade1cad3--- /dev/null+++ b/euicc/src/main/java/com/vayunmathur/euicc/data/Profile.kt@@ -0,0 +1,27 @@+package com.vayunmathur.euicc.data++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/** One installed eSIM profile, deserialized from the native GetProfilesInfo JSON. */+@Serializable+data class Profile(+ /** Raw ICCID octets as hex; the key passed back into profile operations. */+ val iccid: String = "",+ /** Human-readable ICCID digits. */+ val iccidDisplay: String = "",+ val isdpAid: String = "",+ /** "enabled", "disabled", or "unknown". */+ val state: String = "unknown",+ /** "operational", "test", "provisioning", or "unknown". */+ @SerialName("class") val profileClass: String = "unknown",+ val nickname: String = "",+ val serviceProvider: String = "",+ val name: String = "",+) {+ val isEnabled: Boolean get() = state == "enabled"++ /** Best label to show for this profile. */+ val displayName: String+ get() = nickname.ifBlank { name.ifBlank { serviceProvider.ifBlank { iccidDisplay } } }+}
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.ktindex e6be3919a9..d8419faabc 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccApp.kt@@ -2,80 +2,204 @@ package com.vayunmathur.euicc.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.euicc.data.EuiccInfo+import com.vayunmathur.euicc.data.Notification+import com.vayunmathur.euicc.data.Profile+import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ConfirmDialog import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.OverflowMenu import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton @Composable fun EuiccApp(viewModel: EuiccViewModel) {+ val state = viewModel.state+ var renameTarget by remember { mutableStateOf<Profile?>(null) }+ var deleteTarget by remember { mutableStateOf<Profile?>(null) }+ AppScaffold( title = "EUICC", actions = {- IconButton(onClick = viewModel::refresh) { IconRefresh() }+ IconButton(onClick = viewModel::reload, enabled = !state.loading) { IconRefresh() } }, ) { padding -> Column( modifier = Modifier- .fillMaxSize()+ .fillMaxWidth() .padding(padding) .padding(16.dp) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp), ) {- when (val state = viewModel.state) {- is EuiccUiState.Loading -> CircularProgressIndicator()- is EuiccUiState.Error -> Text(state.message)- is EuiccUiState.Ready -> ReadyContent(state)- }+ if (state.loading) CircularProgressIndicator()+ state.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }++ ProfilesSection(+ profiles = state.profiles,+ onEnable = { viewModel.enable(it.iccid) },+ onDisable = { viewModel.disable(it.iccid) },+ onRename = { renameTarget = it },+ onDelete = { deleteTarget = it },+ )+ NotificationsSection(+ notifications = state.notifications,+ onRemove = { viewModel.removeNotification(it.seqNumber) },+ )+ EuiccSection(eid = state.eid, info = state.info) } }++ renameTarget?.let { profile ->+ RenameDialog(+ profile = profile,+ onConfirm = { name ->+ viewModel.rename(profile.iccid, name)+ renameTarget = null+ },+ onDismiss = { renameTarget = null },+ )+ }++ deleteTarget?.let { profile ->+ ConfirmDialog(+ title = "Delete ${profile.displayName}?",+ message = "This permanently removes the profile from the eUICC.",+ confirmLabel = "Delete",+ destructive = true,+ onConfirm = {+ viewModel.delete(profile.iccid)+ deleteTarget = null+ },+ onDismiss = { deleteTarget = null },+ )+ } } @Composable-private fun ReadyContent(state: EuiccUiState.Ready) {- LabeledCard(label = "EID") {- Text(state.eid ?: "unavailable")+private fun ProfilesSection(+ profiles: List<Profile>,+ onEnable: (Profile) -> Unit,+ onDisable: (Profile) -> Unit,+ onRename: (Profile) -> Unit,+ onDelete: (Profile) -> Unit,+) {+ SectionCard(title = "Profiles") {+ if (profiles.isEmpty()) {+ Text("No profiles installed.")+ return@SectionCard+ }+ for (profile in profiles) {+ ListItem(+ headlineContent = { Text(profile.displayName) },+ supportingContent = {+ Text(+ "${if (profile.isEnabled) "Enabled" else "Disabled"} · ${profile.iccidDisplay}",+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ },+ trailingContent = {+ OverflowMenu {+ if (profile.isEnabled) {+ Item("Disable") { onDisable(profile) }+ } else {+ Item("Enable") { onEnable(profile) }+ }+ Item("Rename") { onRename(profile) }+ Item("Delete") { onDelete(profile) }+ }+ },+ )+ } }- val info = state.info- if (info != null) {- LabeledCard(label = "eUICC info") {- Text("SGP.22 version: ${info.svn.ifEmpty { "unknown" }}")- KeyIdList("CI keys (verification)", info.ciPkIdListForVerification)- KeyIdList("CI keys (signing)", info.ciPkIdListForSigning)+}++@Composable+private fun NotificationsSection(+ notifications: List<Notification>,+ onRemove: (Notification) -> Unit,+) {+ SectionCard(title = "Notifications") {+ if (notifications.isEmpty()) {+ Text("No pending notifications.")+ return@SectionCard+ }+ for (note in notifications) {+ ListItem(+ headlineContent = { Text("#${note.seqNumber} · ${note.operation}") },+ supportingContent = {+ Text(note.address, maxLines = 1, overflow = TextOverflow.Ellipsis)+ },+ trailingContent = {+ TextButton(onClick = { onRemove(note) }) { Text("Remove") }+ },+ ) } } } @Composable-private fun KeyIdList(label: String, ids: List<String>) {- if (ids.isEmpty()) return- Text(label, style = MaterialTheme.typography.labelMedium)- for (id in ids) {- Text(id, maxLines = 1, overflow = TextOverflow.Ellipsis)+private fun EuiccSection(eid: String?, info: EuiccInfo?) {+ SectionCard(title = "eUICC") {+ Text("EID", style = MaterialTheme.typography.labelMedium)+ Text(eid ?: "unavailable")+ if (info != null) {+ Text("SGP.22 version", style = MaterialTheme.typography.labelMedium)+ Text(info.svn.ifEmpty { "unknown" })+ } } } @Composable-private fun LabeledCard(label: String, content: @Composable () -> Unit) {- Card(modifier = Modifier.fillMaxSize()) {+private fun RenameDialog(profile: Profile, onConfirm: (String) -> Unit, onDismiss: () -> Unit) {+ var name by remember { mutableStateOf(profile.nickname) }+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text("Rename profile") },+ text = {+ OutlinedTextField(+ value = name,+ onValueChange = { name = it },+ label = { Text("Nickname") },+ )+ },+ confirmButton = { TextButton(onClick = { onConfirm(name) }) { Text("Save") } },+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },+ )+}++@Composable+private fun SectionCard(title: String, content: @Composable () -> Unit) {+ Card(modifier = Modifier.fillMaxWidth()) { Column(- modifier = Modifier.padding(16.dp),+ modifier = Modifier.padding(16.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp), ) {- Text(label, style = MaterialTheme.typography.titleMedium)+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(title, style = MaterialTheme.typography.titleMedium)+ } content() } }
euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt
diff --git a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.ktindex 3bafeb5c6b..83714ca386 100644--- a/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt+++ b/euicc/src/main/java/com/vayunmathur/euicc/ui/EuiccViewModel.kt@@ -8,46 +8,82 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.euicc.EuiccNative import com.vayunmathur.euicc.data.EuiccInfo+import com.vayunmathur.euicc.data.Notification+import com.vayunmathur.euicc.data.Profile import com.vayunmathur.euicc.telephony.EuiccChannelManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json -/** UI state for the EID / eUICC-info screen. */-sealed interface EuiccUiState {- data object Loading : EuiccUiState- data class Ready(val eid: String?, val info: EuiccInfo?) : EuiccUiState- data class Error(val message: String) : EuiccUiState-}+/** Aggregate UI state for the LPA screen. */+data class EuiccScreenState(+ val loading: Boolean = true,+ val error: String? = null,+ val eid: String? = null,+ val info: EuiccInfo? = null,+ val profiles: List<Profile> = emptyList(),+ val notifications: List<Notification> = emptyList(),+) class EuiccViewModel(app: Application) : AndroidViewModel(app) { private val channelManager = EuiccChannelManager(app) private val json = Json { ignoreUnknownKeys = true } - var state by mutableStateOf<EuiccUiState>(EuiccUiState.Loading)+ var state by mutableStateOf(EuiccScreenState()) private set init {- refresh()+ reload() } - /** Opens the ISD-R channel and reads the EID + EUICCInfo1 off the eUICC. */- fun refresh() {- state = EuiccUiState.Loading+ /** Reads EID, eUICC info, profiles, and notifications in one channel session. */+ fun reload() {+ state = state.copy(loading = true, error = null) viewModelScope.launch {- state = withContext(Dispatchers.IO) {- try {+ val outcome = withContext(Dispatchers.IO) {+ runCatching { channelManager.withIsdrChannel {- val eid = EuiccNative.nativeGetEid()- val info = EuiccNative.nativeGetEuiccInfo()- ?.let { json.decodeFromString<EuiccInfo>(it) }- EuiccUiState.Ready(eid, info)+ EuiccScreenState(+ loading = false,+ eid = EuiccNative.nativeGetEid(),+ info = EuiccNative.nativeGetEuiccInfo()?.let { json.decodeFromString<EuiccInfo>(it) },+ profiles = EuiccNative.nativeGetProfiles()+ ?.let { json.decodeFromString<List<Profile>>(it) } ?: emptyList(),+ notifications = EuiccNative.nativeListNotifications()+ ?.let { json.decodeFromString<List<Notification>>(it) } ?: emptyList(),+ ) }- } catch (e: Exception) {- EuiccUiState.Error(e.message ?: "eUICC unavailable") } }+ state = outcome.getOrElse {+ state.copy(loading = false, error = it.message ?: "eUICC unavailable")+ }+ }+ }++ fun enable(iccid: String) = action { EuiccNative.nativeEnableProfile(iccid) }+ fun disable(iccid: String) = action { EuiccNative.nativeDisableProfile(iccid) }+ fun delete(iccid: String) = action { EuiccNative.nativeDeleteProfile(iccid) }+ fun rename(iccid: String, nickname: String) = action { EuiccNative.nativeSetNickname(iccid, nickname) }+ fun removeNotification(seq: Int) = action { EuiccNative.nativeRemoveNotification(seq) }++ /** Runs a single ES10 mutation in its own channel session, then reloads. */+ private fun action(op: () -> Int) {+ state = state.copy(loading = true, error = null)+ viewModelScope.launch {+ val outcome = withContext(Dispatchers.IO) {+ runCatching { channelManager.withIsdrChannel { op() } }+ }+ val error = outcome.fold(+ onSuccess = { code -> if (code == 0) null else "Operation failed (code $code)" },+ onFailure = { it.message ?: "Operation failed" },+ )+ if (error == null) {+ reload()+ } else {+ state = state.copy(loading = false, error = error)+ } } } }
euicc/src/main/rust/src/es10.rs
diff --git a/euicc/src/main/rust/src/es10.rs b/euicc/src/main/rust/src/es10.rsindex 17e0de47c5..b1aff6b0df 100644--- a/euicc/src/main/rust/src/es10.rs+++ b/euicc/src/main/rust/src/es10.rs@@ -18,6 +18,32 @@ const TAG_SVN: u32 = 0x82; // [2] version (3 octets: major.minor.rev) const TAG_CI_PKID_VERIFICATION: u32 = 0xA9; // [9] SEQUENCE OF SubjectKeyIdentifier const TAG_CI_PKID_SIGNING: u32 = 0xAA; // [10] SEQUENCE OF SubjectKeyIdentifier +const TAG_PROFILE_INFO_LIST: u32 = 0xBF2D; // ES10c GetProfilesInfo request/response+const TAG_PROFILE_LIST_OK: u32 = 0xA0; // [0] SEQUENCE OF ProfileInfo+const TAG_PROFILE_INFO: u32 = 0xE3; // [PRIVATE 3] ProfileInfo+const TAG_ICCID: u32 = 0x5A; // [APPLICATION 26] ICCID (same numeric tag as EID)+const TAG_ISDP_AID: u32 = 0x4F; // [APPLICATION 15] ISD-P AID+const TAG_PROFILE_STATE: u32 = 0x9F70; // [112] ProfileState+const TAG_NICKNAME: u32 = 0x90; // [16] profileNickname UTF8String+const TAG_SPN: u32 = 0x91; // [17] serviceProviderName UTF8String+const TAG_PROFILE_NAME: u32 = 0x92; // [18] profileName UTF8String+const TAG_PROFILE_CLASS: u32 = 0x95; // [21] ProfileClass++const TAG_ENABLE: u32 = 0xBF31; // ES10c EnableProfile+const TAG_DISABLE: u32 = 0xBF32; // ES10c DisableProfile+const TAG_DELETE: u32 = 0xBF33; // ES10c DeleteProfile+const TAG_SET_NICKNAME: u32 = 0xBF29; // ES10c SetNickname+const TAG_REFRESH_FLAG: u32 = 0x81; // [1] refreshFlag BOOLEAN+const TAG_RESULT: u32 = 0x80; // [0] result INTEGER (enable/disable/delete/setNickname)++const TAG_LIST_NOTIFICATION: u32 = 0xBF28; // ES10b ListNotification+const TAG_NOTIFICATION_LIST: u32 = 0xA0; // [0] SEQUENCE OF NotificationMetadata+const TAG_NOTIFICATION_METADATA: u32 = 0xBF2F; // [47] NotificationMetadata+const TAG_SEQ_NUMBER: u32 = 0x80; // [0] seqNumber INTEGER+const TAG_NOTIFICATION_EVENT: u32 = 0x81; // [1] profileManagementOperation BIT STRING+const TAG_NOTIFICATION_ADDRESS: u32 = 0x82; // [2] notificationAddress UTF8String+const TAG_REMOVE_NOTIFICATION: u32 = 0xBF30; // ES10b RemoveNotificationFromList+ /// Parsed subset of EUICCInfo1 useful for display. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EuiccInfo1 {@@ -29,20 +55,46 @@ pub struct EuiccInfo1 { pub ci_pkid_signing: Vec<String>, } +/// One installed profile, as reported by GetProfilesInfo.+#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub struct ProfileInfo {+ /// Raw ICCID octets as hex (nibble-swapped form); used as the command key.+ pub iccid: String,+ /// Human-readable ICCID digits (nibble-swapped and trimmed).+ pub iccid_display: String,+ pub isdp_aid: String,+ /// "enabled", "disabled", or "unknown".+ pub state: String,+ /// "operational", "test", "provisioning", or "unknown".+ pub class: String,+ pub nickname: String,+ pub service_provider: String,+ pub name: String,+}++/// One pending notification, as reported by ListNotification.+#[derive(Debug, Clone, PartialEq, Eq, Default)]+pub struct NotificationInfo {+ pub seq_number: i64,+ /// "install", "enable", "disable", "delete", or "unknown".+ pub operation: String,+ pub address: String,+ pub iccid_display: String,+}++// ---------------------------------------------------------------------------+// GetEID+// ---------------------------------------------------------------------------+ /// Builds the ES10c GetEID request (GetEuiccData with a tag list of `{EID}`). pub fn build_get_eid() -> Vec<u8> {- // BF3E 03 5C 01 5A let tag_list = asn1::tlv(TAG_TAG_LIST, &[TAG_EID as u8]); asn1::tlv(TAG_GET_EUICC_DATA, &tag_list) } /// Parses a GetEuiccData response and returns the EID as 32 hex digits.-///-/// The 16 EID octets already encode the 32 decimal digits (one per nibble), so-/// a plain hex encoding of the octets is the canonical EID string. pub fn parse_eid(response: &[u8]) -> Result<String, String> {- let body = asn1::find(response, TAG_GET_EUICC_DATA)- .ok_or("GetEuiccData: missing BF3E")?;+ let body = asn1::find(response, TAG_GET_EUICC_DATA).ok_or("GetEuiccData: missing BF3E")?; let eid = asn1::find(body, TAG_EID).ok_or("GetEuiccData: missing EID (5A)")?; if eid.len() != 16 { return Err(format!("EID length {} != 16", eid.len()));@@ -50,6 +102,10 @@ pub fn parse_eid(response: &[u8]) -> Result<String, String> { Ok(hex(eid)) } +// ---------------------------------------------------------------------------+// GetEUICCInfo1+// ---------------------------------------------------------------------------+ /// Builds the ES10c GetEUICCInfo1 request (empty BF20). pub fn build_get_euicc_info1() -> Vec<u8> { asn1::tlv(TAG_EUICC_INFO1, &[])@@ -78,6 +134,160 @@ pub fn parse_euicc_info1(response: &[u8]) -> Result<EuiccInfo1, String> { }) } +// ---------------------------------------------------------------------------+// GetProfilesInfo+// ---------------------------------------------------------------------------++/// Builds the ES10c GetProfilesInfo request with a tag list of the fields we+/// display.+pub fn build_get_profiles() -> Vec<u8> {+ // Two-byte tag 9F70 is included as its two octets; the rest are one byte.+ let tags: &[u8] = &[+ TAG_ICCID as u8,+ TAG_ISDP_AID as u8,+ 0x9F,+ 0x70,+ TAG_NICKNAME as u8,+ TAG_SPN as u8,+ TAG_PROFILE_NAME as u8,+ TAG_PROFILE_CLASS as u8,+ ];+ let tag_list = asn1::tlv(TAG_TAG_LIST, tags);+ asn1::tlv(TAG_PROFILE_INFO_LIST, &tag_list)+}++/// Parses a GetProfilesInfo response into the list of installed profiles.+pub fn parse_profiles(response: &[u8]) -> Result<Vec<ProfileInfo>, String> {+ let body = asn1::find(response, TAG_PROFILE_INFO_LIST).ok_or("ProfileInfoList: missing BF2D")?;+ // profileInfoListOk [0]; absent means an error CHOICE was returned.+ let ok = asn1::find(body, TAG_PROFILE_LIST_OK)+ .ok_or("ProfileInfoList: error result (no A0)")?;++ let mut profiles = Vec::new();+ for child in asn1::children(ok).ok_or("ProfileInfoList: malformed list")? {+ if child.tag != TAG_PROFILE_INFO {+ continue;+ }+ let p = child.value;+ let raw_iccid = asn1::find(p, TAG_ICCID).unwrap_or(&[]);+ profiles.push(ProfileInfo {+ iccid: hex(raw_iccid),+ iccid_display: decode_iccid(raw_iccid),+ isdp_aid: asn1::find(p, TAG_ISDP_AID).map(hex).unwrap_or_default(),+ state: match asn1::find(p, TAG_PROFILE_STATE).and_then(first_byte) {+ Some(0) => "disabled".into(),+ Some(1) => "enabled".into(),+ _ => "unknown".into(),+ },+ class: match asn1::find(p, TAG_PROFILE_CLASS).and_then(first_byte) {+ Some(0) => "test".into(),+ Some(1) => "provisioning".into(),+ Some(2) => "operational".into(),+ _ => "unknown".into(),+ },+ nickname: asn1::find(p, TAG_NICKNAME).map(utf8).unwrap_or_default(),+ service_provider: asn1::find(p, TAG_SPN).map(utf8).unwrap_or_default(),+ name: asn1::find(p, TAG_PROFILE_NAME).map(utf8).unwrap_or_default(),+ });+ }+ Ok(profiles)+}++// ---------------------------------------------------------------------------+// Enable / Disable / Delete / SetNickname+// ---------------------------------------------------------------------------++/// Builds an EnableProfile request keyed by ICCID.+pub fn build_enable(iccid: &[u8], refresh: bool) -> Vec<u8> {+ let mut v = asn1::tlv(TAG_ICCID, iccid);+ v.extend(asn1::tlv(TAG_REFRESH_FLAG, &[if refresh { 0xFF } else { 0x00 }]));+ asn1::tlv(TAG_ENABLE, &v)+}++/// Builds a DisableProfile request keyed by ICCID.+pub fn build_disable(iccid: &[u8], refresh: bool) -> Vec<u8> {+ let mut v = asn1::tlv(TAG_ICCID, iccid);+ v.extend(asn1::tlv(TAG_REFRESH_FLAG, &[if refresh { 0xFF } else { 0x00 }]));+ asn1::tlv(TAG_DISABLE, &v)+}++/// Builds a DeleteProfile request keyed by ICCID.+pub fn build_delete(iccid: &[u8]) -> Vec<u8> {+ let inner = asn1::tlv(TAG_ICCID, iccid);+ asn1::tlv(TAG_DELETE, &inner)+}++/// Builds a SetNickname request for a profile keyed by ICCID.+pub fn build_set_nickname(iccid: &[u8], nickname: &str) -> Vec<u8> {+ let mut v = asn1::tlv(TAG_ICCID, iccid);+ v.extend(asn1::tlv(TAG_NICKNAME, nickname.as_bytes()));+ asn1::tlv(TAG_SET_NICKNAME, &v)+}++/// Parses the INTEGER result of Enable/Disable/Delete/SetNickname. 0 = success.+pub fn parse_result(response: &[u8], tag: u32) -> Result<i64, String> {+ let body = asn1::find(response, tag).ok_or("result: missing response TLV")?;+ let code = asn1::find(body, TAG_RESULT).ok_or("result: missing code (80)")?;+ Ok(parse_int(code))+}++/// Result tag for an EnableProfile response.+pub const RESULT_TAG_ENABLE: u32 = TAG_ENABLE;+pub const RESULT_TAG_DISABLE: u32 = TAG_DISABLE;+pub const RESULT_TAG_DELETE: u32 = TAG_DELETE;+pub const RESULT_TAG_SET_NICKNAME: u32 = TAG_SET_NICKNAME;++// ---------------------------------------------------------------------------+// Notifications+// ---------------------------------------------------------------------------++/// Builds the ES10b ListNotification request (all events).+pub fn build_list_notifications() -> Vec<u8> {+ asn1::tlv(TAG_LIST_NOTIFICATION, &[])+}++/// Parses a ListNotification response into pending notifications.+pub fn parse_notifications(response: &[u8]) -> Result<Vec<NotificationInfo>, String> {+ let body = asn1::find(response, TAG_LIST_NOTIFICATION).ok_or("ListNotification: missing BF28")?;+ let list = asn1::find(body, TAG_NOTIFICATION_LIST)+ .ok_or("ListNotification: error result (no A0)")?;++ let mut out = Vec::new();+ for child in asn1::children(list).ok_or("ListNotification: malformed list")? {+ if child.tag != TAG_NOTIFICATION_METADATA {+ continue;+ }+ let m = child.value;+ out.push(NotificationInfo {+ seq_number: asn1::find(m, TAG_SEQ_NUMBER).map(parse_int).unwrap_or(-1),+ operation: asn1::find(m, TAG_NOTIFICATION_EVENT)+ .map(decode_event)+ .unwrap_or_else(|| "unknown".into()),+ address: asn1::find(m, TAG_NOTIFICATION_ADDRESS).map(utf8).unwrap_or_default(),+ iccid_display: asn1::find(m, TAG_ICCID).map(decode_iccid).unwrap_or_default(),+ });+ }+ Ok(out)+}++/// Builds the ES10b RemoveNotificationFromList request for a sequence number.+pub fn build_remove_notification(seq: u32) -> Vec<u8> {+ let inner = asn1::tlv(TAG_SEQ_NUMBER, &encode_int_minimal(seq));+ asn1::tlv(TAG_REMOVE_NOTIFICATION, &inner)+}++/// Parses the RemoveNotificationFromList result. 0 = success.+pub fn parse_remove_result(response: &[u8]) -> Result<i64, String> {+ let body = asn1::find(response, TAG_REMOVE_NOTIFICATION)+ .ok_or("RemoveNotification: missing BF30")?;+ let code = asn1::find(body, TAG_SEQ_NUMBER).ok_or("RemoveNotification: missing code")?;+ Ok(parse_int(code))+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------+ /// Lowercase hex encoding. pub fn hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2);@@ -87,6 +297,99 @@ pub fn hex(bytes: &[u8]) -> String { s } +/// Decodes hex, returning empty on malformed input.+pub fn hex_decode(s: &str) -> Vec<u8> {+ if s.len() % 2 != 0 {+ return Vec::new();+ }+ let mut out = Vec::with_capacity(s.len() / 2);+ let bytes = s.as_bytes();+ let mut i = 0;+ while i < bytes.len() {+ let hi = (bytes[i] as char).to_digit(16);+ let lo = (bytes[i + 1] as char).to_digit(16);+ match (hi, lo) {+ (Some(h), Some(l)) => out.push((h * 16 + l) as u8),+ _ => return Vec::new(),+ }+ i += 2;+ }+ out+}++fn first_byte(v: &[u8]) -> Option<u8> {+ v.first().copied()+}++fn utf8(v: &[u8]) -> String {+ String::from_utf8_lossy(v).into_owned()+}++/// Parses a (short) two's-complement BER INTEGER into i64.+fn parse_int(v: &[u8]) -> i64 {+ if v.is_empty() {+ return 0;+ }+ let mut acc: i64 = if v[0] & 0x80 != 0 { -1 } else { 0 };+ for &b in v {+ acc = (acc << 8) | b as i64;+ }+ acc+}++/// Minimal unsigned big-endian INTEGER encoding (always at least one byte, with+/// a leading zero when the top bit would otherwise make it negative).+fn encode_int_minimal(mut v: u32) -> Vec<u8> {+ if v == 0 {+ return vec![0];+ }+ let mut bytes = Vec::new();+ while v > 0 {+ bytes.insert(0, (v & 0xFF) as u8);+ v >>= 8;+ }+ if bytes[0] & 0x80 != 0 {+ bytes.insert(0, 0x00);+ }+ bytes+}++/// Decodes an SGP.22 ICCID (BCD, nibble-swapped, F-padded) into decimal digits.+fn decode_iccid(raw: &[u8]) -> String {+ let mut s = String::with_capacity(raw.len() * 2);+ for &b in raw {+ let lo = b & 0x0F;+ let hi = b >> 4;+ for nib in [lo, hi] {+ if nib == 0x0F {+ continue;+ }+ if nib < 10 {+ s.push((b'0' + nib) as char);+ }+ }+ }+ s+}++/// Decodes a NotificationEvent BIT STRING into the first set operation label.+fn decode_event(v: &[u8]) -> String {+ // BIT STRING: first byte is the count of unused bits, then the bit octets.+ let data = v.get(1).copied().unwrap_or(0);+ // Bit 0 is the MSB of the first data octet.+ if data & 0x80 != 0 {+ "install".into()+ } else if data & 0x40 != 0 {+ "enable".into()+ } else if data & 0x20 != 0 {+ "disable".into()+ } else if data & 0x10 != 0 {+ "delete".into()+ } else {+ "unknown".into()+ }+}+ #[cfg(test)] mod tests { use super::*;@@ -98,7 +401,6 @@ mod tests { #[test] fn parse_eid_from_response() {- // BF3E 12 5A 10 <89 04 40 ... 16 octets> let mut inner = vec![0x5A, 0x10]; let octets: [u8; 16] = [ 0x89, 0x04, 0x40, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,@@ -117,16 +419,8 @@ mod tests { #[test] fn parse_euicc_info1_svn_and_lists() { let svn = asn1::tlv(TAG_SVN, &[0x02, 0x02, 0x00]);- let ver_list = {- let mut kids = Vec::new();- kids.extend(asn1::tlv(0x04, &[0xAA; 20]));- asn1::tlv(TAG_CI_PKID_VERIFICATION, &kids)- };- let sign_list = {- let mut kids = Vec::new();- kids.extend(asn1::tlv(0x04, &[0xBB; 20]));- asn1::tlv(TAG_CI_PKID_SIGNING, &kids)- };+ let ver_list = asn1::tlv(TAG_CI_PKID_VERIFICATION, &asn1::tlv(0x04, &[0xAA; 20]));+ let sign_list = asn1::tlv(TAG_CI_PKID_SIGNING, &asn1::tlv(0x04, &[0xBB; 20])); let mut body = Vec::new(); body.extend(svn); body.extend(ver_list);@@ -138,4 +432,94 @@ mod tests { assert_eq!(info.ci_pkid_verification, vec!["aa".repeat(20)]); assert_eq!(info.ci_pkid_signing, vec!["bb".repeat(20)]); }++ #[test]+ fn iccid_decoding() {+ // 98 10 32 -> swap each byte -> "890123"+ assert_eq!(decode_iccid(&[0x98, 0x10, 0x32]), "890123");+ // Trailing F is padding and dropped.+ assert_eq!(decode_iccid(&[0x21, 0xF3]), "123");+ }++ #[test]+ fn parse_profiles_list() {+ let iccid = [0x98, 0x10, 0x32, 0x54, 0x76];+ let mut p = Vec::new();+ p.extend(asn1::tlv(TAG_ICCID, &iccid));+ p.extend(asn1::tlv(TAG_PROFILE_STATE, &[0x01])); // enabled+ p.extend(asn1::tlv(TAG_PROFILE_CLASS, &[0x02])); // operational+ p.extend(asn1::tlv(TAG_NICKNAME, "Work".as_bytes()));+ p.extend(asn1::tlv(TAG_SPN, "Carrier".as_bytes()));+ let profile = asn1::tlv(TAG_PROFILE_INFO, &p);+ let ok = asn1::tlv(TAG_PROFILE_LIST_OK, &profile);+ let resp = asn1::tlv(TAG_PROFILE_INFO_LIST, &ok);++ let profiles = parse_profiles(&resp).unwrap();+ assert_eq!(profiles.len(), 1);+ let pi = &profiles[0];+ assert_eq!(pi.iccid, "9810325476");+ assert_eq!(pi.iccid_display, "8901234567");+ assert_eq!(pi.state, "enabled");+ assert_eq!(pi.class, "operational");+ assert_eq!(pi.nickname, "Work");+ assert_eq!(pi.service_provider, "Carrier");+ }++ #[test]+ fn enable_disable_delete_requests() {+ let iccid = [0x11, 0x22, 0x33];+ assert_eq!(+ build_enable(&iccid, true),+ vec![0xBF, 0x31, 0x08, 0x5A, 0x03, 0x11, 0x22, 0x33, 0x81, 0x01, 0xFF],+ );+ assert_eq!(+ build_disable(&iccid, false),+ vec![0xBF, 0x32, 0x08, 0x5A, 0x03, 0x11, 0x22, 0x33, 0x81, 0x01, 0x00],+ );+ assert_eq!(+ build_delete(&iccid),+ vec![0xBF, 0x33, 0x05, 0x5A, 0x03, 0x11, 0x22, 0x33],+ );+ }++ #[test]+ fn set_nickname_request() {+ let iccid = [0xAA, 0xBB];+ assert_eq!(+ build_set_nickname(&iccid, "Hi"),+ vec![0xBF, 0x29, 0x08, 0x5A, 0x02, 0xAA, 0xBB, 0x90, 0x02, b'H', b'i'],+ );+ }++ #[test]+ fn parse_result_code() {+ let body = asn1::tlv(TAG_RESULT, &[0x00]);+ let resp = asn1::tlv(TAG_ENABLE, &body);+ assert_eq!(parse_result(&resp, RESULT_TAG_ENABLE).unwrap(), 0);+ }++ #[test]+ fn remove_notification_request() {+ assert_eq!(+ build_remove_notification(5),+ vec![0xBF, 0x30, 0x03, 0x80, 0x01, 0x05],+ );+ }++ #[test]+ fn parse_notifications_list() {+ let mut m = Vec::new();+ m.extend(asn1::tlv(TAG_SEQ_NUMBER, &[0x03]));+ m.extend(asn1::tlv(TAG_NOTIFICATION_EVENT, &[0x00, 0x40])); // enable+ m.extend(asn1::tlv(TAG_NOTIFICATION_ADDRESS, "smdp.example.com".as_bytes()));+ let meta = asn1::tlv(TAG_NOTIFICATION_METADATA, &m);+ let list = asn1::tlv(TAG_NOTIFICATION_LIST, &meta);+ let resp = asn1::tlv(TAG_LIST_NOTIFICATION, &list);++ let notes = parse_notifications(&resp).unwrap();+ assert_eq!(notes.len(), 1);+ assert_eq!(notes[0].seq_number, 3);+ assert_eq!(notes[0].operation, "enable");+ assert_eq!(notes[0].address, "smdp.example.com");+ } }
euicc/src/main/rust/src/jni.rs
diff --git a/euicc/src/main/rust/src/jni.rs b/euicc/src/main/rust/src/jni.rsindex a6bf8b8651..04248b0877 100644--- a/euicc/src/main/rust/src/jni.rs+++ b/euicc/src/main/rust/src/jni.rs@@ -7,8 +7,8 @@ //! the `EuiccNative.transmitApdu` upcall (which owns the telephony logical //! channel on the Kotlin side), and converts results to Kotlin types. -use jni::objects::{JByteArray, JClass, JValue};-use jni::sys::jstring;+use jni::objects::{JByteArray, JClass, JString, JValue};+use jni::sys::{jint, jstring}; use jni::JNIEnv; use crate::{es10, VERSION};@@ -84,6 +84,154 @@ fn new_jstring(env: &JNIEnv, s: &str) -> jstring { } } +/// Reads a Java string into a Rust `String`, or `None` on error.+fn read_string(env: &mut JNIEnv, s: &JString) -> Option<String> {+ env.get_string(s).ok().map(|js| js.into())+}++/// Sends a request and parses its INTEGER result, returning the eUICC result+/// code (0 = success) or -1 on a transport/parse error.+fn run_result(env: &mut JNIEnv, request: &[u8], tag: u32) -> jint {+ match store_data(env, request).and_then(|resp| es10::parse_result(&resp, tag)) {+ Ok(code) => code as jint,+ Err(_) => -1,+ }+}++/// `nativeGetProfiles()` — installed profiles as a JSON array, or null on error.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeGetProfiles<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+) -> jstring {+ let result = store_data(&mut env, &es10::build_get_profiles())+ .and_then(|resp| es10::parse_profiles(&resp));+ match result {+ Ok(profiles) => {+ let arr: Vec<_> = profiles+ .iter()+ .map(|p| {+ serde_json::json!({+ "iccid": p.iccid,+ "iccidDisplay": p.iccid_display,+ "isdpAid": p.isdp_aid,+ "state": p.state,+ "class": p.class,+ "nickname": p.nickname,+ "serviceProvider": p.service_provider,+ "name": p.name,+ })+ })+ .collect();+ new_jstring(&env, &serde_json::Value::Array(arr).to_string())+ }+ Err(_) => std::ptr::null_mut(),+ }+}++/// `nativeEnableProfile(iccid)` — 0 on success, eUICC error code, or -1.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeEnableProfile<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ iccid: JString<'l>,+) -> jint {+ let Some(hex) = read_string(&mut env, &iccid) else {+ return -1;+ };+ run_result(&mut env, &es10::build_enable(&es10::hex_decode(&hex), true), es10::RESULT_TAG_ENABLE)+}++/// `nativeDisableProfile(iccid)` — 0 on success, eUICC error code, or -1.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeDisableProfile<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ iccid: JString<'l>,+) -> jint {+ let Some(hex) = read_string(&mut env, &iccid) else {+ return -1;+ };+ run_result(&mut env, &es10::build_disable(&es10::hex_decode(&hex), true), es10::RESULT_TAG_DISABLE)+}++/// `nativeDeleteProfile(iccid)` — 0 on success, eUICC error code, or -1.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeDeleteProfile<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ iccid: JString<'l>,+) -> jint {+ let Some(hex) = read_string(&mut env, &iccid) else {+ return -1;+ };+ run_result(&mut env, &es10::build_delete(&es10::hex_decode(&hex)), es10::RESULT_TAG_DELETE)+}++/// `nativeSetNickname(iccid, nickname)` — 0 on success, eUICC error code, or -1.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeSetNickname<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ iccid: JString<'l>,+ nickname: JString<'l>,+) -> jint {+ let (Some(hex), Some(name)) = (read_string(&mut env, &iccid), read_string(&mut env, &nickname))+ else {+ return -1;+ };+ run_result(+ &mut env,+ &es10::build_set_nickname(&es10::hex_decode(&hex), &name),+ es10::RESULT_TAG_SET_NICKNAME,+ )+}++/// `nativeListNotifications()` — pending notifications as a JSON array, or null.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeListNotifications<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+) -> jstring {+ let result = store_data(&mut env, &es10::build_list_notifications())+ .and_then(|resp| es10::parse_notifications(&resp));+ match result {+ Ok(notes) => {+ let arr: Vec<_> = notes+ .iter()+ .map(|n| {+ serde_json::json!({+ "seqNumber": n.seq_number,+ "operation": n.operation,+ "address": n.address,+ "iccidDisplay": n.iccid_display,+ })+ })+ .collect();+ new_jstring(&env, &serde_json::Value::Array(arr).to_string())+ }+ Err(_) => std::ptr::null_mut(),+ }+}++/// `nativeRemoveNotification(seq)` — 0 on success, eUICC error code, or -1.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeRemoveNotification<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ seq: jint,+) -> jint {+ if seq < 0 {+ return -1;+ }+ match store_data(&mut env, &es10::build_remove_notification(seq as u32))+ .and_then(|resp| es10::parse_remove_result(&resp))+ {+ Ok(code) => code as jint,+ Err(_) => -1,+ }+}+ /// `nativeVersion()` — native core version string. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_euicc_EuiccNative_nativeVersion<'l>(