diff --git a/README.md b/README.md index 2f41eab..b2f88b8 100644 --- a/README.md +++ b/README.md @@ -377,3 +377,28 @@ docs/ RESEARCH.md, screenshots MIT. See [LICENSE](LICENSE). AirBridge is not affiliated with Apple, Google or the LocalSend project. The Android app uses the [Inter](https://rsms.me/inter/) typeface, under the SIL Open Font License ([android/third_party/inter/OFL.txt](android/third_party/inter/OFL.txt)). + +### Share with a phone without the app (Wi-Fi Direct) + +On Android, choose **Share with a phone without the app**. Grant Nearby Wi-Fi +permission (Location on Android 12 and older; Location services may also need to +be enabled). AirBridge creates a Wi-Fi Direct network and tries 5 GHz first, +falling back to the device's automatic band selection. + +On the other Android phone or iPhone, scan the first QR to join Wi-Fi, or enter +the displayed network name and password. Stay connected when warned that the +network has no internet. Then show and scan the second QR to open the browser +companion. Choose files in the browser to send to AirBridge and accept the +request on the app phone; received files go to Downloads/AirBridge. Use **Offer +files to the other phone** on the app phone to send in the other direction. + +No router, internet connection, shared home Wi-Fi password, or second app is +needed. Keep the sharing screen open; leaving it, stopping the service, losing +the group, or reaching the 30-minute session limit removes the network. The +session link grants access: share it only with the intended recipient. Data uses +plain HTTP inside the password-protected Wi-Fi Direct network. Browser downloads +support byte ranges for resuming; uploads stream to storage with three files in +parallel. The 2 GB in 30–60 seconds target needs real-device verification and is +not guaranteed: storage speed, Wi-Fi hardware, vendor 5 GHz support, and iPhone +joining behavior all affect it. Android versions below the app's minimum API 29 +are not supported. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 60807a4..74b2fb7 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -19,6 +19,8 @@ android { versionName = "0.1.5" } + sourceSets["main"].assets.srcDir("../../linux/ui") + buildTypes { release { isMinifyEnabled = true @@ -54,6 +56,7 @@ android { } dependencies { + implementation("com.google.zxing:core:3.5.3") val composeBom = platform("androidx.compose:compose-bom:2024.12.01") implementation(composeBom) implementation("androidx.compose.ui:ui") diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 01acb61..7e6e8a8 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -4,6 +4,11 @@ + + + + + diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/core/BrowserCompanion.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/BrowserCompanion.kt new file mode 100644 index 0000000..902b8d7 --- /dev/null +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/BrowserCompanion.kt @@ -0,0 +1,170 @@ +package io.github.mdhaarith.airbridge.core + +import kotlinx.coroutines.delay +import kotlinx.serialization.json.* +import java.io.IOException +import java.security.MessageDigest +import java.security.SecureRandom +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +/** Browser protocol adapter; file acceptance and storage stay in the LocalSend engine. */ +class BrowserCompanion(private val engine: Engine, private val asset: (String) -> ByteArray) { + val secret = randomToken() + private data class Upload(val owner: String, val session: PrepareUploadResponse) + private val uploads = ConcurrentHashMap() + private val incomingPeers = ConcurrentHashMap.newKeySet() + private val offered = ConcurrentHashMap.newKeySet() + private val requests = RateLimit(20, 120, 60_000) + @Volatile private var closed = false + private fun json(value: JsonElement) = HttpResponse.json(200, value.toString()) + private fun hello() = buildJsonObject { + put("alias", engine.me().alias); put("deviceModel", engine.me().deviceModel) + put("poll", true); put("text", false) + } + + fun offer(uris: List): String? = engine.browserOffer(uris)?.also { offered.add(it) } + + fun close() { + closed = true + (offered + uploads.keys + engine.transfers.value.filter { it.peerId in incomingPeers && !it.status.isFinal }.map { it.id }).forEach { engine.finish(it, Status.CANCELLED, "Session ended") } + uploads.clear() + offered.clear() + } + + suspend fun handle(req: HttpRequest): HttpResponse { + if (closed) return HttpResponse.error(410, "Session ended") + // The fragment cannot authenticate the first navigation. Only this inert bootstrap is public. + if (req.method == "GET" && req.path == "/") return HttpResponse(200, BOOTSTRAP.toByteArray(), "text/html") + if (!authorized(secret, req.query["k"])) return HttpResponse.error(403, "Invalid session key") + if (req.method == "GET" && req.path == "/app") { + val html = String(asset("companion.html")) + .replace(Regex("(/assets/[^\" ]+)")) { "${it.value}?k=$secret" } + return HttpResponse(200, html.toByteArray(), "text/html") + } + if (req.method == "GET" && req.path.startsWith("/assets/")) { + val name = req.path.removePrefix("/assets/") + if (name !in ASSETS) return HttpResponse.error(404, "Not found") + val type = when (name.substringAfterLast('.')) { "js" -> "text/javascript"; "css" -> "text/css"; else -> "image/svg+xml" } + return HttpResponse(200, asset(name), type) + } + if (req.path == "/hello" && req.method == "GET") return json(hello()) + val client = req.query["id"]?.takeIf { it.length in 1..64 && it.all { c -> c.isLetterOrDigit() } } + ?: return HttpResponse.error(400, "Missing client id") + if (req.path == "/poll" && req.method == "GET") { + repeat(20) { + if (closed) return HttpResponse.error(410, "Session ended") + val cancelled = offered.mapNotNull(engine::transfer).firstOrNull { it.status in setOf(Status.CANCELLED, Status.FAILED, Status.DECLINED) } + if (cancelled != null) { + offered.remove(cancelled.id) + return json(buildJsonArray { add(buildJsonObject { put("type", "cancel"); put("id", cancelled.id) }) }) + } + val offers = offered.mapNotNull(engine::transfer).filter { it.status == Status.WAITING } + if (offers.isNotEmpty()) return json(buildJsonArray { offers.take(1).forEach { t -> add(buildJsonObject { + put("type", "offer"); put("id", t.id); put("from", engine.me().alias) + putJsonArray("files") { t.files.forEach { f -> add(buildJsonObject { + put("id", f.id); put("name", f.name); put("size", f.size); put("type", f.mime) + }) } } + }) } }) + delay(500) + } + return json(JsonArray(emptyList())) + } + if (req.path == "/send" && req.method == "POST") { + uploads.entries.removeAll { engine.transfer(it.key)?.status?.isFinal != false } + if (!requests.hit(req.remoteIp) || uploads.size >= 32) return HttpResponse.error(429, "Too many requests") + val files = runCatching { + val list = Protocol.json.parseToJsonElement(String(req.readBody())).jsonObject.getValue("files").jsonArray + require(list.size in 1..Protocol.MAX_FILES) + list.associate { item -> + val f = item.jsonObject + val id = UUID.randomUUID().toString() + val name = f.getValue("name").jsonPrimitive.content + require(name.isNotBlank() && name.length <= 1024) + id to FileDto(id, safeSegments(name).joinToString("/"), f.getValue("size").jsonPrimitive.long, + f["type"]?.jsonPrimitive?.content ?: "application/octet-stream") + } + }.getOrNull() ?: return HttpResponse.error(400, "Invalid files") + val peerId = MessageDigest.getInstance("SHA-256").digest((secret + client).toByteArray()).joinToString("") { "%02x".format(it) } + incomingPeers.add(peerId) + if (closed) return HttpResponse.error(410, "Session ended") + val response = engine.prepareUpload(req, PrepareUploadRequest(DeviceInfo("Phone (browser)", fingerprint = peerId, protocol = "http", deviceType = "web"), files)) + if (response.status != 200) return response + val prepared = Protocol.json.decodeFromString(PrepareUploadResponse.serializer(), String(response.body)) + val transfer = engine.transfers.value.firstOrNull { t -> t.peerId == peerId && t.files.any { it.id in files } && t.status == Status.TRANSFERRING } + ?: return HttpResponse.error(409, "Session ended") + if (closed) { engine.cancel(transfer.id); return HttpResponse.error(410, "Session ended") } + uploads[transfer.id] = Upload(client, prepared) + return json(buildJsonObject { + put("transfer", transfer.id) + putJsonArray("files") { files.keys.forEach { add(buildJsonObject { put("id", it) }) } } + }) + } + if (req.path == "/upload" && req.method == "POST") { + val entry = uploads[req.query["transfer"]] ?: return HttpResponse.error(403, "Unknown transfer") + val file = req.query["file"] ?: return HttpResponse.error(400, "Missing file") + if (entry.owner != client) return HttpResponse.error(403, "Wrong client") + val token = entry.session.files[file] ?: return HttpResponse.error(403, "Unknown file") + return engine.upload(HttpRequest(req.method, req.path, mapOf("sessionId" to entry.session.sessionId, "fileId" to file, "token" to token), req.headers, req.body, req.remoteIp, null) {}) + } + val parts = req.path.split('/') + if (parts.size == 4 && parts[1] == "offer" && req.method == "POST" && parts[2] in offered) { + if (parts[3] !in setOf("accept", "decline")) return HttpResponse.error(400, "Invalid action") + engine.browserAnswer(parts[2], parts[3] == "accept") + return HttpResponse.json(200, "{}") + } + if (parts.size == 4 && parts[1] == "download" && req.method == "GET" && parts[2] in offered) { + val t = engine.transfer(parts[2]) ?: return HttpResponse.error(404, "Not found") + if (t.status != Status.TRANSFERRING && t.status != Status.DONE) return HttpResponse.error(409, "Not accepted") + val f = t.files.firstOrNull { it.id == parts[3] } ?: return HttpResponse.error(404, "Not found") + val range = byteRange(req.headers["range"], f.size) + if (range == null) return HttpResponse(416, headers = mapOf("Content-Range" to "bytes */${f.size}")) + val (start, count) = range + val headers = mutableMapOf("Accept-Ranges" to "bytes", "Cache-Control" to "no-store", + "Content-Disposition" to "attachment; filename=\"${safeSegments(f.name).last().map { if (it.code in 32..126 && it != '"' && it != '\\') it else '_' }.joinToString("")}\"") + if (req.headers["range"] != null) headers["Content-Range"] = "bytes $start-${start + count - 1}/${f.size}" + return HttpResponse(if (req.headers["range"] == null) 200 else 206, contentType = "application/octet-stream", headers = headers, length = count, stream = { out -> + engine.browserOpen(f.uri!!).use { input -> + var skip = start + while (skip > 0) { val n = input.skip(skip); if (n > 0) skip -= n else if (input.read() >= 0) skip-- else throw IOException("Truncated file") } + val buffer = ByteArray(256 * 1024) + var remaining = count + while (remaining > 0) { + if (closed || engine.transfer(t.id)?.status?.isFinal == true && engine.transfer(t.id)?.status != Status.DONE) throw IOException("Cancelled") + val n = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt()) + if (n < 0) throw IOException("Truncated file") + out.write(buffer, 0, n); remaining -= n + if (start == 0L && t.status != Status.DONE) engine.progress(t.id, f.id, count - remaining) + } + out.flush() + // shortcut: resumed ranges do not complete transfer history; track coverage if resume completion reporting is needed. + if (start == 0L && count == f.size) engine.browserDownloaded(t.id, f.id) + } + }) + } + return HttpResponse.error(404, "Not found") + } + + companion object { + private val ASSETS = setOf("shared.js", "shared.css", "companion.js", "companion.css", "icon.svg") + private const val BOOTSTRAP = """AirBridge""" + fun randomToken(): String = ByteArray(24).also(SecureRandom()::nextBytes).joinToString("") { "%02x".format(it) } + fun authorized(expected: String, supplied: String?) = supplied != null && MessageDigest.isEqual(expected.toByteArray(), supplied.toByteArray()) + /** Single HTTP byte range, represented as offset and length; null means 416. */ + fun byteRange(header: String?, size: Long): Pair? { + if (size < 0) return null + if (header == null) return 0L to size + val match = Regex("bytes=(\\d*)-(\\d*)").matchEntire(header) ?: return null + val a = match.groupValues[1]; val b = match.groupValues[2] + if (size == 0L) return null + if (a.isEmpty()) { + val suffix = b.toLongOrNull()?.takeIf { it > 0 } ?: return null + val count = minOf(suffix, size) + return size - count to count + } + val start = a.toLongOrNull()?.takeIf { it < size } ?: return null + val end = if (b.isEmpty()) size - 1 else b.toLongOrNull()?.coerceAtMost(size - 1) ?: return null + return if (end < start) null else start to end - start + 1 + } + } +} diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/core/Engine.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/Engine.kt index 723c300..e0a899f 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/core/Engine.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/Engine.kt @@ -120,6 +120,7 @@ class Engine(private val platform: Platform) { private val storage = platform.files private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private var server: HttpServer? = null + var stopCompanion: (() -> Unit)? = null var discovery: Discovery? = null private set @@ -168,6 +169,7 @@ class Engine(private val platform: Platform) { @Synchronized fun stop() { + stopCompanion?.invoke() if (!_running.value) return discovery?.stop() discovery = null @@ -246,7 +248,7 @@ class Engine(private val platform: Platform) { change(id) { t -> t.copy(files = t.files.map { if (it.id == fileId) block(it) else it }) } /** Progress updates are throttled so the UI recomposes ~10×/s, not per chunk. */ - private fun progress(id: String, fileId: String, bytes: Long) { + internal fun progress(id: String, fileId: String, bytes: Long) { val session = sessions[id] ?: return val now = System.currentTimeMillis() if (now - session.lastEmit < 100) return @@ -365,9 +367,9 @@ class Engine(private val platform: Platform) { return null } - private suspend fun prepareUpload(req: HttpRequest): HttpResponse { - checkPin(req)?.let { return it } - val body = runCatching { + internal suspend fun prepareUpload(req: HttpRequest, browser: PrepareUploadRequest? = null): HttpResponse { + if (browser == null) checkPin(req)?.let { return it } + val body = browser ?: runCatching { Protocol.json.decodeFromString(PrepareUploadRequest.serializer(), String(req.readBody())) }.getOrNull() ?: return HttpResponse.error(400, "Invalid body") val (info, verified) = verifiedInfo(req, body.info) ?: return HttpResponse.error(400, "Invalid sender") @@ -379,7 +381,7 @@ class Engine(private val platform: Platform) { ?: return HttpResponse.error(400, "Invalid file sizes") // Every request reaches the user (a prompt or a message): not too many. if (!requests.hit(req.remoteIp)) return HttpResponse.error(429, "Too many requests") - upsertPeer(info, req.remoteIp, verified) + if (browser == null) upsertPeer(info, req.remoteIp, verified) // Only your own devices, proven by their certificate, skip the question. val autoAccept = settings.value.autoAcceptTrusted && verified && isTrusted(info.fingerprint) @@ -415,13 +417,17 @@ class Engine(private val platform: Platform) { add(base) } - val accepted = if (decision == null) { + val accepted = try { if (decision == null) { true } else { req.onDisconnect { if (decision.isActive) finish(base.id, Status.CANCELLED, "The sender cancelled") } _events.tryEmit(EngineEvent.Incoming(base.id)) withTimeoutOrNull(5 * 60_000) { runCatching { decision.await() }.getOrDefault(false) } ?: false } + } catch (e: kotlinx.coroutines.CancellationException) { + finish(base.id, Status.CANCELLED, "Session ended") + throw e + } session.decision = null if (transfer(base.id)?.status?.isFinal != false) return HttpResponse.error(403, "Cancelled") if (!accepted) { @@ -438,7 +444,7 @@ class Engine(private val platform: Platform) { return HttpResponse.json(200, Protocol.json.encodeToString(PrepareUploadResponse.serializer(), response)) } - private suspend fun upload(req: HttpRequest): HttpResponse { + internal suspend fun upload(req: HttpRequest): HttpResponse { val sessionId = req.query["sessionId"] val fileId = req.query["fileId"] val token = req.query["token"] @@ -450,11 +456,13 @@ class Engine(private val platform: Platform) { if (expected == null || !MessageDigest.isEqual(expected.toByteArray(), token.toByteArray())) return HttpResponse.error(403, "Invalid token") val transfer = transfer(id) ?: return HttpResponse.error(403, "Invalid session") val file = transfer.files.firstOrNull { it.id == fileId } ?: return HttpResponse.error(403, "Invalid file") - if (file.status == FileStatus.DONE) return HttpResponse.error(409, "Already received") - if (file.status == FileStatus.TRANSFERRING) return HttpResponse.error(409, "Already receiving") val declared = req.headers["content-length"]?.toLongOrNull() if (declared != null && declared > file.size) return HttpResponse.error(413, "More data than announced") - + synchronized(session) { + val current = transfer(id)?.files?.firstOrNull { it.id == fileId } + if (current == null || current.status != FileStatus.QUEUED || transfer(id)?.status != Status.TRANSFERRING) return HttpResponse.error(409, "Already receiving or session over") + updateFile(id, fileId) { it.copy(status = FileStatus.TRANSFERRING) } + } return withContext(Dispatchers.IO) { var pending: FileStore.Pending? = null try { @@ -524,6 +532,29 @@ class Engine(private val platform: Platform) { // ---------------------------------------------------------------- sending + internal fun browserOffer(uris: List): String? { + val picked = describe(uris) + if (picked.isEmpty() || picked.size > Protocol.MAX_FILES) return null + val t = Transfer(UUID.randomUUID().toString(), Direction.OUT, "browser", "Phone (browser)", "web", + files = picked.map { TFile(UUID.randomUUID().toString(), it.name, it.size, it.mime, uri = it.uri) }) + sessions[t.id] = Session(peerIp = "browser") + add(t) + return t.id + } + + internal fun browserAnswer(id: String, accept: Boolean) { + if (transfer(id)?.peerId != "browser") return + if (!accept) finish(id, Status.DECLINED) + else change(id) { if (it.status == Status.WAITING) it.copy(status = Status.TRANSFERRING, started = System.currentTimeMillis()) else it } + } + + internal fun browserDownloaded(id: String, file: String) { + updateFile(id, file) { it.copy(status = FileStatus.DONE, done = it.size) } + finishIfComplete(id) + } + + internal fun browserOpen(uri: String) = storage.open(uri) + fun describe(uris: List): List = uris.mapNotNull(storage::describe) fun sendFiles(peer: Peer, uris: List): String? { diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/core/HttpServer.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/HttpServer.kt index 59c7251..c65a080 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/core/HttpServer.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/HttpServer.kt @@ -48,7 +48,11 @@ class HttpRequest( fun onDisconnect(onGone: () -> Unit) = watcher(onGone) } -class HttpResponse(val status: Int, val body: ByteArray = ByteArray(0), val contentType: String = "application/json") { +class HttpResponse(val status: Int, val body: ByteArray = ByteArray(0), val contentType: String = "application/json", + val headers: Map = emptyMap(), + val length: Long = body.size.toLong(), + val stream: ((java.io.OutputStream) -> Unit)? = null, +) { companion object { fun json(status: Int, json: String) = HttpResponse(status, json.toByteArray()) fun error(status: Int, message: String) = @@ -70,7 +74,9 @@ class HttpServer( var port = 0 private set - fun start(preferredPort: Int): Int { + @Synchronized + fun start(preferredPort: Int, bindAddress: String? = null): Int { + check(scope.isActive) { "Server stopped" } var lastError: IOException? = null for (candidate in preferredPort until preferredPort + 10) { try { @@ -80,11 +86,13 @@ class HttpServer( ServerSocket() } socket.reuseAddress = true - socket.bind(InetSocketAddress(candidate)) + socket.receiveBufferSize = 1024 * 1024 + socket.bind(if (bindAddress == null) InetSocketAddress(candidate) else InetSocketAddress(bindAddress, candidate)) + val actualPort = socket.localPort server = socket - port = candidate + port = actualPort scope.launch { acceptLoop(socket) } - return candidate + return actualPort } catch (e: IOException) { lastError = e } @@ -92,12 +100,15 @@ class HttpServer( throw lastError ?: IOException("no free port") } + @Synchronized fun stop() { runCatching { server?.close() } scope.cancel() + clients.forEach { runCatching { it.close() } } } /** Open connections per address: enough for real devices, not for a flood. */ + private val clients = java.util.concurrent.ConcurrentHashMap.newKeySet() private val open = mutableMapOf() private suspend fun acceptLoop(socket: ServerSocket) { @@ -122,10 +133,13 @@ class HttpServer( runCatching { client.close() } continue } + clients.add(client) + if (!scope.isActive) { clients.remove(client); client.close(); continue } scope.launch { try { serve(client) } finally { + clients.remove(client) synchronized(open) { val left = (open[ip] ?: 1) - 1 if (left <= 0) open.remove(ip) else open[ip] = left @@ -137,14 +151,16 @@ class HttpServer( private suspend fun serve(socket: Socket) { try { + socket.receiveBufferSize = 1024 * 1024 + socket.sendBufferSize = 1024 * 1024 socket.soTimeout = HEAD_TIMEOUT_MS var fingerprint: String? = null if (socket is SSLSocket) { socket.startHandshake() fingerprint = runCatching { (socket.session.peerCertificates.first() as X509Certificate).let(Identity::fingerprintOf) }.getOrNull() } - val input = BufferedInputStream(socket.getInputStream(), 64 * 1024) - val output = BufferedOutputStream(socket.getOutputStream(), 64 * 1024) + val input = BufferedInputStream(socket.getInputStream(), 256 * 1024) + val output = BufferedOutputStream(socket.getOutputStream(), 256 * 1024) val remoteIp = socket.inetAddress.hostAddress?.removePrefix("::ffff:") ?: "" while (true) { // The request line and headers must arrive promptly, and be small. @@ -200,6 +216,7 @@ class HttpServer( Log.w(TAG, "handler failed", e) HttpResponse.error(500, "Internal error") } + if (response.status >= 400) closeAfter = true // Leftover body we did not read (e.g. a rejected upload): close instead of draining gigabytes. if (body is BoundedInputStream && body.remaining > 1_000_000) closeAfter = true if (!closeAfter) runCatching { while (body.read(ByteArray(8192)) >= 0) Unit } @@ -220,13 +237,17 @@ class HttpServer( private fun write(out: BufferedOutputStream, response: HttpResponse, close: Boolean) { val head = buildString { append("HTTP/1.1 ${response.status} ${reason(response.status)}\r\n") - if (response.body.isNotEmpty()) append("Content-Type: ${response.contentType}\r\n") - append("Content-Length: ${response.body.size}\r\n") + if (response.length > 0) append("Content-Type: ${response.contentType}\r\n") + append("Content-Length: ${response.length}\r\n") + response.headers.forEach { (name, value) -> + require(name.none { it == '\r' || it == '\n' } && value.none { it == '\r' || it == '\n' }) + append("$name: $value\r\n") + } append(if (close) "Connection: close\r\n" else "Connection: keep-alive\r\n") append("\r\n") } out.write(head.toByteArray(Charsets.ISO_8859_1)) - out.write(response.body) + if (response.stream != null) response.stream.invoke(out) else out.write(response.body) out.flush() } diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/core/WifiDirectCompanion.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/WifiDirectCompanion.kt new file mode 100644 index 0000000..9569150 --- /dev/null +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/core/WifiDirectCompanion.kt @@ -0,0 +1,162 @@ +package io.github.mdhaarith.airbridge.core + +import android.annotation.SuppressLint +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.net.wifi.WifiManager +import android.net.wifi.p2p.WifiP2pConfig +import android.net.wifi.p2p.WifiP2pManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.os.PowerManager +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.MutableStateFlow + +/** Owned by the QR screen; closing the screen or stopping the service removes the group. */ +@SuppressLint("MissingPermission", "WakelockTimeout") +class WifiDirectCompanion(private val context: Context, private val engine: Engine) { + data class State(val message: String = "Creating Wi-Fi Direct network…", val ssid: String = "", val password: String = "", val url: String = "") + val state = MutableStateFlow(State()) + private val manager = context.getSystemService(Context.WIFI_P2P_SERVICE) as? WifiP2pManager + private val handler = Handler(Looper.getMainLooper()) + private val channel = manager?.initialize(context, Looper.getMainLooper()) { stop("Wi-Fi Direct disconnected") } + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + private var active = false + private var creating = false + private var disposed = false + private var server: HttpServer? = null + private var companion: BrowserCompanion? = null + private var wifiLock: WifiManager.WifiLock? = null + private var wakeLock: PowerManager.WakeLock? = null + private var registered = false + private val stopAction: () -> Unit = { handler.post { stop() }; Unit } + private val receiver = object : BroadcastReceiver() { + override fun onReceive(c: Context?, intent: Intent?) { + if (intent?.action == WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION) inspect() + if (intent?.action == WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION && + intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1) == WifiP2pManager.WIFI_P2P_STATE_DISABLED) stop("Enable Wi-Fi to share") + } + } + + fun start() { + if (active) return + if (manager == null || channel == null) { state.value = State("Wi-Fi Direct is unavailable on this device"); return } + active = true + engine.stopCompanion = stopAction + val filter = IntentFilter(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION).apply { addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION) } + if (Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) else context.registerReceiver(receiver, filter) + registered = true + scope.launch { delay(30 * 60_000L); stop("Session timed out") } + scope.launch { delay(30_000); if (active && companion == null) stop("Could not create network. Enable Location on Android 12 or older, then retry.") } + create(true) + } + + private fun create(fiveGhz: Boolean) { + if (!active || manager == null || channel == null) return + creating = true + val listener = object : WifiP2pManager.ActionListener { + override fun onSuccess() { creating = false; if (active) inspect() else removeGroup() } + override fun onFailure(reason: Int) { + creating = false + if (!active) { if (disposed) channel.close(); return } + if (fiveGhz && Build.VERSION.SDK_INT >= 29) create(false) + else stop("Could not create Wi-Fi Direct group (error $reason). Check Wi-Fi and Location settings.") + } + } + try { + if (Build.VERSION.SDK_INT >= 29) { + val credentials = credentials() + val config = WifiP2pConfig.Builder().setNetworkName(credentials.first).setPassphrase(credentials.second) + .setGroupOperatingBand(operatingBand(fiveGhz)).build() + manager.createGroup(channel, config, listener) + } else manager.createGroup(channel, listener) + } catch (e: Exception) { creating = false; stop(e.message ?: "Wi-Fi Direct permission denied") } + } + + private fun inspect() { + if (!active || manager == null || channel == null) return + try { + manager.requestGroupInfo(channel) { group -> + if (!active) return@requestGroupInfo + if (group == null) { if (companion != null) stop("Wi-Fi Direct group ended"); return@requestGroupInfo } + if (!group.isGroupOwner) { stop("This phone must own the Wi-Fi Direct group"); return@requestGroupInfo } + manager.requestConnectionInfo(channel) { info -> + if (!active || companion != null || !info.groupFormed || !info.isGroupOwner) return@requestConnectionInfo + val ip = info.groupOwnerAddress?.hostAddress ?: return@requestConnectionInfo + val ssid = group.networkName ?: return@requestConnectionInfo + val password = group.passphrase ?: return@requestConnectionInfo + val web = BrowserCompanion(engine) { context.assets.open(it).use { stream -> stream.readBytes() } } + companion = web + scope.launch { + try { + val http = HttpServer(null, web::handle) + server = http + val port = withContext(Dispatchers.IO) { http.start(53318, ip) } + if (!active) { http.stop(); return@launch } + wifiLock = (context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager) + .createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "AirBridge:companion").apply { acquire() } + wakeLock = (context.getSystemService(Context.POWER_SERVICE) as PowerManager) + .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AirBridge:companion").apply { acquire(30 * 60_000L) } + state.value = State("Keep this screen open while sharing", ssid, password, "http://$ip:$port/#k=${web.secret}") + } catch (e: Exception) { stop(e.message ?: "Could not start companion") } + } + } + } + } catch (e: Exception) { stop(e.message ?: "Wi-Fi Direct permission denied") } + } + + fun offer(uris: List) = companion?.offer(uris) + + fun stop(message: String = "Session stopped") { + val wasActive = active + active = false + companion?.close(); companion = null + server?.stop(); server = null + scope.coroutineContext.cancelChildren() + if (registered) { context.unregisterReceiver(receiver); registered = false } + if (wasActive) removeGroup() + wifiLock?.let { if (it.isHeld) it.release() }; wifiLock = null + wakeLock?.let { if (it.isHeld) it.release() }; wakeLock = null + if (engine.stopCompanion === stopAction) engine.stopCompanion = null + state.value = State(message) + } + + private fun removeGroup() { + val p2p = manager ?: return + val currentChannel = channel ?: return + runCatching { + p2p.removeGroup(currentChannel, object : WifiP2pManager.ActionListener { + override fun onSuccess() { if (disposed && !creating) currentChannel.close() } + override fun onFailure(reason: Int) { + if (!creating) state.value = state.value.copy(message = "Session stopped; Wi-Fi Direct cleanup failed ($reason). Turn Wi-Fi off if the network remains.") + if (disposed && !creating) currentChannel.close() + } + }) + }.onFailure { if (disposed && !creating) currentChannel.close() } + } + + fun dispose() { + disposed = true + val wasActive = active + stop() + // Keep the channel alive until a pending create callback can remove its group. + if (!wasActive && !creating) channel?.close() + scope.cancel() + } + + companion object { + fun operatingBand(fiveGhz: Boolean) = if (fiveGhz) WifiP2pConfig.GROUP_OWNER_BAND_5GHZ else WifiP2pConfig.GROUP_OWNER_BAND_AUTO + + fun credentials(): Pair { + val token = BrowserCompanion.randomToken() + return "DIRECT-${token.take(2)}-AirBridge" to token.substring(2, 26) + } + fun wifiQr(ssid: String, password: String): String { + fun escape(s: String) = s.flatMap { if (it in "\\;,:\"") listOf('\\', it) else listOf(it) }.joinToString("") + return "WIFI:T:WPA;S:${escape(ssid)};P:${escape(password)};;" + } + } +} diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt index 0ac7c1e..4542885 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt @@ -7,9 +7,13 @@ import android.content.ContentUris import android.content.Context import android.content.Intent import android.graphics.Canvas +import android.graphics.LinearGradient import android.graphics.Paint +import android.graphics.Path import android.graphics.PixelFormat +import android.graphics.Point import android.graphics.RectF +import android.graphics.Shader import android.net.Uri import android.os.Build import android.provider.MediaStore @@ -133,6 +137,8 @@ class EdgePanel(private val context: Context) { ).apply { gravity = Gravity.TOP or if (rightSide) Gravity.END else Gravity.START y = (metrics.heightPixels * engine.settings.value.edgeY).toInt() + // Reach into the notch's strip so the handle can wrap around it. + layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES } runCatching { windows.addView(view, params) } .onSuccess { handle = view } @@ -568,35 +574,151 @@ class EdgePanel(private val context: Context) { fun destroy() = owner.destroy() } - /** The resting handle: a quiet gray pill, like the home indicator. Tap or swipe it in to open the panel; drag it along the edge to move it. */ + /** + * The resting handle: a glass bump on the screen edge. It swells and follows + * the finger while held, wraps around a notch or punch-hole when it sits + * beside one, fades once left alone and all but disappears over fullscreen + * apps. Tap or swipe it in to open the panel; drag it along the edge to move it. + */ @SuppressLint("ViewConstructor", "ClickableViewAccessibility") private inner class HandleView(context: Context, private val rightSide: Boolean, private val window: View) : View(context) { - private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = HANDLE_IDLE } + private val glass = Paint(Paint.ANTI_ALIAS_FLAG) + private val rim = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = dp(1).toFloat() } + // A dark hairline under the bright rim keeps the glass readable on light screens too. + private val shade = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = dp(2).toFloat(); color = HANDLE_SHADE } + private val path = Path() + private val screen = Point() + private val location = IntArray(2) private val slop = ViewConfiguration.get(context).scaledTouchSlop private var downX = 0f private var downY = 0f private var startY = 0 private var dragging = false + private var pressed = false + private var fingerY = 0f + private var pull = 0f + private var fullscreen = false + private val rest = Runnable { animate().alpha(if (fullscreen) FULLSCREEN_ALPHA else IDLE_ALPHA).setDuration(700).start() } + + // The bump as drawn, easing toward where it should be each frame. + private var depth = 0f + private var center = -1f + private var half = 0f + + init { + setOnApplyWindowInsetsListener { _, insets -> + // Another app hid the status bar: it's showing something fullscreen, so stay out of the way. + val hidden = Build.VERSION.SDK_INT >= 30 && !insets.isVisible(android.view.WindowInsets.Type.statusBars()) + if (hidden != fullscreen) { fullscreen = hidden; settle() } + invalidate() + insets + } + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + wake() + } + + override fun onDetachedFromWindow() { + removeCallbacks(rest) + super.onDetachedFromWindow() + } + + /** Full strength for a moment, then [rest]. */ + private fun wake() { + animate().cancel() + alpha = 1f + settle(IDLE_DELAY) + } + + private fun settle(delay: Long = 0) { + removeCallbacks(rest) + if (!pressed) postDelayed(rest, delay) + } + + /** The notch or punch-hole on our edge that overlaps this window, in view coordinates. */ + @Suppress("DEPRECATION") + private fun notch(): RectF? { + val cutouts = windows.defaultDisplay.cutout?.boundingRects ?: return null + windows.defaultDisplay.getRealSize(screen) + getLocationOnScreen(location) + val near = cutouts.firstOrNull { r -> + (if (rightSide) r.right >= screen.x - 1 else r.left <= 0) && + r.bottom > location[1] && r.top < location[1] + height + } ?: return null + return RectF(near).apply { offset(-location[0].toFloat(), -location[1].toFloat()) } + } override fun onDraw(canvas: Canvas) { - val pillWidth = dp(5).toFloat() - val left = if (rightSide) width - pillWidth - dp(2) else dp(2).toFloat() - canvas.drawRoundRect(RectF(left, height * 0.08f, left + pillWidth, height * 0.92f), pillWidth / 2, pillWidth / 2, paint) + val notch = notch() + // How far the notch reaches in from our edge. + val reach = notch?.let { if (rightSide) width - it.left else it.right } ?: 0f + val fits = if (notch != null) (reach + dp(16)).toInt().coerceAtLeast(dp(HANDLE_WIDTH)) else dp(HANDLE_WIDTH) + if (width != fits && visibility == VISIBLE) post { resize(fits) } + + val targetDepth = when { + notch != null -> reach + dp(if (pressed) 12 else 8) + pressed -> dp(12) + pull * 0.4f + else -> dp(6).toFloat() + }.coerceAtMost((width - dp(2)).toFloat()) + val targetCenter = notch?.centerY() ?: if (pressed) fingerY else height / 2f + val targetHalf = notch?.let { it.height() / 2 + dp(24) } ?: (height * if (pressed) 0.4f else 0.3f) + if (center < 0) { depth = targetDepth; center = targetCenter; half = targetHalf } + depth += (targetDepth - depth) * EASE + center += (targetCenter - center) * EASE + half += (targetHalf - half) * EASE + val settling = abs(targetDepth - depth) + abs(targetCenter - center) + abs(targetHalf - half) > 0.5f + // While held the window moves under the finger, so keep looking for the notch. + if (settling || pressed) postInvalidateOnAnimation() + + val edge = if (rightSide) width.toFloat() else 0f + val tip = if (rightSide) edge - depth else edge + depth + val top = center - half + val bottom = center + half + val ease = half * 0.45f + path.rewind() + path.moveTo(edge, top) + path.cubicTo(edge, top + ease, tip, center - ease, tip, center) + path.cubicTo(tip, center + ease, edge, bottom - ease, edge, bottom) + path.close() + + val (inner, outer) = if (pressed) GLASS_PRESSED else GLASS + glass.shader = LinearGradient(edge, 0f, tip, 0f, inner, outer, Shader.TileMode.CLAMP) + rim.color = if (pressed) HANDLE_ACCENT else HANDLE_RIM + canvas.drawPath(path, shade) + canvas.drawPath(path, glass) + canvas.drawPath(path, rim) + } + + private fun resize(to: Int) { + val params = window.layoutParams as? WindowManager.LayoutParams ?: return + if (params.width == to || visibility != VISIBLE) return + params.width = to + runCatching { windows.updateViewLayout(window, params) } } override fun onTouchEvent(event: MotionEvent): Boolean { val params = window.layoutParams as? WindowManager.LayoutParams ?: return false + fingerY = event.y when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { downX = event.rawX downY = event.rawY startY = params.y dragging = false + pressed = true + pull = 0f + performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) + wake() + invalidate() } + MotionEvent.ACTION_CANCEL -> { pressed = false; invalidate(); settle(IDLE_DELAY) } MotionEvent.ACTION_MOVE -> { val dx = event.rawX - downX val dy = event.rawY - downY val inward = if (rightSide) -dx else dx + pull = inward.coerceAtLeast(0f) if (!dragging && inward > slop * 2 && abs(dy) < inward) { dragging = true open() @@ -607,6 +729,9 @@ class EdgePanel(private val context: Context) { } } MotionEvent.ACTION_UP -> { + pressed = false + invalidate() + settle(IDLE_DELAY) if (!dragging) { performClick() } else if (params.y != startY) { @@ -643,7 +768,16 @@ class EdgePanel(private val context: Context) { companion object { private const val TAG = "EdgePanel" - private const val HANDLE_IDLE = 0x998E8E93.toInt() + private const val HANDLE_RIM = 0xB3FFFFFF.toInt() + private const val HANDLE_SHADE = 0x2E000000 + private const val HANDLE_ACCENT = 0xFF0A84FF.toInt() + // Glass: (at the edge, at the tip). Brighter toward the tip, like light catching a lens. + private val GLASS = 0x40FFFFFF to 0x8CFFFFFF.toInt() + private val GLASS_PRESSED = 0x4D0A84FF to 0xA6FFFFFF.toInt() + private const val EASE = 0.22f + private const val IDLE_ALPHA = 0.45f + private const val FULLSCREEN_ALPHA = 0.12f + private const val IDLE_DELAY = 2500L private const val HANDLE_WIDTH = 26 private const val HANDLE_HEIGHT = 120 private val DROP_TYPES = arrayOf("image/*", "video/*", "audio/*", "text/*", "application/*", "font/*", "model/*") diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/AppViewModel.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/AppViewModel.kt index 42ef59b..407f62a 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/AppViewModel.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/AppViewModel.kt @@ -18,7 +18,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -enum class Screen { HOME, ACTIVITY, SETTINGS } +enum class Screen { HOME, ACTIVITY, SETTINGS, COMPANION } /** Files or text waiting for the user to pick a device (AirDrop-style). */ data class PendingShare(val items: List = emptyList(), val text: String? = null) { diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/CompanionScreen.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/CompanionScreen.kt new file mode 100644 index 0000000..f5a1320 --- /dev/null +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/CompanionScreen.kt @@ -0,0 +1,67 @@ +package io.github.mdhaarith.airbridge.ui + +import android.Manifest +import android.content.pm.PackageManager +import android.graphics.Bitmap +import android.os.Build +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.google.zxing.BarcodeFormat +import com.google.zxing.qrcode.QRCodeWriter +import io.github.mdhaarith.airbridge.core.WifiDirectCompanion +import io.github.mdhaarith.airbridge.service.AirBridgeService + +@Composable +fun CompanionScreen(vm: AppViewModel) { + val context = LocalContext.current + val controller = remember { WifiDirectCompanion(context, vm.engine) } + val state by controller.state.collectAsStateWithLifecycle() + var step by remember { mutableIntStateOf(1) } + var permissionError by remember { mutableStateOf(false) } + val permission = if (Build.VERSION.SDK_INT >= 33) Manifest.permission.NEARBY_WIFI_DEVICES else Manifest.permission.ACCESS_FINE_LOCATION + val request = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (granted) { AirBridgeService.start(context); controller.start() } else permissionError = true + } + val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> + if (controller.offer(uris.map { it.toString() }) == null && uris.isNotEmpty()) vm.toast("Couldn't offer files", good = false) + } + DisposableEffect(controller) { + if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) { + AirBridgeService.start(context); controller.start() + } else request.launch(permission) + onDispose { controller.dispose() } + } + Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + SecondaryButton("Stop and go back") { vm.screen = Screen.HOME } + Text(color = LocalAir.current.text, text = "Share with a phone without the app") + Text(color = LocalAir.current.text, text = if (permissionError) "Nearby Wi-Fi permission is required. Go back and retry to grant access." else state.message) + if (state.url.isNotEmpty()) { + Text(color = LocalAir.current.text, text = "1. On the other phone, scan to join Wi-Fi. Stay connected even if it says no internet.") + Text(color = LocalAir.current.text, text = "Network: ${state.ssid}\nPassword: ${state.password}") + SecondaryButton(if (step == 1) "Joined Wi-Fi — show link QR" else "Show Wi-Fi QR") { step = if (step == 1) 2 else 1 } + val value = if (step == 1) WifiDirectCompanion.wifiQr(state.ssid, state.password) else state.url + val bitmap = remember(value) { + val matrix = QRCodeWriter().encode(value, BarcodeFormat.QR_CODE, 600, 600) + Bitmap.createBitmap(600, 600, Bitmap.Config.ARGB_8888).apply { + setPixels(IntArray(600 * 600) { i -> if (matrix[i % 600, i / 600]) android.graphics.Color.BLACK else android.graphics.Color.WHITE }, 0, 600, 0, 0, 600, 600) + }.asImageBitmap() + } + Image(bitmap, contentDescription = if (step == 1) "Wi-Fi join QR code" else "Browser link QR code", modifier = Modifier.fillMaxWidth().aspectRatio(1f)) + if (step == 2) { Text(color = LocalAir.current.text, text = "2. Scan to open AirBridge in the browser."); Text(color = LocalAir.current.text, text = state.url) } + PrimaryButton("Offer files to the other phone") { picker.launch(arrayOf("*/*")) } + Text(color = LocalAir.current.text, text = "To receive files, choose Files in the other phone's browser and accept here. Session ends after 30 minutes or when this screen closes.") + } + } +} diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/HomeScreen.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/HomeScreen.kt index b9f68f6..25442d3 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/HomeScreen.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/HomeScreen.kt @@ -150,6 +150,7 @@ fun HomeScreen(vm: AppViewModel) { Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()) .padding(horizontal = 16.dp).navigationBarsPadding().padding(top = 8.dp, bottom = 24.dp), ) { + SecondaryButton("Share with a phone without the app") { vm.screen = Screen.COMPANION } // ------------------------------------------------- this phone val ip = remember(running, peers.size) { Discovery.localAddresses().firstOrNull()?.address?.hostAddress } Row( diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/Root.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/Root.kt index 37a99db..1c9c291 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/Root.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/ui/Root.kt @@ -94,6 +94,7 @@ fun AirBridgeRoot(vm: AppViewModel) { Screen.HOME -> HomeScreen(vm) Screen.ACTIVITY -> ActivityScreen(vm) Screen.SETTINGS -> SettingsScreen(vm) + Screen.COMPANION -> CompanionScreen(vm) } } BackHandler(enabled = vm.screen != Screen.HOME) { vm.screen = Screen.HOME } diff --git a/android/app/src/test/java/io/github/mdhaarith/airbridge/core/CompanionTest.kt b/android/app/src/test/java/io/github/mdhaarith/airbridge/core/CompanionTest.kt new file mode 100644 index 0000000..033c8a4 --- /dev/null +++ b/android/app/src/test/java/io/github/mdhaarith/airbridge/core/CompanionTest.kt @@ -0,0 +1,155 @@ +package io.github.mdhaarith.airbridge.core + +import kotlinx.coroutines.* +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.net.Socket + +class CompanionTest { + @get:Rule val tmp = TemporaryFolder() + + private fun request(path: String, key: String? = null, method: String = "GET", body: String = "", query: Map = emptyMap(), headers: Map = emptyMap()) = + HttpRequest(method, path, query + if (key == null) emptyMap() else mapOf("k" to key, "id" to "browser1"), headers, ByteArrayInputStream(body.toByteArray()), "127.0.0.1", null) {} + + @Test fun authorizationAndAssetTraversal() = runBlocking { + val engine = Engine(FakePlatform(tmp.newFolder(), "Phone")) + val web = BrowserCompanion(engine) { "asset".toByteArray() } + for (route in listOf("/app", "/hello", "/poll", "/send", "/upload", "/text", "/ws", "/offer/a/accept", "/download/a/b", "/assets/shared.js")) { + assertEquals(route, 403, web.handle(request(route)).status) + assertEquals(route, 403, web.handle(request(route, "wrong")).status) + } + assertEquals(200, web.handle(request("/")).status) + assertEquals(200, web.handle(request("/hello", web.secret)).status) + assertEquals(404, web.handle(request("/assets/../identity", web.secret)).status) + assertEquals(404, web.handle(request("/assets/%2e%2e/identity", web.secret)).status) + assertEquals(200, web.handle(request("/assets/shared.js", web.secret)).status) + assertFalse(BrowserCompanion.authorized(web.secret, null)) + assertTrue(BrowserCompanion.authorized(web.secret, web.secret)) + web.close() + assertEquals(410, web.handle(request("/hello", web.secret)).status) + } + + @Test fun rangeParsing() { + assertEquals(0L to 10L, BrowserCompanion.byteRange(null, 10)) + assertEquals(2L to 4L, BrowserCompanion.byteRange("bytes=2-5", 10)) + assertEquals(8L to 2L, BrowserCompanion.byteRange("bytes=8-", 10)) + assertEquals(7L to 3L, BrowserCompanion.byteRange("bytes=-3", 10)) + assertEquals(0L to 10L, BrowserCompanion.byteRange("bytes=-30", 10)) + assertEquals(8L to 2L, BrowserCompanion.byteRange("bytes=8-100", 10)) + assertEquals(0L to 0L, BrowserCompanion.byteRange(null, 0)) + for (bad in listOf("bytes=10-", "bytes=3-2", "bytes=-0", "bytes=-", "bytes=0-1,3-4", "bytes=999999999999999999999-", "items=0-1")) { + assertNull(bad, BrowserCompanion.byteRange(bad, 10)) + } + assertNull(BrowserCompanion.byteRange("bytes=0-", 0)) + } + + @Test fun p2pCredentialsAndWifiQrEscaping() { + assertEquals(android.net.wifi.p2p.WifiP2pConfig.GROUP_OWNER_BAND_5GHZ, WifiDirectCompanion.operatingBand(true)) + assertEquals(android.net.wifi.p2p.WifiP2pConfig.GROUP_OWNER_BAND_AUTO, WifiDirectCompanion.operatingBand(false)) + val (ssid, password) = WifiDirectCompanion.credentials() + assertTrue(ssid.matches(Regex("DIRECT-[0-9a-f]{2}-AirBridge"))) + assertTrue(password.length in 8..63) + assertNotEquals(password, WifiDirectCompanion.credentials().second) + assertEquals("WIFI:T:WPA;S:DIRECT-ab-AirBridge;P:ab\\;c\\:d\\\\e;;", WifiDirectCompanion.wifiQr("DIRECT-ab-AirBridge", "ab;c:d\\e")) + assertEquals(listOf("folder", "photo.jpg"), safeSegments("../../folder/../photo.jpg")) + } + + @Test fun acceptedUploadUsesStorageAndRejectsDuplicateAndWrongOwner() = runBlocking { + val platform = FakePlatform(tmp.newFolder(), "Phone") + val engine = Engine(platform) + val web = BrowserCompanion(engine) { ByteArray(0) } + val response = async(Dispatchers.IO) { + web.handle(request("/send", web.secret, "POST", """{"files":[{"name":"../../photo.jpg","size":5,"type":"image/jpeg"}]}""")) + } + val transfer = withTimeout(10_000) { + while (engine.transfers.value.isEmpty()) delay(10) + engine.transfers.value.first() + } + assertEquals(Status.WAITING, transfer.status) + engine.decide(transfer.id, true) + val prepared = response.await() + assertEquals(200, prepared.status) + val data = Protocol.json.parseToJsonElement(String(prepared.body)).jsonObject + val params = mapOf("transfer" to data.getValue("transfer").jsonPrimitive.content, "file" to data.getValue("files").jsonArray.first().jsonObject.getValue("id").jsonPrimitive.content) + val wrong = request("/upload", web.secret, "POST", "hello", params + ("id" to "wrong")) + // request helper puts its default id last; construct the wrong owner explicitly. + assertEquals(403, web.handle(HttpRequest("POST", "/upload", wrong.query + ("id" to "wrong"), emptyMap(), wrong.body, "127.0.0.1", null) {}).status) + assertEquals(200, web.handle(request("/upload", web.secret, "POST", "hello", params)).status) + assertEquals("hello", File(platform.downloads, "photo.jpg").readText()) + assertEquals(Status.DONE, engine.transfer(transfer.id)?.status) + assertEquals(403, web.handle(request("/upload", web.secret, "POST", "hello", params)).status) + web.close() + } + + @Test fun invalidMetadataAndStoppingPendingRequest() = runBlocking { + val engine = Engine(FakePlatform(tmp.newFolder(), "Phone")) + val web = BrowserCompanion(engine) { ByteArray(0) } + for (body in listOf( + """{"files":[]}""", + """{"files":[{"name":"","size":1}]}""", + """{"files":[{"name":"file","size":-1}]}""", + """{"files":[{"name":"a","size":9223372036854775807},{"name":"b","size":1}]}""", + )) assertEquals(400, web.handle(request("/send", web.secret, "POST", body)).status) + assertTrue(engine.transfers.value.isEmpty()) + val pending = async(Dispatchers.IO) { + web.handle(request("/send", web.secret, "POST", """{"files":[{"name":"file","size":1}]}""")) + } + withTimeout(10_000) { while (engine.transfers.value.isEmpty()) delay(10) } + web.close() + assertEquals(403, pending.await().status) + assertEquals(Status.CANCELLED, engine.transfers.value.first().status) + } + + @Test fun downloadsRequireAcceptanceAndStreamRanges() = runBlocking { + val platform = FakePlatform(tmp.newFolder(), "Phone") + val engine = Engine(platform) + val web = BrowserCompanion(engine) { ByteArray(0) } + val file = tmp.newFile("source.txt").apply { writeText("0123456789") } + val id = web.offer(listOf(file.path))!! + val fileId = engine.transfer(id)!!.files.first().id + val path = "/download/$id/$fileId" + val offers = web.handle(request("/poll", web.secret)) + assertTrue(String(offers.body).contains(id)) + assertEquals(409, web.handle(request(path, web.secret)).status) + assertEquals(200, web.handle(request("/offer/$id/accept", web.secret, "POST")).status) + val res = web.handle(request(path, web.secret, headers = mapOf("range" to "bytes=2-5"))) + assertEquals(206, res.status) + assertEquals("bytes 2-5/10", res.headers["Content-Range"]) + assertEquals(4L, res.length) + val output = ByteArrayOutputStream() + res.stream!!.invoke(output) + assertEquals("2345", output.toString()) + assertEquals(Status.TRANSFERRING, engine.transfer(id)!!.status) + val whole = web.handle(request(path, web.secret)) + whole.stream!!.invoke(ByteArrayOutputStream()) + assertEquals(Status.DONE, engine.transfer(id)!!.status) + assertEquals(416, web.handle(request(path, web.secret, headers = mapOf("range" to "bytes=10-"))).status) + val cancelled = web.offer(listOf(file.path))!! + engine.cancel(cancelled) + val cancellation = web.handle(request("/poll", web.secret)) + assertTrue(String(cancellation.body).contains("cancel")) + assertTrue(String(cancellation.body).contains(cancelled)) + web.close() + } + + @Test fun httpResponseStreamsWithHeadersAndClosesOnStop() { + val server = HttpServer(null) { HttpResponse(206, contentType = "application/octet-stream", headers = mapOf("Content-Range" to "bytes 2-5/10"), length = 4, stream = { it.write("2345".toByteArray()) }) } + val port = server.start(0, "127.0.0.1") + try { + Socket("127.0.0.1", port).use { socket -> + socket.soTimeout = 5000 + socket.getOutputStream().write("GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".toByteArray()) + val response = socket.getInputStream().readBytes().toString(Charsets.UTF_8) + assertTrue(response, response.startsWith("HTTP/1.1 206")) + assertTrue(response, response.contains("Content-Length: 4\r\n")) + assertTrue(response, response.endsWith("\r\n\r\n2345")) + } + } finally { server.stop() } + } +} diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_home.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_home.png index 248e2ce..c7323c8 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_home.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_home.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeFirstRun.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeFirstRun.png index e68f7ef..697da14 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeFirstRun.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeFirstRun.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeLight.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeLight.png index 07f3937..eaac17a 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeLight.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_homeLight.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingFiles.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingFiles.png index 69e6c43..fc48a29 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingFiles.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingFiles.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingPhotos.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingPhotos.png index d1698f5..346b2c4 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingPhotos.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingPhotos.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequest.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequest.png index 5d2e14c..0e80fbd 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequest.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequest.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequestDark.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequestDark.png index c335590..4cb4aa9 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequestDark.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_incomingRequestDark.png differ diff --git a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_pickADevice.png b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_pickADevice.png index 12af779..52dc65e 100644 Binary files a/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_pickADevice.png and b/android/app/src/test/snapshots/images/io.github.mdhaarith.airbridge.ui_ScreenshotTest_pickADevice.png differ diff --git a/linux/ui/companion.js b/linux/ui/companion.js index 998035e..bc871ec 100644 --- a/linux/ui/companion.js +++ b/linux/ui/companion.js @@ -13,7 +13,7 @@ const store = { const hashKey = new URLSearchParams(location.hash.slice(1)).get("k"); if (hashKey) { store.set("ab_key", hashKey); - history.replaceState(null, "", location.pathname); + history.replaceState(null, "", location.pathname + location.search); } const key = hashKey || store.get("ab_key"); let clientId = store.get("ab_id"); @@ -69,6 +69,12 @@ async function checkPairing() { let retry = 0; function connect() { + if (session.desktop?.poll) { + setLink(true, `Connected to ${session.desktop.alias}`); + $("targetName").textContent = session.desktop.alias; + if (session.desktop.text === false) $("btnText").hidden = true; + return poll(); + } const ws = new WebSocket(`ws://${location.host}/ws?${query({ name: deviceName, model: deviceModel })}`); session.ws = ws; ws.onopen = () => { retry = 0; }; @@ -93,6 +99,32 @@ function connect() { }; } +// Android's small HTTP server uses polling; Linux keeps its WebSocket transport. +let lastOffer = null; +async function poll() { + try { + const res = await fetch(`/poll?${query()}`); + if (res.status === 403 || res.status === 410) return showUnpaired(); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + setLink(true, `Connected to ${session.desktop.alias}`); + $("targetName").textContent = session.desktop.alias; + for (const msg of await res.json()) { + if (msg.type === "cancel" && session.offer?.id === msg.id) { + closeOffer(); + toast("Cancelled", "The sender cancelled the transfer"); + } + if (msg.type === "offer" && msg.id !== lastOffer) { + lastOffer = msg.id; + showOffer(msg); + } + } + setTimeout(poll, 500); + } catch (_) { + setLink(false, "Reconnecting…"); + setTimeout(poll, 2000); + } +} + function showUnpaired() { $("home").hidden = true; $("unpaired").hidden = false; @@ -152,17 +184,20 @@ async function sendFiles(files) { }); const data = await res.json(); if (!res.ok) throw new Error(data.message || "The computer refused"); - let sentBefore = 0; + const loaded = files.map(() => 0); const started = performance.now(); - for (let i = 0; i < files.length; i++) { - const file = files[i]; - await upload(file, data.transfer, data.files[i].id, (loaded) => { - const done = sentBefore + loaded; - const secs = (performance.now() - started) / 1000; - setTarget("busy", total ? done / total : 1, `Sending… ${bytes(done / Math.max(secs, 0.1))}/s`); - }); - sentBefore += file.size; - } + let next = 0; + await Promise.all(Array.from({ length: Math.min(3, files.length) }, async () => { + while (next < files.length) { + const i = next++; + await upload(files[i], data.transfer, data.files[i].id, (n) => { + loaded[i] = n; + const done = loaded.reduce((sum, value) => sum + value, 0); + const secs = (performance.now() - started) / 1000; + setTarget("busy", total ? done / total : 1, `Sending… ${bytes(done / Math.max(secs, 0.1))}/s`); + }); + } + })); setTarget("success", 1, "Sent"); if (navigator.vibrate) navigator.vibrate(18); addRecent({