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
+188
-40
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user