1package com.peachpasswords.sync23import android.content.Context4import android.net.nsd.NsdManager5import android.net.nsd.NsdServiceInfo6import android.os.Build7import dagger.hilt.android.qualifiers.ApplicationContext8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.channels.awaitClose11import kotlinx.coroutines.flow.Flow12import kotlinx.coroutines.flow.callbackFlow13import kotlinx.coroutines.isActive14import kotlinx.coroutines.launch15import kotlinx.coroutines.withContext16import org.json.JSONObject17import java.net.ServerSocket18import java.net.Socket19import java.nio.charset.StandardCharsets20import javax.inject.Inject21import javax.inject.Singleton222324252627282930313233343536373839404142434445464748@Singleton49class MdnsPairingServer @Inject constructor(50 private val deviceStore: PairedDeviceStore,51 @ApplicationContext private val ctx: Context,52) {53 private var serverSocket: ServerSocket? = null54 private var nsdManager: NsdManager? = null55 private var registrationListener: NsdManager.RegistrationListener? = null5657 585960616263646566 fun start(67 scope: CoroutineScope,68 ourStaticPrivateKey: ByteArray,69 ourStaticPublicKey: ByteArray,70 localIdentity: LocalChirpIdentity,71 vaultFactory: () -> ChirpSyncVaultAdapter?,72 ): Flow<PairingServerEvent> = callbackFlow {73 val socket = withContext(Dispatchers.IO) { ServerSocket(0) }74 serverSocket = socket75 val port = socket.localPort7677 registerMdns(port, ourStaticPublicKey, localIdentity.deviceId)78 trySend(PairingServerEvent.Started(port))7980 val acceptJob = scope.launch(Dispatchers.IO) {81 while (isActive && !socket.isClosed) {82 val client = try {83 socket.accept()84 } catch (_: Throwable) {85 break86 }87 launch {88 val event = handleClient(client, ourStaticPrivateKey, ourStaticPublicKey, localIdentity, vaultFactory)89 trySend(event)90 }91 }92 }9394 awaitClose {95 acceptJob.cancel()96 stop()97 }98 }99100 fun stop() {101 registrationListener?.let { l -> runCatching { nsdManager?.unregisterService(l) } }102 registrationListener = null103 runCatching { serverSocket?.close() }104 serverSocket = null105 }106107 private suspend fun handleClient(108 socket: Socket,109 ourStaticPrivateKey: ByteArray,110 ourStaticPublicKey: ByteArray,111 localIdentity: LocalChirpIdentity,112 vaultFactory: () -> ChirpSyncVaultAdapter?,113 ): PairingServerEvent {114 val transport = SocketFrameIO(115 input = socket.getInputStream(),116 output = socket.getOutputStream(),117 onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },118 )119 var noiseSession: NoiseNKSession? = null120 return try {121 val selector = JSONObject(String(transport.receive(), Charsets.UTF_8))122 require(selector.optString("type") == "PEACH_RECONNECT") { "expected PEACH_RECONNECT" }123 val rendezvousId = selector.optString("rendezvous_id")124 val known = Rendezvous.resolvePeer(deviceStore.getAll(), rendezvousId)125 ?: throw IllegalArgumentException("unknown reconnect peer")126 val initiatorKeyHex = known.longTermPublicKeyHex127 ?: throw IllegalArgumentException("known peer missing static key")128 val initiatorKey = hexToPubkey(initiatorKeyHex)129130 val session = noiseKKResponder(131 ourStaticPrivateKey,132 ourStaticPublicKey,133 initiatorKey,134 transport::send,135 transport::receive,136 )137 noiseSession = session138139 140 141 val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))142 require(theirIdentity.deviceId == known.deviceId) { "peer device id changed after KK" }143 require(144 CryptoCompare.hex(theirIdentity.longTermPublicKeyHex, initiatorKeyHex),145 ) { "peer identity does not match authenticated KK key" }146 transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))147148 val sas = SASDerivation.derive(session.handshakeHash)149 150 val vault = vaultFactory()151 if (vault != null) {152 vault.bindAuthenticatedPeer(known)153 val syncSession = chirpSessionOver(session, transport, initiatorKey)154 val outcome = runChirpSyncResponder(syncSession, vault)155 if (outcome.status == SyncOutcomeStatus.COMPLETED) {156 deviceStore.updateLastSync(known.deviceId)157 }158 }159 transport.close()160 PairingServerEvent.SyncComplete(known.deviceId, sas)161 } catch (e: Throwable) {162 transport.close()163 PairingServerEvent.Error(e.message ?: "pairing_server_error")164 } finally {165 noiseSession?.close()166 }167 }168169 private fun registerMdns(port: Int, staticPub: ByteArray, deviceId: String) {170 val manager = ctx.getSystemService(NsdManager::class.java) ?: return171 nsdManager = manager172 val info = NsdServiceInfo().apply {173 serviceName = buildServiceName(deviceId)174 serviceType = PEACH_SERVICE_TYPE175 this.port = port176 177 setAttribute("v", PROTOCOL_VERSION)178 setAttribute("pk", pubkeyToHex(staticPub))179 setAttribute("id", deviceId)180 }181 val listener = object : NsdManager.RegistrationListener {182 override fun onServiceRegistered(info: NsdServiceInfo) {}183 override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {}184 override fun onServiceUnregistered(info: NsdServiceInfo) {}185 override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {}186 }187 registrationListener = listener188 manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)189 }190191 private fun buildServiceName(deviceId: String): String {192 val shortId = deviceId.take(8)193 val model = Build.MODEL.replace(Regex("[^A-Za-z0-9-]"), "")194 195 196 val maxModel = 63 - "Peach-".length - 1 - shortId.length197 val trimmedModel = if (model.length > maxModel && maxModel > 0) model.take(maxModel) else model198 return "Peach-$trimmedModel-$shortId".take(63)199 }200201 private companion object {202 const val PEACH_SERVICE_TYPE = "_peach._tcp"203 const val PROTOCOL_VERSION = "1"204 }205}206207sealed class PairingServerEvent {208 data class Started(val port: Int) : PairingServerEvent()209 data class SyncComplete(val deviceId: String, val sas: String) : PairingServerEvent()210 data class Error(val message: String) : PairingServerEvent()211 data object Stopped : PairingServerEvent()212}213214215216217internal data class PairIdentity(218 val deviceId: String,219 val deviceName: String,220 val deviceType: DeviceType,221 val longTermPublicKeyHex: String,222 val signingPublicKeyHex: String?,223 val wsPort: Int?,224 val relayUrl: String?,225)226227internal fun encodePairIdentityFrame(id: LocalChirpIdentity): ByteArray {228 val sb = StringBuilder()229 sb.append('{')230 sb.append("\"type\":\"PAIR_IDENTITY\"")231 sb.append(",\"device_id\":\"").append(jsonEscape(id.deviceId)).append('"')232 sb.append(",\"device_name\":\"").append(jsonEscape(id.deviceName)).append('"')233 sb.append(",\"device_type\":\"").append(id.deviceType.wireValue).append('"')234 sb.append(",\"long_term_public_key_hex\":\"").append(id.longTermPublicKeyHex).append('"')235 sb.append(",\"signing_public_key_hex\":\"").append(id.signingPublicKeyHex).append('"')236 id.wsPort?.let { sb.append(",\"ws_port\":").append(it) }237 sb.append(",\"relay_url\":\"").append(jsonEscape(id.relayUrl)).append('"')238 sb.append('}')239 return sb.toString().toByteArray(StandardCharsets.UTF_8)240}241242internal fun parsePairIdentityFrame(bytes: ByteArray): PairIdentity {243 val map = miniJsonObject(String(bytes, StandardCharsets.UTF_8))244 require(map["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }245 val deviceType = when (map["device_type"]) {246 "extension" -> DeviceType.EXTENSION247 "android" -> DeviceType.ANDROID248 "ios" -> DeviceType.IOS249 else -> error("device_type missing")250 }251 val ltpk = map["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")252 require(ltpk.matches(Regex("^[0-9a-f]{64}$"))) { "long_term_public_key_hex not 32-byte hex" }253 return PairIdentity(254 deviceId = map["device_id"] ?: error("device_id missing"),255 deviceName = map["device_name"] ?: error("device_name missing"),256 deviceType = deviceType,257 longTermPublicKeyHex = ltpk,258 signingPublicKeyHex = map["signing_public_key_hex"]?.takeIf { it.isNotBlank() },259 wsPort = map["ws_port"]?.toIntOrNull(),260 relayUrl = map["relay_url"]?.let(Rendezvous::normalizeRelayUrl),261 )262}263264internal fun pairIdentityToPairedDevice(id: PairIdentity): PairedDevice = PairedDevice(265 deviceId = id.deviceId,266 deviceName = id.deviceName,267 deviceType = id.deviceType.wireValue,268 longTermPublicKeyHex = id.longTermPublicKeyHex,269 signingPublicKeyHex = id.signingPublicKeyHex,270 trustSource = "direct",271 wsPort = id.wsPort,272 relayUrl = id.relayUrl,273 pairedAt = System.currentTimeMillis(),274 lastSyncedAt = System.currentTimeMillis(),275)276277278279280281282283internal fun chirpSessionOver(284 session: NoiseNKSession,285 transport: SocketFrameIO,286 remoteStaticPublicKey: ByteArray = ByteArray(0),287): ChirpSyncSession =288 ChirpSyncSession(289 remoteStaticPublicKey = remoteStaticPublicKey.copyOf(),290 291 292 send = { plaintext -> transport.sendBlocking(session.encrypt(plaintext)) },293 receive = { session.decrypt(transport.receive()) },294 close = {295 try {296 session.close()297 } finally {298 transport.close()299 }300 },301 )302303private fun jsonEscape(value: String): String = buildString(value.length) {304 for (ch in value) when (ch) {305 '\\' -> append("\\\\"); '"' -> append("\\\"")306 '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t")307 else -> append(ch)308 }309}310311private fun miniJsonObject(text: String): Map<String, String> {312 val trimmed = text.trim()313 require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }314 val body = trimmed.substring(1, trimmed.length - 1)315 val out = linkedMapOf<String, String>()316 var i = 0317 while (i < body.length) {318 while (i < body.length && body[i].isWhitespace()) i++319 if (i >= body.length || body[i] != '"') break320 i++321 val keyStart = i322 while (i < body.length && body[i] != '"') i++323 val key = body.substring(keyStart, i); i++324 while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++325 val value: String326 if (i < body.length && body[i] == '"') {327 i++328 val vStart = i329 while (i < body.length && body[i] != '"') i++330 value = body.substring(vStart, i); i++331 } else {332 val vStart = i333 while (i < body.length && body[i] != ',') i++334 value = body.substring(vStart, i).trim()335 }336 out[key] = value337 while (i < body.length && body[i].isWhitespace()) i++338 if (i < body.length && body[i] == ',') i++339 }340 return out341}