Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsProvisioning.kt

RcsProvisioning.kt276 lines · 13.2 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import android.telephony.ims.stub.ImsRegistrationImplBase
4import android.telephony.ims.feature.MmTelFeature
5import android.Manifest
6import android.content.Context
7import android.content.pm.PackageManager
8import android.telephony.CarrierConfigManager
9import android.telephony.SubscriptionManager
10import android.telephony.TelephonyManager
11import android.telephony.ims.ImsManager
12import com.vayunmathur.library.log.Log
13import androidx.core.content.ContextCompat
14import com.vayunmathur.library.network.NetworkClient
15import kotlinx.coroutines.flow.MutableStateFlow
16import kotlinx.coroutines.flow.StateFlow
17import kotlinx.coroutines.flow.asStateFlow
18
19/**
20 * Why the RCS transport is unavailable. Surfaced in the UI so an unprovisioned
21 * SIM (e.g. Astound with an empty `rcs_config_server_url`) reads as a reason,
22 * not a silent failure.
23 */
24enum class RcsUnavailableReason {
25 NoEntitlementUrl,
26 NoCarrierPrivilege,
27 NotSupported,
28 NoSubscription,
29 ProvisioningRequired,
30 UceDisabled,
31 TransportDenied,
32 ServiceUnavailable,
33 Unknown,
34}
35
36/**
37 * Lifecycle of the RCS single-registration transport.
38 *
39 * `Disabled` is the release-build state (gate off). Everything else is dev-only.
40 * There are no RCS credentials to persist — provisioning IS the session — so
41 * this doubles as the line session: `Available` means signed-in.
42 */
43sealed interface RcsRegistrationState {
44 /** Registration state not yet determined. */
45 data object Unknown : RcsRegistrationState
46 /** Carrier RCS provisioning is in progress. */
47 data object Provisioning : RcsRegistrationState
48 /** RCS is provisioned and available. */
49 data object Available : RcsRegistrationState
50 /** RCS is unavailable, with the reason. */
51 data class Unavailable(val reason: RcsUnavailableReason) : RcsRegistrationState
52 /** RCS is disabled (release builds / gate off). */
53 data object Disabled : RcsRegistrationState
54}
55
56/**
57 * TS.43 entitlement + carrier-config provisioning check.
58 *
59 * Reads `rcs_config_server_url` for the active data subscription; an empty URL
60 * means the carrier never provisioned RCS (the Astound case) and maps to
61 * [RcsUnavailableReason.NoEntitlementUrl]. Never throws; caches the last
62 * result. All entry points early-return `Disabled` when the dev gate is off so
63 * release builds strip cleanly.
64 */
65object RcsProvisioning {
66 private const val TAG = "RcsProvisioning"
67
68 private val _state = MutableStateFlow<RcsRegistrationState>(RcsRegistrationState.Unknown)
69 val state: StateFlow<RcsRegistrationState> = _state.asStateFlow()
70
71 /** Last carrier config URL seen, for the status screen. Null = never probed. */
72 @Volatile
73 var lastConfigServerUrl: String? = null
74 private set
75
76 fun reset() {
77 _state.value = if (RcsFeature.enabled) RcsRegistrationState.Unknown else RcsRegistrationState.Disabled
78 lastConfigServerUrl = null
79 }
80
81 /**
82 * Run the provisioning check for [subscriptionId] (defaults to the default
83 * SMS subscription, mirroring TestRcsApp). Updates [state]; also returns it.
84 */
85 suspend fun probe(context: Context, subscriptionId: Int = defaultSubscriptionId()): RcsRegistrationState {
86 if (!RcsFeature.enabled) {
87 _state.value = RcsRegistrationState.Disabled
88 return _state.value
89 }
90 _state.value = RcsRegistrationState.Provisioning
91 _state.value = checkProvisioning(context.applicationContext, subscriptionId)
92 return _state.value
93 }
94
95 private fun checkProvisioning(context: Context, subscriptionId: Int): RcsRegistrationState {
96 if (!SubscriptionManager.isValidSubscriptionId(subscriptionId)) {
97 Log.status(TAG, "probe: invalid subId=$subscriptionId")
98 return RcsRegistrationState.Unavailable(RcsUnavailableReason.NoSubscription)
99 }
100 readConfigServerUrl(context, subscriptionId)?.let { return it }
101 provisioningGate(context, subscriptionId)?.let { return it }
102 singleRegGate(context, subscriptionId)?.let { return it }
103 Log.status(TAG, "probe: AVAILABLE for subId=$subscriptionId")
104 return RcsRegistrationState.Available
105 }
106
107 /** Carrier-config URL probe; returns a terminal state, or null to continue. */
108 private fun readConfigServerUrl(context: Context, subscriptionId: Int): RcsRegistrationState? {
109 // Carrier config is the source of truth for "does this SIM do RCS".
110 // Keyed query avoids the deprecated whole-bundle getter.
111 val url = try {
112 val ccm = context.getSystemService(CarrierConfigManager::class.java)
113 ?: return RcsRegistrationState.Unavailable(
114 RcsUnavailableReason.ServiceUnavailable,
115 )
116 // The keyed getter is API 34+; on 31-33 fall back to the
117 // whole-bundle getter for the subscription and read the key.
118 val bundle = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
119 ccm.getConfigForSubId(
120 subscriptionId,
121 CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING,
122 )
123 } else {
124 @Suppress("DEPRECATION")
125 ccm.getConfigForSubId(subscriptionId)
126 }
127 bundle?.getString(CarrierConfigManager.KEY_RCS_CONFIG_SERVER_URL_STRING).orEmpty()
128 } catch (e: SecurityException) {
129 Log.status(TAG, "probe: carrier-config read denied: $e")
130 return RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)
131 } catch (e: IllegalStateException) {
132 Log.status(TAG, "probe: carrier-config read failed: $e")
133 return RcsRegistrationState.Unavailable(RcsUnavailableReason.ServiceUnavailable)
134 }
135 lastConfigServerUrl = url.ifEmpty { null }
136 // Note — an empty config URL no longer hard-blocks. MVNOs and
137 // Jibe-backed carriers (US Mobile, for one) routinely leave the
138 // rcs_config_server_url key empty while still accepting a single-reg
139 // delegate; the delegate request itself is the real test, and a denial
140 // surfaces as TransportDenied via onFeatureTagStatusChanged. The URL
141 // is still recorded for the status screen and the TS.43 entitlement.
142 if (url.isBlank()) {
143 Log.status(
144 "RcsProvisioning",
145 "No carrier RCS config URL; attempting delegate creation anyway",
146 )
147 }
148 return null
149 }
150
151 /** Provisioning-manager gate; returns a terminal state, or null to continue. */
152 private fun provisioningGate(context: Context, subscriptionId: Int): RcsRegistrationState? {
153 // Secondary signal: the provisioning manager's status for the
154 // call-composer capability (an MmTel capability, so the non-RCS
155 // provisioning pair is the correct query). The provisioning manager
156 // is API 33+ and needs READ_PRECISE_PHONE_STATE; without either, this
157 // gate degrades to "not required" — the carrier-config URL above is
158 // the authoritative gate.
159 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return null
160 // READ_PRECISE_PHONE_STATE is declared in the manifest; it is only
161 // granted to carrier-privileged builds, and the SecurityException
162 // catch below degrades to "not required" everywhere else.
163 val provisioningRequired = try {
164 val ims = context.getSystemService(ImsManager::class.java)
165 ?: return null
166 val pm = ims.getProvisioningManager(subscriptionId)
167 pm.isProvisioningRequiredForCapability(
168 MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
169 ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
170 ) && !pm.getProvisioningStatusForCapability(
171 MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
172 ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
173 )
174 } catch (_: SecurityException) {
175 false
176 } catch (_: Exception) {
177 false
178 }
179 if (provisioningRequired) {
180 Log.status(TAG, "probe: carrier provisioning required (call-composer cap unprovisioned)")
181 return RcsRegistrationState.Unavailable(RcsUnavailableReason.ProvisioningRequired)
182 }
183 return null
184 }
185
186 /** Single-registration support gate; returns a terminal state, or null to continue. */
187 private fun singleRegGate(context: Context, subscriptionId: Int): RcsRegistrationState? {
188 // Tertiary signal, after TestRcsApp's ProvisioningActivity: the hidden
189 // single-registration-capability query on the per-sub manager. It is
190 // tri-state — a null result (bridge failure, say the role is not yet
191 // granted) means unknown rather than not capable, so it never blocks
192 // on permission errors.
193 val singleRegCapable = runCatching {
194 val pm = RcsHiddenApi.provisioningManager(subscriptionId)
195 ?: return@runCatching null
196 RcsHiddenApi.isSingleRegCapable(pm)
197 }.getOrDefault(null)
198 if (singleRegCapable == false) {
199 // Framework verdict is negative: distinguish "device can't" from
200 // "carrier won't". Carrier privilege decides which: without it
201 // the carrier blocks every IMS path (delegate SecurityException,
202 // direct-socket EPERM, no GBA). hasCarrierPrivileges is public API.
203 val privileged = runCatching {
204 val tm = context.getSystemService(TelephonyManager::class.java)
205 val subTm = runCatching { tm?.createForSubscriptionId(subscriptionId) }
206 .getOrNull() ?: tm
207 subTm?.hasCarrierPrivileges() == true
208 }.getOrDefault(false)
209 Log.status(TAG, "probe: single-reg verdict=false privileged=$privileged subId=$subscriptionId")
210 return if (privileged) {
211 RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported)
212 } else {
213 RcsRegistrationState.Unavailable(RcsUnavailableReason.NoCarrierPrivilege)
214 }
215 }
216 // Single-registration support gate: without it there is no delegate to create.
217 // The feature constant is @SystemApi/hidden; the AOSP value is used directly.
218 val singleReg = context.packageManager.hasSystemFeature(FEATURE_SINGLE_REG)
219 Log.status(TAG, "probe: singleRegCapable=$singleRegCapable hasFeature=$singleReg")
220 if (!singleReg) {
221 return RcsRegistrationState.Unavailable(RcsUnavailableReason.NotSupported)
222 }
223 return null
224 }
225
226 /**
227 * TS.43 entitlement check against the carrier config server (§7.1).
228 * Real flow: GET `<url>?vers=<version>&terminal=<model>` with the
229 * proper Accept header; a 200 whose body names an RCS config endpoint
230 * means entitled. Best-effort: any failure maps to false, never throws.
231 * The carrier URL is dynamic, so system trust is used.
232 */
233 suspend fun entitlementCheck(url: String): Boolean {
234 if (!RcsFeature.enabled || url.isBlank()) return false
235 return runCatching {
236 val terminal = "${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}"
237 val query = url + (if (url.contains("?")) "&" else "?") +
238 "vers=1.0&terminal=${java.net.URLEncoder.encode(terminal, "UTF-8")}"
239 val response = NetworkClient.performRequest(
240 url = query,
241 method = "GET",
242 headers = mapOf("Accept" to "text/xml, application/xml, text/plain"),
243 useSystemTrust = true,
244 )
245 if (!response.isSuccess) return@runCatching false
246 // Entitled responses name the config server / token. Absent both
247 // but HTTP-200 → treat as entitled (some carriers return empty).
248 val body = response.body
249 body.isBlank() || body.contains("config", ignoreCase = true) ||
250 body.contains("token", ignoreCase = true) ||
251 body.contains("rcs", ignoreCase = true)
252 }.getOrDefault(false)
253 }
254
255 private fun defaultSubscriptionId(): Int = runCatching {
256 // TestRcsApp keys everything off the default SMS subscription.
257 SubscriptionManager.getDefaultSmsSubscriptionId()
258 }.getOrDefault(SubscriptionManager.INVALID_SUBSCRIPTION_ID)
259
260 fun hasPhoneStatePermission(context: Context): Boolean =
261 ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) ==
262 PackageManager.PERMISSION_GRANTED
263
264 /**
265 * Device-level single-reg feature flag (framework capability, not carrier
266 * verdict). True on your Pixel 8 even when the carrier profile reports
267 * single-reg NOT capable — that combination routes to direct SIP.
268 */
269 fun deviceSupportsSingleReg(context: Context): Boolean =
270 context.packageManager.hasSystemFeature(FEATURE_SINGLE_REG)
271
272 // AOSP values from hidden surface (verified against frameworks/base main).
273 // Call-composer is an MmTel capability (1 shl 4) and LTE the registration
274 // tech, expressed with the public provisioning constants below.
275 private const val FEATURE_SINGLE_REG = "android.hardware.telephony.ims.singlereg"
276}