messages: remove experiments
- Commit
5595b085c2d5c45c0b1b3d2f862fc21caf52176d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-23 23:21 UTC (4 months ago)
- Parents
c762f59
Diff
GOOGLE_VOICE_CALLING_HANDOFF.md
diff --git a/GOOGLE_VOICE_CALLING_HANDOFF.md b/GOOGLE_VOICE_CALLING_HANDOFF.mddeleted file mode 100644index b0e654a5f0..0000000000--- a/GOOGLE_VOICE_CALLING_HANDOFF.md+++ /dev/null@@ -1,512 +0,0 @@-# Google Voice Calling Integration — Project Handoff--**Date:** 2026-07-21-**Status:** Phase 1 Complete — API reverse-engineered, PJSIP integrated, SIP credentials API working. Phase 2 blocked on SIP server IP discovery.-------## Executive Summary--This document summarizes extensive reverse engineering work completed to add Google Voice VoIP calling to the Modern-Apps Messages app. The Google Voice APK was decompiled (Java + native C++), the GetSIPRegisterInfo API was reverse-engineered and is working, PJSIP SIP stack is built from source and integrated as a Gradle module, and the complete code architecture is mapped through obfuscated layers.--**Current blocker:** The SIP server `voice.sip.google.com` does not resolve in public DNS (returns NXDOMAIN even on Google DNS 8.8.8.8). The official GV app receives SIP server IP addresses dynamically via server-side configuration (Phenotype feature flags or config API) delivered as preresolved addresses in a `wra` proto structure. The specific API endpoint delivering this configuration has not yet been identified in the heavily obfuscated decompiled code.-------## 1. What Was Accomplished--### 1.1 APK Decompilation & Analysis ✅--**APK extracted from device:**-- Package: `com.google.android.apps.googlevoice`-- Base APK: 23.9 MB + arm64 split: 8.0 MB-- Location: `/Users/vayun/Documents/Modern-Apps/reverse-engineering/gvoice-re/`-- Decompiled with: apktool (resources/smali), jadx (Java), Ghidra (native binary)--**Key findings from decompiled code:**--**AndroidManifest.xml** (`apktool-out/AndroidManifest.xml`):-- Permissions: `CALL_PHONE`, `RECORD_AUDIO`, `MANAGE_OWN_CALLS`, `FOREGROUND_SERVICE_PHONE_CALL`, `FOREGROUND_SERVICE_MICROPHONE`-- Services:- - `com.google.android.apps.voice.voip.telephony.connectionservice.selfmanaged.VoipConnectionService` (extends `android.telecom.ConnectionService`)- - `com.google.android.apps.voice.voip.ui.callservice.CallForegroundService`-- Activities: `VoipCallActivity` (in-call UI), `PlaceProxyCallActivity`, dialer intent handlers for `tel:` scheme--**Java layer architecture** (jadx output at `jadx-out/sources/`):-- `com.google.android.apps.voice.voip.telephony.birdsongimpl.BirdsongTelephonyImpl` → obfuscated as `defpackage.mbb`-- `com.google.android.apps.voice.voip.telephony.birdsongimpl.CallManagerWrapper` → obfuscated as `defpackage.mbv`-- `com.google.android.apps.voice.voip.telephony.birdsongimpl.BirdsongV1ToV2Bridge` → obfuscated as `defpackage.mbk`-- Heavy ProGuard obfuscation: single-letter class/method names throughout--**Native library analysis** (`lib/arm64-v8a/libtacl_jni.so`, 7.3 MB ARM64 ELF, stripped):-- Birdsong SIP stack (Google proprietary, based on reSIProcate)-- Custom DNS resolver: `"Using BirdsongDns in reSIProcate"`-- SRV lookups: `"_sips._tcp."`, `"_sips._udp."`, `"_sip._tcp."`, `"_sip._udp."`, `"_sip._dtls."`-- Preresolved address support: `"birdsong.BirdsongConfig.DnsOptions.PreresolvedAddress"`, `"using preresolved_address: "`-- Google DNS hardcoded: `"8.8.8.8"`-- SIP hostnames: `"voice.sip.google.com"`, `"conf.w.pbx.voice.sip.google.com"`-- No hardcoded SIP server IPs in binary-- SIP Digest auth fully implemented (RFC 3261)-- OAuth integration: `getGaiaOauthToken`, `setAuthenticationToken` JNI symbols--**Ghidra analysis completed** on native binary (89 sec analysis time, stripped binary with some decompilation errors — normal for optimized C++).--### 1.2 API Reverse Engineering ✅--**GetSIPRegisterInfo endpoint discovered and working:**--**Endpoint:** `https://clients6.google.com/voice/v1/voiceclient/sipregisterinfo/get`--**Request format discovered via live testing:**-```protobuf-message ReqGetSIPRegisterInfo {- int32 client_type = 1; // enum value 3 = GV_WEB- string sip_device_id = 2; // from GetAccount API response-}-```--**Response structure discovered via live testing:**-```protobuf-message RespGetSIPRegisterInfo {- SIPRegisterInfo sip_register_info = 1;- SIPCredentials credentials = 4; // <-- actual credentials here-}--message SIPRegisterInfo {- int64 field_1 = 1; // timestamp (changes each call, e.g., 1784825405 = 2026-07-23)- int64 field_2 = 2; // unknown int (possibly expiry or ID)-}--message SIPCredentials {- string token_1 = 1; // 124-char base64url token- string token_2 = 2; // 24-char base64 token (decodes to 16 bytes binary)-}-```--**Live API test results:**-- ✅ API call succeeds with HTTP 200 when correct request format used-- ✅ Returns 2 tokens consistently across multiple test runs-- ✅ Token1: 124 chars base64url → decodes to 93 bytes binary starting with 0x01 (likely protobuf or encrypted blob)-- ✅ Token2: 24 chars base64 → decodes to 16 bytes binary (likely cryptographic key/nonce/HMAC)-- ❌ Tokens do NOT map directly to SIP username/password — they're processed opaquely by native Birdsong code--**SIP device ID source confirmed:**-- From GetAccount API: `account.phones[].linkedVoIPDevices[].SIPDeviceID`-- Example: `"BF64C4FE8E6AB1E3FFACA3FE0B1173F895E590385B2FD45B929FB8CA8F42DF77"` (64-char hex)-- Account API already implemented in existing codebase--### 1.3 PJSIP Integration ✅--**PJSIP built from source for Android:**-- Version: 2.14.1-- Source location: `/Users/vayun/Documents/Modern-Apps/third_party/pjsip/`-- Configured for: arm64-v8a, Android API 31, NDK 29.0.14206865-- Built libraries: libpj, libpjsip, libpjsip-ua, libpjsip-simple, libpjsua, libpjsua2, libpjmedia (+ codecs), libpjmedia-audiodev, libpjmedia-videodev, libpjnath, libpjlib-util, plus third-party libs (libsrtp, libwebrtc, libyuv, libspeex, libgsmcodec, libilbccodec, libg7221codec, libresample)--**SWIG Java bindings generated:**-- 282 Java classes in `org.pjsip.pjsua2` package-- Native shared library: `libpjsua2.so` (6.6 MB) + `libc++_shared.so` (8.9 MB)-- Location in repo: `pjsip/src/main/java/org/pjsip/` and `pjsip/src/main/jniLibs/arm64-v8a/`--**Gradle module created:**-- New module `:pjsip` added to `settings.gradle.kts`-- `pjsip/build.gradle.kts` configured as Android library module-- Messages module depends on `:pjsip` via `implementation(project(":pjsip"))`-- Compiles successfully (after fixing Kotlin/Java interop issues with SWIG-generated code)--### 1.4 SIP Manager Implementation ✅--**Files created:**-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCredentials.kt` — data class for SIP auth credentials from API-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.kt` — PJSUA2 wrapper singleton with init(), register(), makeCall(), endCall(), destroy() methods--**SipManager features:**-- PJSIP endpoint initialization with WebRTC AEC echo cancellation (matching GV app)-- DNS resolver configured with public nameservers (8.8.8.8, 8.8.4.4, 1.1.1.1, 1.0.0.1)-- SIP UDP transport on port 5060, TLS transport attempted on 5061-- Account registration with digest auth support-- Call state and media state callbacks-- Audio routing to Android sound device--**GVoiceClient extensions:**-- `fetchSipCredentials()` method added to call GetSIPRegisterInfo API and parse response into SipCredentials object-- `getSIPRegisterInfo()` test method updated to attempt PJSIP registration and log results--### 1.5 Live Testing Results ✅--**Test setup:** Messages app with test button in Settings screen calling `vm.testSIPRegisterInfo()`--**Results from live testing on device:**-- ✅ GetSIPRegisterInfo API call succeeds (HTTP 200)-- ✅ SIP device ID correctly extracted from GetAccount API response-- ✅ PJSIP endpoint initializes successfully-- ✅ PJSIP DNS configured with 8.8.8.8, 8.8.4.4, 1.1.1.1, 1.0.0.1-- ✅ PJSIP attempts DNS SRV lookup for `_sip._udp.voice.sip.google.com`-- ❌ **DNS SRV lookup fails: NXDOMAIN** (domain does not exist)-- ❌ **DNS A record lookup fails: NXDOMAIN** for `voice.sip.google.com`-- ❌ **SIP REGISTER fails with 502** due to DNS resolution failure-- ✅ Same NXDOMAIN result across all 4 public DNS servers tested--**Conclusion from live testing:** `voice.sip.google.com` does not exist in public DNS, not even on Google's own DNS servers. The official GV app must receive SIP server IP addresses via a different mechanism.-------## 2. Code Architecture Deep Dive — What Was Mapped--### 2.1 Proto Structure Mapping (from decompiled APK)--**wra proto** (`defpackage.wra` → likely `VoiceAccountConfig` or similar):-```-message wra { // obfuscated name, likely VoiceConfig or SipServerConfig- 1: string c- 2: string d- 6: bytes e- 8: repeated wqz f // <-- preresolved addresses list- 9: wor g-}-```--**wqz proto** (`defpackage.wqz` → likely `PreresolvedAddress`):-```-message wqz { // obfuscated name, likely PreresolvedAddress- 1: string b // hostname (e.g., "voice.sip.google.com")- 2: repeated bytes c // IPv4 addresses list- 3: repeated bytes d // IPv6 addresses list-}-```--**BirdsongConfig proto** (from `BirdsongConfigOuterClass$BirdsongConfig`):-```-message BirdsongConfig {- 1: string sip_server_uri // setSipServerUri()- 2: string secondary_sip_server_uri // setSecondarySipServerUri()- 3: string auth_realm // setAuthRealm()- 4: string auth_user // setAuthUser()- 5: string client_id // setClientId() - same as auth_user- 6: string client_version_label- 7: ClientType client_type // GV_ANDROID enum value- 8: string device_type // Build.MODEL- 11: bool enable_long_lived_connection- 12: string birdsong_directory- 13: LoggingOptions logging_options- 14: MediaNegotiationOptions (deprecated)- 15: AudioOptions audio_options- 16: bool enable_qos- 17: bool use_tcp- 18: string additional_root_cert_file- 20: DnsOptions dns_options // <-- setDnsOptions(ugfVar)- 21: repeated ClientGroup client_group- 22: bool run_tcp_probe- 23: AuthScheme auth_scheme // enum: UNSPECIFIED(0), BEARER(1), DIGEST(2)- 24: bool enable_remote_hold- 26: int32 audio_media_stats_interval_ms- 27: bool disable_registration_retries- 28: bool disable_tls_cert_validation- 29: bool enable_webrtc_tls // deprecated- 30: bool enable_unified_thread // deprecated- 31: int32 call_stale_timeout_seconds // default 70-}--message DnsOptions { // ugf in obfuscated code- 2: repeated PreresolvedAddress preresolved_addresses-}--message PreresolvedAddress { // uge in obfuscated code- 1: string hostname- 2: repeated bytes ipv4_addrs- 3: repeated bytes ipv6_addrs-}-```--### 2.2 Data Flow Through Obfuscated Code (fully traced)--```-Server config API / Phenotype flags- → lwp.java (obfuscated DI provider, implements lwl/lwv)- → builds wqc proto with wij inside- → wij.m field contains wra proto- → wra.f contains repeated wqz (preresolved addresses)- → mbb.g(wra) converts to ugf (DnsOptions)- → mbv constructor sets BirdsongConfig.setDnsOptions(ugfVar)- → VoiceCallManagerBuilder.setBirdsongConfig()- → Native Birdsong SIP stack receives preresolved IPs- → Bypasses DNS lookup entirely, connects directly to provided IPs-```--**Key classes in decompiled APK** (obfuscated names → likely real names):-- `defpackage.mbv` → `CallManagerWrapper` — builds BirdsongConfig, line 133 sets DnsOptions-- `defpackage.mbk` → `BirdsongV1ToV2Bridge` — bridges to native, line 234 sets DnsOptions-- `defpackage.mbb` → `BirdsongTelephonyImpl` — line 39 hardcodes `"voice.sip.google.com"`, line 62 `g(wra)` converts wra→DnsOptions-- `defpackage.lwp` → builds wqc/wij/wra protos via DI, many instances across codebase-- `defpackage.lwh` → has `x()` method returning `Optional<wra>` from `wqc.d.m`-- `defpackage.mcv` → `VoipAuthTokenManager` — handles GetSIPRegisterInfo API, caches tokens in `mcs` proto-- `defpackage.mbt` → `GaiaOauthTokenGetterAsync` — provides OAuth tokens to native Birdsong at SIP REGISTER time--### 2.3 Authentication Flow--**From code analysis of mcv.java (VoipAuthTokenManager):**--```java-// mcv.java decompiled structure:-class mcv { // VoipAuthTokenManager- Map k; // cache keyed by rkp (account identifier)- // ...- swq a(rkp rkpVar) { // getAuthToken- return this.h.b(swq.g(d(rkpVar).A()), ...);- }- iog d(rkp rkpVar) { // returns gRPC stub- return ((mcu) rez.M(context, mcu.class, rkpVar)).aQ();- }- String c(mcs mcsVar) { // formats token for logging- // "[auth_time=%s (%s ago) exp_time=%s (%s from now) token=[[%s]]"- // mcs.b = token string, mcs.c = auth_time, mcs.d = exp_time- }-}--class mcs { // proto storage for cached token- String b; // token string- long c; // auth_time (epoch millis)- long d; // exp_time (epoch millis)-}-```--**mcu interface:**-```java-public interface mcu {- iog aQ(); // returns gRPC stub for GetSIPRegisterInfo API- iij g();-}-```--**Flow:** GetSIPRegisterInfo API → mcs proto (b=token, c=auth_time, d=exp_time) → cached in mcv.k Map → mbt (GaiaOauthTokenGetterAsync) provides token to native Birdsong at SIP REGISTER time → native adds Authorization header (likely Bearer OAuth or SIP Digest derived from token).--**Only ONE token flows to native** (mcs.b singular), despite API returning 2 tokens (token_1 124-char base64url + token_2 24-char base64). Token_2 is likely used server-side to bind token_1 to sip_device_id, or stripped during client-side parsing, or used in OAuth token exchange but not passed to Birdsong directly.-------## 3. What Remains — Next Steps for Future Agent--### 3.1 Immediate Next Step: Identify Server Configuration Delivery Mechanism--**The critical blocker:** Find which specific API endpoint or Phenotype flag delivers the `wra` proto containing preresolved SIP server IP addresses.--**Approach options:**--**Option A: Network capture from official GV app (recommended, most direct)**-- Install Packet Capture app (uses local VPN, no root, captures plaintext SIP not HTTPS)-- OR use mitmproxy with custom CA for HTTPS API capture-- Open official Google Voice app, observe network traffic at startup-- Look for API responses containing SIP server hostnames, IP addresses, or wra/wqz/uge/ugf proto structures-- Likely candidates: Phenotype flag sync API, account config API, or dedicated voice config endpoint-- Expected to find preresolved IP addresses for voice.sip.google.com in the response--**Option B: Runtime instrumentation of official GV app**-- Use Frida framework to hook into official GV app process on rooted device or emulator-- Hook `lwh.x()` method to dump wra proto contents when called-- Or hook `mbb.g()` to see what preresolved addresses are passed to BirdsongConfig-- Requires root or emulator with Frida Gadget injected--**Option C: Continue static code analysis deeper**-- Trace through obfuscated DI providers (kjv, kjt, ybu types in lwp constructor) to find where wra values originate-- Search for Phenotype flag names related to voice/sip/server/dns in decompiled resources-- Look for API endpoint strings beyond GetSIPRegisterInfo that might deliver server config-- Very time-consuming due to heavy obfuscation across dozens of files with single-letter names--**Option D: Brute force Google IP ranges**-- Google owns large IP blocks: 8.34.208.0/20, 8.35.192.0/20, 34.0.0.0/8, 35.184.0.0/13, 35.190.0.0/15, 35.192.0.0/12, 35.208.0.0/12, 35.224.0.0/12, 35.240.0.0/13, 104.154.0.0/15, 104.196.0.0/14, etc.-- Try PJSIP registration against likely SIP server IPs in these ranges on ports 5060/5061-- Time-consuming and may trigger rate limiting or blocking--### 3.2 Once SIP Server IPs Are Known--**Update SipManager to use preresolved addresses:**-1. Add method to configure PJSIP with explicit server IP bypassing DNS (similar to Birdsong's preresolved address mechanism)-2. In PJSIP, this can be done via `pjsua_acc_add()` with explicit `reg_uri` containing IP instead of hostname, OR via DNS SRV override, OR via hosts file manipulation on rooted device for testing-3. Update `SipCredentials` class to include server IP addresses alongside tokens-4. Test SIP registration — expect 401 Unauthorized challenge (proving server is reachable and credentials are being evaluated, even if mapping is wrong), then iterate on credential format until 200 OK--### 3.3 Determine Correct Credential Mapping--**Current hypothesis from code analysis:**-- BirdsongConfig has `auth_user` (string), `auth_realm` (string), `auth_scheme` enum (BEARER or DIGEST), but **no password field**-- `GaiaOauthTokenGetterAsync` provides OAuth token to native code at REGISTER time-- Native Birdsong likely constructs SIP Authorization header using OAuth Bearer token scheme, OR exchanges OAuth token for SIP digest credentials internally--**To test credential mappings with PJSIP:**-1. Try SIP Digest auth with various username/password combinations derived from API tokens-2. Try SIP Bearer auth (RFC 8760) with OAuth token in Authorization header if PJSIP supports it, or via custom header-3. Observe SIP response codes to narrow down correct format--**Credential variants to test** (already partially implemented in SipManager.getCredentialVariants()):-- A: username=sipDeviceId (64-char hex), password=token1 (124-char base64url)-- B: username=sipDeviceId, password=token2 (24-char base64)-- C: username=sipDeviceId, password=token2 decoded to hex (16 bytes → 32 hex chars)-- D: username=token1 truncated, password=token2-- E: username=sipDeviceId, password=token1 decoded to hex (93 bytes → 186 hex chars)-- Additional variants to try: username from GetAccount API primaryDestinationID (+1213... phone number), password as OAuth Bearer token via custom SIP header, etc.--### 3.4 Complete Voice Calling Implementation--Once SIP registration succeeds (200 OK response), remaining work per original plan:--**Android Telecom Integration:**-- Create `GVoiceConnectionService.kt` extending `android.telecom.ConnectionService`-- Create `GVoiceConnection.kt` extending `android.telecom.Connection`-- Create `GVoicePhoneAccountRegistrar.kt` to register PhoneAccount with TelecomManager-- Handle incoming/outgoing call lifecycle via Telecom callbacks--**UI Integration:**-- Add call button to ConversationScreen top bar (next to edit contact button)-- Show only for Voice conversations with peer phone number-- Launch call via ViewModel → SessionManager → GVoiceClient → SipManager flow--**Audio Pipeline:**-- PJSIP already configured with WebRTC AEC echo cancellation-- Handle audio focus, routing (earpiece/speaker/bluetooth), mute/unmute-- Test audio quality--**Permissions** (already in GV APK manifest as reference, need to add to our app):-- RECORD_AUDIO, MODIFY_AUDIO_SETTINGS, MANAGE_OWN_CALLS, READ_PHONE_STATE-- FOREGROUND_SERVICE_PHONE_CALL, FOREGROUND_SERVICE_MICROPHONE, FOREGROUND_SERVICE_MEDIA_PLAYBACK-------## 4. File Inventory — What's Been Modified/Created--### New Files Created This Session--**PJSIP Module:**-- `/Users/vayun/Documents/Modern-Apps/pjsip/build.gradle.kts` — Android library module config-- `/Users/vayun/Documents/Modern-Apps/pjsip/src/main/java/org/pjsip/pjsua2/` — 282 generated Java classes from SWIG (copied from PJSIP build output)-- `/Users/vayun/Documents/Modern-Apps/pjsip/src/main/jniLibs/arm64-v8a/libpjsua2.so` — 6.6 MB native shared library-- `/Users/vayun/Documents/Modern-Apps/pjsip/src/main/jniLibs/arm64-v8a/libc++_shared.so` — 8.9 MB C++ runtime--**SIP Implementation:**-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCredentials.kt` — data class for SIP auth credentials-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.kt` — PJSUA2 wrapper singleton (init, register, makeCall, endCall, destroy)--**Documentation:**-- `/Users/vayun/Documents/Modern-Apps/GOOGLE_VOICE_CALLING_PLAN.md` — Original implementation plan with architecture overview-- `/Users/vayun/Documents/Modern-Apps/GOOGLE_VOICE_CALLING_HANDOFF.md` — This document--**Reverse Engineering Artifacts:**-- `/Users/vayun/Documents/Modern-Apps/reverse-engineering/gvoice-re/` — Decompiled GV APK- - `base.apk` (23.9 MB) + `split_config.arm64_v8a.apk` (8.0 MB) — pulled from device- - `apktool-out/` — decompiled resources and smali- - `jadx-out/` — decompiled Java source (obfuscated)- - `lib/arm64-v8a/libtacl_jni.so` (7.3 MB) — extracted native library with Birdsong SIP stack--### Modified Files This Session--**Proto definitions:**-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/proto/requests.proto` — Added ReqGetSIPRegisterInfo message with client_type and sip_device_id fields-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/proto/responses.proto` — Added RespGetSIPRegisterInfo, SIPRegisterInfo, SIPCredentials messages matching actual API response structure discovered via live testing--**GVoice client:**-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt` — Added fetchSipCredentials() and getSIPRegisterInfo() methods--**Session management:**-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/util/MessagesSessionManager.kt` — Added getSIPRegisterInfo() passthrough-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/util/MessagesViewModel.kt` — Added testSIPRegisterInfo() for UI testing--**UI for testing:**-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/ui/SettingsScreen.kt` — Added test button to trigger SIP API test--**Build configuration:**-- `/Users/vayun/Documents/Modern-Apps/settings.gradle.kts` — Added include(":pjsip")-- `/Users/vayun/Documents/Modern-Apps/messages/build.gradle.kts` — Added ktor-client-okhttp dependency (fixes TLS hostname verification), added pjsip module dependency, removed duplicate okhttp dependency-- `/Users/vayun/Documents/Modern-Apps/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceRpcClient.kt` — Switched from Ktor CIO engine to OkHttp engine to fix "hostname aware checkServerTrusted" TLS error on newer Android--**Third-party source:**-- `/Users/vayun/Documents/Modern-Apps/third_party/pjsip/` — PJSIP 2.14.1 source code (9.8MB tarball extracted), configured and built for Android arm64-v8a-------## 5. Key Technical Details for Next Agent--### 5.1 API Endpoints Discovered--**Working endpoints (confirmed via live testing):**-- `https://clients6.google.com/voice/v1/voiceclient/account/get` — GetAccount API, returns account info including SIP device ID-- `https://clients6.google.com/voice/v1/voiceclient/sipregisterinfo/get` — GetSIPRegisterInfo API, returns SIP credentials tokens (requires client_type + sip_device_id in request)--**Endpoint from constants but not yet tested:**-- `https://clients6.google.com/voice/v1/voiceclient/api2thread/*` — messaging endpoints (already working in existing codebase)-- Other endpoints defined in `VoiceEndpoints` object in Constants.kt--### 5.2 Test Method Available--In the app, go to **Settings → tap "Test SIP Register Info" button** to trigger the full test flow:-1. Fetches account to get SIP device ID-2. Calls GetSIPRegisterInfo API with client_type=3 + sip_device_id-3. Logs full response structure including raw protobuf bytes and unknown fields-4. Attempts PJSIP registration with multiple credential variants-5. Logs SIP registration results via logcat tags: `GVoiceClient`, `SipManager`, `SipAccount`, `PJSIP`, `SIP_TEST`--**To view logs:** `adb logcat -d -s GVoiceClient:I SIP_TEST:I SipManager:I SipAccount:I PJSIP:D`--### 5.3 Build Commands--```bash-# Build and install dev variant (preserves data, debug build over debug build)-cd /Users/vayun/Documents/Modern-Apps-./gradlew :messages:installDev --no-daemon--# If build cache issues occur:-./gradlew clean --no-daemon --no-configuration-cache-./gradlew :messages:installDev --no-daemon --no-configuration-cache--# View logs-adb logcat -c # clear-adb logcat -s GVoiceClient:I SIP_TEST:I SipManager:I SipAccount:I PJSIP:D-```--### 5.4 Decompiled APK Locations--- **Java decompiled:** `/Users/vayun/Documents/Modern-Apps/reverse-engineering/gvoice-re/jadx-out/sources/`- - GV app code: `com/google/android/apps/voice/`- - Obfuscated DI: `defpackage/` (single-letter class names)- - Key classes: `mbb.java` (BirdsongTelephonyImpl), `mbk.java` (BirdsongV1ToV2Bridge), `mbv.java` (CallManagerWrapper), `mcv.java` (VoipAuthTokenManager), `lwh.java` (has x() returning wra), `lwp.java` (builds wqc/wij/wra protos), `wra.java`, `wqz.java`, `wqc.java`, `wij.java` (proto definitions)--- **Native library:** `/Users/vayun/Documents/Modern-Apps/reverse-engineering/gvoice-re/lib/arm64-v8a/libtacl_jni.so` (7.3 MB, ARM64 ELF, stripped)- - Analyzed with: strings, nm/objdump, Ghidra headless import completed- - Key strings found confirming BirdsongDns, preresolved addresses, SRV lookups, Google DNS 8.8.8.8--- **APK resources:** `/Users/vayun/Documents/Modern-Apps/reverse-engineering/gvoice-re/apktool-out/`- - AndroidManifest.xml with VoIP permissions and services- - Layout resources including express_sign_in layouts (OneGoogle sign-in UI)--### 5.5 Go Bridge Reference--Local clone at `/Users/vayun/Documents/bridges/gvoice/` — mautrix-gvoice Matrix bridge with Go implementation of Google Voice protocol. Contains:-- `pkg/libgv/client.go` — HTTP client with cookie auth and API methods (but GetSIPRegisterInfo not implemented — only endpoint constant exists)-- `pkg/libgv/constants.go` — endpoint URLs including EndpointGetSIPRegisterInfo-- `pkg/libgv/gvproto/` — protobuf definitions (but SIP register info protos missing, matching what we discovered)--The Go bridge was useful as reference for existing API patterns but does not implement voice calling functionality.-------## 6. Estimated Remaining Work--| Task | Effort | Notes |-|------|--------|-------|-| Identify server config delivery mechanism (wra proto source) | 1-3 days | Requires network capture or deep obfuscated code tracing through DI layers |-| Determine SIP credential mapping from API tokens | 1-2 days | Try PJSIP registration with various token interpretations, observe SIP response codes |-| Configure PJSIP with preresolved SIP server IPs | 0.5 days | Once IPs are known, straightforward PJSIP config update |-| Android Telecom integration (ConnectionService) | 2-3 days | Standard Android Telecom API implementation |-| Call button UI + ViewModel integration | 1 day | Add to ConversationScreen, wire through existing layers |-| Audio pipeline testing & polish | 2-3 days | PJSIP already configured with WebRTC AEC |-| **Total remaining** | **~1-2 weeks** | After SIP server IPs and credential mapping are resolved |-------## 7. Important Notes for Next Agent--- **Do NOT suggest network capture** — user has explicitly declined this approach multiple times, prefers code analysis only-- **Do NOT suggest uninstalling the app** — user lost data previously, always use `./gradlew :messages:installDev` for debug builds to preserve data-- **PJSIP is already built and integrated** — don't rebuild from scratch unless modifying PJSIP source itself; the `:pjsip` module is ready to use-- **Test button is in Settings screen** — "Test SIP Register Info" triggers the full test flow including PJSIP registration attempts-- **Logs to watch:** `adb logcat -s GVoiceClient:I SIP_TEST:I SipManager:I SipAccount:I PJSIP:D`-- **The 2 tokens from API are key** — 124-char base64url token likely contains SIP credentials in some encoded/encrypted form that needs to be decoded or mapped correctly for PJSIP digest auth-- **DNS NXDOMAIN is expected behavior** — voice.sip.google.com intentionally does not resolve publicly; official app receives preresolved IPs via server config (wra proto field 8 / wqz list)
GOOGLE_VOICE_CALLING_PLAN.md
diff --git a/GOOGLE_VOICE_CALLING_PLAN.md b/GOOGLE_VOICE_CALLING_PLAN.mddeleted file mode 100644index b6e9ee0226..0000000000--- a/GOOGLE_VOICE_CALLING_PLAN.md+++ /dev/null@@ -1,435 +0,0 @@-# Google Voice Calling Integration Plan--## Executive Summary--This document outlines the implementation plan to add **full in-app VoIP calling** to the Messages app in Modern-Apps, enabling Google Voice voice calls via SIP protocol — matching the functionality of the official Google Voice Android app.--**Current Status:**-- ✅ APK pulled from device and decompiled (base.apk + split_config.arm64_v8a.apk)-- ✅ Decompiled with apktool and jadx-- ✅ Existing GVoiceClient handles SMS/MMS but NOT voice calling-- ✅ EndpointGetSIPRegisterInfo constant exists but is unused-- ⚠️ Protobuf definitions for SIP registration are missing-------## 1. Reverse Engineering Findings--### 1.1 APK Analysis--**Package:** `com.google.android.apps.googlevoice`-**Size:** 23.9 MB base + 8.0 MB arm64 split-**Key Components Found:**--```-AndroidManifest.xml permissions:- - CALL_PHONE, RECORD_AUDIO, MODIFY_AUDIO_SETTINGS- - MANAGE_OWN_CALLS, READ_PHONE_STATE- - FOREGROUND_SERVICE_PHONE_CALL, FOREGROUND_SERVICE_MICROPHONE- - FOREGROUND_SERVICE_MEDIA_PLAYBACK--Key Services:- - com.google.android.apps.voice.voip.telephony.connectionservice.selfmanaged.VoipConnectionService- (extends android.telecom.ConnectionService)- - com.google.android.apps.voice.voip.ui.callservice.CallForegroundService- - com.google.android.apps.voice.voip.ui.VoipCallActivity--Key UI:- - VoipCallActivity (in-call screen)- - CallForegroundService (foreground service for ongoing calls)- - OngoingCallActionReceiver (handles answer/hangup/decline actions)-```--### 1.2 SIP Architecture Discovered--**SIP Server:** `voice.sip.google.com` (hardcoded in decompiled code: `mbb.java:39`)--**SIP Stack:** Google uses **Birdsong** — a proprietary SIP/WebRTC implementation:-- `com.google.third_party.resiprocate.src.apps.birdsong.ReferState`-- `com.google.android.apps.voice.voip.telephony.birdsongimpl.BirdsongTelephonyImpl`-- References to `NetworkQualityMetrics$NetworkQualityMeasurementResult`--**Key Decompiled Classes:**-- `VoipConnectionService.java` — Android Telecom ConnectionService implementation-- `BirdsongTelephonyImpl` (obfuscated as `mbb.java`) — Core SIP/WebRTC engine-- Uses WebRTC for audio: `org.webrtc.audio.WebRtcAudioTrack`, `WebRtcAudioRecord`--### 1.3 Missing Pieces--The existing Modern-Apps codebase has:-- ✅ `EndpointGetSIPRegisterInfo` constant defined-- ❌ No protobuf definition for SIP register request/response-- ❌ No SIP client implementation-- ❌ No WebRTC/SIP library integration-- ❌ No ConnectionService implementation-- ❌ No in-call UI-------## 2. Technical Architecture--### 2.1 High-Level Flow--```-User taps call button in ConversationScreen- ↓-MessagesViewModel.startVoiceCall(phoneNumber)- ↓-GVoiceClient.startCall(phoneNumber)- ↓-1. Call GetSIPRegisterInfo API to get SIP credentials-2. Initialize SIP stack (PJSIP or similar) with credentials-3. Register with voice.sip.google.com-4. Place SIP INVITE to destination- ↓-Android Telecom ConnectionService displays system call UI- ↓-WebRTC handles audio stream- ↓-Call ends → SIP BYE → unregister-```--### 2.2 Components to Build--#### A. Protobuf Definitions (Priority: HIGH)-Add to `messages/src/main/proto/`:--```protobuf-// requests.proto additions-message ReqGetSIPRegisterInfo {- // Empty or minimal fields - needs verification via network capture-}--// responses.proto additions -message RespGetSIPRegisterInfo {- SIPRegisterInfo sip_register_info = 1;-}--message SIPRegisterInfo {- string username = 1; // SIP username- string password = 2; // SIP password / auth token- string domain = 3; // voice.sip.google.com- string proxy = 4; // SIP proxy server- int32 expires = 5; // Registration expiry seconds- string display_name = 6;- string authorization_id = 7;- // Additional fields TBD via network capture-}-```--#### B. SIP Client Layer (Priority: HIGH)--**Library Choice:** Use **PJSIP** (pjsip.org) via JNI wrapper or **baresip** — both are mature open-source SIP stacks for Android.--Recommended: **PJSIP Android** (`org.pjsip:pjsua2`)-- Mature, well-documented-- Supports TLS, SRTP, WebRTC audio-- Android NDK integration available-- Alternative: Use WebRTC directly with SIP over WebSocket (more complex)--**New files:**-- `messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.kt` — SIP registration and call control-- `messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCall.kt` — Per-call state machine-- `messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipAccount.kt` — SIP account configuration--#### C. Android Telecom Integration (Priority: HIGH)--**New files:**-- `messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnectionService.kt`- - Extends `android.telecom.ConnectionService`- - Handles `onCreateOutgoingConnection()`, `onCreateIncomingConnection()`- - Manages call lifecycle with system UI--- `messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnection.kt`- - Extends `android.telecom.Connection`- - Per-call connection object- - Handles answer, reject, hold, mute, disconnect--- `messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoicePhoneAccountRegistrar.kt`- - Registers PhoneAccount with TelecomManager- - Required for system to route calls through our app--#### D. In-Call UI (Priority: MEDIUM)--**New files:**-- `messages/src/main/java/com/vayunmathur/messages/ui/VoiceCallScreen.kt`- - Compose UI for active call- - Mute, speaker, keypad, hangup buttons- - Call duration timer- - Audio device selector--- Update `AndroidManifest.xml`:- - Add `VoipCallActivity` equivalent- - Add `ConnectionService` declaration- - Add required permissions (already present in GV APK manifest as reference)--#### E. GVoiceClient Extensions (Priority: HIGH)--Extend existing `GVoiceClient.kt`:-```kotlin-suspend fun getSIPRegisterInfo(): SIPCredentials?-suspend fun startVoiceCall(phoneNumber: String): Boolean-suspend fun endVoiceCall(callId: String): Boolean-fun observeIncomingCalls(): Flow<IncomingCallEvent>-```--#### F. UI Integration (Priority: MEDIUM)--Update `ConversationScreen.kt`:-- Add call button in top app bar (next to edit contact button)-- Only show for Voice conversations with peer phone number-- Launch call via ViewModel--Update `MessagesViewModel.kt`:-```kotlin-fun startVoiceCall(conversationId: String, onResult: (Boolean) -> Unit = {})-fun endVoiceCall(onResult: (Boolean) -> Unit = {})-val activeCallState: StateFlow<CallState?>-```-------## 3. Implementation Phases--### Phase 1: Protocol Discovery (1-2 days)-**Goal:** Understand SIP registration API response format--Tasks:-1. Add protobuf definitions for ReqGetSIPRegisterInfo / RespGetSIPRegisterInfo-2. Implement `GVoiceClient.getSIPRegisterInfo()` method-3. Test API call with existing cookie auth — log response structure-4. Document SIP credentials format (username, password, domain, proxy, etc.)-5. Verify SIP server is `voice.sip.google.com` and test connectivity--**Deliverable:** Documented SIP credentials API response format--### Phase 2: SIP Stack Integration (3-5 days)-**Goal:** Establish SIP registration and basic call capability--Tasks:-1. Add PJSIP Android dependency to `messages/build.gradle.kts`-2. Create JNI wrapper or use pjsua2 Java bindings-3. Implement `SipManager` singleton:- - Initialize PJSIP endpoint- - Configure audio devices (WebRTC AEC, NS)- - Register SIP account with credentials from Phase 1- - Handle registration state changes-4. Implement basic outgoing call flow (SIP INVITE)-5. Test SIP registration succeeds--**Deliverable:** Working SIP registration, logs show "registered" state--### Phase 3: Android Telecom Integration (2-3 days)-**Goal:** System call UI integration--Tasks:-1. Create `GVoiceConnectionService` extending `ConnectionService`-2. Create `GVoiceConnection` extending `Connection`-3. Implement `GVoicePhoneAccountRegistrar`-4. Register PhoneAccount on app startup (if Voice is connected)-5. Test: placing call shows system incoming/outgoing call UI-6. Handle call actions (answer, hangup, hold, mute) via Connection callbacks--**Deliverable:** Tapping call button shows Android system call screen--### Phase 4: Audio Pipeline (2-3 days)-**Goal:** Two-way audio works--Tasks:-1. Configure PJSIP audio with WebRTC AEC/NS (matches GV app's approach)-2. Handle audio focus and routing (earpiece, speaker, bluetooth)-3. Implement mute/unmute-4. Test audio quality, echo cancellation-5. Handle audio device changes during call--**Deliverable:** Working two-way voice call with clear audio--### Phase 5: In-Call UI & Polish (2 days)-**Goal:** Complete user experience--Tasks:-1. Build `VoiceCallScreen` Compose UI (or rely on system UI via Telecom)-2. Add call button to ConversationScreen top bar-3. Handle incoming call notifications-4. Add call history to conversation thread (already partially supported via message types)-5. Permissions handling (RECORD_AUDIO, etc.)-6. Foreground service for ongoing calls--**Deliverable:** End-to-end calling UX matching Google Voice app--### Phase 6: Testing & Edge Cases (2 days)-Tasks:-1. Test incoming calls-2. Test call hold/resume-3. Test network switching (WiFi ↔ cellular)-4. Test Bluetooth headset-5. Test with Do Not Disturb-6. Battery optimization handling-7. Reconnection logic-------## 4. Dependencies to Add--### build.gradle.kts (messages module)-```kotlin-dependencies {- // PJSIP for SIP stack- implementation("org.pjsip:pjsua2:2.13") // or latest- - // Alternative: WebRTC for audio processing- implementation("org.webrtc:google-webrtc:1.0.32006")- - // Android Telecom already available via SDK-}-```--### AndroidManifest.xml additions-```xml-<uses-permission android:name="android.permission.RECORD_AUDIO" />-<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />-<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />-<uses-permission android:name="android.permission.READ_PHONE_STATE" />-<uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />-<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />--<service- android:name=".gvoice.voice.GVoiceConnectionService"- android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE"- android:exported="true">- <intent-filter>- <action android:name="android.telecom.ConnectionService" />- </intent-filter>-</service>-```-------## 5. Key Technical Challenges--### Challenge 1: SIP Credentials API-**Risk:** GetSIPRegisterInfo response format unknown-**Mitigation:** Phase 1 is dedicated to discovering this via actual API call with logging. The endpoint constant already exists in codebase, suggesting it's the right path.--### Challenge 2: PJSIP Integration Complexity -**Risk:** PJSIP JNI setup is complex on Android-**Mitigation:** Use pre-built pjsua2 AAR if available, or evaluate alternative SIP stacks (baresip, sipdroid-lib). Fallback: implement minimal SIP over WebSocket if PJSIP proves too heavy.--### Challenge 3: Audio Quality-**Risk:** Echo, latency, or poor audio quality-**Mitigation:** Google Voice APK uses WebRTC audio processing (AEC, NS). We'll configure PJSIP to use WebRTC audio device or similar echo cancellation.--### Challenge 4: Background Execution-**Risk:** Android kills SIP connection in background-**Mitigation:** Use foreground service with FOREGROUND_SERVICE_PHONE_CALL type (as GV app does). Request battery optimization exemption.--### Challenge 5: Incoming Calls-**Risk:** Receiving incoming SIP calls requires persistent connection-**Mitigation:** Maintain SIP registration via foreground service. Use FCM push as fallback wake-up (GV app uses FCM per manifest).-------## 6. Files to Modify/Create--### New Files (15)-```-messages/src/main/proto/sip.proto # SIP register request/response-messages/src/main/java/com/vayunmathur/messages/gvoice/sip/- SipManager.kt # SIP stack singleton- SipAccount.kt # SIP account config- SipCall.kt # Per-call state- SipCredentials.kt # Credentials data class-messages/src/main/java/com/vayunmathur/messages/gvoice/voice/- GVoiceConnectionService.kt # Telecom ConnectionService- GVoiceConnection.kt # Telecom Connection- GVoicePhoneAccountRegistrar.kt # PhoneAccount registration- CallState.kt # Call state enum/sealed class- VoiceCallManager.kt # High-level call orchestration-messages/src/main/java/com/vayunmathur/messages/ui/- VoiceCallScreen.kt # In-call Compose UI (optional)- VoiceCallNotificationManager.kt # Ongoing call notification-```--### Modified Files (6)-```-messages/src/main/java/com/vayunmathur/messages/gvoice/- Constants.kt # Already has endpoint- GVoiceClient.kt # Add startCall(), getSIPRegisterInfo()- GVoiceRpcClient.kt # No changes needed (generic)--messages/src/main/java/com/vayunmathur/messages/util/- MessagesSessionManager.kt # Route call requests to GVoiceClient- MessagesViewModel.kt # Expose startVoiceCall() to UI--messages/src/main/java/com/vayunmathur/messages/ui/- ConversationScreen.kt # Add call button to top bar--messages/build.gradle.kts # Add PJSIP/WebRTC dependencies-messages/src/main/AndroidManifest.xml # Add ConnectionService, permissions-```-------## 7. Testing Strategy--1. **Unit tests:** SIP credentials parsing, call state machine-2. **Integration tests:** SIP registration flow with mock server, then real GV API-3. **Manual tests:**- - Outgoing call to real phone number- - Incoming call reception- - Audio quality test- - Bluetooth headset test- - Network switch test- - Background/foreground transitions-------## 8. Open Questions for Next Steps--1. **PJSIP vs alternatives:** Should we evaluate baresip or Linphone SDK as alternatives to PJSIP for simpler Android integration?-2. **Incoming call push:** Does GV use FCM to wake app for incoming calls, or rely on persistent SIP connection? (Manifest shows FCM service)-3. **STUN/TURN:** Does voice.sip.google.com require STUN/TURN servers for NAT traversal? Need to discover via network capture.-4. **Call recording:** Out of scope for v1, but note GV app may support it per legal requirements.-------## 9. Success Criteria--- [ ] User can tap call button in Voice conversation-- [ ] System call UI appears showing outgoing call-- [ ] Remote party's phone rings-- [ ] Two-way audio works with acceptable quality-- [ ] User can end call via system UI or in-app button-- [ ] Call appears in conversation history as "Voice call • X min Y sec"-- [ ] Incoming calls ring and can be answered-- [ ] Works on WiFi and cellular data-- [ ] Bluetooth headset audio routing works-------## 10. Estimated Timeline--| Phase | Duration | Cumulative |-|-------|----------|------------|-| Protocol Discovery | 1-2 days | 2 days |-| SIP Stack Integration | 3-5 days | 7 days |-| Telecom Integration | 2-3 days | 10 days |-| Audio Pipeline | 2-3 days | 13 days |-| UI & Polish | 2 days | 15 days |-| Testing | 2 days | 17 days |-| **Total** | **~2.5 weeks** | |-------## Appendix A: Decompiled Code References--**APK Location:** `/Users/vayun/Documents/Modern-Apps/reverse-engineering/gvoice-re/`--**Key findings:**-- `jadx-out/sources/com/google/android/apps/voice/voip/` — Full VoIP implementation-- `mbb.java:39` — SIP server hardcoded as `"voice.sip.google.com"`-- Uses Birdsong SIP stack (Google internal, based on reSIProcate)-- WebRTC for audio processing-- Android Telecom ConnectionService for system integration--**Next action:** Run Phase 1 to discover GetSIPRegisterInfo response format via live API call.
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 673f2008c5..37265460da 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -9,13 +9,6 @@ quickjs = "1.0.5" brotli = "0.1.2" # Build & Core Language agp = "9.4.0-alpha04"-# Google Play Services for RCS attestation (DroidGuard, SafetyNet, Firebase IID)-playServicesBase = "18.6.0"-playServicesAuth = "21.3.0"-playServicesSafetyNet = "18.1.0"-playIntegrity = "1.4.0"-firebaseMessaging = "24.1.0"-firebaseInstallations = "18.0.0" fhirModel = "1.0.0-beta02" flatgeobuf = "3.29.0" kotlin = "2.4.0"@@ -234,12 +227,6 @@ zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } keepassjava2-dom = { module = "org.linguafranca.pwdb:KeePassJava2-dom", version.ref = "keepassJava2" } bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" } bouncycastle-pkix = { module = "org.bouncycastle:bcpkix-jdk18on", version.ref = "bouncycastle" }-play-services-base = { group = "com.google.android.gms", name = "play-services-base", version.ref = "playServicesBase" }-play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" }-play-services-safetynet = { group = "com.google.android.gms", name = "play-services-safetynet", version.ref = "playServicesSafetyNet" }-play-integrity = { group = "com.google.android.play", name = "integrity", version.ref = "playIntegrity" }-firebase-messaging = { group = "com.google.firebase", name = "firebase-messaging", version.ref = "firebaseMessaging" }-firebase-installations = { group = "com.google.firebase", name = "firebase-installations", version.ref = "firebaseInstallations" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" }
messages/build.gradle.kts
diff --git a/messages/build.gradle.kts b/messages/build.gradle.ktsindex ea923d77c0..6971145ed2 100644--- a/messages/build.gradle.kts+++ b/messages/build.gradle.kts@@ -180,9 +180,6 @@ dependencies { implementation(libs.androidx.camera.lifecycle) implementation(libs.androidx.camera.view) - // OkHttp — WebSocket transport for Signal- implementation("com.squareup.okhttp3:okhttp:4.12.0")- // Bouncy Castle — AES-IGE for MTProto encryption, X25519 for WhatsApp Noise implementation(libs.bouncycastle) @@ -197,23 +194,9 @@ dependencies { // protobuf 4.x. libsignal-android 0.86 (Signal bridge) cannot decrypt WhatsApp's X3DH pkmsgs. implementation(project(mapOf("path" to ":whatsapp-signal", "configuration" to "shaded"))) - // OkHttp — WebSocket transport for Signal- implementation("com.squareup.okhttp3:okhttp:4.12.0") // Ktor OkHttp engine — required for proper TLS hostname verification (fixes GVoice "hostname aware checkServerTrusted" error) implementation("io.ktor:ktor-client-okhttp:3.2.3") // kotlinx.serialization — session data persistence implementation(libs.kotlinx.serialization.json)-- // PJSIP — SIP stack for Google Voice calling- implementation(project(":pjsip"))-- // Google Play Services — for RCS attestation (DroidGuard, SafetyNet, Firebase IID)- // Required for Google Jibe ACS provisioning per decompiled Google Messages code analysis- implementation(libs.play.services.base)- implementation(libs.play.services.auth)- implementation(libs.play.services.safetynet)- implementation(libs.play.integrity)- implementation(libs.firebase.messaging)- implementation(libs.firebase.installations) }
messages/src/main/AndroidManifest.xml
diff --git a/messages/src/main/AndroidManifest.xml b/messages/src/main/AndroidManifest.xmlindex 9eca104029..cb79c751bd 100644--- a/messages/src/main/AndroidManifest.xml+++ b/messages/src/main/AndroidManifest.xml@@ -22,16 +22,6 @@ FindFamily app's CreateLinkIntent (location-share feature). --> <uses-permission android:name="com.vayunmathur.findfamily.permissions.ACCESS_FAMILY" /> - <!-- Google Voice calling permissions -->- <uses-permission android:name="android.permission.GET_ACCOUNTS" />- <uses-permission android:name="android.permission.RECORD_AUDIO" />- <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />- <uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />- <uses-permission android:name="android.permission.READ_PHONE_STATE" />- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />- <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />- <!-- Package visibility (Android 11+): we resolve/launch the FindFamily link-creation activity and the system camera app explicitly. --> <queries>@@ -136,15 +126,6 @@ </intent-filter> </receiver> - <!-- Google Voice Telecom ConnectionService for system calling integration -->- <service- android:name=".gvoice.voice.GVoiceConnectionService"- android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE"- android:exported="true">- <intent-filter>- <action android:name="android.telecom.ConnectionService" />- </intent-filter>- </service> </application> </manifest>
messages/src/main/java/com/vayunmathur/messages/MainActivity.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt b/messages/src/main/java/com/vayunmathur/messages/MainActivity.ktindex b417eb0ebf..6abb11eb6a 100644--- a/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt+++ b/messages/src/main/java/com/vayunmathur/messages/MainActivity.kt@@ -47,8 +47,6 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()- // Register Google Voice PhoneAccount for Telecom integration on app startup- com.vayunmathur.messages.gvoice.voice.GVoicePhoneAccountRegistrar.register(this) pendingIntent.value = intent setContent { DynamicTheme {@@ -96,7 +94,6 @@ sealed interface Route : NavKey { @Serializable data object LoginWhatsApp : Route @Serializable data object LoginMessenger : Route @Serializable data object LoginInstagram : Route- @Serializable data object LoginRcs : Route /** * "Compose new" screen — recipient picker + body + media preview.@@ -169,9 +166,6 @@ private fun Navigation( entry<Route.LoginInstagram> { com.vayunmathur.messages.ui.setup.InstagramLoginScreen(backStack) }- entry<Route.LoginRcs> {- com.vayunmathur.messages.ui.setup.RcsLoginScreen(backStack)- } entry<Route.Compose> { route -> ComposeScreen( backStack = backStack,
messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt b/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.ktindex d6802b5be7..3608fc23d5 100644--- a/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt+++ b/messages/src/main/java/com/vayunmathur/messages/data/MessageSource.kt@@ -30,11 +30,7 @@ enum class MessageSource { MESSENGER, /** Conversations on Instagram Direct, accessed via MQTT. */- INSTAGRAM,-- /** Conversations via RCS (Rich Communication Services) using Google Jibe- * backend over Tachyon gRPC protocol with SIP for messaging. */- RCS;+ INSTAGRAM; /** Prefix for compound primary keys (e.g. "msgs:<id>"). */ val idPrefix: String get() = when (this) {@@ -45,7 +41,6 @@ enum class MessageSource { WHATSAPP -> "wa" MESSENGER -> "fb" INSTAGRAM -> "ig"- RCS -> "rcs" } }
messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.ktindex 728ba8a82e..0d48ffd3f5 100644--- a/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt+++ b/messages/src/main/java/com/vayunmathur/messages/data/MessagesDatabase.kt@@ -93,7 +93,13 @@ class MessagesConverters { @TypeConverter fun fromSource(value: MessageSource): String = value.name @TypeConverter- fun toSource(value: String): MessageSource = MessageSource.valueOf(value)+ fun toSource(value: String): MessageSource = try {+ MessageSource.valueOf(value)+ } catch (_: IllegalArgumentException) {+ // Handles stale RCS rows after Phase 2 removal (DB version 9 -> 10)+ android.util.Log.w("MessagesConverters", "Unknown MessageSource $value, falling back to MESSAGES_WEB")+ MessageSource.MESSAGES_WEB+ } @TypeConverter fun fromDirection(value: MessageDirection): String = value.name@@ -108,7 +114,7 @@ class MessagesConverters { @androidx.room.Database( entities = [Conversation::class, Message::class],- version = 9,+ version = 10, exportSchema = false, ) @TypeConverters(MessagesConverters::class)
messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.ktindex 59983ac289..c24c33b040 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt@@ -45,7 +45,6 @@ object VoiceEndpoints { const val EndpointGetAccount = "$ApiBaseUrl/account/get" const val EndpointGetThread = "$ApiBaseUrl/api2thread/get" const val EndpointListThreads = "$ApiBaseUrl/api2thread/list"- const val EndpointGetSIPRegisterInfo = "$ApiBaseUrl/sipregisterinfo/get" const val EndpointSendSms = "$ApiBaseUrl/api2thread/sendsms" const val EndpointGetThreadingInfo = "$ApiBaseUrl/threadinginfo/get" const val EndpointUpdateAttributes = "$ApiBaseUrl/thread/updateattributes"
messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.ktindex b7b7901eb8..a0f5d66abc 100644--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt+++ b/messages/src/main/java/com/vayunmathur/messages/gvoice/GVoiceClient.kt@@ -1,9 +1,7 @@ package com.vayunmathur.messages.gvoice -import android.accounts.AccountManager import android.content.Context import android.util.Log-import com.google.android.gms.auth.GoogleAuthUtil import com.vayunmathur.messages.data.MessageSource import com.vayunmathur.messages.gmessages.GMEvent import kotlinx.coroutines.CoroutineScope@@ -20,7 +18,6 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.delay import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock-import kotlinx.coroutines.withContext import requests.Requests import responses.Responses import threads.Threads@@ -784,333 +781,6 @@ object GVoiceClient { // Internals // ---------------------------------------------------------------- - /**- * Fetch SIP registration credentials for VoIP calling.- * Obtains OAuth token via Google Auth API for Bearer authentication- * (RFC 8760) with voice.sip.google.com via PJSIP.- *- * Based on deobfuscation (task 7):- * - snj abstract class defines OAuth scope via a() method- * - snl concrete implementation holds scope string- * - lou.java:40 returns tvt.cc("oauth2:https://www.googleapis.com/auth/sipregistrar")- * - snk.java uses mxc.d(Account, scope) to fetch token via GoogleAuthUtil- * - Official app uses Bearer OAuth, not digest authentication- * - BirdsongConfig provides auth_user and auth_realm- *- * OAuth scope: https://www.googleapis.com/auth/sipregistrar- *- * @return SipCredentials on success, null on failure- */- suspend fun fetchSipCredentials(): com.vayunmathur.messages.gvoice.sip.SipCredentials? {- val client = rpc ?: return null- return try {- // First, fetch account to get SIP device ID and BirdsongConfig- val accResp = client.postPbLite(- url = VoiceEndpoints.EndpointGetAccount,- body = Requests.ReqGetAccount.newBuilder().setUnknownInt2(1).build(),- responseTemplate = Responses.RespGetAccount.getDefaultInstance(),- )- Log.i(TAG, "=== ACCOUNT API RESPONSE (checking for SIP server info) ===")- Log.i(TAG, "Account proto: ${accResp.account.toString().take(4000)}")- Log.i(TAG, "Account unknown fields: ${accResp.account.unknownFields}")- val account = accResp.account-- // Parse and log BirdsongConfig SIP server URIs from account response- if (account.hasIntegration()) {- val integration = account.integration- Log.i(TAG, "Account has Integration field")- if (integration.hasVoipSettings()) {- val voipSettings = integration.voipSettings- Log.i(TAG, "Integration has VoipSettings")- if (voipSettings.hasBirdsongConfig()) {- val birdsong = voipSettings.birdsongConfig- Log.i(TAG, "=== BIRDSONG CONFIG SIP SERVER URIs ===")- Log.i(TAG, "SIP server URI: ${birdsong.sipServerUri}")- Log.i(TAG, "Secondary SIP server URI: ${birdsong.secondarySipServerUri}")- if (birdsong.hasPreresolvedAddress()) {- val preresolved = birdsong.preresolvedAddress- Log.i(TAG, "Preresolved address - hostname: ${preresolved.hostname}, ipv4: ${preresolved.ipv4}, ipv6: ${preresolved.ipv6}")- }- if (birdsong.hasDnsOptions()) {- val dnsOptions = birdsong.dnsOptions- Log.i(TAG, "DNS options preresolved addresses count: ${dnsOptions.preresolvedAddressesCount}")- for (i in 0 until dnsOptions.preresolvedAddressesCount) {- val addr = dnsOptions.getPreresolvedAddresses(i)- Log.i(TAG, " DNS preresolved[$i]: hostname=${addr.hostname}, ipv4=${addr.ipv4}, ipv6=${addr.ipv6}")- }- }- Log.i(TAG, "=== END BIRDSONG CONFIG ===")- } else {- Log.i(TAG, "VoipSettings missing BirdsongConfig")- }- } else {- Log.i(TAG, "Integration missing VoipSettings")- }- } else {- Log.i(TAG, "Account missing Integration field (or proto not yet generated)")- }- var sipDeviceId: String? = null- for (i in 0 until account.phonesCount) {- val phone = account.getPhones(i)- for (j in 0 until phone.linkedVoIPDevicesCount) {- val device = phone.getLinkedVoIPDevices(j)- if (device.sipDeviceID.isNotBlank()) {- sipDeviceId = device.sipDeviceID- Log.i(TAG, "Found SIP device ID: $sipDeviceId")- break- }- }- if (sipDeviceId != null) break- }- if (sipDeviceId.isNullOrBlank()) {- Log.w(TAG, "No SIP device ID found in account")- return null- }-- // Extract auth_user and auth_realm from BirdsongConfig if available- var authUser = "0"- var authRealm = "voice.sip.google.com"- if (account.hasIntegration() && account.integration.hasVoipSettings()) {- val voipSettings = account.integration.voipSettings- if (voipSettings.hasBirdsongConfig()) {- // BirdsongConfig fields per deobfuscation findings- // Note: proto currently only has sip_server_uri fields, not auth fields yet- // Using defaults for now; task 6 adds proto definitions- Log.i(TAG, "Using BirdsongConfig defaults: auth_user=$authUser, auth_realm=$authRealm")- }- }-- // Task 7: Fetch OAuth token via Google Auth API instead of GetSIPRegisterInfo- // Based on deobfuscation: snj abstract class with a() returning scope string,- // snl implementation holds scope, lou.java:40 returns tvt.cc("oauth2:https://www.googleapis.com/auth/sipregistrar")- // snk.java uses mxc.d(Account, scope) which calls GoogleAuthUtil.getToken()- val oauthScope = "oauth2:https://www.googleapis.com/auth/sipregistrar"- var oauthToken = fetchOAuthToken(oauthScope)- if (oauthToken == null) {- // Temporary: use placeholder to test SIP server response and determine correct auth method- Log.w(TAG, "OAuth token fetch failed, using placeholder to test SIP server auth requirements")- oauthToken = "PLACEHOLDER_OAUTH_TOKEN_FOR_TESTING"- } else {- Log.i(TAG, "Obtained OAuth token via Google Auth API (scope=$oauthScope, len=${oauthToken.length})")- }-- com.vayunmathur.messages.gvoice.sip.SipCredentials(- sipDeviceId = sipDeviceId,- oauthToken = oauthToken,- authUser = authUser,- authRealm = authRealm,- field1 = 0L, // Legacy field from GetSIPRegisterInfo, no longer used- field2 = 0L, // Legacy field from GetSIPRegisterInfo, no longer used- ).also {- Log.i(TAG, "Fetched SIP credentials successfully with Bearer OAuth token")- }-- } catch (t: Throwable) {- Log.e(TAG, "Failed to fetch SIP credentials: ${t.message}", t)- null- }- }-- /**- * Fetch OAuth token via Google Auth API for the given scope.- *- * Based on deobfuscation findings:- * - mxc.java d(Account, String) method fetches token via GoogleAuthUtil- * - mxu.java wraps Google Auth Client for token requests- * - Scope format: "oauth2:https://www.googleapis.com/auth/sipregistrar"- *- * @param scope OAuth scope string with "oauth2:" prefix- * @return OAuth access token or null on failure- */- private suspend fun fetchOAuthToken(scope: String): String? = withContext(Dispatchers.IO) {- try {- // Check for user-selected account from SharedPreferences (via account picker)- val prefs = appContext.getSharedPreferences("gvoice_oauth", Context.MODE_PRIVATE)- val selectedAccount = prefs.getString("selected_account", null)-- val accountName = selectedAccount ?: run {- // Fallback: try AccountManager directly (may return empty on modern Android)- val accountManager = AccountManager.get(appContext)- val accounts = accountManager.getAccountsByType("com.google")- if (accounts.isNotEmpty()) accounts[0].name else null- }-- if (accountName != null) {- Log.i(TAG, "Fetching OAuth token for account: $accountName, scope: $scope")-- // Fetch token via GoogleAuthUtil (matches mxc.d() in decompiled code)- // This is the equivalent of GaiaOauthTokenGetterAsync in native GV app- // Note: Account must have been selected via newChooseAccountIntent() to grant access- val token = GoogleAuthUtil.getToken(appContext, accountName, scope)- Log.i(TAG, "Successfully obtained OAuth token via AccountManager (length: ${token.length})")- return@withContext token- }-- // Fallback: No Google account selected, use cookie-based OAuth flow- // The app already has valid Google session cookies for voice.google.com API.- // We can use the OAuth2 token endpoint with the existing session to obtain- // an access token for the sipregistrar scope.- Log.i(TAG, "No Google accounts on device, falling back to cookie-based OAuth flow")- return@withContext fetchOAuthTokenViaCookies(scope)- } catch (e: Exception) {- Log.e(TAG, "Failed to fetch OAuth token: ${e.message}", e)- null- }- }-- /**- * Fetch OAuth token using existing Google session cookies.- * Used when AccountManager has no Google accounts (cookie-only auth mode).- *- * The app already has valid session cookies (SID, HSID, SSID, SAPISID, etc.)- * from the Voice login flow. We use these to call Google's OAuth token- * endpoint to obtain an access token for the requested scope.- */- private suspend fun fetchOAuthTokenViaCookies(scope: String): String? {- val client = rpc ?: return null- return try {- // Strip "oauth2:" prefix if present for the scope parameter- val cleanScope = scope.removePrefix("oauth2:")- Log.i(TAG, "Requesting OAuth token via cookie session for scope: $cleanScope")-- // Google's OAuth token endpoint for web sessions- // Uses existing session cookies to authorize the token request- val tokenUrl = "https://accounts.google.com/o/oauth2/token"- val form = mapOf(- "scope" to cleanScope,- "grant_type" to "urn:ietf:params:oauth:grant-type:jwt-bearer",- // The cookie session authenticates this request- )-- // Note: This is a simplified approach. In practice, Google's web OAuth- // flow for existing sessions may require additional parameters or use- // a different endpoint. Let's try the standard OAuth2 token endpoint- // with cookie authentication first.- //- // Alternative approach: Use the existing Voice API session to call- // an endpoint that returns OAuth tokens, or parse the token from- // account metadata.-- // For now, let's try a pragmatic approach: the SAPISID cookie can be- // used to generate SAPISIDHASH authorization, and we already have- // working Voice API access. The SIP registrar scope token may be- // obtainable via the Voice API itself or we may need to use a- // different strategy.-- // Let's check if there's a Voice API endpoint that returns OAuth tokens,- // or if we should fall back to using the session cookies directly- // as a Bearer token (some Google internal APIs accept session cookies- // as Bearer tokens after transformation).-- Log.w(TAG, "Cookie-based OAuth not yet fully implemented - " +- "attempting to use SAPISID as Bearer token fallback")-- // Fallback: Try using SAPISID cookie value as a Bearer token.- // This is speculative but worth trying since we have a valid session.- val sapisid = client.let {- // Access cookies via reflection or through a getter we'd need to add- // For now, return null to trigger the existing error path gracefully- null as String?- }-- if (sapisid != null) {- Log.i(TAG, "Using SAPISID cookie as OAuth token fallback")- return sapisid- }-- // TODO: Implement proper cookie-to-OAuth-token exchange.- // Options:- // 1. Call https://oauth2.googleapis.com/token with cookie auth- // 2. Parse OAuth token from Voice API account response- // 3. Use a WebView to complete OAuth flow and extract token- // 4. Require user to add Google account to device (simplest)-- Log.e(TAG, "Cookie-based OAuth token fetch not implemented yet. " +- "Please add Google account to device Settings → Accounts, " +- "or we need to implement WebView OAuth flow.")- null- } catch (e: Exception) {- Log.e(TAG, "Cookie-based OAuth fetch failed: ${e.message}", e)- null- }- }-- /**- * Test method for Phase 1 discovery - logs full SIP API response and attempts PJSIP registration.- */- suspend fun getSIPRegisterInfo(): String {- val creds = fetchSipCredentials() ?: return "FAILED to fetch SIP credentials"-- val baseInfo = "SUCCESS: SIP credentials obtained\n" +- "Device ID: ${creds.sipDeviceId}\n" +- "OAuth token (${creds.oauthToken.length} chars): ${creds.oauthToken.take(40)}...\n" +- "Auth user: ${creds.authUser}\n" +- "Auth realm: ${creds.authRealm}\n" +- "Field1: ${creds.field1}\n" +- "Field2: ${creds.field2}\n" +- "Server: ${creds.sipServer}:${creds.sipPort}\n\n"-- // Attempt PJSIP registration to discover correct credential mapping- return try {- Log.i(TAG, "=== ATTEMPTING PJSIP REGISTRATION ===")- com.vayunmathur.messages.gvoice.sip.SipManager.init(appContext)- Thread.sleep(500) // Give PJSIP time to initialize-- val registered = com.vayunmathur.messages.gvoice.sip.SipManager.register(creds)- baseInfo + "PJSIP registration initiated: $registered\n" +- "Check logcat for PJSIP logs with tag 'SipAccount' and 'PJSIP' to see SIP server response.\n" +- "Look for: 200 OK (success), 401 Unauthorized (wrong creds), 403 Forbidden, etc."- } catch (t: Throwable) {- baseInfo + "PJSIP registration failed to start: ${t.message}"- }- }-- /**- * Start a voice call to the given phone number.- * Fetches SIP credentials, initializes SipManager, registers account,- * then places call via TelecomManager using GVoicePhoneAccountRegistrar.- *- * @return true if call initiation succeeded- */- suspend fun startVoiceCall(phoneNumber: String): Boolean {- return try {- Log.i(TAG, "Starting voice call to $phoneNumber")-- // 1. Fetch SIP credentials via API- val creds = fetchSipCredentials()- if (creds == null) {- Log.e(TAG, "Failed to fetch SIP credentials for call")- return false- }-- // 2. Initialize SipManager (idempotent)- com.vayunmathur.messages.gvoice.sip.SipManager.init(appContext)-- // 3. Register SIP account- val registered = com.vayunmathur.messages.gvoice.sip.SipManager.register(creds)- if (!registered) {- Log.e(TAG, "SIP registration failed")- return false- }-- // 4. Place call via TelecomManager- val telecomManager = appContext.getSystemService(android.content.Context.TELECOM_SERVICE)- as android.telecom.TelecomManager- val phoneAccountHandle = com.vayunmathur.messages.gvoice.voice.GVoicePhoneAccountRegistrar- .getPhoneAccountHandle(appContext)- val uri = android.net.Uri.fromParts("tel", phoneNumber, null)- val extras = android.os.Bundle().apply {- putParcelable(android.telecom.TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle)- }- telecomManager.placeCall(uri, extras)- Log.i(TAG, "Call placed via TelecomManager to $phoneNumber")- true- } catch (t: Throwable) {- Log.e(TAG, "startVoiceCall failed: ${t.message}", t)- false- }- }- /** * Validate credentials with GetAccount before starting the session. * Mirrors Go's `Connect` which always calls GetAccount first.
messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCredentials.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCredentials.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCredentials.ktdeleted file mode 100644index b780902264..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipCredentials.kt+++ /dev/null@@ -1,44 +0,0 @@-package com.vayunmathur.messages.gvoice.sip--/**- * SIP registration credentials for Bearer OAuth authentication (RFC 8760).- *- * Based on deobfuscation findings:- * - BirdsongConfig has no password field, only auth_user and auth_realm- * - Native code receives OAuth token via GaiaOauthTokenGetterAsync- * - Official app uses Bearer OAuth, not digest authentication- *- * The OAuth token is obtained via Google OAuth flow (task 7) and used- * as Bearer token in SIP Authorization header per RFC 8760.- */-data class SipCredentials(- val sipDeviceId: String,- val oauthToken: String, // Google OAuth access token for Bearer auth (RFC 8760)- val authUser: String = "0", // From BirdsongConfig, defaults to "0" per GV app- val authRealm: String = "voice.sip.google.com", // SIP realm from BirdsongConfig- val field1: Long = 0L, // Legacy field from GetSIPRegisterInfo, kept for compat- val field2: Long = 0L, // Legacy field from GetSIPRegisterInfo, kept for compat-) {- // Based on GV APK decompilation, SIP server is hardcoded- // or obtained from BirdsongConfig.sip_server_uri in account response- val sipServer = "voice.sip.google.com"- val sipPort = 5061 // TLS port for SIP over TLS-- /**- * Get Authorization header value for Bearer OAuth authentication (RFC 8760).- * Format: "Bearer <oauth_token>"- */- fun getAuthorizationHeader(): String = "Bearer $oauthToken"-- /**- * SIP username for registration - uses authUser from BirdsongConfig.- * Defaults to "0" per GV app deobfuscation findings.- */- val username: String get() = authUser-- /**- * SIP ID URI for account configuration.- * Format: sip:<sipDeviceId>@<sipServer>- */- val idUri: String get() = "sip:$sipDeviceId@$sipServer"-}
messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.ktdeleted file mode 100644index 6c0b8ccf54..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/sip/SipManager.kt+++ /dev/null@@ -1,399 +0,0 @@-package com.vayunmathur.messages.gvoice.sip--import android.content.Context-import android.util.Log-import org.pjsip.pjsua2.*-import java.util.concurrent.atomic.AtomicBoolean--/**- * SIP stack manager wrapping PJSUA2 (PJSIP Java bindings).- *- * Handles:- * - PJSIP endpoint initialization- * - SIP account registration with voice.sip.google.com- * - Outgoing call placement- * - Incoming call handling- * - Audio device management- *- * Based on PJSUA2 API: https://docs.pjsip.org/en/latest/pjsua2/intro.html- */-object SipManager {-- private const val TAG = "SipManager"-- private val initialized = AtomicBoolean(false)- private var endpoint: Endpoint? = null- private var account: SipAccount? = null- private var currentCall: SipCall? = null-- /**- * Initialize PJSIP endpoint. Must be called once on app startup- * before any SIP operations.- */- fun init(context: Context) {- if (!initialized.compareAndSet(false, true)) return-- try {- // Load native library- System.loadLibrary("c++_shared")- System.loadLibrary("pjsua2")- Log.i(TAG, "PJSIP native libraries loaded")-- endpoint = Endpoint()- endpoint!!.libCreate()-- // Configure endpoint- val epConfig = EpConfig()- epConfig.uaConfig.threadCnt = 1- epConfig.uaConfig.mainThreadOnly = false-- // Configure DNS resolver with public DNS servers to avoid resolution failures- // PJSIP's UaConfig.nameserver allows setting custom DNS servers- val nameservers = StringVector()- nameservers.add("8.8.8.8") // Google DNS primary- nameservers.add("8.8.4.4") // Google DNS secondary- nameservers.add("1.1.1.1") // Cloudflare DNS- nameservers.add("1.0.0.1") // Cloudflare DNS secondary- epConfig.uaConfig.nameserver = nameservers- Log.i(TAG, "Configured PJSIP DNS resolver with public nameservers (8.8.8.8, 8.8.4.4, 1.1.1.1, 1.0.0.1)")-- // Media config - use WebRTC AEC like GV app does- epConfig.medConfig.ecOptions = pjmedia_echo_flag.PJMEDIA_ECHO_WEBRTC.toLong()- epConfig.medConfig.ecTailLen = 200- epConfig.medConfig.noVad = false- epConfig.medConfig.quality = 4- epConfig.medConfig.ptime = 20- epConfig.medConfig.sndClockRate = 16000-- // Logging- epConfig.logConfig.level = 4- epConfig.logConfig.consoleLevel = 4- val logWriter = object : LogWriter() {- override fun write(entry: LogEntry) {- Log.d("PJSIP", entry.msg.trim())- }- }- epConfig.logConfig.writer = logWriter-- endpoint!!.libInit(epConfig)- Log.i(TAG, "PJSIP endpoint initialized")-- // Create UDP transport for SIP signaling- val transportConfig = TransportConfig()- transportConfig.port = 5060- endpoint!!.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP, transportConfig)- Log.i(TAG, "SIP UDP transport created on port 5060")-- // Create TLS transport for secure SIP (port 5061)- try {- val tlsConfig = TransportConfig()- tlsConfig.port = 5061- endpoint!!.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS, tlsConfig)- Log.i(TAG, "SIP TLS transport created on port 5061")- } catch (e: Exception) {- Log.w(TAG, "Failed to create TLS transport (may need certificates): ${e.message}")- }-- endpoint!!.libStart()- Log.i(TAG, "PJSIP endpoint started successfully")-- } catch (e: Exception) {- Log.e(TAG, "Failed to initialize PJSIP: ${e.message}", e)- initialized.set(false)- }- }-- /**- * Register SIP account with Google Voice SIP server using Bearer OAuth- * authentication (RFC 8760).- *- * Based on deobfuscation findings, the official GV app uses Bearer OAuth- * tokens, not digest authentication. BirdsongConfig has auth_user and- * auth_realm fields but no password field. Native code receives OAuth- * token via GaiaOauthTokenGetterAsync.- *- * PJSIP supports custom headers via AccountConfig.regConfig.headers.- * We inject Authorization: Bearer <oauth_token> header for SIP REGISTER.- *- * @return true if registration initiated successfully- */- fun register(credentials: SipCredentials): Boolean {- val ep = endpoint ?: run {- Log.e(TAG, "Cannot register: endpoint not initialized")- return false- }-- try {- Log.i(TAG, "Registering SIP account with ${credentials.sipServer} using Bearer OAuth (RFC 8760)")- Log.i(TAG, "Device ID: ${credentials.sipDeviceId}")- Log.i(TAG, "Auth user: ${credentials.authUser}")- Log.i(TAG, "Auth realm: ${credentials.authRealm}")- Log.i(TAG, "OAuth token: ${credentials.oauthToken.take(20)}... (${credentials.oauthToken.length} chars)")-- // Use server URI from BirdsongConfig or default- // Try both with and without explicit port for robustness- val serverUris = listOf(- "sip:${credentials.sipServer}", // Without port (let DNS SRV handle)- "sip:${credentials.sipServer}:${credentials.sipPort}" // With explicit port 5061- )-- var successCount = 0- for (serverUri in serverUris) {- try {- Log.i(TAG, "=== Registering with server URI: $serverUri ===")-- val accCfg = AccountConfig()- accCfg.idUri = credentials.idUri- accCfg.regConfig.registrarUri = serverUri-- // Configure Bearer OAuth authentication (RFC 8760)- // PJSIP AccountRegConfig supports custom headers via setHeaders()- // We inject Authorization: Bearer <token> for SIP REGISTER requests- val authHeader = SipHeader()- authHeader.hName = "Authorization"- authHeader.hValue = credentials.getAuthorizationHeader()- val headers = SipHeaderVector()- headers.add(authHeader)- accCfg.regConfig.headers = headers- Log.i(TAG, "Configured Bearer OAuth Authorization header for SIP REGISTER")-- // Set auth creds with Bearer scheme for completeness- // PJSIP may use this for 401 challenges, though with Bearer we send preemptively- val bearerCred = AuthCredInfo(- "Bearer", // RFC 8760 scheme- credentials.authRealm,- credentials.authUser,- 0, // data type (0 = plain text)- credentials.oauthToken- )- accCfg.sipConfig.authCreds.add(bearerCred)-- // Enable preemptive auth to send Authorization header on initial REGISTER- // (not just after 401 challenge)- accCfg.sipConfig.authInitialEmpty = false- accCfg.sipConfig.authInitialAlgorithm = "Bearer"-- // Enable ICE for NAT traversal- accCfg.natConfig.iceEnabled = true- accCfg.natConfig.turnEnabled = false-- // Create account- val sipAccount = SipAccount("Bearer")- sipAccount.create(accCfg)- Log.i(TAG, "[Bearer] SIP account created for $serverUri with OAuth Bearer auth, registration in progress...")- successCount++-- // Store first account as primary (for makeCall/endCall)- if (account == null) {- account = sipAccount- }-- } catch (e: Exception) {- Log.e(TAG, "Failed to create account for $serverUri: ${e.message}", e)- }- }-- Log.i(TAG, "Initiated $successCount registration attempts with Bearer OAuth across ${serverUris.size} server URIs")- return successCount > 0-- } catch (e: Exception) {- Log.e(TAG, "SIP registration failed: ${e.message}", e)- return false- }- }-- /**- * Place an outgoing voice call to the given phone number via SIP.- */- fun makeCall(phoneNumber: String): Boolean {- val acc = account ?: run {- Log.e(TAG, "Cannot make call: not registered")- return false- }-- try {- // Format as SIP URI - GV likely expects E.164 format- val sipUri = if (phoneNumber.startsWith("+")) {- "sip:[email protected]"- } else {- "sip:[email protected]"- }-- Log.i(TAG, "Placing call to $sipUri")-- val call = SipCall(acc, -1)- val prm = CallOpParam(true)- call.makeCall(sipUri, prm)- currentCall = call-- Log.i(TAG, "Call placed successfully")- return true-- } catch (e: Exception) {- Log.e(TAG, "Failed to place call: ${e.message}", e)- return false- }- }-- /**- * End the current active call.- */- fun endCall(): Boolean {- val call = currentCall ?: return false- return try {- val prm = CallOpParam()- prm.statusCode = pjsip_status_code.PJSIP_SC_DECLINE- call.hangup(prm)- currentCall = null- Log.i(TAG, "Call ended")- true- } catch (e: Exception) {- Log.e(TAG, "Failed to end call: ${e.message}", e)- false- }- }-- /**- * Answer the current incoming call.- */- fun answerCall(): Boolean {- val call = currentCall ?: return false- return try {- val prm = CallOpParam()- prm.statusCode = pjsip_status_code.PJSIP_SC_OK- call.answer(prm)- Log.i(TAG, "Call answered")- true- } catch (e: Exception) {- Log.e(TAG, "Failed to answer call: ${e.message}", e)- false- }- }-- /**- * Place the current call on hold.- */- fun holdCall(): Boolean {- val call = currentCall ?: return false- return try {- val prm = CallOpParam()- call.setHold(prm)- Log.i(TAG, "Call held")- true- } catch (e: Exception) {- Log.e(TAG, "Failed to hold call: ${e.message}", e)- false- }- }-- /**- * Unhold the current call.- */- fun unholdCall(): Boolean {- val call = currentCall ?: return false- return try {- val prm = CallOpParam()- prm.options = pjsua_call_flag.PJSUA_CALL_UNHOLD.toLong()- call.reinvite(prm)- Log.i(TAG, "Call unheld")- true- } catch (e: Exception) {- Log.e(TAG, "Failed to unhold call: ${e.message}", e)- false- }- }-- /**- * Set audio route for the call (speaker, earpiece, bluetooth, etc.)- */- fun setAudioRoute(route: Int) {- // TODO: Implement audio routing via AudioManager- // route values from AudioState: ROUTE_EARPIECE, ROUTE_SPEAKER, ROUTE_BLUETOOTH, etc.- Log.i(TAG, "setAudioRoute called with route=$route")- }-- /**- * Clean up PJSIP resources. Call on app shutdown.- */- fun destroy() {- try {- currentCall?.let {- try { it.hangup(CallOpParam()) } catch (_: Exception) {}- }- currentCall = null-- account?.let {- try { it.shutdown() } catch (_: Exception) {}- try { it.delete() } catch (_: Exception) {}- }- account = null-- endpoint?.let {- try { it.libDestroy() } catch (_: Exception) {}- }- endpoint = null- initialized.set(false)- Log.i(TAG, "PJSIP destroyed")- } catch (e: Exception) {- Log.e(TAG, "Error during PJSIP destroy: ${e.message}")- }- }-}--/**- * SIP Account implementation handling registration state changes.- */-private class SipAccount(private val variantName: String = "?") : Account() {- override fun onRegState(prm: OnRegStateParam?) {- Log.i("SipAccount", "[$variantName] Registration state: ${prm?.code} ${prm?.reason}, expiration=${prm?.expiration}")- if (prm?.code == pjsip_status_code.PJSIP_SC_OK) {- Log.i("SipAccount", "[$variantName] SIP REGISTER successful!")- } else if (prm?.code == pjsip_status_code.PJSIP_SC_UNAUTHORIZED) {- Log.i("SipAccount", "[$variantName] SIP REGISTER got 401 Unauthorized - credentials mapping may be close! Server is reachable.")- } else if (prm?.code ?: 0 >= 400) {- Log.e("SipAccount", "[$variantName] SIP REGISTER failed: ${prm?.code} ${prm?.reason}")- }- }-- override fun onIncomingCall(prm: OnIncomingCallParam?) {- Log.i("SipAccount", "[$variantName] Incoming call from ${prm?.callId}")- // TODO: Handle incoming call - create SipCall and notify UI via Telecom ConnectionService- }-}--/**- * SIP Call implementation handling call state changes.- */-private class SipCall(acc: Account, callId: Int = -1) : Call(acc, callId) {- override fun onCallState(prm: OnCallStateParam?) {- val ci = try { getInfo() } catch (_: Exception) { null }- Log.i("SipCall", "Call state: ${ci?.stateText} (${ci?.state}), last status: ${ci?.lastStatusCode} ${ci?.lastReason}")- }-- override fun onCallMediaState(prm: OnCallMediaStateParam?) {- val ci = try { getInfo() } catch (_: Exception) { null }- Log.i("SipCall", "Call media state changed")- // TODO: Handle audio media activation- // Note: media.size() causes Kotlin compiler confusion with SWIG bindings,- // using try-catch with hardcoded loop limit as workaround for now- ci?.media?.let {- for (i in 0 until 10) { // Max 10 media streams is safe upper bound- val media = try { getMedia(i.toLong()) } catch (_: Exception) { break }- if (media == null) break- if (media.type == pjmedia_type.PJMEDIA_TYPE_AUDIO) {- val audioMedia = AudioMedia.typecastFromMedia(media)- // Connect to sound device- try {- val audDevManager = Endpoint.instance().audDevManager()- audioMedia.startTransmit(audDevManager.playbackDevMedia)- audDevManager.captureDevMedia.startTransmit(audioMedia)- Log.i("SipCall", "Audio media connected to sound device")- } catch (e: Exception) {- Log.e("SipCall", "Failed to connect audio: ${e.message}")- }- break- }- }- }- }-}
messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnection.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnection.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnection.ktdeleted file mode 100644index 415a3332d8..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnection.kt+++ /dev/null@@ -1,92 +0,0 @@-package com.vayunmathur.messages.gvoice.voice--import android.net.Uri-import android.telecom.CallAudioState-import android.telecom.Connection-import android.telecom.DisconnectCause-import android.telecom.TelecomManager-import android.util.Log-import com.vayunmathur.messages.gvoice.sip.SipManager--/**- * Telecom Connection implementation for Google Voice calls.- * Bridges Android Telecom framework callbacks to SipManager SIP operations.- */-class GVoiceConnection(private val phoneNumber: String) : Connection() {-- companion object {- private const val TAG = "GVoiceConnection"- }-- init {- // Set initial connection properties- connectionCapabilities = CAPABILITY_HOLD or CAPABILITY_SUPPORT_HOLD or CAPABILITY_MUTE- setCallerDisplayName(phoneNumber, TelecomManager.PRESENTATION_ALLOWED)- val uri = Uri.fromParts("tel", phoneNumber, null)- setAddress(uri, TelecomManager.PRESENTATION_ALLOWED)- }-- override fun onAnswer() {- Log.i(TAG, "onAnswer() called")- // For outgoing calls, answer is a no-op (already dialing)- // For incoming calls, we would answer the SIP call here- if (SipManager.answerCall()) {- setActive()- } else {- setDisconnected(DisconnectCause(DisconnectCause.ERROR))- destroy()- }- }-- override fun onReject() {- Log.i(TAG, "onReject() called")- SipManager.endCall()- setDisconnected(DisconnectCause(DisconnectCause.REJECTED))- destroy()- }-- override fun onDisconnect() {- Log.i(TAG, "onDisconnect() called")- SipManager.endCall()- setDisconnected(DisconnectCause(DisconnectCause.LOCAL))- destroy()- }-- override fun onHold() {- Log.i(TAG, "onHold() called")- if (SipManager.holdCall()) {- setOnHold()- }- }-- override fun onUnhold() {- Log.i(TAG, "onUnhold() called")- if (SipManager.unholdCall()) {- setActive()- }- }-- override fun onCallAudioStateChanged(state: CallAudioState) {- Log.i(TAG, "onCallAudioStateChanged() called: route=${state.route}")- // Route audio via SipManager or AudioManager- SipManager.setAudioRoute(state.route)- super.onCallAudioStateChanged(state)- }-- /**- * Called when outgoing call is placed via Telecom.- * Initiates SIP call and updates connection state.- */- fun placeOutgoingCall() {- Log.i(TAG, "Placing outgoing call to $phoneNumber")- setDialing()- if (SipManager.makeCall(phoneNumber)) {- // SipManager will notify us via callback when call connects- // For now, set to active optimistically- setActive()- } else {- setDisconnected(DisconnectCause(DisconnectCause.ERROR, "Failed to place call"))- destroy()- }- }-}
messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnectionService.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnectionService.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnectionService.ktdeleted file mode 100644index 5a8e760693..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoiceConnectionService.kt+++ /dev/null@@ -1,64 +0,0 @@-package com.vayunmathur.messages.gvoice.voice--import android.telecom.Connection-import android.telecom.ConnectionRequest-import android.telecom.ConnectionService-import android.telecom.PhoneAccountHandle-import android.util.Log--/**- * Android Telecom ConnectionService for Google Voice calling.- * Handles outgoing and incoming call requests from the Telecom framework.- */-class GVoiceConnectionService : ConnectionService() {-- companion object {- private const val TAG = "GVoiceConnectionService"- }-- override fun onCreateOutgoingConnection(- connectionManagerPhoneAccount: PhoneAccountHandle?,- request: ConnectionRequest- ): Connection {- Log.i(TAG, "onCreateOutgoingConnection: ${request.address}")-- val phoneNumber = request.address?.schemeSpecificPart ?: run {- Log.e(TAG, "No phone number in request")- return Connection.createFailedConnection(- android.telecom.DisconnectCause(android.telecom.DisconnectCause.ERROR, "No phone number")- )- }-- val connection = GVoiceConnection(phoneNumber)- connection.placeOutgoingCall()- return connection- }-- override fun onCreateIncomingConnection(- connectionManagerPhoneAccount: PhoneAccountHandle?,- request: ConnectionRequest- ): Connection {- Log.i(TAG, "onCreateIncomingConnection: ${request.address}")- // TODO: Handle incoming SIP calls- // For now, return a failed connection- return Connection.createFailedConnection(- android.telecom.DisconnectCause(android.telecom.DisconnectCause.ERROR, "Incoming calls not yet implemented")- )- }-- override fun onCreateOutgoingConnectionFailed(- connectionManagerPhoneAccount: PhoneAccountHandle?,- request: ConnectionRequest- ) {- Log.e(TAG, "onCreateOutgoingConnectionFailed: ${request.address}")- super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request)- }-- override fun onCreateIncomingConnectionFailed(- connectionManagerPhoneAccount: PhoneAccountHandle?,- request: ConnectionRequest- ) {- Log.e(TAG, "onCreateIncomingConnectionFailed: ${request.address}")- super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request)- }-}
messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoicePhoneAccountRegistrar.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoicePhoneAccountRegistrar.kt b/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoicePhoneAccountRegistrar.ktdeleted file mode 100644index 7deddb3cab..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/gvoice/voice/GVoicePhoneAccountRegistrar.kt+++ /dev/null@@ -1,57 +0,0 @@-package com.vayunmathur.messages.gvoice.voice--import android.content.ComponentName-import android.content.Context-import android.telecom.PhoneAccount-import android.telecom.PhoneAccountHandle-import android.telecom.TelecomManager-import android.util.Log--/**- * Registers the Google Voice phone account with Android Telecom framework.- * This enables the app to place and receive calls via the system Telecom API,- * integrating with the native dialer UI and in-call screen.- */-object GVoicePhoneAccountRegistrar {-- private const val TAG = "GVoicePhoneAccountRegistrar"- private const val ACCOUNT_ID = "gvoice_account"-- /**- * Registers the PhoneAccount with TelecomManager.- * Call this on app startup or when user enables calling.- */- fun register(context: Context) {- val telecomManager = context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager-- val componentName = ComponentName(context, GVoiceConnectionService::class.java)- val phoneAccountHandle = PhoneAccountHandle(componentName, ACCOUNT_ID)-- val phoneAccount = PhoneAccount.builder(phoneAccountHandle, "Google Voice")- .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)- .build()-- telecomManager.registerPhoneAccount(phoneAccount)- Log.i(TAG, "PhoneAccount registered: $phoneAccountHandle")- }-- /**- * Unregisters the PhoneAccount. Call on app shutdown or when user disables calling.- */- fun unregister(context: Context) {- val telecomManager = context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager- val componentName = ComponentName(context, GVoiceConnectionService::class.java)- val phoneAccountHandle = PhoneAccountHandle(componentName, ACCOUNT_ID)-- telecomManager.unregisterPhoneAccount(phoneAccountHandle)- Log.i(TAG, "PhoneAccount unregistered: $phoneAccountHandle")- }-- /**- * Returns the PhoneAccountHandle for this app's Google Voice account.- */- fun getPhoneAccountHandle(context: Context): PhoneAccountHandle {- val componentName = ComponentName(context, GVoiceConnectionService::class.java)- return PhoneAccountHandle(componentName, ACCOUNT_ID)- }-}
messages/src/main/java/com/vayunmathur/messages/rcs/AcsClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/rcs/AcsClient.kt b/messages/src/main/java/com/vayunmathur/messages/rcs/AcsClient.ktdeleted file mode 100644index 27c109fbc9..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/rcs/AcsClient.kt+++ /dev/null@@ -1,541 +0,0 @@-package com.vayunmathur.messages.rcs--import android.content.Context-import android.os.Build-import android.telephony.TelephonyManager-import android.util.Log-import com.google.android.gms.safetynet.SafetyNet-import com.google.android.play.core.integrity.IntegrityManagerFactory-import com.google.android.play.core.integrity.IntegrityTokenRequest-import com.google.firebase.installations.FirebaseInstallations-import com.google.firebase.messaging.FirebaseMessaging-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.tasks.await-import kotlinx.coroutines.withContext-import okhttp3.OkHttpClient-import okhttp3.Request-import org.xmlpull.v1.XmlPullParser-import org.xmlpull.v1.XmlPullParserFactory-import java.io.StringReader-import java.nio.charset.StandardCharsets-import java.security.MessageDigest-import java.util.UUID-import java.util.concurrent.TimeUnit--/**- * ACS (Auto Configuration Server) client implementing GSMA RCC.14 / RCC.15- * Service Provider Device Configuration.- *- * Based on reverse engineering of Shannon RCS:- * com.shannon.rcsservice.deviceprovisioning.impl.gsma.autoconfiguration.AutoConfClient- * com.shannon.rcsservice.deviceprovisioning.impl.gsma.autoconfiguration.AutoConfOps- *- * Flow:- * 1. Construct ACS URL from MCC/MNC: http://config.rcs.mnc<MNC>.mcc<MCC>.pub.3gppnetwork.org/- * 2. Send HTTP GET with device parameters (vers, rcs_version, client info, IMSI, IMEI, msisdn, etc.)- * 3. Handle response:- * - 200 OK: Parse XML configuration, extract SIP credentials- * - 511: SMS OTP required - wait for SMS on port 37273, resend with OTP- * - 403: Forbidden - not authorized- * - 409: Needs user action- * - 503: Retry later with Retry-After header- * 4. Return parsed RcsConfiguration for SIP registration- */-class AcsClient(private val context: Context) {-- companion object {- private const val TAG = "AcsClient"- private const val DEFAULT_ACS_PORT = 80- private const val OTP_SMS_PORT = 37273 // Per DevProvRule.getDesignatedSmsPort()- private const val TIMEOUT_SECONDS = 30L- }-- private val httpClient = OkHttpClient.Builder()- .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)- .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)- .connectionSpecs(- listOf(- okhttp3.ConnectionSpec.CLEARTEXT,- okhttp3.ConnectionSpec.MODERN_TLS,- okhttp3.ConnectionSpec.COMPATIBLE_TLS,- )- )- .build()-- /**- * Perform ACS provisioning request.- *- * @param phoneNumberE164 Phone number in E.164 format (e.g. +1234567890), or null to auto-detect- * @param otp Optional OTP code if resending after 511 response- * @param acsUrlOverride Optional override for ACS URL (for testing or Google Jibe)- * @return AcsResponse indicating success, need OTP, error, etc.- */- suspend fun provision(- phoneNumberE164: String? = null,- otp: String? = null,- acsUrlOverride: String? = null,- ): AcsResponse = withContext(Dispatchers.IO) {- try {- val acsUrl = acsUrlOverride ?: constructAcsUrl()- Log.i(TAG, "Provisioning via ACS: $acsUrl")-- val params = buildRequestParams(phoneNumberE164, otp)-- // Try DroidGuard attestation first (what Google Messages actually uses per decompiled code)- // ecwd.java calls dyxl.b("rcs_provisioning", map, ...) which goes to GMS DroidGuard service- val droidGuardParams = mapOf(- "APP_NAME" to "com.google.android.apps.messaging",- "msisdn" to (phoneNumberE164 ?: ""),- "vers" to "0"- )- val droidGuardResult = getDroidGuardAttestation("rcs_provisioning", droidGuardParams)- if (droidGuardResult != null) {- Log.d(TAG, "Obtained DroidGuard attestation: ${droidGuardResult.take(40)}...")- } else {- Log.w(TAG, "DroidGuard unavailable - trying Play Integrity as fallback")- }-- // Try to obtain Play Integrity token as fallback- val integrityToken = getPlayIntegrityToken()- if (integrityToken != null) {- Log.d(TAG, "Obtained Play Integrity token: ${integrityToken.take(40)}...")- }-- // Decompiled code analysis (dfsz.java / eczp.java):- // - dfsz.l() adds QUERY PARAMETERS to URL (via Uri.Builder.appendQueryParameter)- // - dfsz.k() adds HEADERS via setRequestProperty- // - ecwd.b() calls dfsz.k("Droid-Guard", ...) and dfsz.k("Droid-Guard-Salt", ...)- // - Default HTTP method is GET per eczp.java line 63- // So: GET request with query params in URL, NOT POST body!-- val queryParams = mapOf(- "vers" to params.vers.toString(),- "rcs_version" to params.rcsVersion,- "rcs_profile" to params.rcsProfile,- "client_vendor" to params.clientVendor,- "client_version" to params.clientVersion,- "terminal_vendor" to params.terminalVendor,- "terminal_model" to params.terminalModel,- "terminal_sw_version" to params.terminalSwVersion,- ).toMutableMap()- params.imsi?.let { queryParams["IMSI"] = obfuscate(it) }- params.imei?.let { queryParams["IMEI"] = obfuscate(it) }- params.msisdn?.let { queryParams["msisdn"] = obfuscate(it) }- params.token?.let { queryParams["token"] = obfuscate(it) }- params.otp?.let { queryParams["otp"] = obfuscate(it) }-- val urlWithParams = acsUrl + "?" + queryParams.entries.joinToString("&") { "${it.key}=${it.value}" }- Log.d(TAG, "ACS GET to: $urlWithParams")-- val requestBuilder = Request.Builder()- .url(urlWithParams)- .get()- .header("User-Agent", buildUserAgent())- .header("Accept", "*/*")- .header("Accept-Encoding", "gzip")- .header("Accept-Language", java.util.Locale.getDefault().toLanguageTag())- // Headers from decompiled code analysis (ecyn.java line 277, eczp.java, etc.):- .header("client_channel", "stable")- // ecwd.b() sets Droid-Guard headers - critical for Jibe ACS per decompiled code- // ecwd.java: dfsz.k("Droid-Guard", a(ecwc)) where a() calls dyxl.b("rcs_provisioning",...)- .header("Droid-Guard", droidGuardResult ?: "")- .header("Droid-Guard-Salt", obfuscationKey)- // From eczm.java - headers set via dfsz.k()- .header("gmscore_instance_id_token", "") // Empty until Firebase properly configured with google-services.json- .header("consent_version", "1")- .header("supported_provisioning_types", "1") // Try just HTTP config first, not SMS OTP- // From ecyn.java line 277 - msisdn_source values discovered from decompiled code:- // "msisdn_source_unknown", "msisdn_source_sim", "msisdn_source_manual_entry"- .header("msisdn_source", "msisdn_source_manual_entry") // User entered phone number manually- .header("user_initiated_verification_request", "true")- // Additional headers that may help- .header("X-Requested-With", "com.google.android.apps.messaging")- .header("X-Android-Package", "com.google.android.apps.messaging")- // Try without X-Android-Cert first as it may cause rejection if wrong-- // Add integrity token if obtained- if (integrityToken != null) {- requestBuilder.header("X-Play-Integrity-Token", integrityToken)- }-- val request = requestBuilder.build()-- val response = httpClient.newCall(request).execute()- val code = response.code- val body = response.body?.string().orEmpty()- val retryAfter = response.header("Retry-After")?.toIntOrNull() ?: 0-- Log.i(TAG, "ACS response: $code, body length: ${body.length}")- if (code >= 400) {- Log.w(TAG, "ACS error body: $body")- Log.w(TAG, "ACS response headers: ${response.headers}")- }-- when (code) {- 200 -> {- val config = parseXmlConfiguration(body)- if (config != null) {- AcsResponse.Success(config, body)- } else {- AcsResponse.Error(code, "Failed to parse XML configuration")- }- }- 511 -> {- Log.i(TAG, "ACS requires OTP verification (511)")- AcsResponse.NeedsOtp- }- 403 -> AcsResponse.Forbidden(body.ifBlank { null })- 409 -> AcsResponse.NeedsUserAction(body.ifBlank { null })- 503 -> AcsResponse.RetryLater(retryAfter)- 400 -> AcsResponse.Error(code, "Bad request: $body")- 401 -> AcsResponse.Error(code, "Unauthorized")- 307, 308 -> {- // Redirect - follow Location header- val location = response.header("Location")- if (location != null) {- Log.i(TAG, "ACS redirect to: $location")- // Recursively provision with new URL (with limit to prevent loops)- provision(phoneNumberE164, otp, location)- } else {- AcsResponse.Error(code, "Redirect without Location header")- }- }- else -> AcsResponse.Error(code, body.ifBlank { null })- }-- } catch (e: Exception) {- Log.e(TAG, "ACS provisioning failed", e)- AcsResponse.Error(-1, e.message)- }- }-- /**- * Construct ACS FQDN per GSMA RCC.14 Section 2.2:- * config.rcs.mnc<MNC>.mcc<MCC>.pub.3gppnetwork.org- *- * MNC is zero-padded to 3 digits.- * Falls back to Google Jibe ACS if SIM info unavailable.- */- private fun constructAcsUrl(): String {- val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager- val operator = tm?.simOperator // MCC + MNC as string, e.g. "310260"- val operatorName = tm?.simOperatorName?.lowercase() ?: ""-- // Google Jibe ACS endpoint discovered via PCAP capture from Google Messages:- // rcs-acs-tmo-us.jibe.google.com for T-Mobile US- // Pattern: rcs-acs-{carrier}-{country}.jibe.google.com over HTTPS- if (operator != null && operator.length >= 5) {- val mcc = operator.substring(0, 3)- val mnc = operator.substring(3).padStart(3, '0')-- // Map MCC/MNC to Google Jibe ACS endpoint- // Discovered: T-Mobile US (310/260, 310/490, etc.) -> rcs-acs-tmo-us.jibe.google.com- val jibeEndpoint = when {- mcc == "310" && mnc in listOf("260", "026", "490", "660", "800", "240", "160", "200", "210", "220", "230", "250", "270", "280", "290", "300", "310", "330", "350", "370", "380", "400", "460", "470", "500", "510", "520", "530", "540", "570", "580", "590", "600", "610", "640", "670", "680", "690", "770", "790", "820", "830", "860", "870", "880", "890", "900", "910", "920", "950", "970", "980") -> "rcs-acs-tmo-us.jibe.google.com"- mcc == "310" && mnc in listOf("410", "012", "013", "590", "890") -> "rcs-acs-att-us.jibe.google.com" // AT&T likely pattern- mcc == "311" && mnc in listOf("480", "481", "482", "483") -> "rcs-acs-vzw-us.jibe.google.com" // Verizon likely- mcc == "310" && mnc == "120" -> "rcs-acs-sprint-us.jibe.google.com" // Sprint/T-Mo- // Add more carriers as discovered via PCAP captures- else -> null- }-- if (jibeEndpoint != null) {- Log.i(TAG, "Using Google Jibe ACS: $jibeEndpoint for MCC=$mcc MNC=$mnc ($operatorName)")- return "https://$jibeEndpoint"- }-- // Fallback to GSMA standard ACS URL for non-Jibe carriers- Log.i(TAG, "No Jibe endpoint mapped, using GSMA standard ACS for MCC=$mcc MNC=$mnc")- return "http://config.rcs.mnc$mnc.mcc$mcc.pub.3gppnetwork.org"- }-- // No SIM info - try generic Jibe endpoint or fail gracefully- Log.w(TAG, "No SIM operator info available")- return "https://rcs-acs.jibe.google.com"- }-- // Obfuscation key for this provisioning session (matches ecvy.g in decompiled code)- private var obfuscationKey: String = UUID.randomUUID().toString()-- /**- * Obfuscate parameter value per ecwc.o() from decompiled Google Messages code.- * ecwc.o(str, key) = hex( SHA-384( str + key as UTF-8 ) )- * From: messages-re/jadx-out/sources/defpackage/ecwc.java:142-144- */- private fun obfuscate(value: String, key: String = obfuscationKey): String {- return try {- val bytes = (value + key).toByteArray(StandardCharsets.UTF_8)- val md = MessageDigest.getInstance("SHA-384")- val hash = md.digest(bytes)- // Convert to lowercase hex string (matches flsp.toString() in decompiled code)- hash.joinToString("") { "%02x".format(it) }- } catch (e: Exception) {- Log.w(TAG, "Obfuscation failed, using plaintext", e)- value- }- }-- private suspend fun buildRequestParams(phoneNumberE164: String?, otp: String?): AcsRequestParams {- val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager-- // Generate new obfuscation key per provisioning session (matches ecwc.m() in decompiled code)- obfuscationKey = UUID.randomUUID().toString()-- // Initialize Firebase if needed- try {- com.google.firebase.FirebaseApp.initializeApp(context)- } catch (_: Exception) { /* already initialized */ }-- // Obtain Firebase Installation ID (replaces GMSCORE_IID_TOKEN from decompiled code)- val firebaseIid = try {- com.google.firebase.installations.FirebaseInstallations.getInstance().id.await()- } catch (e: Exception) {- Log.w(TAG, "Failed to get Firebase Installation ID: ${e.message}")- // Generate a random ID as fallback to at least send something- UUID.randomUUID().toString().replace("-", "")- }-- // Obtain Firebase Cloud Messaging token (may be used as MSISDN_TOKEN or similar)- val fcmToken = try {- com.google.firebase.messaging.FirebaseMessaging.getInstance().token.await()- } catch (e: Exception) {- Log.w(TAG, "Failed to get FCM token: ${e.message}")- null- }-- Log.d(TAG, "Firebase IID: ${firebaseIid?.take(20)}..., FCM: ${fcmToken?.take(20)}...")- Log.d(TAG, "Obfuscation key: ${obfuscationKey.take(8)}...")-- return AcsRequestParams(- vers = 0, // 0 for first request, ACS returns version to use for updates- rcsVersion = AcsRequestParams.DEFAULT_RCS_VERSION,- rcsProfile = AcsRequestParams.DEFAULT_RCS_PROFILE,- clientVendor = AcsRequestParams.DEFAULT_CLIENT_VENDOR,- clientVersion = AcsRequestParams.DEFAULT_CLIENT_VERSION,- terminalVendor = Build.MANUFACTURER.take(4).replace(" ", ""),- terminalModel = Build.MODEL.take(10).replace(" ", ""),- terminalSwVersion = Build.VERSION.INCREMENTAL.take(10).replace(" ", ""),- imsi = try { tm?.subscriberId } catch (_: SecurityException) { null },- imei = try { tm?.imei } catch (_: SecurityException) { null },- msisdn = phoneNumberE164,- token = firebaseIid, // Use Firebase Installation ID as token- otp = otp,- )- }-- /**- * Obtain Play Integrity token for device attestation.- * Google Jibe ACS likely requires this per decompiled code showing DROIDGUARD usage.- * Play Integrity is the modern replacement for SafetyNet Attestation.- */- private suspend fun getPlayIntegrityToken(): String? = withContext(Dispatchers.IO) {- try {- val integrityManager = IntegrityManagerFactory.create(context)- // Use a nonce tied to RCS provisioning- val nonce = UUID.randomUUID().toString()- val request = IntegrityTokenRequest.builder()- .setNonce(nonce)- // Cloud project number - would need actual Google Cloud project for RCS- // For now, try without or with placeholder- .build()- val response = integrityManager.requestIntegrityToken(request).await()- response.token()- } catch (e: Exception) {- Log.w(TAG, "Play Integrity token failed (expected without proper Cloud setup)", e)- null- }- }-- /**- * Obtain SafetyNet attestation as fallback/alternative to Play Integrity.- * Decompiled code shows DroidGuard usage which is related to SafetyNet.- */- private suspend fun getSafetyNetAttestation(nonce: String): String? = withContext(Dispatchers.IO) {- try {- // Note: SafetyNet Attestation API requires API key from Google Cloud Console- // and is deprecated in favor of Play Integrity, but trying for completeness- val result = SafetyNet.getClient(context).attest(nonce.toByteArray(), "YOUR_API_KEY").await()- result.jwsResult- } catch (e: Exception) {- Log.w(TAG, "SafetyNet attestation failed", e)- null- }- }-- /**- * Attempt DroidGuard attestation via Google Play Services internal API.- * Based on decompiled code: ecwd.java calls dyxl.b("rcs_provisioning", map, new DroidGuardResultsRequest())- * where dyxl wraps com.google.android.gms.droidguard API.- *- * DroidGuard is INTERNAL Google API not in public SDK, accessed via reflection.- * Returns attestation token string for Droid-Guard HTTP header, or null if unavailable.- */- private suspend fun getDroidGuardAttestation(- method: String,- params: Map<String, String>- ): String? = withContext(Dispatchers.IO) {- try {- // Try to access DroidGuard API via reflection- // Based on decompiled code structure from Google Messages APK- val droidGuardClass = Class.forName("com.google.android.gms.droidguard.DroidGuardResultsRequest")- val builderClass = Class.forName("com.google.android.gms.droidguard.DroidGuardResultsRequest\$Builder")- val builder = builderClass.getDeclaredConstructor().newInstance()-- // Build DroidGuard request - exact API unclear from decompiled code due to obfuscation- // but we know method name "rcs_provisioning" is passed per ecwd.java- val request = builderClass.getMethod("build").invoke(builder)-- // Try to find DroidGuard client API via reflection- // In decompiled code this goes through dyxl -> dyzj -> dyyk -> GMS Binder IPC- // The actual API is likely in a GMS internal package not accessible to third-party apps- // even via reflection without Google app signature-- Log.d(TAG, "Attempting DroidGuard attestation for method: $method")- Log.d(TAG, "DroidGuard params: ${params.keys.joinToString()}")-- // For now, return null to indicate DroidGuard unavailable- // In a full implementation, this would call into GMS DroidGuard service- // via Binder IPC similar to how Google Messages does it via dyxl/dyzj classes- null-- } catch (e: ClassNotFoundException) {- Log.w(TAG, "DroidGuard API not available (expected - internal Google API)")- null- } catch (e: Exception) {- Log.w(TAG, "DroidGuard attestation failed", e)- null- }- }-- private fun buildUserAgent(): String {- // Format per GSMA RCC.14, similar to Shannon's UserAgent construction- val vendor = AcsRequestParams.DEFAULT_CLIENT_VENDOR- val version = AcsRequestParams.DEFAULT_CLIENT_VERSION- val terminalVendor = Build.MANUFACTURER.take(4).replace(" ", "")- val terminalModel = Build.MODEL.take(10).replace(" ", "")- val terminalSw = Build.VERSION.INCREMENTAL.take(10).replace(" ", "")- return "$vendor-$version/$terminalVendor-$terminalModel-$terminalSw"- }-- /**- * Parse ACS XML configuration response per GSMA RCC.14.- * Extracts IMS/SIP credentials and service configuration.- */- private fun parseXmlConfiguration(xml: String): RcsConfiguration? {- return try {- val factory = XmlPullParserFactory.newInstance()- factory.isNamespaceAware = true- val parser = factory.newPullParser()- parser.setInput(StringReader(xml))-- val params = mutableMapOf<String, String>()- var currentType: String? = null-- var eventType = parser.eventType- while (eventType != XmlPullParser.END_DOCUMENT) {- when (eventType) {- XmlPullParser.START_TAG -> {- when (parser.name) {- "characteristic" -> {- currentType = parser.getAttributeValue(null, "type")- }- "parm" -> {- val name = parser.getAttributeValue(null, "name")- val value = parser.getAttributeValue(null, "value")- if (name != null && value != null) {- val key = if (currentType != null) "$currentType.$name" else name- params[key] = value- }- }- }- }- }- eventType = parser.next()- }-- Log.d(TAG, "Parsed ${params.size} parameters from ACS XML")-- // Extract IMS parameters (required)- val pcscf = params["IMS.P-CSCF_Address"]- ?: params["IMS.pcscf_address"]- ?: params["P-CSCF_Address"]- ?: return null-- val publicId = params["IMS.Public_user_identity"]- ?: params["IMS.public_user_identity"]- ?: return null-- val privateId = params["IMS.Private_user_identity"]- ?: params["IMS.private_user_identity"]- ?: publicId-- val homeDomain = params["IMS.Home_network_domain_name"]- ?: params["IMS.home_network_domain_name"]- ?: extractDomainFromSipUri(publicId)- ?: "rcs.telephony.goog"-- val authTypeStr = params["IMS.IMS_Auth_Type"]- ?: params["IMS.AuthType"]- ?: "DIGEST"-- val username = params["IMS.IMS_User_Name"]- ?: params["IMS.username"]- ?: extractUserFromSipUri(publicId)- ?: return null-- val password = params["IMS.IMS_Password"]- ?: params["IMS.password"]- ?: ""-- RcsConfiguration(- pcscfAddress = pcscf,- publicUserIdentity = publicId,- privateUserIdentity = privateId,- homeDomain = homeDomain,- authType = RcsConfiguration.fromAuthTypeString(authTypeStr),- username = username,- password = password,- chatAuth = params["SERVICES.ChatAuth"]?.toIntOrNull() == 1,- groupChatAuth = params["SERVICES.GroupChatAuth"]?.toIntOrNull() == 1,- ftAuth = params["SERVICES.ftAuth"]?.toIntOrNull() == 1- || params["FILETRANSFER.ftAuth"]?.toIntOrNull() == 1,- standaloneMsgAuth = params["SERVICES StandAloneMsgAuth"]?.toIntOrNull() == 1- || params["SERVICES.StandAloneMsgAuth"]?.toIntOrNull() == 1,- geolocPushAuth = params["SERVICES.geolocPushAuth"]?.toIntOrNull() == 1,- geolocPullAuth = params["SERVICES.geolocPullAuth"]?.toIntOrNull() == 1,- ftHttpServer = params["FILETRANSFER.ftHTTPCSURI"]- ?: params["FILETRANSFER.ftHttpCsUri"],- ftHttpUser = params["FILETRANSFER.ftHTTPCSUser"]- ?: params["FILETRANSFER.ftHttpCsUser"],- ftHttpPassword = params["FILETRANSFER.ftHTTPCSPwd"]- ?: params["FILETRANSFER.ftHttpCsPwd"],- ftDefaultMech = params["FILETRANSFER.ftDefaultMech"],- messagingUx = params["MESSAGING.UX"]?.toIntOrNull() ?: 1,- presenceAuth = params["PRESENCE.presenceAuth"]?.toIntOrNull() == 1,- version = params["VERS.version"]?.toIntOrNull() ?: 0,- validitySeconds = params["VERS.validity"]?.toLongOrNull() ?: 86400,- token = params["TOKEN.token"],- )-- } catch (e: Exception) {- Log.e(TAG, "Failed to parse ACS XML", e)- null- }- }-- private fun extractDomainFromSipUri(sipUri: String): String? {- // sip:[email protected] -> rcs.telephony.goog- val atIndex = sipUri.indexOf('@')- if (atIndex < 0) return null- var domain = sipUri.substring(atIndex + 1)- // Remove parameters and port- domain = domain.substringBefore(';').substringBefore(':').substringBefore('>')- return domain- }-- private fun extractUserFromSipUri(sipUri: String): String? {- // sip:[email protected] -> +1234567890- val withoutScheme = sipUri.substringAfter("sip:", sipUri)- return withoutScheme.substringBefore('@').ifBlank { null }- }-}
messages/src/main/java/com/vayunmathur/messages/rcs/RcsClient.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/rcs/RcsClient.kt b/messages/src/main/java/com/vayunmathur/messages/rcs/RcsClient.ktdeleted file mode 100644index 57816a6636..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/rcs/RcsClient.kt+++ /dev/null@@ -1,354 +0,0 @@-package com.vayunmathur.messages.rcs--import android.content.Context-import android.util.Log-import com.vayunmathur.messages.data.MessageSource-import com.vayunmathur.messages.gmessages.GMEvent-import com.vayunmathur.messages.util.ContactSuggestion-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.Job-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.flow.MutableSharedFlow-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.SharedFlow-import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.asSharedFlow-import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.launch-import java.util.concurrent.atomic.AtomicBoolean--/**- * RCS client for Google Jibe backend via Tachyon gRPC protocol.- *- * Architecture based on reverse engineering:- * - Google Messages APK (com.google.android.apps.messaging)- * - Google Play Services GMS (com.google.android.gms) - Tachyon endpoints- * - Shannon RCS service (com.shannon.rcsservice) - GSMA RCC.14 reference- *- * Protocol flow:- * 1. ACS Provisioning: HTTP GET to config.rcs.mnc<MNC>.mcc<MCC>.pub.3gppnetwork.org- * or Google Jibe ACS at *.telephony.goog- * 2. Handle 200 OK (XML config) or 511 (SMS OTP required)- * 3. Parse XML for SIP credentials (P-CSCF, username, password, auth type)- * 4. SIP REGISTER to Jibe IMS core- * 5. Tachyon gRPC for messaging (Google's proprietary layer over SIP)- * Endpoints: tachyon-*-rcs-*-grpc.*.googleapis.com- * OAuth scopes: https://www.googleapis.com/auth/tachyon,- * https://www.googleapis.com/auth/android-messages- *- * Current status: SKELETON - protocol implementation is TODO.- * See reverse-engineering findings in:- * - reverse-engineering/messages-re/FINDINGS.md- * - reverse-engineering/shannon-re/FINDINGS.md- */-object RcsClient {-- private const val TAG = "RcsClient"-- sealed interface State {- data object Idle : State- data object NeedsSetup : State- data object Connecting : State- data object Connected : State- data class Disconnected(val reason: String) : State- /** Waiting for SMS OTP during ACS provisioning (511 response) */- data object AwaitingOtp : State- /** ACS provisioning in progress */- data object Provisioning : State- }-- val source: MessageSource = MessageSource.RCS-- private val _state = MutableStateFlow<State>(State.Idle)- val state: StateFlow<State> = _state.asStateFlow()-- private val _events = MutableSharedFl
Diff truncated.