Contact one STUN server and one tracker at a time
Both sides used to contact every STUN server and tracker at once, so each of them learned the IP address and each tracker that A sent to B. Connections now use one STUN server: the first in the list that reports a public address to a throwaway probe connection within 2 s. It stays for the page's lifetime. If a connection gets no address from it, the next connection probes on from the server after it. A probe runs only while a session waits for it and stops once none does, STUN is turned off or the list changes. The sender joins the first tracker that accepts it and moves to the next only once that one rejects it, can't be reached within 10 s or is lost. The receiver walks the list with one offer each and stays where a tracker reports a seeder (complete), which is the sender: it always announces before anyone has the code. Trackers it passed keep its offer. backend/tracker.mjs now sends complete. wss://tracker.pagequit.net comes first in the default trackers, the public ones are fallbacks. TODO.md drops the server tasks, they aren't work on this codebase. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5729ed62f7
commit
840bc3572b
6 files changed
+361
-85
No files matched your search
+144
-21
@@ -22,7 +22,8 @@ import { build, createServer, preview, type ViteDevServer } from 'vite';
|
||||
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
|
||||
// Chromium needs a permission for the copy buttons, Firefox lets the click do it and rejects the name.
|
||||
const PERMISSIONS: Record<string, string[]> = { chromium: ['clipboard-write'], firefox: [] };
|
||||
// The live tests use the public trackers and STUN servers, the defaults in src/core.ts.
|
||||
// The live tests use the default trackers and STUN servers in src/core.ts. The first tracker,
|
||||
// HellCon's own, refuses the dev server's origin, so both sides go on to this one.
|
||||
const TRACKER = 'wss://tracker.webtorrent.dev';
|
||||
const SIZE = 5_000_000;
|
||||
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
|
||||
@@ -30,9 +31,9 @@ const SIZE = 5_000_000;
|
||||
const LARGE_SIZE = 2.5 * 2 ** 30;
|
||||
// Big enough that the transfer still runs while a test cancels or disconnects.
|
||||
const RUNNING_SIZE = 100_000_000;
|
||||
// WINDOW, CHUNK_SIZE, ICE_TIMEOUT and PROOF_TIMEOUT in src/core.ts.
|
||||
// WINDOW, PROBE_TIMEOUT and PROOF_TIMEOUT in src/core.ts.
|
||||
const WINDOW = 8 * 2 ** 20;
|
||||
const ICE_TIMEOUT = 5000;
|
||||
const PROBE_TIMEOUT = 2000;
|
||||
const PROOF_TIMEOUT = 10_000;
|
||||
// Enough for a transfer whose receiver holds back its reads to pause at the window.
|
||||
const HELD_SIZE = 3 * WINDOW;
|
||||
@@ -493,19 +494,83 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
expect((await core())[1]).toContain('wss://tracker.webtorrent.dev');
|
||||
});
|
||||
|
||||
// 192.0.2.1 is reserved for documentation and never answers. Without the early stop in gatherIce
|
||||
// Chromium would wait 40 s for it, with only the hard timeout still ICE_TIMEOUT.
|
||||
test(`gather: ${name} stops at the first STUN answer`, async () => {
|
||||
// Only the STUN server in use learns the address. 192.0.2.1 is reserved for documentation and never
|
||||
// answers, a connection with it would wait ICE_TIMEOUT in src/core.ts. The probe passes it over
|
||||
// once, later connections go straight to the one that answered, until it stops.
|
||||
test(`stun: ${name} uses the first STUN server that answers, the next once it stops`, async () => {
|
||||
const page = await open(name);
|
||||
const first = await fakeStun();
|
||||
const servers = [
|
||||
'stun:192.0.2.1:3478',
|
||||
...[first, stun].map((socket) => `stun:${LOCAL_ADDRESS}:${socket.address().port}`),
|
||||
];
|
||||
await page.click('#servers summary');
|
||||
await page.fill('#stun-servers', `stun:${LOCAL_ADDRESS}:${stun.address().port}\nstun:192.0.2.1:3478`);
|
||||
await page.fill('#stun-servers', servers.join('\n'));
|
||||
await page.setInputFiles('input[type=file]', await payload(Buffer.alloc(1)));
|
||||
await page.click('#send-manual summary');
|
||||
const start = Date.now();
|
||||
// The offer's SDP, how long it took and the STUN servers of the page's open connection.
|
||||
const offer = async () => {
|
||||
const start = Date.now();
|
||||
await page.click('#create-offer');
|
||||
await expect(page.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
|
||||
return {
|
||||
sdp: Buffer.from(await page.inputValue('#offer'), 'base64').toString(),
|
||||
ms: Date.now() - start,
|
||||
servers: await page.evaluate(() =>
|
||||
(window as unknown as { peers: RTCPeerConnection[] }).peers
|
||||
.filter((pc) => pc.signalingState !== 'closed')
|
||||
.flatMap((pc) => pc.getConfiguration().iceServers!.flatMap(({ urls }) => urls)),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const probed = await offer();
|
||||
expect(probed.ms).toBeGreaterThanOrEqual(PROBE_TIMEOUT);
|
||||
expect(probed.sdp).toContain(`${PUBLIC_ADDRESS} `);
|
||||
expect(probed.servers).toEqual([servers[1]]);
|
||||
const known = await offer();
|
||||
expect(known.ms).toBeLessThan(PROBE_TIMEOUT);
|
||||
expect(known.servers).toEqual([servers[1]]);
|
||||
|
||||
first.close();
|
||||
const stopped = await offer();
|
||||
expect(stopped.sdp).not.toContain(`${PUBLIC_ADDRESS} `);
|
||||
const next = await offer();
|
||||
expect(next.sdp).toContain(`${PUBLIC_ADDRESS} `);
|
||||
expect(next.servers).toEqual([servers[2]]);
|
||||
});
|
||||
|
||||
// A probe serves the sessions waiting for it. A new session takes it over, one without STUN stops
|
||||
// it: the server after the one it was at hears nothing. 192.0.2.x never answer.
|
||||
test(`stun: ${name} probing stops once no session waits for it`, async () => {
|
||||
const page = await open(name);
|
||||
const fakes = [await fakeStun(), await fakeStun()];
|
||||
const requests = [0, 0];
|
||||
for (const [i, socket] of fakes.entries()) socket.on('message', () => requests[i]!++);
|
||||
const fake = (i: number) => `stun:${LOCAL_ADDRESS}:${fakes[i]!.address().port}`;
|
||||
const offer = async () => {
|
||||
await expect(page.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
|
||||
return Buffer.from(await page.inputValue('#offer'), 'base64').toString();
|
||||
};
|
||||
await page.click('#servers summary');
|
||||
await page.setInputFiles('input[type=file]', await payload(Buffer.alloc(1)));
|
||||
await page.click('#send-manual summary');
|
||||
|
||||
await page.fill('#stun-servers', `stun:192.0.2.1:3478\n${fake(0)}`);
|
||||
await page.click('#create-offer');
|
||||
await expect(page.locator('#offer')).toHaveValue(/.+/);
|
||||
expect(Date.now() - start).toBeLessThan(ICE_TIMEOUT / 2);
|
||||
expect(Buffer.from(await page.inputValue('#offer'), 'base64').toString()).toContain(`${PUBLIC_ADDRESS} `);
|
||||
await page.waitForTimeout(PROBE_TIMEOUT / 4);
|
||||
await page.click('#create-offer');
|
||||
expect(await offer()).toContain(`${PUBLIC_ADDRESS} `);
|
||||
|
||||
await page.fill('#stun-servers', `stun:192.0.2.2:3478\n${fake(1)}`);
|
||||
await page.click('#create-offer');
|
||||
await page.waitForTimeout(PROBE_TIMEOUT / 4);
|
||||
await page.uncheck('#stun');
|
||||
await page.click('#create-offer');
|
||||
expect(await offer()).not.toContain(`${PUBLIC_ADDRESS} `);
|
||||
await page.waitForTimeout(PROBE_TIMEOUT * 1.5);
|
||||
expect(requests[1]).toBe(0);
|
||||
for (const socket of fakes) socket.close();
|
||||
});
|
||||
|
||||
test(`update: ${name} receives after sw.js changed`, async () => {
|
||||
@@ -875,7 +940,8 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
const trackers = await Promise.all(
|
||||
[sender, receiver].map((page) => mockTrackers(page, () => ({ 'failure reason': 'not here' }))),
|
||||
);
|
||||
const rejected = /^no tracker accepted it \(wss:\S+: not here; wss:\S+: not here\), check the list under Servers/;
|
||||
const rejected =
|
||||
/^no tracker accepted it \((wss:\S+: not here; ){2}wss:\S+: not here\), check the list under Servers/;
|
||||
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||
@@ -887,12 +953,68 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await expect
|
||||
.poll(() => trackers.map(({ sockets, open }) => [sockets.length, open]))
|
||||
.toEqual([
|
||||
[2, 0],
|
||||
[2, 0],
|
||||
[3, 0],
|
||||
[3, 0],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// Only the tracker in use learns about the share, the next one only once that one failed it.
|
||||
test(`tracker: ${name} sender stays on the first tracker that accepts it`, async () => {
|
||||
const sender = await open(name);
|
||||
const urls = ['wss://one.test', 'wss://two.test', 'wss://three.test'];
|
||||
const trackers: Awaited<ReturnType<typeof mockTrackers>> = await mockTrackers(sender, ({ info_hash }, ws) =>
|
||||
ws === trackers.sockets[0] ? { 'failure reason': 'not here' } : { action: 'announce', interval: 120, info_hash },
|
||||
);
|
||||
|
||||
await withLogs(sender, sender, async () => {
|
||||
await sender.click('#servers summary');
|
||||
await sender.fill('#trackers', urls.join('\n'));
|
||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||
await sender.click('#share');
|
||||
await expect(sender.locator('#log')).toContainText(`rejected by ${urls[0]}: not here`);
|
||||
await expect(sender.locator('#log')).toContainText(`waiting on ${urls[1]}`);
|
||||
// A third one would come within milliseconds.
|
||||
await sender.waitForTimeout(1000);
|
||||
expect(trackers.sockets.length).toBe(2);
|
||||
|
||||
trackers.sockets[1]!.close();
|
||||
await expect(sender.locator('#log')).toContainText(`waiting on ${urls[2]}`);
|
||||
await expect(sender.locator('#send-error')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
// The sender is on the first tracker that accepted it, the receiver goes on until it finds it there.
|
||||
// The trackers it passed keep its offer, in case the sender comes.
|
||||
test(`tracker: ${name} receiver walks the trackers until one has a seeder`, async () => {
|
||||
const receiver = await open(name);
|
||||
const urls = ['wss://one.test', 'wss://two.test', 'wss://three.test'];
|
||||
const trackers: Awaited<ReturnType<typeof mockTrackers>> = await mockTrackers(receiver, ({ info_hash }, ws) => ({
|
||||
action: 'announce',
|
||||
interval: 120,
|
||||
info_hash,
|
||||
complete: ws === trackers.sockets[1] ? 1 : 0,
|
||||
}));
|
||||
|
||||
await withLogs(receiver, receiver, async () => {
|
||||
await receiver.uncheck('#stun');
|
||||
await receiver.click('#servers summary');
|
||||
await receiver.fill('#trackers', urls.join('\n'));
|
||||
await receiver.fill('#receive-code', 'somecode');
|
||||
await receiver.click('#receive');
|
||||
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[1]}`);
|
||||
// A third one would come within milliseconds.
|
||||
await receiver.waitForTimeout(1000);
|
||||
expect([trackers.sockets.length, trackers.open]).toEqual([2, 2]);
|
||||
|
||||
// The sender lost the second one, its next reply has no seeder.
|
||||
trackers.sockets[1]!.send(JSON.stringify({ action: 'announce', interval: 120, complete: 0 }));
|
||||
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[2]}`);
|
||||
expect([trackers.sockets.length, trackers.open]).toEqual([3, 3]);
|
||||
await expect(receiver.locator('#receive-error')).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
// Anyone with the code can send offers no browser can parse, as many as they like. The share lets
|
||||
// go of each one's connection and keeps using the tracker. Without the code they get no connection.
|
||||
test(`tracker: ${name} sender keeps nothing of repeated unusable offers`, async () => {
|
||||
@@ -906,21 +1028,21 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||
await sender.click('#share');
|
||||
const code = (await sender.locator('#send-code').textContent())!;
|
||||
await expect.poll(() => trackers.sockets.length).toBe(2);
|
||||
await expect.poll(() => trackers.sockets.length).toBe(1);
|
||||
for (let offers = 1; offers <= 25; offers++) {
|
||||
trackers.sockets[0]!.send(garbageOffer(code));
|
||||
await expect.poll(unusable).toBe(offers);
|
||||
// Once it accepted the announcement, a failure only concerns that one message.
|
||||
if (offers === 1) trackers.sockets[0]!.send(JSON.stringify({ 'failure reason': 'slow down' }));
|
||||
}
|
||||
for (let offers = 0; offers < 5; offers++) trackers.sockets[1]!.send(garbageOffer());
|
||||
for (let offers = 0; offers < 5; offers++) trackers.sockets[0]!.send(garbageOffer());
|
||||
await expect.poll(async () => (await log(sender))!.match(/offer without the code/g)?.length ?? 0).toBe(5);
|
||||
expect(await unusable()).toBe(25);
|
||||
await expect(sender.locator('#log')).toContainText(': slow down');
|
||||
await expect(sender.locator('#log')).not.toContainText('rejected by');
|
||||
await expect(sender.locator('#send-error')).toHaveCount(0);
|
||||
// One per tracker socket and the expiry, none for the closed connections.
|
||||
expect(await listeners()).toBe(3);
|
||||
// The tracker socket's and the expiry's, none for the closed connections.
|
||||
expect(await listeners()).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -950,14 +1072,15 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await expect(sender.locator('label[for=send-code]')).toHaveText(/valid until \d/);
|
||||
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
|
||||
await receiver.click('#receive');
|
||||
await expect.poll(() => announced.map((msgs) => msgs.length)).toEqual([2, 2]);
|
||||
// The sender on the first tracker, the receiver on all of them: the mocks report no seeder.
|
||||
await expect.poll(() => announced.map((msgs) => msgs.length)).toEqual([1, 3]);
|
||||
// Until the replies with the interval reached the pages, and any early announce the test.
|
||||
await sender.waitForTimeout(500);
|
||||
await fastForward(25_000);
|
||||
await sender.waitForTimeout(500);
|
||||
expect(again().map((msgs) => msgs.length)).toEqual([0, 0]);
|
||||
await fastForward(5_000);
|
||||
await expect.poll(() => again().map((msgs) => msgs.length)).toEqual([2, 2]);
|
||||
await expect.poll(() => again().map((msgs) => msgs.length)).toEqual([1, 3]);
|
||||
// The receiver's offers again, a busy sender may have dropped them.
|
||||
const offers = announced[1]!.filter((msg) => msg.event === 'started').map((msg) => msg.offers[0].offer_id);
|
||||
expect(
|
||||
@@ -1031,7 +1154,7 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||
await sender.click('#share');
|
||||
const code = (await sender.locator('#send-code').textContent())!;
|
||||
await expect.poll(() => trackers.sockets.length).toBe(2);
|
||||
await expect.poll(() => trackers.sockets.length).toBe(1);
|
||||
trackers.sockets[0]!.send(garbageOffer(code));
|
||||
await expect.poll(decrypts).toEqual({ held: 1, done: 0 });
|
||||
await sender.clock.fastForward('06:00');
|
||||
|
||||
Reference in new issue
Block a user