Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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()}")
}
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading