Skip to content
Aditya Bhalsod
← Mobile
MobileAdvanced

Parallel Byte-Range Downloads Over Plain FTP on Android

How MobileFTP splits one FTP download into parallel byte ranges with REST and RETR, writes each range in place, and resumes from chunk offsets stored in Room.

  • #android
  • #kotlin
  • #ftp
  • #networking
  • #coroutines
Contents
  1. FTP can start mid-file, but it cannot stop
  2. Hanging up on purpose
  3. Splitting the file and writing in place
  4. Resuming from Room
  5. Where this approach stops

MobileFTP is an Android app that works in both directions. It runs an FTP server on the phone with Apache FtpServer, and it is an FTP client with a file browser and a transfer queue built on Apache Commons Net. It is written in Kotlin with Jetpack Compose, Room and WorkManager.

The client is the half worth writing about. It downloads a single file over several FTP connections at once, 8 by default and up to 32. FTP was not designed for that: it has a way to start a transfer partway into a file, but no way to stop at a given byte. This post covers how the engine gets byte ranges out of plain FTP anyway, and how it remembers them for a retry.

FTP can start mid-file, but it cannot stop

A download in FTP is a RETR command. The server opens a data connection and streams the file to the end. Before RETR the client may send REST with a byte offset, and the server starts there instead of at zero. That gives you the start of a range. There is no matching end.

So in ChunkTransferEngine.kt each chunk borrows its own connection, sets the restart offset to the first byte of its range, and reads exactly as many bytes as the range holds:

Kotlin
client.restartOffset = range.first
val stream = client.retrieveFileStream(remotePath)
    ?: throw FtpClientException(
        "Server refused to send $remotePath: ${client.replyString?.trim().orEmpty()}"
    )
stream.use { input ->
    RandomAccessFile(localFile, "rw").use { raf ->
        val channel: FileChannel = raf.channel
        channel.position(range.first)
        val buf = ByteArray(bufferEngine.bufferSize())
        var remaining = length
        while (remaining > 0L) {
            val toRead = if (remaining < buf.size.toLong()) remaining.toInt() else buf.size
            val read = input.read(buf, 0, toRead)
            if (read <= 0) break
            // ... update the MD5 digest, write to the channel, report progress
            remaining -= read
        }
    }
}

Setting restartOffset sends nothing by itself. Commons Net issues the REST just before the RETR. A null stream means the server refused one of the two, and the engine throws instead of carrying on.

Hanging up on purpose

Once a chunk has its bytes, it closes the stream while the server is still sending. To the server that is an aborted transfer, and it usually replies 426. The engine expects this:

Kotlin
// A chunk that stops before the end of the file closes the data connection
// early, so the server answers 426 here; that's expected. Any other failure
// leaves the control connection in an unknown state, so drop it from the pool.
val finished = runCatching { client.completePendingCommand() }.getOrDefault(false)
if (!finished) runCatching { client.disconnect() }

if (transferred < length) {
    throw FtpClientException(
        "Download of $remotePath stopped after $transferred of $length bytes" +
            (client.replyString?.trim()?.takeIf { it.isNotEmpty() }?.let { ": $it" } ?: ".")
    )
}

I didn't try to guess the state of the control connection after an abort: if the transfer didn't end cleanly, the client is disconnected. The connection pool handles the rest: release drops any client that is no longer connected, and borrow sends a NOOP to an idle client before handing it out.

The byte check below it matters just as much. Once a 426 is a normal outcome, the reply code can't tell you whether a chunk succeeded. The byte count can. If a chunk received fewer bytes than its range holds, the whole download fails. The unit tests run the real engine against an embedded Apache FtpServer and cover this: a 5,000,003-byte file in 8 chunks compared byte for byte, a file shorter than its listed size, and a file that doesn't exist.

Splitting the file and writing in place

The ranges come from one small function:

Kotlin
private fun computeRanges(totalBytes: Long, chunkCount: Int, startOffsets: List<Long>?): List<LongRange> {
    if (chunkCount <= 1 || totalBytes <= ONE_MB) {
        val start = startOffsets?.firstOrNull() ?: 0L
        return listOf(start until totalBytes)
    }
    val n = chunkCount.coerceAtLeast(1)
    val size = totalBytes / n
    val ranges = ArrayList<LongRange>(n)
    var pos = 0L
    for (i in 0 until n) {
        val start = startOffsets?.getOrNull(i) ?: pos
        val end = if (i == n - 1) totalBytes else (pos + size)
        ranges += start until end
        pos += size
    }
    return ranges
}

Files of 1 MB or less get a single range. Larger files are divided evenly and the last range takes the remainder, which is why that test uses an odd size. startOffsets is the resume hook, covered below.

Before any chunk starts, the engine creates the local file and extends it to full size with RandomAccessFile.setLength. Each chunk then opens the file itself and positions its FileChannel at range.first. Chunks never touch each other's bytes, so there are no part files and no merge step. The chunks run as async blocks on Dispatchers.IO.limitedParallelism(32), and the engine waits on awaitAll().

If the directory listing reported a size of 0, the engine doesn't trust it. It asks the server with SIZE, falls back to MLST, and fails if neither gives an answer.

Resuming from Room

Each transfer is a row in a transfer_jobs table, with its chunks in transfer_chunks. A chunk row stores startOffset, endOffset, transferredBytes, state and an md5. The transfer runs in a WorkManager worker, and the first thing it does is decide whether it is starting or continuing:

Kotlin
val existingChunks = transferRepository.listChunks(jobId)
val chunks = if (existingChunks.isEmpty()) {
    transferRepository.saveChunks(buildChunks(jobId, job.totalBytes, job.chunkCount))
    transferRepository.listChunks(jobId).sortedBy { it.index }
} else existingChunks.sortedBy { it.index }
val chunkOffsets = chunks.map { it.startOffset + it.transferredBytes }

Those offsets go straight into computeRanges as startOffsets. A finished chunk gets an empty range and is marked done at once. A chunk that stopped halfway restarts at the byte where it stopped, through the same REST and RETR path as a fresh one. The file is opened in "rw" mode, which doesn't truncate, so the bytes already on disk stay where they are. The Retry button on the Transfers screen re-enqueues the same job, and the worker picks up from the stored rows.

Progress reaches the database two ways: per-chunk progress is written to the chunk rows as it changes, and a loop writes the job's running total every 2 seconds.

Where this approach stops

It only helps downloads. Uploads go through the same engine but one range at a time: STOR for the first range, APPE for the rest. A comment in the code gives the reason, that REST with STOR doesn't support concurrent writes to one remote file.

It also depends on the server honouring REST before RETR. If it refuses, the engine fails the job loudly instead of falling back to a single stream. Loud is easier to debug, but a fallback would be friendlier.

A few things I would change. Each job builds its own connection pool and warms it to the profile's chunk count, so even a file under 1 MB opens several logins before it uses one. After a resume, the progress written back counts from the resume point rather than from the chunk's start, so a second interruption re-fetches bytes the file already has. Positional writes keep the result correct, but storing absolute positions would avoid the waste. And each chunk's MD5 is computed while it streams and saved to its row, but nothing compares it with anything, so for now it is a record rather than a check.

The core idea carries over to any FTP library that lets you set a restart offset and read the data stream yourself: start with REST, count the bytes, hang up, and judge the result by what landed on disk.

Found this useful? Share it with your team.

Keep reading

More from Mobile and beyond