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:
SchluffeandClaude Opus 5.5 committed 2026-10-25 18:51:42 +01:00
1 parent 5729ed62f7
commit 840bc3572b
6 files changed
+360 -84

No files matched your search

+8 -5
View File
@@ -69,9 +69,11 @@ networks, a direct connection may not be possible.
## Privacy
- The file only goes to the person you connected with.
- That person learns your IP address, as with any direct connection. The tracker and the STUN
servers see it too, from the request itself. Nobody without the code learns it through the
tracker.
- That person learns your IP address, as with any direct connection. One STUN server and one or a
few trackers see it too, from the request itself. HellCon tries the STUN servers in order and
sticks with the first that answers. The sender stays on the first tracker that accepts it. The
receiver goes down the list until it finds the sender, and the trackers it passes keep its
encrypted offer. Nobody without the code learns your address through a tracker.
- Settings (STUN on or off, your server lists) are kept in your browser only.
- Whoever hosts HellCon serves the code that runs in your browser. If you'd rather not trust that,
host your own (below).
@@ -80,8 +82,9 @@ networks, a direct connection may not be possible.
Under **Servers** you can change which STUN servers and trackers your browser uses, one address per
line. Any WebTorrent compatible tracker works, including one you run yourself. **Reset to defaults**
brings back the original lists. Both sides must use at least one tracker in common to find each
other.
brings back the original lists. The order matters: the sender stays on the first tracker that
works, the receiver tries them in order until it finds the sender. Both lists must contain that
tracker.
## Host your own
+1 -17
View File
@@ -1,21 +1,5 @@
# TODO
## Server at pagequit.net
`backend/` holds both servers, tested locally: a real transfer Chromium to Firefox through only them,
and the tracker's limits one by one. Left to do on the server:
- Replace the running coturn with `backend/compose.yaml`. coturn 4.18 has the admin CLI, DTLS, the
RFC 3489 MAPPED-ADDRESS and the software attribute off by default, the `--no-` options for them are
gone. Set `ORIGINS` in `backend/.env`, and `CADDY_NETWORK` if Caddy's network isn't `caddy`.
- Add `tracker.pagequit.net` to Caddy and DNS (A record, like `stun.pagequit.net`).
- Check that the logs hold no client addresses: transfer once, then
`docker compose logs | grep <your IP>` should stay empty.
- Then put `wss://tracker.pagequit.net` first in `DEFAULT_TRACKERS` and keep the public trackers as
fallbacks.
- coturn doesn't rate limit STUN requests. A response is about as big as the request, so it's a weak
amplifier. If it gets abused, an nftables `limit` on the UDP port would help.
## Ideas
- Resume interrupted transfers: the receiver already reports how much the download manager has
@@ -40,6 +24,6 @@ and the tracker's limits one by one. Left to do on the server:
happens again.
- `boundary: chromium sends an empty file` timed out in the first two full runs after `backend/`'s
tests were added (2026-10-25), with empty logs on both sides. It passed alone 8 times, and in 5
tests were added (2026-10-25), with empty logs on both sides. It passed alone 8 times, and in 7
full runs since, one of them with a cold Vite cache. The suite without the new tests passed 4
times. Not reproduced, cause unknown.
+3 -1
View File
@@ -126,8 +126,10 @@ function announce(peer, msg) {
}
}
// complete counts the seeders, HellCon's receiver moves on to its next tracker without one.
if (peer.ws.readyState === peer.ws.OPEN) {
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash });
const complete = [...swarm.values()].filter((other) => other.seeder).length;
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash, complete });
}
}
+17 -1
View File
@@ -107,16 +107,32 @@ test('refuses connections from other origins', async () => {
expect(await open({ origin: '' })).toBeUndefined();
});
test('acknowledges an announce with the interval only', async () => {
test('acknowledges an announce with the interval and the seeders only', async () => {
const client = await open();
const hash = id();
expect(await announce(client, { info_hash: hash, peer_id: id(), left: 0 })).toEqual({
action: 'announce',
interval: 60,
info_hash: hash,
complete: 1,
});
});
test('counts the seeders of the swarm in complete', async () => {
const hash = id();
const receiver = { ...(await open()), id: id() };
const seeders = async () => (await announce(receiver, { info_hash: hash, peer_id: receiver.id, left: 1 })).complete;
expect(await seeders()).toBe(0);
// Another swarm's sender doesn't count.
await announce(await open(), { info_hash: id(), peer_id: id(), left: 0 });
const sender = { ...(await open()), id: id() };
await announce(sender, { info_hash: hash, peer_id: sender.id, left: 0 });
expect(await seeders()).toBe(1);
// Gone once the tracker saw the connection close, which may be after the client did.
sender.ws.close();
await expect.poll(seeders).toBe(0);
});
test('forwards an offer to the sender only, rebuilt from its checked fields', async () => {
const peers = await swarm();
const other = { ...(await open()), id: id() };
+143 -20
View File
@@ -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');
// 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(/.+/);
expect(Date.now() - start).toBeLessThan(ICE_TIMEOUT / 2);
expect(Buffer.from(await page.inputValue('#offer'), 'base64').toString()).toContain(`${PUBLIC_ADDRESS} `);
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 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');
+188 -40
View File
@@ -1,4 +1,8 @@
export const DEFAULT_TRACKERS = ['wss://tracker.webtorrent.dev', 'wss://open.ftorrent.com'];
export const DEFAULT_TRACKERS = [
'wss://tracker.pagequit.net',
'wss://tracker.webtorrent.dev',
'wss://open.ftorrent.com',
];
export const DEFAULT_STUN_SERVERS = [
'stun:stun.pagequit.net:3478',
@@ -25,6 +29,10 @@ const WINDOW = 8 * 1024 * 1024;
const KEEPALIVE = 10_000;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
// A STUN server that reports no public address by then gets passed over, see stunServer.
const PROBE_TIMEOUT = 2000;
// A tracker that accepted no announcement by then counts as unreachable, the next one gets its turn.
const TRACKER_TIMEOUT = 10_000;
// A tracker peer that got an answer but never opens the data channel gives up its turn after this,
// e.g. one whose SDP has no usable candidates: its connection never even fails.
const CONNECT_TIMEOUT = 30_000;
@@ -104,10 +112,109 @@ function deadline(signal: AbortSignal, expire: () => void) {
return owned;
}
function createPeerConnection(signal: AbortSignal) {
// An empty urls list is a syntax error.
const stun = settings.stun && settings.stunServers.length;
return own(signal, new RTCPeerConnection({ iceServers: stun ? [{ urls: settings.stunServers }] : [] }));
// Whether url reports a public address to a throwaway connection within PROBE_TIMEOUT. Not once stop
// aborted, the connection closes right away then.
async function probe(url: string, stop: AbortSignal) {
const pc = new RTCPeerConnection({ iceServers: [{ urls: url }] });
let timeout: ReturnType<typeof setTimeout> | undefined;
let abort = () => {};
try {
// Without anything to negotiate nothing is gathered.
pc.createDataChannel('probe');
const answered = new Promise<boolean>((resolve) => {
timeout = setTimeout(() => resolve(false), PROBE_TIMEOUT);
abort = () => resolve(false);
stop.addEventListener('abort', abort, { once: true });
pc.addEventListener('icecandidate', ({ candidate }) => candidate?.type === 'srflx' && resolve(true));
pc.addEventListener('icegatheringstatechange', () => pc.iceGatheringState === 'complete' && resolve(false));
});
await pc.setLocalDescription();
return await answered;
} catch {
return false;
} finally {
clearTimeout(timeout);
stop.removeEventListener('abort', abort);
pc.close();
}
}
// Probes list in order from start on, the ones before start last, see stunServer.
function probeFrom(list: string[], start: number) {
const key = list.join('\n');
const stop = new AbortController();
let at = start;
let settled = false;
let waiting = 0;
const server = (async () => {
for (let n = 0; n < list.length; n++, at = (at + 1) % list.length) {
// No further server is contacted once nobody waits, STUN was turned off or the list changed.
if (stop.signal.aborted || !settings.stun || settings.stunServers.join('\n') !== key) return;
if (await probe(list[at]!, stop.signal)) return list[at];
}
})().finally(() => (settled = true));
const choice = {
list,
key,
server,
// Before it found one, the next probe goes on where this one stopped.
stopped: false,
// The server for a session's connection. Once no session waits for it any more, the probe stops.
async wait(signal: AbortSignal) {
if (signal.aborted) return;
waiting++;
const leave = () => {
if (--waiting || settled) return;
choice.stopped = true;
resume = { key, at };
stop.abort();
};
signal.addEventListener('abort', leave, { once: true });
try {
return await server;
} finally {
signal.removeEventListener('abort', leave);
if (!signal.aborted) waiting--;
}
},
};
// E.g. offline, the next connection probes again.
void server.then((url) => {
if (!url && stun === choice) stun = undefined;
});
return choice;
}
let stun: ReturnType<typeof probeFrom> | undefined;
// Where the next probe of the list with key starts, if not at its first server.
let resume: { key: string; at: number } | undefined;
// Each connection uses one STUN server, so only that one learns the address: the first in the list
// that reports one. It stays for the page's lifetime, unless a connection gets no address from it,
// then the next connection probes on from the server after it. A changed list starts over. None, or
// none reporting an address, means connections without STUN. A device with a public address of its
// own gets none reported (browsers drop it as redundant) and probes them all for every connection.
function stunServer(signal: AbortSignal) {
if (!settings.stun || !settings.stunServers.length) return Promise.resolve(undefined);
const key = settings.stunServers.join('\n');
if (stun?.key !== key || stun.stopped) {
stun = probeFrom(settings.stunServers, resume?.key === key ? resume.at : 0);
resume = undefined;
}
return stun.wait(signal);
}
// A connection got no public address from url.
async function stunFailed(url: string) {
const choice = stun;
if (!choice || (await choice.server) !== url || stun !== choice) return;
resume = { key: choice.key, at: (choice.list.indexOf(url) + 1) % choice.list.length };
stun = undefined;
}
async function createPeerConnection(signal: AbortSignal) {
const server = await stunServer(signal);
return own(signal, new RTCPeerConnection({ iceServers: server ? [{ urls: server }] : [] }));
}
// Peers and trackers send JSON objects. Anything else, malformed or not an object, counts as nothing.
@@ -212,10 +319,12 @@ function announce(ws: WebSocket, hash: string, peerId: string, params: object) {
}
// The SDP is exchanged only once, so it has to carry the candidates. Gathering only completes after
// every STUN server answered or timed out (40 s in Chromium for a silent one), but they all report
// the same public address: the first one plus a short grace for the other IP family is enough.
// the STUN server answered or timed out (40 s in Chromium for a silent one): its first address plus a
// short grace for the other IP family is enough. Without one the STUN server stopped answering, the
// next connection gets another one.
async function gatherIce(pc: RTCPeerConnection) {
if (pc.iceGatheringState === 'complete') return;
let reported = false;
await new Promise<void>((resolve) => {
const timeout = setTimeout(resolve, ICE_TIMEOUT);
const done = () => {
@@ -226,9 +335,13 @@ async function gatherIce(pc: RTCPeerConnection) {
if (pc.iceGatheringState === 'complete') done();
});
pc.addEventListener('icecandidate', ({ candidate }) => {
if (candidate?.type === 'srflx') setTimeout(done, ICE_GRACE);
if (candidate?.type !== 'srflx') return;
reported = true;
setTimeout(done, ICE_GRACE);
});
});
const [server] = pc.getConfiguration().iceServers ?? [];
if (server && !reported && pc.signalingState !== 'closed') void stunFailed([server.urls].flat()[0]!);
}
// Anti-MITM check: the first 8 bytes of both DTLS certificate fingerprints, fewer an interposer can
@@ -638,7 +751,7 @@ function failUnconnected(pc: RTCPeerConnection, opened: () => boolean, events: E
// The sender offers, the receiver answers, no tracker involved.
export async function createOffer(file: File, events: Events, signal: AbortSignal) {
events = live(events, signal);
const pc = createPeerConnection(signal);
const pc = await createPeerConnection(signal);
const channel = pc.createDataChannel('file');
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
failUnconnected(pc, () => channel.readyState !== 'connecting', events);
@@ -664,7 +777,7 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
events = live(events, signal);
const description = decode(offer, 'offer');
await downloadsReady();
const pc = createPeerConnection(signal);
const pc = await createPeerConnection(signal);
let opened = false;
pc.ondatachannel = ({ channel }) => {
// The sender's file channel, anything more is none of ours.
@@ -686,8 +799,8 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
// A socket to the tracker at url, closed with the session. Messages arrive parsed. A failure reason
// before anything else rejects the announcement, the tracker is no use then and its socket closes, a
// later one only concerns that message and is logged. message may be async, the next message doesn't
// wait for it. lost runs once it closed without close() being called: unreachable, lost or rejected.
// again announces once more, on the first interval it names.
// wait for it. lost runs once it closed without close() being called: unreachable, lost, rejected or
// without an answer within TRACKER_TIMEOUT. again announces once more, on the first interval it names.
function trackerSocket(
url: string,
signal: AbortSignal,
@@ -704,12 +817,14 @@ function trackerSocket(
const end = (reason: string) => {
if (closed) return;
closed = true;
clearTimeout(timeout);
clearInterval(reannounce);
// Already closed unless rejected, this only lets go of it.
// Already closed unless rejected or silent, this only lets go of it.
ws.close();
events.log(reason);
lost();
};
const timeout = setTimeout(() => end(opened ? `${url} did not answer` : `${url} unreachable`), TRACKER_TIMEOUT);
const tracker = {
ws,
// What the tracker answered, if it rejected the announcement.
@@ -718,6 +833,7 @@ function trackerSocket(
close: () => {
if (closed) return;
closed = true;
clearTimeout(timeout);
clearInterval(reannounce);
ws.close();
},
@@ -729,6 +845,7 @@ function trackerSocket(
if (typeof failure !== 'string') {
if (!msg) return;
accepted = true;
clearTimeout(timeout);
// Seconds, JSON may give Infinity for a huge one. Beyond TRACKER_WAIT it would never come.
if (!reannounce && !closed && typeof msg.interval === 'number') {
reannounce = setInterval(again, Math.min(TRACKER_WAIT, Math.max(MIN_INTERVAL, msg.interval * 1000)));
@@ -752,17 +869,20 @@ function noTracker(trackers: (Tracker | undefined)[]) {
return `${reason}, check the list under Servers and try again`;
}
// Tracker signaling (optional): sender joins the swarm on every tracker and answers one offer at a
// time. An offer not sealed with the code gets no turn, a peer that found the swarm without it doesn't
// even learn the sender's address. Until a receiver proved the code, the next one gets its turn: an
// offer that can't be answered, never connects or proves nothing doesn't end the share. Once the
// download started the share is used up, the trackers go. After TRACKER_WAIT they go as well, a
// Tracker signaling (optional): sender joins the swarm on the first tracker that accepts it, so only
// that one learns about the share, and moves on to the next only once it lost that one. It answers one
// offer at a time. An offer not sealed with the code gets no turn, a peer that found the swarm without
// it doesn't even learn the sender's address. Until a receiver proved the code, the next one gets its
// turn: an offer that can't be answered, never connects or proves nothing doesn't end the share. Once
// the download started the share is used up, the tracker goes. After TRACKER_WAIT it goes as well, a
// receiver connected by then still gets its turn.
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
events = live(events, signal);
const code = randomCode();
const { hash, key, sealing } = await secrets(code);
const peerId = randomBinary(20);
const urls = [...settings.trackers];
// Every one tried so far, only the last can be alive.
const trackers: Tracker[] = [];
let busy = false;
let shared = false;
@@ -801,7 +921,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
) {
busy = true;
events.log(`offer via ${url}`);
const pc = createPeerConnection(signal);
const pc = await createPeerConnection(signal);
// Until the data channel opens this ends the turn, from then on connected does.
let settled = false;
const giveUp = (reason: string) => {
@@ -848,7 +968,9 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
});
}
for (const url of settings.trackers) {
// The tracker at urls[i]. Receivers that come later walk on to the next one too, see receiveViaTracker.
function join(i: number) {
const url = urls[i]!;
const tracker = trackerSocket(
url,
signal,
@@ -858,14 +980,18 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
if (shared || typeof msg.offer?.sdp !== 'string' || typeof msg.peer_id !== 'string') return;
if (typeof msg.offer_id !== 'string') return;
const sdp = await unseal(sealing, 'offer', msg.offer.sdp);
// Meanwhile the share may have been used up, expired or ended, its trackers closed then.
// Meanwhile the share may have been used up, expired or ended, its tracker closed then.
if (signal.aborted || !tracker.alive()) return;
if (sdp === undefined) return events.log(`offer without the code via ${url}`);
const offer = { offer: { sdp }, peer_id: msg.peer_id, offer_id: msg.offer_id };
if (busy) waiting = () => answer(tracker.ws, url, offer);
else void answer(tracker.ws, url, offer);
},
() => stranded() && end(noTracker(trackers)),
() => {
if (signal.aborted) return;
if (i + 1 < urls.length) join(i + 1);
else if (stranded()) end(noTracker(trackers));
},
() => announce(tracker.ws, hash, peerId, { left: 0 }),
);
tracker.ws.onopen = () => {
@@ -875,24 +1001,29 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
trackers.push(tracker);
}
join(0);
return code;
}
// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails
// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have
// queued one of them. An answer not sealed with the code is ignored, the offer waits for the real one.
// One that can't be used or never connects is replaced right away. Once the download started, every
// other offer and tracker socket goes. After TRACKER_WAIT no offer is made or kept any more, a sender
// connected by then still gets its turn.
// Receiver walks the trackers in order with one offer each, until one has a seeder: the sender, which
// announced before anyone had the code. It moves on from a tracker without one, unreachable or lost,
// and stays where the sender is. A wrong code still walks them all. The first data channel that opens
// wins. If its check fails or the sender leaves before, the used up offers are replaced. The others
// stay, a sender may have queued one of them, or come to a tracker it passed. An answer not sealed with
// the code is ignored, the offer waits for the real one. One that can't be used or never connects is
// replaced right away. Once the download started, every other offer and tracker socket goes. After
// TRACKER_WAIT no offer is made or kept any more, a sender connected by then still gets its turn.
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
events = live(events, signal);
await downloadsReady();
const { hash, key, sealing } = await secrets(code.trim());
if (signal.aborted) return;
const peerId = randomBinary(20);
// The current offer per tracker, its socket only until the answer came. lost: the socket closed
// before that.
const offers = new Map<string, { pc: RTCPeerConnection; tracker?: Tracker; lost: boolean }>();
const urls = [...settings.trackers];
// The current offer per tracker by its place in urls, its connection once made, its socket only
// until the answer came. lost: the socket closed before that.
type Offer = { pc?: RTCPeerConnection; tracker?: Tracker; lost: boolean };
const offers = new Map<number, Offer>();
let isConnected = false;
let started = false;
let expired = false;
@@ -903,7 +1034,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
expiry.close();
for (const { pc, tracker } of offers.values()) {
tracker?.close();
pc.close();
pc?.close();
}
events.error(reason);
};
@@ -919,13 +1050,23 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
if (signal.aborted) return;
if (expired) return end(nobody);
events.log('looking again');
for (const [url, { pc }] of offers) if (pc.signalingState === 'closed') offer(url);
for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i);
};
function offer(url: string) {
const pc = createPeerConnection(signal);
const entry: { pc: RTCPeerConnection; tracker?: Tracker; lost: boolean } = { pc, lost: false };
offers.set(url, entry);
// The tracker after urls[i], unless it has an offer already.
const walk = (i: number) => {
if (signal.aborted || started || expired || i + 1 >= urls.length || offers.has(i + 1)) return;
void offer(i + 1);
};
async function offer(i: number) {
const url = urls[i]!;
const entry: Offer = { lost: false };
offers.set(i, entry);
const pc = await createPeerConnection(signal);
entry.pc = pc;
// Meanwhile the download may have started or the search ended.
if (signal.aborted || started || expired) return pc.close();
const channel = pc.createDataChannel('file');
const offerId = randomBinary(20);
let timeout: ReturnType<typeof setTimeout> | undefined;
@@ -935,7 +1076,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
if (pc.signalingState === 'closed') return;
events.log(reason);
pc.close();
if (!isConnected && !started && !signal.aborted && !expired) offer(url);
if (!isConnected && !started && !signal.aborted && !expired) void offer(i);
};
channel.onopen = () => {
clearTimeout(timeout);
@@ -948,7 +1089,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
expiry.close();
for (const other of offers.values()) {
other.tracker?.close();
if (other.pc !== pc) other.pc.close();
if (other.pc !== pc) other.pc?.close();
}
};
receiveFile(pc, channel, events, { ...handshake, start }, signal);
@@ -976,6 +1117,12 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
signal,
events,
async (msg) => {
// The tracker's reply to an announcement, complete counts the seeders. Without one the
// sender isn't here, or no longer.
if (msg.answer === undefined && msg.offer === undefined) {
if (!(msg.complete > 0)) walk(i);
return;
}
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
const answer = await unseal(sealing, 'answer', msg.answer.sdp);
// Only one answer per offer, a replacement opens its own socket. Meanwhile it may have
@@ -989,6 +1136,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
},
() => {
entry.lost = true;
walk(i);
if (!isConnected && !started && [...offers.values()].every((other) => other.lost)) {
end(noTracker([...offers.values()].map((other) => other.tracker)));
}
@@ -1005,5 +1153,5 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
.catch((error) => pc.signalingState === 'closed' || events.error(String(error)));
}
for (const url of settings.trackers) offer(url);
void offer(0);
}