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

Modern-Apps.git / scripts / networklocation / wps_harvest / reference / ApplePositioningService.kt.txt

ApplePositioningService.kt.txt1 lines · 6.0 KiBRaw
1package com.vayunmathur.networklocation.appleimport com.vayunmathur.networklocation.APPLE_COORD_SCALEimport com.vayunmathur.networklocation.BeaconFiximport com.vayunmathur.networklocation.BeaconIdimport com.vayunmathur.networklocation.UNKNOWN_ACCURACYimport com.vayunmathur.networklocation.proto.AppleWpsimport java.io.ByteArrayOutputStreamimport java.net.HttpURLConnectionimport 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 }}