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
9 changes: 9 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ jobs:
env:
ARIA2_E2E_BIN: ${{ github.workspace }}/src/aria2c
run: node --test test/e2e/select-dns.e2e.test.mjs
- name: Verify nested cloud-drive output paths
if: matrix.bittorrent == 'with-bt'
env:
ARIA2_E2E_BIN: ${{ github.workspace }}/src/aria2c
run: node --test test/e2e/nested-output.e2e.test.mjs
- name: Verify legacy recovery and schema upgrade snapshots
if: matrix.bittorrent == 'with-bt'
env:
Expand Down Expand Up @@ -228,6 +233,10 @@ jobs:
env:
ARIA2_E2E_BIN: ${{ github.workspace }}\bin\aria2c.exe
run: node --test test/e2e/select-dns.e2e.test.mjs
- name: Verify nested cloud-drive output paths
env:
ARIA2_E2E_BIN: ${{ github.workspace }}\bin\aria2c.exe
run: node --test test/e2e/nested-output.e2e.test.mjs
- name: Verify native HTTP redirect policy
env:
ARIA2_E2E_BIN: ${{ github.workspace }}\bin\aria2c.exe
Expand Down
7 changes: 6 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
inputs:
version:
description: 'Version for a dry run (no leading v)'
default: '1.37.0-motrix.22-dev'
default: '1.37.0-motrix.23-dev'

permissions:
contents: write
Expand Down Expand Up @@ -412,6 +412,8 @@ jobs:
fi
- name: Verify task cookies and credential redirects
run: node --test --test-concurrency=1 test/e2e/task-cookies.e2e.test.mjs test/e2e/http-retry.e2e.test.mjs
- name: Verify nested cloud-drive output paths
run: node --test test/e2e/nested-output.e2e.test.mjs

