share: a failed AirDrop upload deletes the files it already extracted
- Commit
4ad7ba3feb87df5a49070ca091c8935211ab1c4d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 09:00 UTC (5 days ago)
- Parents
482bf43
upload() publishes extracted files only after the whole archive succeeds, but extractCpio/extractZip wrote each entry into app-private staging as they went and only the entry being written at the failure was ever deleted. On a truncated archive, every complete entry before the failure stayed on disk — unpublished (the Failed notification has no Share/Save action), unreachable, and removed only by the 24-hour cold-start orphan sweep. Extraction now cleans up all-or-nothing: on any failure both extractors delete every file written for that archive and rethrow; successful transfers are unchanged. Regression test (accepted Ask, then a cpio upload whose second entry is truncated) failed pre-fix with the first entry left staged while receivedFiles was empty. Intent handling, send-side staging, Quick Share receive and path confinement were audited and cleared. Verified: :share:testDevUnitTest 104 tests pass; lint error is pre-existing on an untouched file. Nothing newly finished on CI; latest still stale, run in flight.
Diff
share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt
diff --git a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.ktindex 690f74482c..608b5de37a 100644--- a/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt+++ b/share/src/main/java/com/vayunmathur/share/platform/airdrop/AirDropReceiver.kt@@ -222,26 +222,40 @@ class AirDropReceiver( private fun extractCpio(input: InputStream, onBytes: (Long) -> Unit): List<File> { val reader = Cpio.Reader(input) val written = mutableListOf<File>()- while (true) {- val (entry, content) = reader.next() ?: break- if (entry.isFile) {- AirDropMessages.safeRelativePath(entry.name)?.let { name ->- written += writeEntry(name, content, onBytes)+ try {+ while (true) {+ val (entry, content) = reader.next() ?: break+ if (entry.isFile) {+ AirDropMessages.safeRelativePath(entry.name)?.let { name ->+ written += writeEntry(name, content, onBytes)+ } } }+ } catch (e: Exception) {+ // All-or-nothing: the caller only publishes `written` on success, so an+ // entry completed before a truncated/corrupt tail would otherwise stay+ // staged with no notification able to offer Share/Save for it.+ written.forEach { it.delete() }+ throw e } return written } private fun extractZip(zip: ZipInputStream, onBytes: (Long) -> Unit): List<File> { val written = mutableListOf<File>()- while (true) {- val entry = zip.nextEntry ?: break- if (!entry.isDirectory) {- AirDropMessages.safeRelativePath(entry.name)?.let { name ->- written += writeEntry(name, zip, onBytes)+ try {+ while (true) {+ val entry = zip.nextEntry ?: break+ if (!entry.isDirectory) {+ AirDropMessages.safeRelativePath(entry.name)?.let { name ->+ written += writeEntry(name, zip, onBytes)+ } } }+ } catch (e: Exception) {+ // See extractCpio: a failed archive must not strand its earlier entries.+ written.forEach { it.delete() }+ throw e } return written }
share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropFailedUploadCleanupTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropFailedUploadCleanupTest.kt b/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropFailedUploadCleanupTest.ktnew file mode 100644index 0000000000..5efe9b0e67--- /dev/null+++ b/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropFailedUploadCleanupTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.share.platform.airdrop++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.share.domain.airdrop.AirDropMessages+import com.vayunmathur.share.domain.airdrop.BinaryPlist+import com.vayunmathur.share.domain.airdrop.Cpio+import com.vayunmathur.share.domain.protocol.ShareState+import com.vayunmathur.share.network.airdrop.AirDropHttp+import com.vayunmathur.share.platform.ReceivedFileStore+import com.vayunmathur.testsupport.awaitValue+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.net.InetAddress+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Regression: an AirDrop upload whose archive fails after one or more entries+ * have been fully extracted must not leave those entries in the received+ * staging directory. They were never published in `receivedFiles`, so no+ * notification offers Share/Save for them; before the fix they stayed on disk+ * as unreachable orphans until the 24-hour cold-start sweep.+ */+@RunWith(RobolectricTestRunner::class)+class AirDropFailedUploadCleanupTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val remote: InetAddress = InetAddress.getByName("127.0.0.1")++ private fun request(path: String, body: ByteArray, headers: Map<String, String> = emptyMap()): AirDropHttp.Request {+ val h = AirDropHttp.Headers(headers.mapKeys { it.key.lowercase() })+ return AirDropHttp.Request("POST", path, h, ByteArrayInputStream(body))+ }++ @Test+ fun `truncated upload deletes entries extracted before the failure`() = runBlocking {+ val receiver = AirDropReceiver(ReceivedFileStore(ctx), { "TestMac" }, { 1_000_000_000L }, { _, _ -> })+ val firstName = "cleanup-first-${System.nanoTime()}.txt"+ val secondName = "cleanup-second-${System.nanoTime()}.txt"+ val stagedFirst = File(ctx.filesDir, "received/$firstName")+ stagedFirst.delete()++ val ask = AirDropMessages.AskRequest(+ senderComputerName = "PeerPhone",+ senderModelName = "Phone",+ senderId = "wxyz",+ files = listOf(+ AirDropMessages.AskFile.forFile(firstName, 5L),+ AirDropMessages.AskFile.forFile(secondName, 10L),+ ),+ transferId = "tid-cleanup",+ )+ val askJob = async { receiver.handle(request("/Ask", BinaryPlist.encode(ask.toPlist())), remote) }+ val handle = receiver.incoming.awaitValue { it.isNotEmpty() }.first().sessionHandle+ val incoming = receiver.sessionFor(handle)!!+ assertEquals(0, receiver.accept(handle, true))+ assertEquals(200, askJob.await().status)++ // A complete first entry followed by a second entry whose body is cut+ // short: the reader hits EOF while extracting the second file.+ val archiveOut = ByteArrayOutputStream()+ val cpio = Cpio.Writer(archiveOut)+ cpio.file("./$firstName", 5, ByteArrayInputStream("first".toByteArray()))+ cpio.file("./$secondName", 10, ByteArrayInputStream("0123456789".toByteArray()))+ cpio.finish()+ val truncated = archiveOut.toByteArray().dropLast(8).toByteArray()++ val uploadResp = receiver.handle(+ request(+ "/Upload",+ truncated,+ mapOf(+ "Content-Type" to AirDropMessages.CONTENT_TYPE_CPIO,+ "TransferID" to "tid-cleanup",+ ),+ ),+ remote,+ )++ assertEquals(500, uploadResp.status)+ assertEquals(ShareState.Failed, incoming.state.value)+ assertTrue(incoming.receivedFiles.value.isEmpty())+ assertFalse(+ "entry extracted before the failure was left staged: $stagedFirst",+ stagedFirst.exists(),+ )+ }+}