Modern Apps git

← Modern-Apps.git

networklocation: add always-on network location provider (gs-loc client, apple_wps protobuf, beacon cache, manifest/perms)

Commit
7089da96aced99558b636c415858aa078dbfedd0
Author
Vayun Mathur <[email protected]>
When
2026-08-09 22:16 UTC (3 months ago)
Parents
b058bf3

Diff

networklocation/build.gradle.kts
diff --git a/networklocation/build.gradle.kts b/networklocation/build.gradle.ktsindex 7e585683fd..67bd13e3c1 100644--- a/networklocation/build.gradle.kts+++ b/networklocation/build.gradle.kts@@ -1,5 +1,10 @@+import java.io.File+import java.net.HttpURLConnection+import java.net.URI+ plugins {     id("common-conventions-app")+    alias(libs.plugins.protobuf) }  launcherIcon {@@ -47,17 +52,17 @@ val fetchGeocoderDb = tasks.register("fetchGeocoderDb") {             return@doLast         }         geocoderDbFile.parentFile.mkdirs()-        val tmp = java.io.File(geocoderDbFile.parentFile, "geocoder.geodb.part")+        val tmp = File(geocoderDbFile.parentFile, "geocoder.geodb.part")         tmp.delete()         logger.lifecycle("Fetching geocoder.geodb from $geocoderDbUrl (this is large; first build only)…")         try {-            val conn = (java.net.URI(geocoderDbUrl).toURL().openConnection() as java.net.HttpURLConnection).apply {+            val conn = (URI(geocoderDbUrl).toURL().openConnection() as HttpURLConnection).apply {                 connectTimeout = 30_000                 readTimeout = 60_000                 instanceFollowRedirects = true             }             val code = conn.responseCode-            if (code != java.net.HttpURLConnection.HTTP_OK) {+            if (code != HttpURLConnection.HTTP_OK) {                 conn.disconnect()                 error("server returned HTTP $code")             }@@ -91,8 +96,29 @@ dependencies {     // Compile-only stubs for the framework's unbundled provider API (com.android.location.provider).     // Provided at runtime by <uses-library>; must NOT be packaged.     compileOnly(project(":library:locationprovider"))+    // Apple gs-loc request/response wire format (proto/apple_wps.proto).+    implementation(libs.protobuf.javalite)+    // Beacon-location cache (in-memory TimedLruCache in front of a Room table).+    implementRoom(libs)+    // Reporting loop + IO for the gs-loc queries.+    implementation(libs.kotlinx.coroutines.android)     // Geocoder DB is a self-contained mmap'd binary (see geocoder/). Block compression uses     // java.util.zip (Deflate) — no external dependency needed for the core.     // kotlinx-serialization-json (from the app convention) is used only by the generator to     // parse osmium's GeoJSONSeq export. }++protobuf {+    protoc {+        artifact = "com.google.protobuf:protoc:${libs.versions.protobufJavalite.get()}"+    }+    generateProtoTasks {+        all().forEach { task ->+            task.builtins {+                create("java") {+                    option("lite")+                }+            }+        }+    }+}
networklocation/src/main/AndroidManifest.xml
diff --git a/networklocation/src/main/AndroidManifest.xml b/networklocation/src/main/AndroidManifest.xmlindex 093fede52e..23b7828c6c 100644--- a/networklocation/src/main/AndroidManifest.xml+++ b/networklocation/src/main/AndroidManifest.xml@@ -1,6 +1,22 @@ <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> +    <!-- Position estimation needs location + the radios it derives location from. -->+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />+    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />+    <!-- Reaching Apple's gs-loc proxy for beacon coordinates. -->+    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <!-- Privileged: register as the platform network/geocode provider and attribute work. -->+    <uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER" />+    <uses-permission android:name="android.permission.LOCATION_HARDWARE" />+    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />+    <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />+     <application         android:allowBackup="false"         android:icon="@mipmap/ic_launcher"@@ -13,6 +29,16 @@              the platform at runtime, not packaged in this APK. -->         <uses-library android:name="com.android.location.provider" android:required="false" /> +        <!-- Network location provider. Bound by the framework via the v3 provider action; becomes+             THE network provider once config_networkLocationProviderPackageName points here. -->+        <service+            android:name=".NetworkLocationService"+            android:exported="true">+            <intent-filter>+                <action android:name="com.android.location.service.v3.NetworkLocationProvider" />+            </intent-filter>+        </service>+         <!-- Offline geocoder. Bound by the framework via the GeocodeProvider action; becomes THE              system geocoder once config_geocodeProviderPackageName points here (MAOS overlay). -->         <service
networklocation/src/main/java/com/vayunmathur/networklocation/NetworkLocationService.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/NetworkLocationService.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/NetworkLocationService.ktnew file mode 100644index 0000000000..fa2c3f6f06--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/NetworkLocationService.kt@@ -0,0 +1,30 @@+package com.vayunmathur.networklocation++import android.app.Service+import android.content.Intent+import android.os.IBinder+import com.vayunmathur.networklocation.provider.LocationProviderImpl++/**+ * The bound service the framework's LocationManager connects to for network+ * location. Declared in the manifest with the+ * `com.android.location.service.v3.NetworkLocationProvider` action so the platform+ * discovers it; becomes THE network provider once MAOS points+ * `config_networkLocationProviderPackageName` at this package.+ */+class NetworkLocationService : Service() {+    private var provider: LocationProviderImpl? = null++    override fun onCreate() {+        super.onCreate()+        provider = LocationProviderImpl(this)+    }++    override fun onBind(intent: Intent?): IBinder? = provider?.binder++    override fun onDestroy() {+        provider?.shutdown()+        provider = null+        super.onDestroy()+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.ktnew file mode 100644index 0000000000..c2223d5da4--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/PositioningData.kt@@ -0,0 +1,43 @@+package com.vayunmathur.networklocation++/**+ * Plain domain types shared across the network-location pipeline (scan → gs-loc+ * query → cache → position estimate). Kept free of Android/proto types so the+ * pieces compose cleanly.+ */++/** A radio beacon we can ask Apple to locate: a WiFi access point or a cell tower. */+sealed interface BeaconId {+    data class Wifi(val bssid: String) : BeaconId++    data class Cell(+        val mcc: Int,+        val mnc: Int,+        val cellId: Int,+        val tacOrLac: Int,+    ) : BeaconId+}++/**+ * A beacon whose coordinates are known (from gs-loc or the local cache).+ * [accuracyMeters] is the beacon's own horizontal accuracy radius.+ */+data class BeaconFix(+    val id: BeaconId,+    val latitude: Double,+    val longitude: Double,+    val accuracyMeters: Double,+)++/** An estimated device position: the output of the Rust weighted-centroid solver. */+data class DevicePosition(+    val latitude: Double,+    val longitude: Double,+    val accuracyMeters: Double,+)++/** Apple encodes coordinates as fixed-point integers of degrees * 1e8. */+const val APPLE_COORD_SCALE: Double = 1e8++/** gs-loc returns this sentinel accuracy for beacons it has no fix for. */+const val UNKNOWN_ACCURACY: Int = -1
networklocation/src/main/java/com/vayunmathur/networklocation/apple/ApplePositioningService.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/apple/ApplePositioningService.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/apple/ApplePositioningService.ktnew file mode 100644index 0000000000..ba0722c2a8--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/apple/ApplePositioningService.kt@@ -0,0 +1,161 @@+package com.vayunmathur.networklocation.apple++import com.vayunmathur.networklocation.APPLE_COORD_SCALE+import com.vayunmathur.networklocation.BeaconFix+import com.vayunmathur.networklocation.BeaconId+import com.vayunmathur.networklocation.UNKNOWN_ACCURACY+import com.vayunmathur.networklocation.proto.AppleWps+import java.io.ByteArrayOutputStream+import java.net.HttpURLConnection+import java.net.URI++/**+ * Client for Apple's location proxy (`gs-loc.apple.com/clls/wloc`). Given the+ * identifiers of nearby WiFi APs / cell towers, it asks Apple for their known+ * coordinates. Apple does NOT return a device position — it returns each beacon's+ * own location; turning that beacon set into a device fix is the Rust solver's job.+ *+ * The request/response framing (a small ASCII header in front of a serialized+ * protobuf) is reconstructed from the well-documented community reverse-engineering+ * of the protocol; only WiFi/cell identifiers ever leave the device.+ */+class ApplePositioningService(+    private val locale: String = "en_US",+    private val identifier: String = "com.apple.locationd",+    private val version: String = "8.4.1.12H321",+) {+    /** Resolve nearby WiFi APs to beacon fixes. Unknown APs are simply omitted. */+    fun queryWifi(bssids: List<String>): List<BeaconFix> {+        if (bssids.isEmpty()) return emptyList()+        val request = AppleWps.WifiPositioning.newBuilder()+            .setNumResults(bssids.size)+            .apply {+                for (bssid in bssids) {+                    addDevices(AppleWps.WifiDevice.newBuilder().setBssid(bssid))+                }+            }+            .build()++        val body = post(request.toByteArray()) ?: return emptyList()+        val response = runCatching { AppleWps.WifiPositioning.parseFrom(body) }.getOrNull()+            ?: return emptyList()++        return response.devicesList.mapNotNull { device ->+            if (!device.hasLocation()) return@mapNotNull null+            val fix = device.location.toFix(BeaconId.Wifi(device.bssid)) ?: return@mapNotNull null+            fix+        }+    }++    /** Resolve nearby cell towers to beacon fixes. */+    fun queryCell(cells: List<BeaconId.Cell>): List<BeaconFix> {+        if (cells.isEmpty()) return emptyList()+        val request = AppleWps.CellPositioning.newBuilder()+            .setNumResults(cells.size)+            .apply {+                for (c in cells) {+                    addTowers(+                        AppleWps.CellTower.newBuilder()+                            .setMcc(c.mcc)+                            .setMnc(c.mnc)+                            .setCellId(c.cellId)+                            .setTacOrLac(c.tacOrLac),+                    )+                }+            }+            .build()++        val body = post(request.toByteArray()) ?: return emptyList()+        val response = runCatching { AppleWps.CellPositioning.parseFrom(body) }.getOrNull()+            ?: return emptyList()++        return response.towersList.mapNotNull { tower ->+            if (!tower.hasLocation()) return@mapNotNull null+            val id = BeaconId.Cell(tower.mcc, tower.mnc, tower.cellId, tower.tacOrLac)+            tower.location.toFix(id)+        }+    }++    private fun AppleWps.BeaconLocation.toFix(id: BeaconId): BeaconFix? {+        // Apple flags "no fix" with a negative accuracy and/or a sentinel coordinate.+        if (horizontalAccuracy == UNKNOWN_ACCURACY || horizontalAccuracy < 0) return null+        if (latitude == -1L && longitude == -1L) return null+        return BeaconFix(+            id = id,+            latitude = latitude / APPLE_COORD_SCALE,+            longitude = longitude / APPLE_COORD_SCALE,+            accuracyMeters = horizontalAccuracy.toDouble(),+        )+    }++    /** POST a serialized protobuf; returns the protobuf slice of the response, or null. */+    private fun post(payload: ByteArray): ByteArray? {+        val conn = runCatching {+            (URI(ENDPOINT).toURL().openConnection() as HttpURLConnection)+        }.getOrNull() ?: return null+        return try {+            conn.requestMethod = "POST"+            conn.connectTimeout = 15_000+            conn.readTimeout = 20_000+            conn.doOutput = true+            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")+            conn.setRequestProperty(+                "User-Agent",+                "locationd/1753.17 CFNetwork/711.1.12 Darwin/14.0.0",+            )+            conn.outputStream.use { it.write(frame(payload)) }+            if (conn.responseCode != HttpURLConnection.HTTP_OK) return null+            val raw = conn.inputStream.use { it.readBytes() }+            if (raw.size <= RESPONSE_HEADER_BYTES) null+            else raw.copyOfRange(RESPONSE_HEADER_BYTES, raw.size)+        } catch (_: Exception) {+            null+        } finally {+            conn.disconnect()+        }+    }++    /**+     * Wrap the protobuf in Apple's request envelope: a version short, three+     * length-prefixed ASCII strings (locale / bundle id / OS version), two fixed+     * ints, then a short payload length and the payload itself.+     */+    private fun frame(payload: ByteArray): ByteArray {+        val out = ByteArrayOutputStream()+        out.writeShort(1)+        out.writeLenString(locale)+        out.writeLenString(identifier)+        out.writeLenString(version)+        out.writeInt(1)+        out.writeInt(0)+        out.writeShort(payload.size)+        out.write(payload)+        return out.toByteArray()+    }++    private fun ByteArrayOutputStream.writeShort(v: Int) {+        write((v ushr 8) and 0xFF)+        write(v and 0xFF)+    }++    private fun ByteArrayOutputStream.writeInt(v: Int) {+        write((v ushr 24) and 0xFF)+        write((v ushr 16) and 0xFF)+        write((v ushr 8) and 0xFF)+        write(v and 0xFF)+    }++    private fun ByteArrayOutputStream.writeLenString(s: String) {+        val bytes = s.toByteArray(Charsets.US_ASCII)+        writeShort(bytes.size)+        write(bytes)+    }++    companion object {+        private const val ENDPOINT = "https://gs-loc.apple.com/clls/wloc"++        // Apple prefixes the response protobuf with a fixed-size header; the+        // serialized message begins after it.+        private const val RESPONSE_HEADER_BYTES = 10+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.ktnew file mode 100644index 0000000000..318e235a27--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/cache/BeaconCache.kt@@ -0,0 +1,98 @@+package com.vayunmathur.networklocation.cache++import android.content.Context+import androidx.room.Dao+import androidx.room.Database+import androidx.room.Entity+import androidx.room.PrimaryKey+import androidx.room.Query+import androidx.room.Room+import androidx.room.RoomDatabase+import androidx.room.Upsert+import com.vayunmathur.networklocation.BeaconFix+import com.vayunmathur.networklocation.BeaconId++/** Stable string key for a beacon, used as the cache primary key. */+fun BeaconId.key(): String = when (this) {+    is BeaconId.Wifi -> "wifi:${bssid.lowercase()}"+    is BeaconId.Cell -> "cell:$mcc:$mnc:$cellId:$tacOrLac"+}++@Entity(tableName = "beacon")+data class CachedBeaconEntity(+    @PrimaryKey val key: String,+    val latitude: Double,+    val longitude: Double,+    val accuracyMeters: Double,+    val updatedAt: Long,+)++@Dao+interface BeaconDao {+    @Query("SELECT * FROM beacon WHERE key IN (:keys)")+    suspend fun byKeys(keys: List<String>): List<CachedBeaconEntity>++    @Upsert+    suspend fun upsertAll(rows: List<CachedBeaconEntity>)++    @Query("DELETE FROM beacon WHERE updatedAt < :cutoff")+    suspend fun deleteOlderThan(cutoff: Long)+}++@Database(entities = [CachedBeaconEntity::class], version = 1, exportSchema = false)+abstract class BeaconDatabase : RoomDatabase() {+    abstract fun beaconDao(): BeaconDao+}++/**+ * Two-tier beacon-location cache: an in-memory [TimedLruCache] in front of a Room+ * table. Beacon coordinates are effectively static, so caching them locally is the+ * whole point — it means a given AP/tower is asked of Apple's proxy once, then+ * served offline forever (until the TTL sweep). The cache holds only public beacon+ * coordinates, so it is stored unencrypted.+ */+class BeaconCache(+    context: Context,+    private val memory: TimedLruCache<String, BeaconFix> =+        TimedLruCache(maxSize = 4096, ttlMillis = 24L * 60 * 60 * 1000),+) {+    private val dao: BeaconDao =+        Room.databaseBuilder(+            context.applicationContext,+            BeaconDatabase::class.java,+            "networklocation-beacons",+        ).build().beaconDao()++    /** Fetch cached fixes for [ids], checking memory first then the DB. */+    suspend fun get(ids: List<BeaconId>): Map<BeaconId, BeaconFix> {+        if (ids.isEmpty()) return emptyMap()+        val out = HashMap<BeaconId, BeaconFix>(ids.size)+        val misses = ArrayList<BeaconId>()+        for (id in ids) {+            val hit = memory.get(id.key())+            if (hit != null) out[id] = hit else misses.add(id)+        }+        if (misses.isNotEmpty()) {+            val byKey = misses.associateBy { it.key() }+            for (row in dao.byKeys(misses.map { it.key() })) {+                val id = byKey[row.key] ?: continue+                val fix = BeaconFix(id, row.latitude, row.longitude, row.accuracyMeters)+                memory.put(row.key, fix)+                out[id] = fix+            }+        }+        return out+    }++    /** Persist newly-resolved [fixes] into both tiers. */+    suspend fun put(fixes: List<BeaconFix>) {+        if (fixes.isEmpty()) return+        val now = System.currentTimeMillis()+        for (f in fixes) memory.put(f.id.key(), f)+        dao.upsertAll(+            fixes.map {+                CachedBeaconEntity(it.id.key(), it.latitude, it.longitude, it.accuracyMeters, now)+            },+        )+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.ktnew file mode 100644index 0000000000..944650ab2c--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/cache/TimedLruCache.kt@@ -0,0 +1,42 @@+package com.vayunmathur.networklocation.cache++/**+ * A size- and time-bounded LRU cache. Entries older than [ttlMillis] are treated+ * as absent; once [maxSize] is exceeded the least-recently-used live entry is+ * evicted. Used as the in-memory front of the persistent beacon cache so repeat+ * scans in one session never touch the DB (or the network).+ *+ * Not thread-safe on its own; callers synchronize (the reporting loop is+ * single-threaded, but [get]/[put] are `@Synchronized` for safety).+ */+class TimedLruCache<K, V>(+    private val maxSize: Int,+    private val ttlMillis: Long,+    private val clock: () -> Long = System::currentTimeMillis,+) {+    private data class Timed<V>(val value: V, val insertedAt: Long)++    // accessOrder=true makes this a genuine LRU: get() moves the entry to the tail.+    private val map = object : LinkedHashMap<K, Timed<V>>(16, 0.75f, true) {+        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, Timed<V>>): Boolean =+            size > maxSize+    }++    @Synchronized+    fun get(key: K): V? {+        val entry = map[key] ?: return null+        if (clock() - entry.insertedAt > ttlMillis) {+            map.remove(key)+            return null+        }+        return entry.value+    }++    @Synchronized+    fun put(key: K, value: V) {+        map[key] = Timed(value, clock())+    }++    @Synchronized+    fun clear() = map.clear()+}
networklocation/src/main/java/com/vayunmathur/networklocation/cell/NearbyCells.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/cell/NearbyCells.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/cell/NearbyCells.ktnew file mode 100644index 0000000000..8effdfbdec--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/cell/NearbyCells.kt@@ -0,0 +1,55 @@+package com.vayunmathur.networklocation.cell++import android.content.Context+import android.telephony.CellIdentityGsm+import android.telephony.CellIdentityLte+import android.telephony.CellIdentityNr+import android.telephony.CellIdentityWcdma+import android.telephony.CellInfo+import android.telephony.CellInfoGsm+import android.telephony.CellInfoLte+import android.telephony.CellInfoNr+import android.telephony.CellInfoWcdma+import android.telephony.TelephonyManager+import com.vayunmathur.networklocation.BeaconId++/**+ * Reads nearby cell towers from [TelephonyManager]. Only towers with a full,+ * non-sentinel identity (MCC/MNC/cell id/area code) are usable as gs-loc beacons.+ */+class NearbyCells(context: Context) {+    private val telephonyManager =+        context.applicationContext.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager++    fun scan(): List<BeaconId.Cell> {+        val infos = runCatching { telephonyManager?.allCellInfo }.getOrNull() ?: return emptyList()+        return infos.mapNotNull { it.toCell() }.distinct()+    }++    private fun CellInfo.toCell(): BeaconId.Cell? = when (this) {+        is CellInfoLte -> cellIdentity.toCell()+        is CellInfoGsm -> cellIdentity.toCell()+        is CellInfoWcdma -> cellIdentity.toCell()+        is CellInfoNr -> (cellIdentity as? CellIdentityNr)?.toCell()+        else -> null+    }++    private fun CellIdentityLte.toCell(): BeaconId.Cell? =+        build(mccString?.toIntOrNull(), mncString?.toIntOrNull(), ci, tac)++    private fun CellIdentityGsm.toCell(): BeaconId.Cell? =+        build(mccString?.toIntOrNull(), mncString?.toIntOrNull(), cid, lac)++    private fun CellIdentityWcdma.toCell(): BeaconId.Cell? =+        build(mccString?.toIntOrNull(), mncString?.toIntOrNull(), cid, lac)++    private fun CellIdentityNr.toCell(): BeaconId.Cell? =+        build(mccString?.toIntOrNull(), mncString?.toIntOrNull(), nci.toInt(), tac)++    private fun build(mcc: Int?, mnc: Int?, cellId: Int, areaCode: Int): BeaconId.Cell? {+        if (mcc == null || mnc == null) return null+        if (cellId == CellInfo.UNAVAILABLE || areaCode == CellInfo.UNAVAILABLE) return null+        if (cellId <= 0) return null+        return BeaconId.Cell(mcc = mcc, mnc = mnc, cellId = cellId, tacOrLac = areaCode)+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationProviderImpl.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationProviderImpl.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationProviderImpl.ktnew file mode 100644index 0000000000..4c2f8295ee--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationProviderImpl.kt@@ -0,0 +1,52 @@+package com.vayunmathur.networklocation.provider++import android.content.Context+import android.os.WorkSource+import com.android.location.provider.LocationProviderBase+import com.android.location.provider.ProviderPropertiesUnbundled+import com.android.location.provider.ProviderRequestUnbundled++/**+ * The unbundled network location provider. The framework binds our+ * [NetworkLocationService], calls [onSetRequest] as clients start/stop requesting+ * location, and we push fixes back via [reportLocation].+ *+ * ALWAYS-ON: unlike GrapheneOS, this deliberately does NOT consult+ * `Settings.Global.network_location`. The provider is active whenever the OS master+ * Location switch is on and a client is requesting fixes; there is no separate+ * per-provider toggle to gate on.+ */+class LocationProviderImpl(context: Context) : LocationProviderBase(context, TAG, PROPERTIES) {+    private val task = LocationReportingTask(context) { reportLocation(it) }++    override fun onSetRequest(request: ProviderRequestUnbundled, source: WorkSource) {+        if (request.reportLocation) {+            task.start(request.interval)+        } else {+            task.stop()+        }+    }++    fun shutdown() = task.stop()++    private companion object {+        const val TAG = "NetworkLocationProvider"++        // Network provider: needs the network, no cost, coarse accuracy, low power.+        val PROPERTIES: ProviderPropertiesUnbundled = ProviderPropertiesUnbundled.create(+            /* requiresNetwork = */ true,+            /* requiresSatellite = */ false,+            /* requiresCell = */ false,+            /* hasMonetaryCost = */ false,+            /* supportsAltitude = */ false,+            /* supportsSpeed = */ false,+            /* supportsBearing = */ false,+            /* powerUsage = */ POWER_LOW,+            /* accuracy = */ ACCURACY_COARSE,+        )++        // Mirror android.location.Criteria constants without depending on them.+        const val POWER_LOW = 1+        const val ACCURACY_COARSE = 2+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.ktnew file mode 100644index 0000000000..3e0249cc9e--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/provider/LocationReportingTask.kt@@ -0,0 +1,124 @@+package com.vayunmathur.networklocation.provider++import android.content.Context+import android.location.Location+import android.location.LocationManager+import android.os.SystemClock+import com.vayunmathur.networklocation.BeaconFix+import com.vayunmathur.networklocation.BeaconId+import com.vayunmathur.networklocation.DevicePosition+import com.vayunmathur.networklocation.NetworkLocationNative+import com.vayunmathur.networklocation.apple.ApplePositioningService+import com.vayunmathur.networklocation.cache.BeaconCache+import com.vayunmathur.networklocation.cell.NearbyCells+import com.vayunmathur.networklocation.util.Throttle+import com.vayunmathur.networklocation.wifi.NearbyWifi+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * The periodic fix loop: scan nearby radios, resolve them to coordinates (cache+ * first, then Apple's proxy for the misses), and estimate the device position with+ * the native solver. Reconstructs GrapheneOS's LocationReportingTask.+ */+class LocationReportingTask(+    context: Context,+    private val onFix: (Location) -> Unit,+) {+    private val appContext = context.applicationContext+    private val wifi = NearbyWifi(appContext)+    private val cells = NearbyCells(appContext)+    private val cache = BeaconCache(appContext)+    private val apple = ApplePositioningService()+    // gs-loc is only consulted for beacons we have never seen; still throttle it so a+    // burst of new APs (e.g. moving fast) cannot spam Apple.+    private val networkThrottle = Throttle(minIntervalMillis = 20_000)++    private var scope: CoroutineScope? = null++    fun start(intervalMillis: Long) {+        if (scope != null) return+        val newScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+        scope = newScope+        newScope.launch {+            while (isActive) {+                runCatching { reportOnce() }+                delay(intervalMillis.coerceAtLeast(MIN_INTERVAL_MS))+            }+        }+    }++    fun stop() {+        scope?.cancel()+        scope = null+    }++    private suspend fun reportOnce() {+        val position = estimate() ?: return+        onFix(position.toLocation())+    }++    /** Full pipeline for a single fix; null when there are no usable beacons. */+    private suspend fun estimate(): DevicePosition? {+        val wifiIds = wifi.scan()+        val cellIds = cells.scan()+        val allIds: List<BeaconId> = wifiIds + cellIds+        if (allIds.isEmpty()) return null++        val fixes = resolveFixes(wifiIds, cellIds, allIds)+        if (fixes.isEmpty()) return null++        val interleaved = DoubleArray(fixes.size * 3)+        for ((i, f) in fixes.withIndex()) {+            interleaved[i * 3] = f.latitude+            interleaved[i * 3 + 1] = f.longitude+            interleaved[i * 3 + 2] = f.accuracyMeters+        }+        val out = NetworkLocationNative.estimatePosition(interleaved) ?: return null+        return DevicePosition(out[0], out[1], out[2])+    }++    private suspend fun resolveFixes(+        wifiIds: List<BeaconId.Wifi>,+        cellIds: List<BeaconId.Cell>,+        allIds: List<BeaconId>,+    ): List<BeaconFix> {+        val cached = cache.get(allIds)+        val resolved = ArrayList(cached.values)++        val missingWifi = wifiIds.filter { it !in cached }+        val missingCell = cellIds.filter { it !in cached }+        if ((missingWifi.isNotEmpty() || missingCell.isNotEmpty()) && networkThrottle.tryAcquire()) {+            val fresh = withContext(Dispatchers.IO) {+                buildList {+                    if (missingWifi.isNotEmpty()) addAll(apple.queryWifi(missingWifi.map { it.bssid }))+                    if (missingCell.isNotEmpty()) addAll(apple.queryCell(missingCell))+                }+            }+            if (fresh.isNotEmpty()) {+                cache.put(fresh)+                resolved.addAll(fresh)+            }+        }+        return resolved+    }++    private fun DevicePosition.toLocation(): Location =+        Location(LocationManager.NETWORK_PROVIDER).apply {+            latitude = [email protected]+            longitude = [email protected]+            accuracy = accuracyMeters.toFloat()+            time = System.currentTimeMillis()+            elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()+        }++    private companion object {+        const val MIN_INTERVAL_MS = 1_000L+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/util/Throttle.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/util/Throttle.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/util/Throttle.ktnew file mode 100644index 0000000000..9d9a5196ea--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/util/Throttle.kt@@ -0,0 +1,26 @@+package com.vayunmathur.networklocation.util++/**+ * Minimal rate limiter: [tryAcquire] succeeds at most once per [minIntervalMillis].+ * Guards the gs-loc network queries so a tight request interval from the framework+ * cannot hammer Apple's proxy (which also protects the user's privacy/quota).+ */+class Throttle(+    private val minIntervalMillis: Long,+    private val clock: () -> Long = System::currentTimeMillis,+) {+    private var lastAllowed = Long.MIN_VALUE++    @Synchronized+    fun tryAcquire(): Boolean {+        val now = clock()+        if (now - lastAllowed < minIntervalMillis) return false+        lastAllowed = now+        return true+    }++    @Synchronized+    fun reset() {+        lastAllowed = Long.MIN_VALUE+    }+}
networklocation/src/main/java/com/vayunmathur/networklocation/wifi/NearbyWifi.kt
diff --git a/networklocation/src/main/java/com/vayunmathur/networklocation/wifi/NearbyWifi.kt b/networklocation/src/main/java/com/vayunmathur/networklocation/wifi/NearbyWifi.ktnew file mode 100644index 0000000000..e2cbe40d01--- /dev/null+++ b/networklocation/src/main/java/com/vayunmathur/networklocation/wifi/NearbyWifi.kt@@ -0,0 +1,29 @@+package com.vayunmathur.networklocation.wifi++import android.content.Context+import android.net.wifi.WifiManager+import com.vayunmathur.networklocation.BeaconId++/**+ * Reads nearby WiFi access points from the platform's last scan. As a privileged+ * system app we can rely on the framework's ongoing scan results rather than+ * kicking (deprecated, rate-limited) scans ourselves.+ */+class NearbyWifi(context: Context) {+    private val wifiManager =+        context.applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager++    fun scan(): List<BeaconId.Wifi> {+        val results = runCatching { wifiManager?.scanResults }.getOrNull() ?: return emptyList()+        return results+            .mapNotNull { it.BSSID }+            .filter { it.isNotBlank() && it != NULL_BSSID }+            .distinct()+            .map { BeaconId.Wifi(it) }+    }++    private companion object {+        // Some drivers report this placeholder for hidden/!associated entries.+        const val NULL_BSSID = "00:00:00:00:00:00"+    }+}
networklocation/src/main/proto/apple_wps.proto
diff --git a/networklocation/src/main/proto/apple_wps.proto b/networklocation/src/main/proto/apple_wps.protonew file mode 100644index 0000000000..8108708a0d--- /dev/null+++ b/networklocation/src/main/proto/apple_wps.proto@@ -0,0 +1,46 @@+syntax = "proto2";++option java_package = "com.vayunmathur.networklocation.proto";+option java_outer_classname = "AppleWps";++// Wire schema for Apple's location proxy (gs-loc.apple.com/clls/wloc), reconstructed+// from the well-known GrapheneOS / community reverse-engineering of the protocol.+//+// A request carries only beacon identifiers (WiFi BSSIDs, cell ids) plus how many+// results are wanted; the response echoes each identifier back with its location+// filled in. One message type therefore serves both directions, mirroring Apple's+// single "AppleWLoc" message.++// Apple encodes coordinates as fixed-point integers of degrees * 1e8. A+// horizontal_accuracy of -1 means "location unknown for this beacon".+message BeaconLocation {+  optional int64 latitude = 1;+  optional int64 longitude = 2;+  optional int32 horizontal_accuracy = 3;+  optional int32 unknown4 = 4;+  optional int32 altitude = 5;+  optional int32 vertical_accuracy = 6;+}++message WifiDevice {+  optional string bssid = 1;+  optional BeaconLocation location = 2;+}++message CellTower {+  optional int32 mcc = 1;+  optional int32 mnc = 2;+  optional int32 cell_id = 3;+  optional int32 tac_or_lac = 4;+  optional BeaconLocation location = 5;+}++message WifiPositioning {+  repeated WifiDevice devices = 2;+  optional int32 num_results = 3;+}++message CellPositioning {+  repeated CellTower towers = 1;+  optional int32 num_results = 2;+}