legacy-checkpoint-contract:
needs: [macos, windows, linux]
Expand Down Expand Up @@ -578,6 +580,8 @@ jobs:
'aria2 fork build for Motrix. Base: upstream 1.37.0.' \
'' \
'Highlights:' \
'- Restore HTTP/FTP output paths relative to the download directory, including leading-slash paths sent by cloud-drive RPC clients (agalwood/Motrix#2502).' \
'- Verify nested Unicode directories, changed output options and SQLite restart recovery while preserving absolute BitTorrent file mappings.' \
'- Retain failed unfinished HTTP task cookies, including explicitly empty cookie contexts, across engine restarts.' \
'- Resume an opted-in HTTP task with its original GID, checkpoint, request options and task-scoped cookies through versioned RPCs.' \
'- Verify the original source, output path and persisted resource validators before reusing partial data; refuse unverifiable or changed resources.' \
Expand All @@ -594,6 +598,7 @@ jobs:
'- Retain task-scoped cookies, cross-origin credential isolation and long-path support.' \
'' \
'Compatibility:' \
'- HTTP/FTP --out is relative to --dir, matching upstream aria2. Use --dir to select an absolute destination; absolute BitTorrent --index-out mappings remain supported.' \
'- Schema 6 cannot be opened by older engines. Downgrades require the pre-upgrade backup; do not delete or reset the upgraded database.' \
'- Native HTTP retry requires enabled SQLite persistence, a supporting client, and historical context captured for an opted-in task. Previously deleted cookies or missing historical validators cannot be reconstructed.' \
'- BT activation verifies pieces and may write shared-piece bytes in an unselected adjacent file; zero upload is not guaranteed.' \
Expand Down
3 changes: 2 additions & 1 deletion src/RpcMethodImpl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2383,7 +2383,8 @@ void changeOption(const std::shared_ptr<RequestGroup>& group,

if (!grOption->blank(PREF_OUT)) {
fileEntry->setPath(
util::applyDir(grOption->get(PREF_DIR), grOption->get(PREF_OUT)));
util::applyDir(grOption->get(PREF_DIR), grOption->get(PREF_OUT),
false));
fileEntry->setSuffixPath(A2STR::NIL);
}
else if (fileEntry->getSuffixPath().empty()) {
Expand Down
2 changes: 1 addition & 1 deletion src/download_helper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ createRequestGroup(const std::shared_ptr<Option>& optionTemplate,
auto dctx = std::make_shared<DownloadContext>(
option->getAsInt(PREF_PIECE_LENGTH), 0,
useOutOption && !option->blank(PREF_OUT)
? util::applyDir(option->get(PREF_DIR), option->get(PREF_OUT))
? util::applyDir(option->get(PREF_DIR), option->get(PREF_OUT), false)
: A2STR::NIL);
dctx->getFirstFileEntry()->setUris(uris);
dctx->getFirstFileEntry()->setMaxConnectionPerServer(
Expand Down
10 changes: 6 additions & 4 deletions src/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2162,18 +2162,20 @@ bool saveAs(const std::string& filename, const std::string& data,
return File(tempFilename).renameTo(filename);
}

std::string applyDir(const std::string& dir, const std::string& relPath)
std::string applyDir(const std::string& dir, const std::string& relPath,
bool allowAbsolutePath)
{
std::string s;
if (!relPath.empty() && relPath[0] == '/') {
if (allowAbsolutePath && !relPath.empty() && relPath[0] == '/') {
s = relPath;
}
#ifdef __MINGW32__
else if (relPath.size() >= 3 && util::isAlpha(relPath[0]) &&
else if (allowAbsolutePath && relPath.size() >= 3 &&
util::isAlpha(relPath[0]) &&
relPath[1] == ':' && (relPath[2] == '/' || relPath[2] == '\\')) {
s = relPath;
}
else if (relPath.size() >= 2 &&
else if (allowAbsolutePath && relPath.size() >= 2 &&
((relPath[0] == '/' && relPath[1] == '/') ||
(relPath[0] == '\\' && relPath[1] == '\\'))) {
s = relPath;
Expand Down
5 changes: 4 additions & 1 deletion src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -732,11 +732,14 @@ bool saveAs(const std::string& filename, const std::string& data,
bool overwrite = false);

// Prepend dir to relPath. If dir is empty, it prepends "." to relPath.
// Absolute paths bypass dir unless allowAbsolutePath is false. HTTP/FTP
// --out uses false to retain upstream aria2's directory-relative semantics.
//
// dir = "/dir", relPath = "foo" => "/dir/foo"
// dir = "", relPath = "foo" => "./foo"
// dir = "/", relPath = "foo" => "/foo"
std::string applyDir(const std::string& dir, const std::string& relPath);
std::string applyDir(const std::string& dir, const std::string& relPath,
bool allowAbsolutePath = true);

// In HTTP/FTP, file name is file component in URI. In HTTP, filename
// may be a value of Content-Disposition header. They are likely
Expand Down
18 changes: 18 additions & 0 deletions test/DownloadHelperTest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class DownloadHelperTest : public CppUnit::TestFixture {

CPPUNIT_TEST_SUITE(DownloadHelperTest);
CPPUNIT_TEST(testCreateRequestGroupForUri);
CPPUNIT_TEST(testCreateRequestGroupForUri_nestedOutput);
CPPUNIT_TEST(testCreateRequestGroupForUri_parameterized);
CPPUNIT_TEST(testCreateRequestGroupForUriList);

Expand All @@ -48,6 +49,7 @@ class DownloadHelperTest : public CppUnit::TestFixture {
void tearDown() {}

void testCreateRequestGroupForUri();
void testCreateRequestGroupForUri_nestedOutput();
void testCreateRequestGroupForUri_parameterized();
void testCreateRequestGroupForUriList();

Expand Down Expand Up @@ -131,6 +133,22 @@ void DownloadHelperTest::testCreateRequestGroupForUri()
}
}

void DownloadHelperTest::testCreateRequestGroupForUri_nestedOutput()
{
option_->put(PREF_SPLIT, "1");
option_->put(PREF_MAX_CONNECTION_PER_SERVER, "1");
option_->put(PREF_DIR, "/downloads");
option_->put(PREF_OUT, "/cloud/album/file.out");
for (const auto& uri : {"http://alpha/file", "ftp://alpha/file"}) {
std::vector<std::shared_ptr<RequestGroup>> result;
createRequestGroupForUri(result, option_, {uri});
CPPUNIT_ASSERT_EQUAL((size_t)1, result.size());
CPPUNIT_ASSERT_EQUAL(
std::string("/downloads//cloud/album/file.out"),
result[0]->getDownloadContext()->getFirstFileEntry()->getPath());
}
}

void DownloadHelperTest::testCreateRequestGroupForUri_parameterized()
{
std::vector<std::string> uris{"http://{alpha, bravo}/file",
Expand Down
10 changes: 10 additions & 0 deletions test/UtilTest2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,16 @@ void UtilTest2::testApplyDir()
CPPUNIT_ASSERT_EQUAL(std::string("/pred"), util::applyDir("/", "pred"));
CPPUNIT_ASSERT_EQUAL(std::string("./pred"), util::applyDir(".", "pred"));
CPPUNIT_ASSERT_EQUAL(std::string("/dl/pred"), util::applyDir("/dl", "pred"));
CPPUNIT_ASSERT_EQUAL(std::string("/dl/album/file"),
util::applyDir("/dl", "album/file", false));
CPPUNIT_ASSERT_EQUAL(std::string("/dl//album/file"),
util::applyDir("/dl", "/album/file", false));
CPPUNIT_ASSERT_EQUAL(std::string("/dl///album/file"),
util::applyDir("/dl", "//album/file", false));
CPPUNIT_ASSERT_EQUAL(std::string(".//album/file"),
util::applyDir("", "/album/file", false));
CPPUNIT_ASSERT_EQUAL(std::string("//album/file"),
util::applyDir("/", "/album/file", false));
#ifndef __MINGW32__
CPPUNIT_ASSERT_EQUAL(std::string("/dev/null"),
util::applyDir(".", "/dev/null"));
Expand Down
127 changes: 127 additions & 0 deletions test/e2e/nested-output.e2e.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Cloud-drive RPC clients send paths such as /album/file in `out`.
// Like upstream aria2, HTTP/FTP output paths are relative to `dir`, even
// with a leading slash (agalwood/Motrix#2502).
import { after, before, describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import http from 'node:http'
import os from 'node:os'
import path from 'node:path'

import { allocPorts, startInstance } from './helpers/aria2-process.mjs'
import { encode } from './helpers/bencode.mjs'
import { Aria2Rpc } from './helpers/rpc-client.mjs'
import { waitFor } from './helpers/wait.mjs'

describe('nested HTTP output paths', { timeout: 30_000 }, () => {
const payload = Buffer.from('cloud-drive nested output\n')
let workDir, server, handle, rpc, url, options

before(async () => {
workDir = await mkdtemp(path.join(os.tmpdir(), 'a2-nested-output-'))
server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Length': payload.length })
res.end(req.method === 'HEAD' ? undefined : payload)
})
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
url = `http://127.0.0.1:${server.address().port}/file.bin`
options = {
...allocPorts(),
rpcSecret: 'nested-output',
dir: path.join(workDir, 'downloads'),
sessionPath: path.join(workDir, 'state', 'aria2.session'),
sqliteDbPath: path.join(workDir, 'state', 'aria2.db'),
logPath: path.join(workDir, 'state', 'aria2.log'),
extra: [
'--no-conf=true', '--no-netrc=true',
'--enable-dht=false', '--enable-dht6=false',
'--all-proxy=', '--http-proxy=', '--https-proxy=', '--ftp-proxy=',
],
}
handle = await startInstance(options)
rpc = new Aria2Rpc({ port: options.rpcPort, secret: options.rpcSecret })
})

after(async () => {
await handle?.stop()
if (server) await new Promise((resolve) => server.close(resolve))
if (workDir && !process.env.ARIA2_E2E_KEEP_TMP) {
await rm(workDir, { recursive: true, force: true })
}
})

async function expectDestination(gid, target) {
const files = await rpc.call('aria2.getFiles', [gid])
assert.equal(path.resolve(files[0].path), path.resolve(target))
}

async function complete(gid, target) {
// Check before unpausing: a broken engine must never write outside the
// test's chosen directory while reproducing this regression.
await expectDestination(gid, target)
await rpc.call('aria2.unpause', [gid])
await waitFor(async () => {
const status = await rpc.call('aria2.tellStatus', [gid, ['status', 'errorCode', 'errorMessage']])
assert.notEqual(status.status, 'error', JSON.stringify(status))
return status.status === 'complete'
}, 10_000, 50, 'nested download to complete')
assert.deepEqual(await readFile(target), payload)
}

for (const out of ['relative/album/file.bin', '/网盘/多层目录/file.bin', '//cloud/album/file.bin']) {
it(`creates directories under the default dir for out=${out}`, async () => {
const gid = await rpc.call('aria2.addUri', [[url], { out, pause: 'true' }])
await complete(gid, path.join(options.dir, out))
})
}

it('uses an explicit dir that does not exist yet', async () => {
const dir = path.join(workDir, 'custom', 'nested')
const out = '/cloud/file.bin'
const gid = await rpc.call('aria2.addUri', [[url], { dir, out, pause: 'true' }])
await complete(gid, path.join(dir, out))
})

it('keeps changed out and dir options relative before starting', async () => {
const gid = await rpc.call('aria2.addUri', [[url], { out: 'initial.bin', pause: 'true' }])
const out = '/changed/album/file.bin'
await rpc.call('aria2.changeOption', [gid, { out }])
await expectDestination(gid, path.join(options.dir, out))
const dir = path.join(workDir, 'changed-directory')
await rpc.call('aria2.changeOption', [gid, { dir }])
await complete(gid, path.join(dir, out))
})

it('restores the relative output after a SQLite session restart', async () => {
const out = '/restored/album/file.bin'
const gid = await rpc.call('aria2.addUri', [[url], { out, pause: 'true' }])
const target = path.join(options.dir, out)
await expectDestination(gid, target)
await handle.stop()
handle = await startInstance(options)
await complete(gid, target)
})

it('preserves absolute BitTorrent index-out mappings', async (t) => {
const version = await rpc.call('aria2.getVersion')
if (!version.enabledFeatures.includes('BitTorrent')) {
t.skip('engine built without BitTorrent')
return
}
const metadata = encode({ info: {
name: 'original.bin',
length: 1,
'piece length': 16384,
pieces: Buffer.alloc(20, 1),
} })
const target = path.join(workDir, 'mapped', 'file.bin')
const gid = await rpc.call('aria2.addTorrent', [metadata.toString('base64'), [], {
'index-out': `1=${target}`,
pause: 'true',
}])
await expectDestination(gid, target)
const changed = path.join(workDir, 'remapped', 'file.bin')
await rpc.call('aria2.changeOption', [gid, { 'index-out': `1=${changed}` }])
await expectDestination(gid, changed)
})
})
Loading