Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsImsNetwork.kt
RcsImsNetwork.kt253 lines · 10.7 KiBRaw
| 1 | package com.vayunmathur.communicate.data.rcs |
| 2 | |
| 3 | import android.content.Context |
| 4 | import android.net.ConnectivityManager |
| 5 | import android.net.Network |
| 6 | import android.net.NetworkCapabilities |
| 7 | import android.net.NetworkRequest |
| 8 | import android.os.Build |
| 9 | import android.telephony.SubscriptionManager |
| 10 | import com.vayunmathur.library.log.Log |
| 11 | import java.net.InetAddress |
| 12 | import java.net.InetSocketAddress |
| 13 | import java.net.ServerSocket |
| 14 | import java.net.Socket |
| 15 | import kotlin.coroutines.resume |
| 16 | import kotlinx.coroutines.suspendCancellableCoroutine |
| 17 | import kotlinx.coroutines.withTimeoutOrNull |
| 18 | |
| 19 | /** |
| 20 | * IMS PDN access for RCS media (MSRP sockets). |
| 21 | * |
| 22 | * Mirrors TestRcsApp's `ImsPdnNetworkFetcher` (NET_CAPABILITY_IMS request → |
| 23 | * cached `Network` → `network.socketFactory` sockets bound to the IMS PDN) |
| 24 | * without Guava: one-shot `requestNetwork` calls wrapped in suspend functions |
| 25 | * with a bounded wait, so a missing IMS PDN degrades to a plain socket instead |
| 26 | * of hanging. |
| 27 | * |
| 28 | * Raw sockets are inherent here (MSRP is a TCP protocol, not HTTP — no HTTP |
| 29 | * client can speak it); FT-over-HTTP stays on `NetworkClient` per the |
| 30 | * networking rules. |
| 31 | * |
| 32 | * Every entry point early-returns null when the dev gate is off and never |
| 33 | * throws; callers fall back to unbound sockets. |
| 34 | */ |
| 35 | object RcsImsNetwork { |
| 36 | private const val TAG = "RcsImsNetwork" |
| 37 | |
| 38 | /** How long to wait for the IMS network before falling back. */ |
| 39 | private const val REQUEST_TIMEOUT_MS = 15_000L |
| 40 | |
| 41 | /** Cached IMS network; invalidated when a socket bind fails. */ |
| 42 | @Volatile |
| 43 | private var cached: Network? = null |
| 44 | |
| 45 | /** Last IMS-PDN local address seen, for SDP offers. Null = unknown. */ |
| 46 | @Volatile |
| 47 | var lastLocalIp: String? = null |
| 48 | private set |
| 49 | |
| 50 | /** |
| 51 | * The IMS PDN `Network`, requesting it when not cached. Null when |
| 52 | * unavailable (no IMS PDN, timeout, or permission failure). |
| 53 | * |
| 54 | * Two paths: (1) scan already-up networks for IMS capability (no request |
| 55 | * needed — the PDN is typically already connected for VoLTE); (2) a |
| 56 | * specifier-pinned `requestNetwork` (CELLULAR + IMS + MMTEL + |
| 57 | * TelephonyNetworkSpecifier, mirroring the system's own IMS request — |
| 58 | * a bare IMS request doesn't match the specifier-gated NetworkAgent). |
| 59 | */ |
| 60 | suspend fun imsNetwork(context: Context, subId: Int = SubscriptionManager.INVALID_SUBSCRIPTION_ID): Network? { |
| 61 | if (!RcsFeature.enabled) return null |
| 62 | cached?.let { return it } |
| 63 | val cm = runCatching { |
| 64 | context.applicationContext.getSystemService(ConnectivityManager::class.java) |
| 65 | }.getOrNull() ?: return null |
| 66 | // Path 1: already-up scan (fast, no request). |
| 67 | scanForIms(cm)?.let { network -> |
| 68 | cached = network |
| 69 | lastLocalIp = localIpFor(context, network) |
| 70 | return network |
| 71 | } |
| 72 | // Path 2: pinned request. |
| 73 | val network = withTimeoutOrNull(REQUEST_TIMEOUT_MS) { |
| 74 | suspendCancellableCoroutine { cont -> |
| 75 | val builder = NetworkRequest.Builder() |
| 76 | .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) |
| 77 | .addCapability(NetworkCapabilities.NET_CAPABILITY_IMS) |
| 78 | // NET_CAPABILITY_MMTEL is API 33+; on 31-32 the IMS |
| 79 | // capability alone still matches the IMS PDN. |
| 80 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { |
| 81 | builder.addCapability(NetworkCapabilities.NET_CAPABILITY_MMTEL) |
| 82 | } |
| 83 | if (SubscriptionManager.isValidSubscriptionId(subId)) { |
| 84 | runCatching { |
| 85 | val specClass = Class.forName( |
| 86 | "android.net.TelephonyNetworkSpecifier", |
| 87 | ) |
| 88 | val ctor = specClass.getDeclaredConstructor(Int::class.javaPrimitiveType) |
| 89 | .apply { isAccessible = true } |
| 90 | builder.setNetworkSpecifier(ctor.newInstance(subId) as android.net.NetworkSpecifier) |
| 91 | }.onFailure { |
| 92 | Log.status(TAG, "TelephonyNetworkSpecifier unavailable", it) |
| 93 | } |
| 94 | } |
| 95 | val request = builder.build() |
| 96 | val callback = object : ConnectivityManager.NetworkCallback() { |
| 97 | override fun onAvailable(network: Network) { |
| 98 | runCatching { cm.unregisterNetworkCallback(this) } |
| 99 | if (cont.isActive) cont.resume(network) |
| 100 | } |
| 101 | |
| 102 | override fun onUnavailable() { |
| 103 | runCatching { cm.unregisterNetworkCallback(this) } |
| 104 | if (cont.isActive) cont.resume(null) |
| 105 | } |
| 106 | } |
| 107 | cont.invokeOnCancellation { |
| 108 | runCatching { cm.unregisterNetworkCallback(callback) } |
| 109 | } |
| 110 | runCatching { cm.requestNetwork(request, callback) } |
| 111 | .onFailure { if (cont.isActive) cont.resume(null) } |
| 112 | } |
| 113 | } |
| 114 | if (network != null) { |
| 115 | cached = network |
| 116 | lastLocalIp = localIpFor(context, network) |
| 117 | } |
| 118 | return network |
| 119 | } |
| 120 | |
| 121 | /** Scan connected networks for IMS capability (no request needed). */ |
| 122 | private fun scanForIms(cm: ConnectivityManager): Network? { |
| 123 | return runCatching { |
| 124 | cm.allNetworks.firstOrNull { network -> |
| 125 | val caps = cm.getNetworkCapabilities(network) ?: return@firstOrNull false |
| 126 | caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_IMS) |
| 127 | } |
| 128 | }.getOrNull() |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Open a TCP socket to [host]:[port], preferring the IMS PDN's socket |
| 133 | * factory (source-bound to the IMS local address like TestRcsApp's |
| 134 | * `MsrpManager.createMsrpSession`). Falls back to a plain socket when the |
| 135 | * IMS network is unavailable. Null only when both paths fail. |
| 136 | */ |
| 137 | suspend fun createSocket( |
| 138 | context: Context, |
| 139 | host: String, |
| 140 | port: Int, |
| 141 | connectTimeoutMs: Int = 10_000, |
| 142 | ): Socket? { |
| 143 | if (!RcsFeature.enabled) return null |
| 144 | // IMS path first. |
| 145 | val ims = imsNetwork(context) |
| 146 | if (ims != null) { |
| 147 | val bound = runCatching { |
| 148 | val factory = ims.getSocketFactory() |
| 149 | val local = lastLocalIp?.let { runCatching { InetAddress.getByName(it) }.getOrNull() } |
| 150 | Log.status(TAG, "IMS socket to $host:$port via ${ims} local=$local") |
| 151 | val socket = if (local != null) { |
| 152 | factory.createSocket(host, port, local, 0) |
| 153 | } else { |
| 154 | val s = factory.createSocket() |
| 155 | s.connect(java.net.InetSocketAddress(host, port), connectTimeoutMs) |
| 156 | s |
| 157 | } |
| 158 | socket.soTimeout = 0 |
| 159 | socket |
| 160 | } |
| 161 | val socket = bound.getOrElse { |
| 162 | Log.status(TAG, "IMS socket bind failed to $host:$port", it) |
| 163 | null |
| 164 | } |
| 165 | if (socket != null && socket.isConnected) return socket |
| 166 | runCatching { socket?.close() } |
| 167 | // IMS network went stale — drop it so the next call re-requests. |
| 168 | cached = null |
| 169 | Log.status(TAG, "IMS socket bind failed; falling back to plain socket") |
| 170 | } |
| 171 | // Plain fallback (v1 behavior). |
| 172 | return runCatching { |
| 173 | val s = Socket() |
| 174 | s.connect(java.net.InetSocketAddress(host, port), connectTimeoutMs) |
| 175 | s.soTimeout = 0 |
| 176 | s |
| 177 | }.getOrNull() |
| 178 | } |
| 179 | |
| 180 | /** Local IP addresses on [network] (link addresses); empty on failure. */ |
| 181 | fun localIps(context: Context, network: Network): List<String> { |
| 182 | if (!RcsFeature.enabled) return emptyList() |
| 183 | return runCatching { |
| 184 | val cm = context.applicationContext.getSystemService(ConnectivityManager::class.java) |
| 185 | ?: return emptyList() |
| 186 | val props = cm.getLinkProperties(network) ?: return emptyList() |
| 187 | props.linkAddresses.mapNotNull { it.address?.hostAddress } |
| 188 | .filter { !it.startsWith("127.") && it != "::1" } |
| 189 | }.getOrDefault(emptyList()) |
| 190 | } |
| 191 | |
| 192 | /** |
| 193 | * Bound MSRP listen socket on the IMS PDN: a `ServerSocket` on an |
| 194 | * ephemeral port, bound to the IMS local address when known. |
| 195 | * |
| 196 | * Note: `Network` exposes a client `SocketFactory` but no server-socket |
| 197 | * factory, so this binds a plain `ServerSocket` explicitly to the IMS |
| 198 | * local address. Inbound TCP to that address arrives on the IMS PDN at |
| 199 | * the IP layer regardless of which `Network` created the socket — the |
| 200 | * routing decision is the peer's (it connects to the address we |
| 201 | * advertise in `a=path`), not ours. |
| 202 | * |
| 203 | * Returns the socket + the local (ip, port) to advertise in `a=path` and |
| 204 | * `c=`, or null when no IMS network / bind fails. The socket is NOT |
| 205 | * closed here — the caller owns the accept loop and closes on teardown. |
| 206 | * Plain-network fallback is deliberately absent: advertising an |
| 207 | * unroutable address is worse than offering active-only. |
| 208 | */ |
| 209 | private const val LISTEN_BACKLOG = 16 |
| 210 | suspend fun listenSocket(context: Context): ListenSocket? { |
| 211 | if (!RcsFeature.enabled) return null |
| 212 | val ims = imsNetwork(context) ?: return null |
| 213 | return runCatching { |
| 214 | val localIp = lastLocalIp |
| 215 | ?.let { runCatching { InetAddress.getByName(it) }.getOrNull() } |
| 216 | ?: return null |
| 217 | val server = ServerSocket() |
| 218 | // Backlog sized for one peer per pending session plus slack. |
| 219 | server.bind(InetSocketAddress(localIp, 0), LISTEN_BACKLOG) |
| 220 | val port = server.localPort.takeIf { it > 0 } ?: run { |
| 221 | runCatching { server.close() } |
| 222 | return null |
| 223 | } |
| 224 | val ip = localIp.hostAddress ?: return null |
| 225 | ListenSocket(server = server, localIp = ip, localPort = port) |
| 226 | }.getOrElse { |
| 227 | Log.status(TAG, "IMS listen bind failed", it) |
| 228 | null |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /** An owned IMS-PDN listen socket with its advertised address. */ |
| 233 | data class ListenSocket( |
| 234 | val server: ServerSocket, |
| 235 | val localIp: String, |
| 236 | val localPort: Int, |
| 237 | ) { |
| 238 | /** `msrp://ip:port/<session>;tcp` path for `a=path`. */ |
| 239 | fun msrpPath(sessionId: String): String = "msrp://$localIp:$localPort/$sessionId;tcp" |
| 240 | |
| 241 | fun close() = runCatching { server.close() } |
| 242 | } |
| 243 | |
| 244 | private fun localIpFor(context: Context, network: Network): String? = |
| 245 | localIps(context, network).firstOrNull { it.contains('.') } |
| 246 | ?: localIps(context, network).firstOrNull() |
| 247 | |
| 248 | /** Drop the cached network (subId change / teardown). */ |
| 249 | fun reset() { |
| 250 | cached = null |
| 251 | lastLocalIp = null |
| 252 | } |
| 253 | } |