Skip to content
Merged
75 changes: 71 additions & 4 deletions controller/app/src/main/java/org/iiab/controller/Aria2Manager.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,46 @@
import org.iiab.controller.download.domain.MetalinkSplit;
import org.iiab.controller.download.domain.MetalinkFile;
import org.iiab.controller.download.domain.DownloadVerifier;
import org.iiab.controller.download.domain.ByteToken;
import org.iiab.controller.download.domain.DownloadEta;
import org.iiab.controller.download.domain.Aria2ProgressLine;

public class Aria2Manager {

private static final String TAG = "IIAB-Aria2-Native";
private Process aria2Process;
private boolean isCancelled = false;
/**
* ADFA-4895: volatile for the same reason as the flag below, and it is the more important of
* the two. It is assigned on the download thread and read by {@code stopDownload()} on the
* caller's, so a stale null there means the process is never destroyed and the user's cancel
* does nothing at all.
*/
private volatile Process aria2Process;
/**
* ADFA-4895: volatile. It is written by {@code stopDownload()} on the caller's thread and read
* by the download thread's loop and its catch block, so without this a stop could go unseen and
* a user cancellation would be reported as a fatal error.
*/
private volatile boolean isCancelled = false;

public interface DownloadListener {
void onProgress(int percentage, String speed, String eta);

/**
* ADFA-4895: the same tick, with the figures as numbers instead of display text.
*
* <p>Added rather than replacing the three-argument form so the two content call sites are
* untouched: they keep overriding that one and inherit this default, which forwards. Only a
* caller that needs to *decide* on the transfer — rather than draw it — overrides this.
*
* @param bytesPerSecond current rate, or {@link ByteToken#UNKNOWN}
* @param etaSeconds our own estimate, or {@link DownloadEta#UNKNOWN}. Not aria2's:
* see ADR-4893 for why a figure we cannot explain is a bad one to
* act on.
*/
default void onProgress(int percentage, String speed, String eta,
long bytesPerSecond, long etaSeconds) {
onProgress(percentage, speed, eta);
}
void onComplete(String downloadPath);
void onError(String error);
/** ADFA-4676: post-download integrity gate failed (size/SHA-256 mismatch). */
Expand Down Expand Up @@ -179,6 +210,20 @@ public void startDownload(Context context, String url, DownloadListener listener
command.add("--summary-interval=1");
command.add("--download-result=hide");

// ADFA-4895: aria2 already knows how to survive a bad link; we were not asking it
// to. These are set explicitly rather than inherited, so the behaviour is pinned by
// this file and does not change under us when the bundled aria2 is rebuilt.
//
// No --lowest-speed-limit here on purpose. It makes aria2 abort a transfer that
// drops below a floor, which is only safe once a caller retries and resumes: on the
// links this product targets, a slow download is the normal case, and aborting one
// with nothing to catch it would be worse than the stall we are trying to detect.
// It lands with the retry loop, not before it.
command.add("--max-tries=5");
command.add("--retry-wait=5"); // default is 0 — retries hammer a struggling server
command.add("--timeout=60"); // per-connection read timeout
command.add("--connect-timeout=30");

// Apply network decision
if (forceIpv4) {
Log.w(TAG, "Network profiler decided to FORCE IPv4.");
Expand All @@ -201,6 +246,7 @@ public void startDownload(Context context, String url, DownloadListener listener
// Example: [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]
Pattern pattern = Pattern.compile("\\((\\d+)%\\).*?DL:([^\\s]+).*?ETA:([^\\s\\]]+)");


while ((line = reader.readLine()) != null) {
if (isCancelled) {
aria2Process.destroy();
Expand All @@ -219,7 +265,21 @@ public void startDownload(Context context, String url, DownloadListener listener
String speed = matcher.group(2) + context.getString(R.string.k2go_rate_per_second);
String eta = matcher.group(3);

mainHandler.post(() -> listener.onProgress(percent, speed, eta));
// ADFA-4895: keep the figures as numbers alongside the display text. The
// rate was being destroyed one line above — concatenated into a localized
// string — so nothing downstream could compare it to anything or divide a
// remaining size by it.
long bytesPerSecond = ByteToken.parse(matcher.group(2));
// The Metalink's size is the authority when we have it: it is what the
// integrity gate will check against, so the estimate and the verdict are
// measured against the same number.
long done = Aria2ProgressLine.completedBytes(line);
long total = (mf != null && mf.sizeBytes() > 0)
? mf.sizeBytes() : Aria2ProgressLine.declaredTotalBytes(line);
long etaSeconds = DownloadEta.secondsRemaining(done, total, bytesPerSecond);
final long rate = bytesPerSecond;
final long secs = etaSeconds;
mainHandler.post(() -> listener.onProgress(percent, speed, eta, rate, secs));
}
}

Expand All @@ -233,7 +293,14 @@ public void startDownload(Context context, String url, DownloadListener listener
}

if (exitCode != 0) {
mainHandler.post(() -> listener.onError("Aria2c native process failed with code " + exitCode));
// ADFA-4895: say what aria2 said. Every non-zero exit used to produce the same
// sentence, so a full disk, a missing mirror and a dropped Wi-Fi were one
// event, and nothing downstream could tell which of them was worth retrying.
org.iiab.controller.download.domain.Aria2Exit.Kind kind =
org.iiab.controller.download.domain.Aria2Exit.kindOf(exitCode);
String reason = org.iiab.controller.download.domain.Aria2Exit.label(exitCode);
Log.e(TAG, "aria2 exit " + exitCode + " (" + kind + "): " + reason);
mainHandler.post(() -> listener.onError(reason));
return;
}
// ADFA-4676: never trust the exit code alone. For a Metalink download,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* ============================================================================
* Name : Aria2Exit.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : ADFA-4895. Pure rule: what an aria2 exit code means.
* No Android, no I/O.
* ============================================================================
*/
package org.iiab.controller.download.domain;

/**
* What aria2 was telling us when it stopped.
*
* <p>Until now every non-zero exit produced the same message — "Aria2c native process failed with
* code N" — and the caller failed the whole install on all of them. That throws away the one thing
* aria2 is careful about: it distinguishes a network hiccup from a missing file from a full disk,
* and only one of those is worth trying again. Retry, resume and any honest report to the user all
* need this distinction first, which is why it lands before them.
*
* <p><b>Describes, does not decide.</b> This class says what happened; it does not say how many
* times to retry or how long to wait. That policy belongs with the caller that owns the download,
* and keeping it out of here is what lets the rootfs path and the content paths make different
* choices from the same reading.
*
* <p><b>Unknown is its own answer</b>, not a synonym for fatal. aria2's own code 1 is literally
* "unknown error" and in practice it covers transient conditions as well as real ones; folding it
* into either bucket would be inventing information we do not have. The caller decides what
* caution means for it.
*/
public final class Aria2Exit {

/** What kind of stop this was. */
public enum Kind {
/** Everything downloaded. */
SUCCESS,
/** A condition that commonly clears by itself: timeouts, resolution, network drops. */
TRANSIENT,
/** aria2 gave up because the transfer was too slow ({@code --lowest-speed-limit}). */
STALLED,
/** Trying again with the same inputs cannot help: not found, no disk space, bad auth. */
PERMANENT,
/** aria2 did not say, or said something this table does not cover. */
UNKNOWN
}

private Aria2Exit() {
}

/**
* Classify an aria2 process exit code.
*
* <p>The table below is aria2's documented set. Codes outside it are {@link Kind#UNKNOWN}
* rather than assumed, so a future aria2 that adds one does not get silently mislabelled.
*/
public static Kind kindOf(int exitCode) {
switch (exitCode) {
case 0: return Kind.SUCCESS;

// Worth another attempt: the far side or the link misbehaved.
case 2: // timeout
case 6: // network problem
case 7: // unfinished downloads remained
case 19: // name resolution failed
case 22: // bad HTTP response header
case 29: // server temporarily unavailable
return Kind.TRANSIENT;

// aria2 aborted the transfer itself for being below the floor we set.
case 5:
return Kind.STALLED;

// Same inputs, same outcome. Retrying only wastes the user's data.
case 3: // resource not found
case 4: // resource not found too many times
case 8: // remote server does not support resume
case 9: // not enough disk space
case 16: // could not open or create the file
case 24: // HTTP authorization failed
return Kind.PERMANENT;

case 1: // aria2's own "unknown error"
default:
return Kind.UNKNOWN;
}
}

/**
* A short, stable English phrase for logs and for the failure text we keep in the install
* state. Not a user-facing string: those are localized resources chosen by the presentation
* layer, which can map {@link Kind} however it needs to.
*/
public static String label(int exitCode) {
switch (exitCode) {
case 0: return "ok";
case 1: return "unspecified aria2 error";
case 2: return "connection timed out";
case 3: return "file not found on the server";
case 4: return "file not found on any mirror";
case 5: return "transfer too slow, aborted";
case 6: return "network problem";
case 7: return "download left unfinished";
case 8: return "server does not support resuming";
case 9: return "not enough disk space";
case 16: return "could not write the file";
case 19: return "could not resolve the host";
case 22: return "bad response from the server";
case 24: return "server rejected the request";
case 29: return "server temporarily unavailable";
default: return "aria2 exit code " + exitCode;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* ============================================================================
* Name : Aria2ProgressLine.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : ADFA-4895. Pure rule: pull the figures out of one line of
* aria2 console output. No Android, no I/O.
* ============================================================================
*/
package org.iiab.controller.download.domain;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Reads one line of aria2's summary output.
*
* <p>A real line looks like this:
*
* <pre>[#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]</pre>
*
* <p><b>Why this is its own class.</b> It began as a second {@link Pattern} inside
* {@code Aria2Manager}, which is an Android class holding a live process and a Handler — so the
* most breakable part of the change, a regex against a third party's output format, was the one
* part no test could reach. Here it is reachable, and a change to aria2's formatting fails a test
* instead of quietly producing a wrong estimate on a device.
*
* <p><b>Deliberately separate from the progress pattern that already worked.</b> The percentage
* and rate the screen has always shown come from a different expression in {@code Aria2Manager}.
* If this one stops matching, the estimate goes unknown and the line the user reads is untouched.
*/
public final class Aria2ProgressLine {

/**
* The completed/total pair that precedes the percentage.
*
* <p>Both halves are a number with an optional unit, so {@code 400MiB/1.0GiB(39%)} yields
* {@code 400MiB} and {@code 1.0GiB}. Anchored on the {@code (NN%)} that follows, which is what
* keeps it from matching the {@code CN:4} or a path with a slash in it.
*/
private static final Pattern SIZES =
Pattern.compile("([\\d.]+[A-Za-z]*)/([\\d.]+[A-Za-z]*)\\(\\d+%\\)");

private Aria2ProgressLine() {
}

/** Bytes transferred so far, or {@link ByteToken#UNKNOWN} if the line does not carry them. */
public static long completedBytes(String line) {
Matcher m = matcher(line);
return m == null ? ByteToken.UNKNOWN : ByteToken.parse(m.group(1));
}

/**
* The size aria2 believes it is fetching, or {@link ByteToken#UNKNOWN}.
*
* <p>Prefer the Metalink's figure over this one where both exist: the Metalink is what the
* integrity gate checks against, so using it keeps the estimate and the verdict measured
* against the same number.
*/
public static long declaredTotalBytes(String line) {
Matcher m = matcher(line);
return m == null ? ByteToken.UNKNOWN : ByteToken.parse(m.group(2));
}

private static Matcher matcher(String line) {
if (line == null || line.isEmpty()) return null;
Matcher m = SIZES.matcher(line);
return m.find() ? m : null;
}
}
Loading
Loading