diff --git a/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt b/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt index 21ee7f4..46120ed 100644 --- a/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt +++ b/app/src/main/java/com/example/downloadmanager/manager/DownloadManager.kt @@ -16,16 +16,17 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.cancelAndJoin -import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request @@ -722,6 +723,9 @@ class DownloadManager( if (!response.isSuccessful) { throw IOException("HTTP ${response.code}: ${response.message}") } + if (response.code == 206 && existingLen == 0L) { + throw IOException("Unexpected HTTP 206 Partial Content for a full download") + } val responseEtag = response.header("ETag") val responseLastMod = response.header("Last-Modified") @@ -1124,12 +1128,7 @@ class DownloadManager( } } } - try { - workers.awaitAll() - } catch (e: Throwable) { - workerJob.cancelChildren() - throw e - } + workers.awaitAll() if (totalDownloaded.get() != totalSize) { throw IOException("Multi-segment total mismatch: expected $totalSize, got ${totalDownloaded.get()}") } @@ -1141,11 +1140,10 @@ class DownloadManager( expectedSha256 = item.expectedSha256 ) } catch (t: Throwable) { - if (t !is CancellationException) { - // Multi-segment partial file has holes; delete it so a subsequent retry starts cleanly - stagingFile.delete() - } else { - // On pause in multi-segment mode, delete hole-filled file so single-stream resume starts cleanly + // Workers can still hold the staging file after another worker fails. + // Wait for their file handles to close before removing a file with holes. + withContext(NonCancellable) { + workerJob.cancelAndJoin() stagingFile.delete() } throw t diff --git a/app/src/main/java/com/example/downloadmanager/manager/VideoDownloadManager.kt b/app/src/main/java/com/example/downloadmanager/manager/VideoDownloadManager.kt index d55fe21..dd35f33 100644 --- a/app/src/main/java/com/example/downloadmanager/manager/VideoDownloadManager.kt +++ b/app/src/main/java/com/example/downloadmanager/manager/VideoDownloadManager.kt @@ -3319,6 +3319,9 @@ class VideoDownloadManager( } throw IOException("HTTP ${response.code}: ${response.message}") } + if (response.code == 206) { + throw IOException("Unexpected HTTP 206 Partial Content for a full media stream") + } val contentType = (response.header("Content-Type") ?: "").lowercase(Locale.US) if (contentType.contains("mpegurl")) { return downloadHlsStreamToFile(downloadId, effectiveUrl, ua, destFile, onProgress) @@ -3767,6 +3770,8 @@ class VideoDownloadManager( expectedStart = byteRange.offset, expectedEndInclusive = byteRange.endInclusive ) + } else if (resp.code == 206) { + throw IOException("Unexpected HTTP 206 Partial Content for an HLS segment without a byte range") } val expectedPartLen = byteRange?.length diff --git a/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt b/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt index 5626cc0..67a5ca2 100644 --- a/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt +++ b/app/src/test/java/com/example/downloadmanager/DownloadManagerCoreVerificationTest.kt @@ -835,6 +835,90 @@ class DownloadManagerCoreVerificationTest { // Phase 3: Narrow Atomic DAO Updates & Worker Lifecycle Serialization Tests // ========================================================================= + @Test + fun fullHttpDownloadRejectsAnUnrequestedPartialBody() = runBlocking { + val target = createTempDirectory("http_unsolicited_partial").toFile() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + val repository = DownloadRepository(InMemoryDownloadDao()) + val manager = DownloadManager(null, repository) + try { + server.createContext("/file.bin") { exchange -> + if (exchange.requestMethod == "HEAD") { + exchange.responseHeaders.set("Content-Length", "8") + exchange.sendResponseHeaders(200, -1) + exchange.close() + } else { + val probe = exchange.requestHeaders.getFirst("Range") == "bytes=0-0" + val payload = if (probe) byteArrayOf(0) else byteArrayOf(4, 5, 6, 7) + exchange.responseHeaders.set("Content-Range", if (probe) "bytes 0-0/8" else "bytes 4-7/8") + exchange.sendResponseHeaders(206, payload.size.toLong()) + exchange.responseBody.use { it.write(payload) } + } + } + server.start() + val id = manager.startDownload( + DownloadItem( + url = "http://127.0.0.1:${server.address.port}/file.bin", + filename = "file.bin", + savePath = target.absolutePath + ) + ) + var error: String? = null + manager.executeDownloadJob( + downloadItem = checkNotNull(repository.getDownloadById(id)), + onProgress = { _, _, _, _ -> }, + onComplete = { fail("A partial response must not complete a full download") }, + onError = { _, message -> error = message }, + preferredSegments = 1 + ) + + assertEquals(DownloadStatus.FAILED, repository.getDownloadById(id)?.status) + assertTrue(error?.contains("Unexpected HTTP 206") == true) + assertFalse(File(target, "file.bin").exists()) + } finally { + server.stop(0) + target.deleteRecursively() + } + } + + @Test + fun fullMediaAndHlsSegmentsRejectUnrequestedPartialBodies() = runBlocking { + val target = createTempDirectory("media_unsolicited_partial").toFile() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + val repository = DownloadRepository(InMemoryDownloadDao()) + val manager = VideoDownloadManager(null, repository) + try { + server.createContext("/partial.mp3") { exchange -> + exchange.responseHeaders.set("Content-Type", "audio/mpeg") + exchange.responseHeaders.set("Content-Range", "bytes 4-7/8") + exchange.sendResponseHeaders(206, 4) + exchange.responseBody.use { it.write(byteArrayOf(4, 5, 6, 7)) } + } + server.createContext("/media.m3u8") { exchange -> + val playlist = "#EXTM3U\n#EXTINF:4,\npartial.mp3\n#EXT-X-ENDLIST\n".toByteArray() + exchange.sendResponseHeaders(200, playlist.size.toLong()) + exchange.responseBody.use { it.write(playlist) } + } + server.start() + val base = "http://127.0.0.1:${server.address.port}" + val output = File(target, "out.mp3") + val direct = runCatching { + manager.streamUrlToFile(1L, "$base/partial.mp3", output, onProgress = { _, _, _, _ -> }) + } + assertTrue(direct.exceptionOrNull()?.message?.contains("Unexpected HTTP 206") == true) + assertFalse(output.exists()) + + val hls = runCatching { + manager.downloadHlsStreamToFile(1L, "$base/media.m3u8", "LucaTest", output) { _, _, _, _ -> } + } + assertTrue(hls.exceptionOrNull()?.message?.contains("Unexpected HTTP 206") == true) + assertEquals(0L, output.length()) + } finally { + server.stop(0) + target.deleteRecursively() + } + } + @Test fun phase3_narrowAtomicProgressUpdate_neverOverwritesPausedOrCancelledState() = runBlocking { val dao = InMemoryDownloadDao()