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 return try {120 val selector = JSONObject(String(transport.receive(), Charsets.UTF_8))121 require(selector.optString("type") == "PEACH_RECONNECT") { "expected PEACH_RECONNECT" }122 val rendezvousId = selector.optString("rendezvous_id")123 val known = Rendezvous.resolvePeer(deviceStore.getAll(), rendezvousId)124 ?: throw IllegalArgumentException("unknown reconnect peer")125 val initiatorKeyHex = known.longTermPublicKeyHex126 ?: throw IllegalArgumentException("known peer missing static key")127 val initiatorKey = hexToPubkey(initiatorKeyHex)128129 val session = noiseKKResponder(130 ourStaticPrivateKey,131 ourStaticPublicKey,132 initiatorKey,133 transport::send,134 transport::receive,135 )136137 138 139 val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))140 require(theirIdentity.deviceId == known.deviceId) { "peer device id changed after KK" }141 require(142 theirIdentity.longTermPublicKeyHex.equals(initiatorKeyHex, ignoreCase = true),143 ) { "peer identity does not match authenticated KK key" }144 transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))145146 val sas = SASDerivation.derive(session.handshakeHash)147 148 val vault = vaultFactory()149 if (vault != null) {150 vault.bindAuthenticatedPeer(known)151 val syncSession = chirpSessionOver(session, transport, initiatorKey)152 val outcome = runChirpSyncResponder(syncSession, vault)153 if (outcome.status == SyncOutcomeStatus.COMPLETED) {154 deviceStore.updateLastSync(known.deviceId)155 }156 }157 transport.close()158 PairingServerEvent.SyncComplete(known.deviceId, sas)159 } catch (e: Throwable) {160 transport.close()161 PairingServerEvent.Error(e.message ?: "pairing_server_error")162 }163 }164165 private fun registerMdns(port: Int, staticPub: ByteArray, deviceId: String) {166 val manager = ctx.getSystemService(NsdManager::class.java) ?: return167 nsdManager = manager168 val info = NsdServiceInfo().apply {169 serviceName = buildServiceName(deviceId)170 serviceType = PEACH_SERVICE_TYPE171 this.port = port172 173 setAttribute("v", PROTOCOL_VERSION)174 setAttribute("pk", pubkeyToHex(staticPub))175 setAttribute("id", deviceId)176 }177 val listener = object : NsdManager.RegistrationListener {178 override fun onServiceRegistered(info: NsdServiceInfo) {}179 override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {}180 override fun onServiceUnregistered(info: NsdServiceInfo) {}181 override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {}182 }183 registrationListener = listener184 manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)185 }186187 private fun buildServiceName(deviceId: String): String {188 val shortId = deviceId.take(8)189 val model = Build.MODEL.replace(Regex("[^A-Za-z0-9-]"), "")190 191 192 val maxModel = 63 - "Peach-".length - 1 - shortId.length193 val trimmedModel = if (model.length > maxModel && maxModel > 0) model.take(maxModel) else model194 return "Peach-$trimmedModel-$shortId".take(63)195 }196197 private companion object {198 const val PEACH_SERVICE_TYPE = "_peach._tcp"199 const val PROTOCOL_VERSION = "1"200 }201}202203sealed class PairingServerEvent {204 data class Started(val port: Int) : PairingServerEvent()205 data class SyncComplete(val deviceId: String, val sas: String) : PairingServerEvent()206 data class Error(val message: String) : PairingServerEvent()207 data object Stopped : PairingServerEvent()208}209210211212213internal data class PairIdentity(214 val deviceId: String,215 val deviceName: String,216 val deviceType: DeviceType,217 val longTermPublicKeyHex: String,218 val signingPublicKeyHex: String?,219 val wsPort: Int?,220 val relayUrl: String?,221)222223internal fun encodePairIdentityFrame(id: LocalChirpIdentity): ByteArray {224 val sb = StringBuilder()225 sb.append('{')226 sb.append("\"type\":\"PAIR_IDENTITY\"")227 sb.append(",\"device_id\":\"").append(jsonEscape(id.deviceId)).append('"')228 sb.append(",\"device_name\":\"").append(jsonEscape(id.deviceName)).append('"')229 sb.append(",\"device_type\":\"").append(id.deviceType.wireValue).append('"')230 sb.append(",\"long_term_public_key_hex\":\"").append(id.longTermPublicKeyHex).append('"')231 sb.append(",\"signing_public_key_hex\":\"").append(id.signingPublicKeyHex).append('"')232 id.wsPort?.let { sb.append(",\"ws_port\":").append(it) }233 sb.append(",\"relay_url\":\"").append(jsonEscape(id.relayUrl)).append('"')234 sb.append('}')235 return sb.toString().toByteArray(StandardCharsets.UTF_8)236}237238internal fun parsePairIdentityFrame(bytes: ByteArray): PairIdentity {239 val map = miniJsonObject(String(bytes, StandardCharsets.UTF_8))240 require(map["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }241 val deviceType = when (map["device_type"]) {242 "extension" -> DeviceType.EXTENSION243 "android" -> DeviceType.ANDROID244 "ios" -> DeviceType.IOS245 else -> error("device_type missing")246 }247 val ltpk = map["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")248 require(ltpk.matches(Regex("^[0-9a-f]{64}$"))) { "long_term_public_key_hex not 32-byte hex" }249 return PairIdentity(250 deviceId = map["device_id"] ?: error("device_id missing"),251 deviceName = map["device_name"] ?: error("device_name missing"),252 deviceType = deviceType,253 longTermPublicKeyHex = ltpk,254 signingPublicKeyHex = map["signing_public_key_hex"]?.takeIf { it.isNotBlank() },255 wsPort = map["ws_port"]?.toIntOrNull(),256 relayUrl = map["relay_url"]?.let(Rendezvous::normalizeRelayUrl),257 )258}259260internal fun pairIdentityToPairedDevice(id: PairIdentity): PairedDevice = PairedDevice(261 deviceId = id.deviceId,262 deviceName = id.deviceName,263 deviceType = id.deviceType.wireValue,264 longTermPublicKeyHex = id.longTermPublicKeyHex,265 signingPublicKeyHex = id.signingPublicKeyHex,266 trustSource = "direct",267 wsPort = id.wsPort,268 relayUrl = id.relayUrl,269 pairedAt = System.currentTimeMillis(),270 lastSyncedAt = System.currentTimeMillis(),271)272273274275276277278279internal fun chirpSessionOver(280 session: NoiseNKSession,281 transport: SocketFrameIO,282 remoteStaticPublicKey: ByteArray = ByteArray(0),283): ChirpSyncSession =284 ChirpSyncSession(285 remoteStaticPublicKey = remoteStaticPublicKey.copyOf(),286 287 288 send = { plaintext -> transport.sendBlocking(session.encrypt(plaintext)) },289 receive = { session.decrypt(transport.receive()) },290 close = { transport.close() },291 )292293private fun jsonEscape(value: String): String = buildString(value.length) {294 for (ch in value) when (ch) {295 '\\' -> append("\\\\"); '"' -> append("\\\"")296 '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t")297 else -> append(ch)298 }299}300301private fun miniJsonObject(text: String): Map<String, String> {302 val trimmed = text.trim()303 require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }304 val body = trimmed.substring(1, trimmed.length - 1)305 val out = linkedMapOf<String, String>()306 var i = 0307 while (i < body.length) {308 while (i < body.length && body[i].isWhitespace()) i++309 if (i >= body.length || body[i] != '"') break310 i++311 val keyStart = i312 while (i < body.length && body[i] != '"') i++313 val key = body.substring(keyStart, i); i++314 while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++315 val value: String316 if (i < body.length && body[i] == '"') {317 i++318 val vStart = i319 while (i < body.length && body[i] != '"') i++320 value = body.substring(vStart, i); i++321 } else {322 val vStart = i323 while (i < body.length && body[i] != ',') i++324 value = body.substring(vStart, i).trim()325 }326 out[key] = value327 while (i < body.length && body[i].isWhitespace()) i++328 if (i < body.length && body[i] == ',') i++329 }330 return out331}