Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalClient.kt
SignalClient.kt599 lines · 27.3 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal |
| 2 | |
| 3 | import android.annotation.SuppressLint |
| 4 | import android.content.Context |
| 5 | import android.util.Base64 as AndroidBase64 |
| 6 | import com.vayunmathur.library.log.Log |
| 7 | import com.vayunmathur.communicate.data.signal.e2e.SignalE2E |
| 8 | import com.vayunmathur.communicate.data.signal.e2e.callIdentityKey |
| 9 | import com.vayunmathur.communicate.data.CommunicateLine |
| 10 | import com.vayunmathur.communicate.data.call.CallCapabilities |
| 11 | import com.vayunmathur.communicate.data.call.InAppCallController |
| 12 | import com.vayunmathur.communicate.data.call.InAppCallPhase |
| 13 | import com.vayunmathur.communicate.data.call.InAppCallRegistry |
| 14 | import com.vayunmathur.communicate.data.call.InAppCallVideoController |
| 15 | import com.vayunmathur.communicate.data.signal.call.IdentityKeyPairBytes |
| 16 | import com.vayunmathur.communicate.data.signal.call.SignalCallManager |
| 17 | import com.vayunmathur.communicate.data.signal.call.SignalCallSignaling |
| 18 | import com.vayunmathur.communicate.data.signal.call.SignalGroupCallManager |
| 19 | import com.vayunmathur.communicate.data.signal.call.accept |
| 20 | import com.vayunmathur.communicate.data.signal.call.eglBaseForGroupCalls |
| 21 | import com.vayunmathur.communicate.data.signal.call.eglContext |
| 22 | import com.vayunmathur.communicate.data.signal.call.flipCamera |
| 23 | import com.vayunmathur.communicate.data.signal.call.hangup |
| 24 | import com.vayunmathur.communicate.data.signal.call.ringRtcCallManager |
| 25 | import com.vayunmathur.communicate.data.signal.call.setAudioEnabled |
| 26 | import com.vayunmathur.communicate.data.signal.call.setScreenShareEnabled |
| 27 | import com.vayunmathur.communicate.data.signal.call.setVideoEnabled |
| 28 | import com.vayunmathur.communicate.data.signal.call.SignalCallMessage |
| 29 | import com.vayunmathur.communicate.data.signal.call.toContent |
| 30 | import com.vayunmathur.communicate.data.signal.call.toRingRtc |
| 31 | import com.vayunmathur.communicate.data.signal.transport.SignalAttachmentUpload |
| 32 | import com.vayunmathur.communicate.data.signal.transport.SignalCallingApi |
| 33 | import com.vayunmathur.communicate.data.signal.transport.SignalGroupsApi |
| 34 | import com.vayunmathur.communicate.data.signal.transport.SignalKeysApi |
| 35 | import com.vayunmathur.communicate.data.signal.transport.SignalPayload |
| 36 | import com.vayunmathur.communicate.data.signal.transport.SignalSocket |
| 37 | import com.vayunmathur.communicate.data.signal.transport.SignalTrust |
| 38 | import org.signal.libsignal.metadata.certificate.SenderCertificate |
| 39 | import org.signal.libsignal.protocol.IdentityKey |
| 40 | import org.signal.libsignal.protocol.UntrustedIdentityException |
| 41 | import org.signal.libsignal.protocol.message.DecryptionErrorMessage |
| 42 | import org.signal.libsignal.protocol.message.PlaintextContent |
| 43 | import org.signal.ringrtc.CallManager |
| 44 | import org.signal.storageservice.storage.protos.groups.GroupChange |
| 45 | import org.webrtc.PeerConnection |
| 46 | import com.vayunmathur.library.network.NetworkClient |
| 47 | import kotlinx.coroutines.CoroutineScope |
| 48 | import kotlinx.coroutines.Dispatchers |
| 49 | import kotlinx.coroutines.Job |
| 50 | import kotlinx.coroutines.SupervisorJob |
| 51 | import kotlinx.coroutines.flow.MutableSharedFlow |
| 52 | import kotlinx.coroutines.flow.MutableStateFlow |
| 53 | import kotlinx.coroutines.flow.SharedFlow |
| 54 | import kotlinx.coroutines.flow.StateFlow |
| 55 | import kotlinx.coroutines.flow.asSharedFlow |
| 56 | import kotlinx.coroutines.flow.asStateFlow |
| 57 | import kotlinx.coroutines.launch |
| 58 | import org.whispersystems.signalservice.internal.push.SignalServiceProtos |
| 59 | import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage |
| 60 | import java.util.concurrent.atomic.AtomicBoolean |
| 61 | |
| 62 | /** |
| 63 | * Singleton facade for the Signal primary client. |
| 64 | * |
| 65 | * Stable public API that repository and ui compile against — signatures are identical to the |
| 66 | * foundation stub. Internals are wired to new transport/crypto/auth (SignalSocket binary |
| 67 | * WebSocketMessage, SignalProtocol protobuf Envelope/Content, SignalE2E PQXDH/SealedSessionCipher, |
| 68 | * dual ACI/PNI SignalAuthData). |
| 69 | * |
| 70 | * All chat sends go through single PUT /v1/messages/{aci} (or /multi) as encrypted Content |
| 71 | * (SignalPayload.buildPutMessagesRequest + SignalSocket.sendRequestAwaitingResponse). No per-action sub-paths. |
| 72 | * Receipts/typing/edit/reactions are Content peers via SignalProtocol/SignalPayload builders. |
| 73 | * GroupsV2 via SignalGroups (GroupMasterKey 32B -> GroupSecretParams, PUT /v2/groups/). |
| 74 | * CDSIv2 via SignalContactSync (POST https://cdsi.signal.org/v1/{mrenclave}/discovery). |
| 75 | */ |
| 76 | // Singleton by design (one Signal account per app). Every Context it or its |
| 77 | // sockets retain is the application context (see init/SignalSocket), so no |
| 78 | // activity or view can leak through these fields. |
| 79 | @SuppressLint("StaticFieldLeak") |
| 80 | object SignalClient { |
| 81 | |
| 82 | internal const val TAG = "SignalClient" |
| 83 | private const val PHONE_SUFFIX_LENGTH = 4 |
| 84 | |
| 85 | /** |
| 86 | * Production sealed-sender trust roots, mirroring the official client's |
| 87 | * `UNIDENTIFIED_SENDER_TRUST_ROOTS` build constant. Two entries so the server can rotate. |
| 88 | */ |
| 89 | internal val TRUST_ROOTS_B64 = listOf( |
| 90 | "BXu6QIKVz5MA8gstzfOgRQGqyLqOwNKHL6INkv3IHWMF", |
| 91 | "BUkY0I+9+oPgDCn4+Ac6Iu813yvqkDr/ga8DzLxFxuk6", |
| 92 | ) |
| 93 | |
| 94 | internal val ACI_REGEX = |
| 95 | Regex("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}") |
| 96 | |
| 97 | /** Attempts allowed to reconcile a recipient's device set before a send is abandoned. */ |
| 98 | internal const val SEND_ATTEMPTS = 4 |
| 99 | |
| 100 | /** Every Signal account has device 1; linked devices get higher ids. */ |
| 101 | internal const val PRIMARY_DEVICE_ID = 1 |
| 102 | |
| 103 | /** Wire prefix distinguishing a phone-number identity from an ACI, which is a bare UUID. */ |
| 104 | internal const val PNI_PREFIX = "PNI:" |
| 105 | |
| 106 | /** Lifecycle state of the Signal line. */ |
| 107 | sealed interface State { |
| 108 | /** Not yet connected. */ |
| 109 | data object Idle : State |
| 110 | /** The line has no registered account yet. */ |
| 111 | data object NeedsSetup : State |
| 112 | /** The socket is connecting / logging in. */ |
| 113 | data object Connecting : State |
| 114 | /** Connected and logged in. */ |
| 115 | data object Connected : State |
| 116 | /** Disconnected, with the reason. */ |
| 117 | data class Disconnected(val reason: String) : State |
| 118 | } |
| 119 | |
| 120 | val source: SignalSource = SignalSource.SIGNAL |
| 121 | |
| 122 | fun isConnected(): Boolean = stateMutable.value is State.Connected |
| 123 | |
| 124 | val stateMutable = MutableStateFlow<State>(State.Idle) |
| 125 | val state: StateFlow<State> = stateMutable.asStateFlow() |
| 126 | |
| 127 | internal val eventsMutable = MutableSharedFlow<SignalEvent>(extraBufferCapacity = 256) |
| 128 | val events: SharedFlow<SignalEvent> = eventsMutable.asSharedFlow() |
| 129 | |
| 130 | private val initialized = AtomicBoolean(false) |
| 131 | internal val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) |
| 132 | |
| 133 | var appContext: Context? = null |
| 134 | var authData: SignalAuthData? = null |
| 135 | var db: SignalDatabase? = null |
| 136 | var e2e: SignalE2E? = null |
| 137 | var socket: SignalSocket? = null |
| 138 | |
| 139 | /** Credential-free socket used only for sealed-sender sends. */ |
| 140 | var unauthSocket: SignalSocket? = null |
| 141 | |
| 142 | /** |
| 143 | * Identity keys peers are presenting that differ from the ones on record, awaiting the user's |
| 144 | * decision. Deliberately in memory: if the process dies the key is re-presented on the next message, |
| 145 | * and a stale pending key should not outlive the session. |
| 146 | */ |
| 147 | val pendingIdentityChanges = java.util.concurrent.ConcurrentHashMap<String, ByteArray>() |
| 148 | internal var processor: SignalEventProcessor? = null |
| 149 | internal var socketJobs: MutableList<Job> = mutableListOf() |
| 150 | private var reconnectJob: Job? = null |
| 151 | |
| 152 | fun get(context: Context): SignalClient = apply { init(context) } |
| 153 | |
| 154 | fun init(context: Context) { |
| 155 | if (!initialized.compareAndSet(false, true)) return |
| 156 | appContext = context.applicationContext |
| 157 | val auth = SignalAuthData.load(context.applicationContext) |
| 158 | authData = auth |
| 159 | try { |
| 160 | db = SignalDatabase.getDatabase(context.applicationContext) |
| 161 | if (auth != null) e2e = SignalE2E(db!!, auth) |
| 162 | } catch (expected: Throwable) { |
| 163 | Log.status(TAG, "db/e2e init failed", expected) |
| 164 | } |
| 165 | stateMutable.value = if (auth?.registered == true) State.Connecting else State.NeedsSetup |
| 166 | try { |
| 167 | val database = db |
| 168 | if (database != null) { |
| 169 | processor = SignalEventProcessor(database).also { it.start(events) } |
| 170 | } |
| 171 | } catch (expected: Throwable) { |
| 172 | Log.status(TAG, "processor start failed", expected) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | fun start() { |
| 177 | if (!initialized.get()) return |
| 178 | if (stateMutable.value is State.Connected) return |
| 179 | val ctx = appContext ?: return |
| 180 | val auth = authData ?: SignalAuthData.load(ctx)?.also { authData = it } |
| 181 | if (auth == null || !auth.registered) { |
| 182 | stateMutable.value = State.NeedsSetup |
| 183 | return |
| 184 | } |
| 185 | if (!ensureStore(ctx, auth)) return |
| 186 | if (processor == null && db != null) try { |
| 187 | processor = SignalEventProcessor(db!!).also { it.start(events) } |
| 188 | } catch (_: Exception) {} |
| 189 | |
| 190 | stateMutable.value = State.Connecting |
| 191 | // Tear down anything from a previous start(); otherwise the old instances keep their own |
| 192 | // reconnect loops running with no reference left to stop them. |
| 193 | disconnectSockets() |
| 194 | connectSockets(ctx, auth) |
| 195 | } |
| 196 | |
| 197 | /** Build the protocol store; false when unavailable (caller disconnects). */ |
| 198 | private fun ensureStore(ctx: android.content.Context, auth: SignalAuthData): Boolean { |
| 199 | if (db == null) try { db = SignalDatabase.getDatabase(ctx) } catch (_: Exception) {} |
| 200 | if (e2e == null && db != null) try { |
| 201 | e2e = SignalE2E(db!!, auth) { peerAci, newKey -> reportIdentityChange(peerAci, newKey) } |
| 202 | } catch (expected: Throwable) { |
| 203 | Log.error(TAG, "could not build the protocol store", expected) |
| 204 | } |
| 205 | if (e2e == null) { |
| 206 | // Connecting without a protocol store would pull messages we cannot decrypt and, since |
| 207 | // they are only acked once handled, leave them cycling on the server queue. |
| 208 | stateMutable.value = State.Disconnected("no protocol store") |
| 209 | return false |
| 210 | } |
| 211 | return true |
| 212 | } |
| 213 | |
| 214 | /** Connect the authenticated + sealed-sender sockets and their collectors. */ |
| 215 | private fun connectSockets(ctx: android.content.Context, auth: SignalAuthData) { |
| 216 | val sock = SignalSocket(ctx, auth) |
| 217 | socket = sock |
| 218 | // Sealed-sender sends go over a second socket with no credentials. It carries no inbound queue, |
| 219 | // so its frames are not collected — only its request/response pairs matter. |
| 220 | val unauthSock = SignalSocket(ctx, auth, authenticated = false) |
| 221 | unauthSocket = unauthSock |
| 222 | |
| 223 | socketJobs.forEach { it.cancel() } |
| 224 | socketJobs.clear() |
| 225 | |
| 226 | sock.connect() |
| 227 | unauthSock.connect() |
| 228 | |
| 229 | socketJobs.add(scope.launch { |
| 230 | sock.connectionState.collect { cs -> |
| 231 | when (cs) { |
| 232 | is SignalSocket.ConnectionState.Connected -> { |
| 233 | stateMutable.value = State.Connected |
| 234 | eventsMutable.emit(SignalEvent.StateChanged(state = SignalState.Connected)) |
| 235 | } |
| 236 | is SignalSocket.ConnectionState.Connecting -> { |
| 237 | stateMutable.value = State.Connecting |
| 238 | eventsMutable.emit(SignalEvent.StateChanged(state = SignalState.Connecting)) |
| 239 | } |
| 240 | is SignalSocket.ConnectionState.Disconnected -> { |
| 241 | stateMutable.value = State.Disconnected(cs.reason) |
| 242 | eventsMutable.emit(SignalEvent.StateChanged( |
| 243 | state = SignalState.Disconnected, |
| 244 | detail = cs.reason)) |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | }) |
| 249 | socketJobs.add(scope.launch { |
| 250 | sock.messages.collect { raw -> |
| 251 | handleInboundFrame(raw) |
| 252 | } |
| 253 | }) |
| 254 | // The unauthenticated socket must not drive client state, but a permanently failing one silently |
| 255 | // degrades every sealed send to the authenticated path, so make that visible. |
| 256 | socketJobs.add(scope.launch { |
| 257 | unauthSock.connectionState.collect { cs -> |
| 258 | if (cs is SignalSocket.ConnectionState.Disconnected) { |
| 259 | Log.status(TAG, "unauthenticated socket down (${cs.reason}); sealed sends will go authenticated") |
| 260 | } |
| 261 | } |
| 262 | }) |
| 263 | // Our own pre-keys must be in the protocol store or inbound pre-key messages cannot decrypt |
| 264 | // ("no signed pre-key <id>"). Registration only wrote them to preferences. |
| 265 | scope.launch { ensureLocalPreKeys() } |
| 266 | |
| 267 | // Discover which address-book numbers are on Signal. Without this, phone-addressed conversations |
| 268 | // have no ACI and cannot be sent to at all. Deliberately not in socketJobs: those are cancelled on |
| 269 | // every reconnect, which would kill a discovery request mid-flight. |
| 270 | scope.launch { runContactDiscovery(ctx) } |
| 271 | Log.status(TAG, "start: socket connecting for ${auth.phoneNumber.takeLast(PHONE_SUFFIX_LENGTH)}" + |
| 272 | " host=${SignalSocket.DEFAULT_HOST}") |
| 273 | } |
| 274 | |
| 275 | fun stop() { |
| 276 | if (!initialized.get()) return |
| 277 | socketJobs.forEach { it.cancel() } |
| 278 | socketJobs.clear() |
| 279 | disconnectSockets() |
| 280 | stateMutable.value = State.NeedsSetup |
| 281 | scope.launch { eventsMutable.emit(SignalEvent.StateChanged( |
| 282 | state = SignalState.Disconnected, |
| 283 | detail = "client stop")) } |
| 284 | } |
| 285 | |
| 286 | fun forceResync() { |
| 287 | if (!initialized.get()) return |
| 288 | socketJobs.forEach { it.cancel() } |
| 289 | socketJobs.clear() |
| 290 | disconnectSockets() |
| 291 | start() |
| 292 | } |
| 293 | |
| 294 | private fun disconnectSockets() { |
| 295 | try { socket?.disconnect() } catch (_: Exception) {} |
| 296 | socket = null |
| 297 | try { unauthSocket?.disconnect() } catch (_: Exception) {} |
| 298 | unauthSocket = null |
| 299 | } |
| 300 | |
| 301 | // ---- send path (envelopeTimestampFor/groupContextFor/sendContent): see SignalSendPipeline.kt (split for file |
| 302 | // length) ---- |
| 303 | |
| 304 | /** |
| 305 | * Encrypt [padded] for every device of [aci] we have a session with and PUT them as one request. |
| 306 | * Returns false rather than falling back to plaintext: an unencrypted Content is a protocol |
| 307 | * violation that real clients discard, so sending one would disclose the message and forfeit |
| 308 | * sender authentication without even being delivered. |
| 309 | */ |
| 310 | /** |
| 311 | * The ACI to address on the wire for [destination], which the app may hand us as a phone number. |
| 312 | * |
| 313 | * Signal addresses messages by ACI, never by phone number, so an E.164 has to be resolved first. We |
| 314 | * only ever learn a real ACI from an inbound message or from CDSI contact discovery, so a number |
| 315 | * belonging to someone who has never messaged us cannot be resolved and the send has to fail. |
| 316 | */ |
| 317 | /** |
| 318 | * Seed our own pre-keys into the protocol store and register anything the server does not yet have. |
| 319 | * Runs once per start; without it a peer's first message cannot be decrypted. |
| 320 | */ |
| 321 | // ---- pre-keys/discovery (ensureLocalPreKeys/signedPreKeyMatchesServer): see SignalSendPipeline.kt (split for |
| 322 | // file length) ---- |
| 323 | |
| 324 | /** Guards against overlapping discovery runs; `start()` can fire more than once. */ |
| 325 | internal val discoveryRunning = AtomicBoolean(false) |
| 326 | |
| 327 | /** |
| 328 | * The inbound call awaiting an answer. RingRTC reports `Ringing` for both directions, so this is what |
| 329 | * distinguishes an incoming call and supplies the id [InAppCallController.answer] needs. |
| 330 | */ |
| 331 | @Volatile |
| 332 | internal var pendingIncomingCallAci: String? = null |
| 333 | |
| 334 | @Volatile |
| 335 | internal var pendingIncomingCallId: Long? = null |
| 336 | |
| 337 | /** Same reason as [discoveryRunning]: without it, each start generates and uploads another batch. */ |
| 338 | internal val preKeysPrepared = AtomicBoolean(false) |
| 339 | |
| 340 | // ---- discovery/resolution (runContactDiscovery/resolveDestinationAci/knownServiceIdFor): see |
| 341 | // SignalSendPipeline.kt (split for file length) ---- |
| 342 | |
| 343 | // ---- encrypt/PUT (sendEncryptedTo/sealedSenderFor/putMessages/reconcileDevices/establishSession): see |
| 344 | // SignalSendPipeline.kt (split for file length) ---- |
| 345 | |
| 346 | internal sealed interface SendOutcome { |
| 347 | data object Success : SendOutcome |
| 348 | data class Failed(val status: Int) : SendOutcome |
| 349 | data class DeviceSetChanged(val status: Int, val body: ByteArray) : SendOutcome |
| 350 | } |
| 351 | |
| 352 | // ---- identity (profileKeyFrom/reportIdentityChange/pendingIdentityChange/safetyNumber/acceptIdentityChange): see |
| 353 | // SignalIdentity.kt (split for file length) ---- |
| 354 | |
| 355 | internal data class SealedSenderAccess(val certificate: SenderCertificate, val accessKey: ByteArray) |
| 356 | |
| 357 | // ---- sealed/PUT helpers continued: see SignalSendPipeline.kt (split for file length) ---- |
| 358 | |
| 359 | /** TLS factory that trusts Signal's private service CA (chat/cdn/storage/cdsi); null before init. */ |
| 360 | internal fun signalTls() = appContext?.let { SignalTrust.sslSocketFactory(it) } |
| 361 | |
| 362 | internal fun basicAuthHeader(): String { |
| 363 | val auth = authData ?: return "" |
| 364 | val login = if (auth.aci.isNotEmpty()) "${auth.aci}.${auth.deviceId}" else auth.phoneNumber |
| 365 | val password = auth.password |
| 366 | val creds = "$login:$password" |
| 367 | return AndroidBase64.encodeToString(creds.toByteArray(Charsets.UTF_8), AndroidBase64.NO_WRAP) |
| 368 | } |
| 369 | |
| 370 | /** The stored master key for a group conversation, or null for a 1:1 or an unknown group. */ |
| 371 | internal suspend fun groupMasterKeyForConversation(conversationId: String): ByteArray? { |
| 372 | if (!SignalProtocol.isGroupConversation(conversationId)) return null |
| 373 | return try { |
| 374 | db?.conversationDao()?.getConversation(conversationId)?.groupMasterKey |
| 375 | } catch (_: Exception) { |
| 376 | null |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | internal suspend fun groupRevisionForConversation(conversationId: String): Int = try { |
| 381 | db?.conversationDao()?.getConversation(conversationId)?.groupRevision ?: 0 |
| 382 | } catch (_: Exception) { |
| 383 | 0 |
| 384 | } |
| 385 | |
| 386 | // ---- Messaging (sendMessage): see SignalMessaging.kt (split for file length) ---- |
| 387 | |
| 388 | /** |
| 389 | * Encrypt, upload, and send an attachment. Returns null on any failure — the plaintext never leaves |
| 390 | * the device unencrypted, so a failed upload simply means no message. |
| 391 | */ |
| 392 | // ---- Messaging (sendMedia): see SignalMessaging.kt (split for file length) ---- |
| 393 | |
| 394 | // ---- Inbound attachments (attachmentsFrom/attachmentUrl): see SignalInbound.kt (split for file length) ---- |
| 395 | |
| 396 | // ---- Messaging (sendMediaFailed): see SignalMessaging.kt (split for file length) ---- |
| 397 | |
| 398 | // ---- Messaging (sendReaction/removeReaction/editMessage/revoke/poll/sendPollVote/readReceipt/markRead): see |
| 399 | // SignalMessaging.kt (split for file length) ---- |
| 400 | |
| 401 | // ---- Groups (createGroup/setGroupName/groupChange/updateGroupParticipants): see SignalGroupOps.kt (split for |
| 402 | // file length) ---- |
| 403 | |
| 404 | // ---- Messaging (sendTyping/isLoggedIn/downloadMedia/refreshPresence): see SignalMessaging.kt (split for file |
| 405 | // length) ---- |
| 406 | |
| 407 | /** |
| 408 | * The RingRTC bridge. Created lazily because it loads native libraries and only matters once a call |
| 409 | * is actually placed or received. |
| 410 | */ |
| 411 | internal val callManager: SignalCallManager? by lazy { |
| 412 | val ctx = appContext ?: return@lazy null |
| 413 | SignalCallManager( |
| 414 | appContext = ctx, |
| 415 | signaling = object : SignalCallSignaling { |
| 416 | override suspend fun sendCallMessage( |
| 417 | aci: String, |
| 418 | deviceId: Int?, |
| 419 | message: SignalCallMessage, |
| 420 | urgent: Boolean, |
| 421 | ): Boolean = sendContent(aci, message.toContent(deviceId), urgent = urgent) |
| 422 | |
| 423 | override suspend fun identityKeys(aci: String): IdentityKeyPairBytes? { |
| 424 | val e = e2e ?: return null |
| 425 | // RingRTC binds the SRTP key derivation to both identity keys, so a call cannot be |
| 426 | // set up before a session with this peer exists. |
| 427 | // Raw 32-byte keys, matching official's WebRtcUtil.getPublicKeyBytes; the serialized |
| 428 | // 33-byte form derives different SRTP keys than the peer. |
| 429 | val remote = e.callIdentityKey(aci) ?: return null |
| 430 | val local = e.ownIdentityPublicKey |
| 431 | // Logged because a size or encoding mismatch here yields SRTP keys that differ from the |
| 432 | // peer's, which looks like a connected call that never progresses. |
| 433 | Log.status( |
| 434 | TAG, |
| 435 | "call identity keys for $aci:" + |
| 436 | "local=${local.size}B(0x${"%02x".format(local.firstOrNull() ?: 0)}) " + |
| 437 | "remote=${remote.size}B(0x${"%02x".format(remote.firstOrNull() ?: 0)})", |
| 438 | ) |
| 439 | return IdentityKeyPairBytes(local = local, remote = remote) |
| 440 | } |
| 441 | |
| 442 | override suspend fun iceServers(): List<PeerConnection.IceServer> = |
| 443 | SignalCallingApi.fetchIceServers(basicAuthHeader(), signalTls()) |
| 444 | |
| 445 | override fun onRemoteVideo(enabled: Boolean) { |
| 446 | InAppCallRegistry.onRemoteVideo(enabled) |
| 447 | } |
| 448 | |
| 449 | override fun onRemoteScreenShare(enabled: Boolean) { |
| 450 | InAppCallRegistry.onRemoteScreenShare(enabled) |
| 451 | } |
| 452 | |
| 453 | override fun onCallStateChanged( |
| 454 | aci: String, |
| 455 | callId: Long, |
| 456 | state: SignalCallManager.CallState, |
| 457 | isVideo: Boolean, |
| 458 | ) { |
| 459 | scope.launch { |
| 460 | publishCallState(aci, state, isVideo) |
| 461 | emitCallState(callId, state, isVideo) |
| 462 | } |
| 463 | } |
| 464 | }, |
| 465 | sslSocketFactory = { signalTls() }, |
| 466 | ) |
| 467 | } |
| 468 | |
| 469 | // ---- Calls (handleCallMessage/publishCallState): see SignalCalls.kt (split for file length) ---- |
| 470 | |
| 471 | /** Video capability for the shared call screen. */ |
| 472 | internal val signalVideoController = object : InAppCallVideoController { |
| 473 | override fun setVideoEnabled(enabled: Boolean) { |
| 474 | callManager?.setVideoEnabled(enabled) |
| 475 | } |
| 476 | |
| 477 | override fun flipCamera() { |
| 478 | callManager?.flipCamera() |
| 479 | } |
| 480 | |
| 481 | override fun eglContext(): org.webrtc.EglBase.Context? = callManager?.eglContext() |
| 482 | |
| 483 | override fun attachLocalRenderer(sink: org.webrtc.VideoSink?) { |
| 484 | callManager?.localVideoSink?.attach(sink) |
| 485 | } |
| 486 | |
| 487 | override fun attachRemoteRenderer(sink: org.webrtc.VideoSink?) { |
| 488 | callManager?.remoteVideoSink?.attach(sink) |
| 489 | } |
| 490 | |
| 491 | override fun setScreenShareEnabled(enabled: Boolean, permission: android.content.Intent?) { |
| 492 | callManager?.setScreenShareEnabled(enabled, permission) |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | /** Bridges the shared call UI and the system call surface onto RingRTC. */ |
| 497 | internal val signalCallController = object : InAppCallController { |
| 498 | override fun answer() { |
| 499 | val id = pendingIncomingCallId |
| 500 | if (id == null) { |
| 501 | Log.status(TAG, "answer with no pending call id; the caller will keep ringing") |
| 502 | return |
| 503 | } |
| 504 | val accepted = callManager?.accept(id) |
| 505 | Log.status(TAG, "accepted call $id: $accepted") |
| 506 | } |
| 507 | |
| 508 | override fun reject() { |
| 509 | callManager?.hangup() |
| 510 | } |
| 511 | |
| 512 | override fun hangup() { |
| 513 | callManager?.hangup() |
| 514 | } |
| 515 | |
| 516 | override fun setMuted(muted: Boolean) { |
| 517 | // RingRTC's flag is "audio enabled", the inverse of muted. |
| 518 | callManager?.setAudioEnabled(!muted) |
| 519 | } |
| 520 | |
| 521 | override fun setSpeaker(on: Boolean) { |
| 522 | // Routing belongs to Telecom while a self-managed connection is active; nothing to do here. |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | // ---- Calls (emitCallState/placeCall/acceptCall/rejectCall/endCall/setCallAudioEnabled): see SignalCalls.kt |
| 527 | // (split for file length) ---- |
| 528 | |
| 529 | // ---- Inbound (handleInboundFrame/ackEnvelope): see SignalInbound.kt (split for file length) ---- |
| 530 | |
| 531 | // ---- Inbound (processEnvelope head): see SignalInbound.kt (split for file length) ---- |
| 532 | |
| 533 | // ---- Inbound (processEnvelope dispatch): see SignalInbound.kt (split for file length) ---- |
| 534 | |
| 535 | // ---- Inbound (sendRetryReceipt): see SignalInbound.kt (split for file length) ---- |
| 536 | |
| 537 | // ---- Identity/contacts (linkPniToAci/contactFor/displayNameFor/conversationIdFor): see SignalIdentity.kt (split |
| 538 | // for file length) ---- |
| 539 | |
| 540 | // ---- Groups (refreshGroup): see SignalGroupOps.kt (split for file length) ---- |
| 541 | |
| 542 | /** |
| 543 | * Group calling, created on demand. Shares the 1:1 manager's RingRTC instance and EGL context — RingRTC |
| 544 | * keeps one factory for all group calls, so a second instance would fight it for the audio device. |
| 545 | */ |
| 546 | internal val groupCallManager: SignalGroupCallManager? by lazy { |
| 547 | val manager = callManager ?: return@lazy null |
| 548 | val egl = manager.eglBaseForGroupCalls() ?: return@lazy null |
| 549 | val ctx = appContext ?: return@lazy null |
| 550 | SignalGroupCallManager( |
| 551 | appContext = ctx, |
| 552 | callManager = manager.ringRtcCallManager() ?: return@lazy null, |
| 553 | eglBase = egl, |
| 554 | signaling = object : SignalGroupCallManager.Signaling { |
| 555 | override suspend fun membershipProof(groupId: ByteArray): ByteArray? = |
| 556 | groupAuthorization(groupId)?.let { SignalGroupsApi.fetchMembershipProof(it, signalTls()) } |
| 557 | |
| 558 | override suspend fun groupMembers(groupId: ByteArray): List<Pair<java.util.UUID, ByteArray>> { |
| 559 | val conversation = conversationForGroupId(groupId) ?: return emptyList() |
| 560 | val masterKey = conversation.groupMasterKey ?: return emptyList() |
| 561 | val secretParams = org.signal.libsignal.zkgroup.groups.GroupSecretParams.deriveFromMasterKey( |
| 562 | org.signal.libsignal.zkgroup.groups.GroupMasterKey(masterKey), |
| 563 | ) |
| 564 | val acis = conversation.participants.split(",") |
| 565 | .map { it.trim() } |
| 566 | .filter { it.isNotEmpty() } |
| 567 | return SignalGroupsApi.groupMemberInfo(secretParams, acis) |
| 568 | } |
| 569 | |
| 570 | override fun onGroupCallStateChanged(groupId: ByteArray, joined: Boolean, participants: Int) { |
| 571 | scope.launch { |
| 572 | val conversationId = SignalProtocol.groupConversationId(groupId) |
| 573 | InAppCallRegistry.onPhase( |
| 574 | if (joined) InAppCallPhase.Active else InAppCallPhase.Connecting, |
| 575 | ) |
| 576 | Log.status(TAG, "group call $conversationId joined=$joined participants=$participants") |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | override fun onGroupCallEnded(groupId: ByteArray, reason: CallManager.CallEndReason?) { |
| 581 | scope.launch { InAppCallRegistry.onEnded(reason?.toString()) } |
| 582 | } |
| 583 | }, |
| 584 | ) |
| 585 | } |
| 586 | |
| 587 | // ---- Calls (placeGroupCall): see SignalCalls.kt (split for file length) ---- |
| 588 | |
| 589 | // ---- Groups (groupAuthorization/conversationForGroupId): see SignalGroupOps.kt (split for file length) ---- |
| 590 | |
| 591 | // ---- Messaging (sendContactCard): see SignalMessaging.kt (split for file length) ---- |
| 592 | |
| 593 | // ---- Groups (rememberInboundGroup): see SignalGroupOps.kt (split for file length) ---- |
| 594 | |
| 595 | // ---- Inbound (emitReadSync/emitDecryptionError/unidentifiedSenderTrustRoots/groupIdFor): see SignalInbound.kt |
| 596 | // (split for file length) ---- |
| 597 | |
| 598 | // ---- Messaging helper (uuidStringToBytes): see SignalMessaging.kt (split for file length) ---- |
| 599 | } |