ws answered every ping on its own, past the message rate limit and past the bound on bytes queued for a peer: a client pinging without reading made the tracker buffer pongs until it ran out of memory. Pongs are now sent by the tracker, pings and pongs count as messages, and a pong is queued only within the same bound as any message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
8.1 KiB
JavaScript
191 lines
8.1 KiB
JavaScript
// HellCon's tracker: the part of the WebTorrent tracker protocol that HellCon uses, nothing more. A
|
|
// connection is one peer in one swarm, bound by its first announce. A receiver's offer goes to one
|
|
// sender in its swarm, the sender's answer only back to whoever sent the offer it got, once. Every
|
|
// forwarded message is built from the checked fields, nothing else passes through. Nothing is logged.
|
|
import { createServer } from 'node:http';
|
|
import { WebSocketServer } from 'ws';
|
|
|
|
// Read on import, 0 picks a free one, see server.address().
|
|
const PORT = Number(process.env.PORT ?? 8000);
|
|
// Where HellCon is served from, separated by commas or spaces. Anything else is refused. Read on every
|
|
// connection, so test files sharing one process can each allow their own.
|
|
const allowed = (origin) =>
|
|
(process.env.ORIGINS ?? '')
|
|
.split(/[\s,]+/)
|
|
.filter(Boolean)
|
|
.includes(origin);
|
|
// Seconds. Peers last as long as their connection, announcing again only resends a receiver's offer,
|
|
// e.g. to a sender that was busy with another receiver.
|
|
const INTERVAL = 60;
|
|
// A sealed SDP is a few KiB.
|
|
const MAX_MESSAGE = 16 * 1024;
|
|
// Per connection: messages within RATE_WINDOW, bytes of SDP it gets forwarded and its lifetime. HellCon
|
|
// gives up a share or a search after 6 minutes.
|
|
const MAX_MESSAGES = 10;
|
|
const RATE_WINDOW = 10_000;
|
|
const MAX_FORWARDED = 64 * 1024;
|
|
// Bytes waiting for a peer that doesn't read, once the kernel's buffers are full. Two sealed SDPs fit,
|
|
// a peer that reads never gets near it.
|
|
const MAX_QUEUED = 32 * 1024;
|
|
const MAX_AGE = 7 * 60_000;
|
|
const MAX_CONNECTIONS = 1024;
|
|
const MAX_PER_IP = 16;
|
|
// A share has one sender, receivers keep one connection per tracker.
|
|
const MAX_SWARM = 8;
|
|
// Offers a sender got and may still answer, the oldest go first.
|
|
const MAX_PENDING = 32;
|
|
|
|
// info_hash → peer_id → peer.
|
|
const swarms = new Map();
|
|
const perIp = new Map();
|
|
let connections = 0;
|
|
|
|
// info_hash, peer_id and offer_id are 20 byte binary strings.
|
|
const isId = (value) => typeof value === 'string' && value.length === 20;
|
|
const isSdp = (value, type) => value?.type === type && typeof value.sdp === 'string';
|
|
|
|
// Behind Caddy, the only way in. Caddy replaces any X-Forwarded-For a client sends, the last entry is
|
|
// its own anyway.
|
|
function clientIp(req) {
|
|
return req.headers['x-forwarded-for']?.split(',').at(-1).trim() || req.socket.remoteAddress;
|
|
}
|
|
|
|
function refuse(socket, status) {
|
|
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n\r\n`);
|
|
}
|
|
|
|
// MAX_FORWARDED limits what each sender sends, this what a peer gets from all of them, e.g. from
|
|
// receivers that reconnect over and over. A peer that stopped reading is dropped at once, close would
|
|
// wait for its close frame.
|
|
function fits(peer, bytes) {
|
|
if (peer.ws.bufferedAmount + bytes <= MAX_QUEUED) return true;
|
|
peer.ws.terminate();
|
|
}
|
|
|
|
function send(peer, message) {
|
|
const data = JSON.stringify(message);
|
|
if (fits(peer, Buffer.byteLength(data))) peer.ws.send(data);
|
|
}
|
|
|
|
// HellCon shows the reason, the connection closes.
|
|
function reject(peer, reason) {
|
|
send(peer, { 'failure reason': reason });
|
|
peer.ws.close();
|
|
}
|
|
|
|
function forward(from, to, message, sdp) {
|
|
from.forwarded += sdp.length;
|
|
if (from.forwarded > MAX_FORWARDED) return reject(from, 'too much signaling');
|
|
send(to, message);
|
|
}
|
|
|
|
function announce(peer, msg) {
|
|
const { info_hash: hash, peer_id: id } = msg;
|
|
if (msg.action !== 'announce' || !isId(hash) || !isId(id)) return reject(peer, 'invalid announce');
|
|
if (!peer.id) {
|
|
const swarm = swarms.get(hash) ?? new Map();
|
|
if (swarm.has(id)) return reject(peer, 'peer_id taken');
|
|
if (swarm.size >= MAX_SWARM) return reject(peer, 'swarm full');
|
|
swarms.set(hash, swarm.set(id, peer));
|
|
peer.id = id;
|
|
peer.hash = hash;
|
|
} else if (peer.id !== id || peer.hash !== hash) return reject(peer, 'one swarm per connection');
|
|
if (msg.event === 'stopped') return peer.ws.close();
|
|
peer.seeder = msg.left === 0;
|
|
const swarm = swarms.get(hash);
|
|
|
|
if (msg.offers !== undefined) {
|
|
const [offer, ...more] = Array.isArray(msg.offers) ? msg.offers : [];
|
|
if (more.length || (offer && (!isId(offer.offer_id) || !isSdp(offer.offer, 'offer')))) {
|
|
return reject(peer, 'invalid offer');
|
|
}
|
|
const senders = [...swarm.values()].filter((other) => other.seeder && other !== peer);
|
|
const sender = senders[Math.floor(Math.random() * senders.length)];
|
|
if (offer && sender) {
|
|
sender.pending.delete(offer.offer_id);
|
|
sender.pending.set(offer.offer_id, peer);
|
|
if (sender.pending.size > MAX_PENDING) sender.pending.delete(sender.pending.keys().next().value);
|
|
const { sdp } = offer.offer;
|
|
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: offer.offer_id };
|
|
forward(peer, sender, { ...message, offer: { type: 'offer', sdp } }, sdp);
|
|
}
|
|
}
|
|
|
|
if (msg.answer !== undefined) {
|
|
if (!isId(msg.to_peer_id) || !isId(msg.offer_id) || !isSdp(msg.answer, 'answer')) {
|
|
return reject(peer, 'invalid answer');
|
|
}
|
|
const receiver = peer.pending.get(msg.offer_id);
|
|
// An offer it never got, answered already or whose receiver left: dropped, a stray answer doesn't
|
|
// cost the share.
|
|
if (receiver?.id === msg.to_peer_id) {
|
|
peer.pending.delete(msg.offer_id);
|
|
const { sdp } = msg.answer;
|
|
const message = { action: 'announce', info_hash: hash, peer_id: id, offer_id: msg.offer_id };
|
|
forward(peer, receiver, { ...message, answer: { type: 'answer', sdp } }, sdp);
|
|
}
|
|
}
|
|
|
|
if (peer.ws.readyState === peer.ws.OPEN) {
|
|
send(peer, { action: 'announce', interval: INTERVAL, info_hash: hash });
|
|
}
|
|
}
|
|
|
|
function open(ws) {
|
|
const peer = { ws, id: undefined, hash: undefined, seeder: false, pending: new Map(), forwarded: 0, messages: 0 };
|
|
const rate = setInterval(() => (peer.messages = 0), RATE_WINDOW);
|
|
const age = setTimeout(() => ws.close(), MAX_AGE);
|
|
// E.g. a message beyond MAX_MESSAGE, the connection closes then. Unhandled, it would end the process.
|
|
ws.on('error', () => {});
|
|
// Pings and pongs count as messages. ws would answer every ping on its own, past the limits.
|
|
const counted = () => ++peer.messages <= MAX_MESSAGES || reject(peer, 'too many messages');
|
|
ws.on('ping', (data) => counted() && fits(peer, data.length) && ws.pong(data));
|
|
ws.on('pong', counted);
|
|
ws.on('message', (data, binary) => {
|
|
if (!counted()) return;
|
|
let msg;
|
|
try {
|
|
msg = binary ? undefined : JSON.parse(data);
|
|
} catch {}
|
|
if (!msg || typeof msg !== 'object') return reject(peer, 'invalid message');
|
|
announce(peer, msg);
|
|
});
|
|
ws.on('close', () => {
|
|
clearInterval(rate);
|
|
clearTimeout(age);
|
|
// Held offers keep their peers alive, a chain of departed peers would grow without bound.
|
|
peer.pending.clear();
|
|
const swarm = swarms.get(peer.hash);
|
|
if (swarm?.get(peer.id) !== peer) return;
|
|
swarm.delete(peer.id);
|
|
if (!swarm.size) swarms.delete(peer.hash);
|
|
// Its offers go only to peers of its swarm.
|
|
for (const other of swarm.values()) {
|
|
for (const [offerId, receiver] of other.pending) if (receiver === peer) other.pending.delete(offerId);
|
|
}
|
|
});
|
|
}
|
|
|
|
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE, clientTracking: false, autoPong: false });
|
|
export const server = createServer((_, res) => res.writeHead(404).end());
|
|
server.on('upgrade', (req, socket, head) => {
|
|
// Node leaves an upgraded socket without one, ws adds its own only once it takes over. Unhandled, a
|
|
// client resetting a refused connection would end the process.
|
|
socket.on('error', () => {});
|
|
const ip = clientIp(req);
|
|
if (!allowed(req.headers.origin)) return refuse(socket, '403 Forbidden');
|
|
if (connections >= MAX_CONNECTIONS) return refuse(socket, '503 Service Unavailable');
|
|
if ((perIp.get(ip) ?? 0) >= MAX_PER_IP) return refuse(socket, '429 Too Many Requests');
|
|
// Counted on the socket, so an upgrade that fails is released too.
|
|
connections++;
|
|
perIp.set(ip, (perIp.get(ip) ?? 0) + 1);
|
|
socket.once('close', () => {
|
|
connections--;
|
|
const left = perIp.get(ip) - 1;
|
|
if (left) perIp.set(ip, left);
|
|
else perIp.delete(ip);
|
|
});
|
|
wss.handleUpgrade(req, socket, head, open);
|
|
});
|
|
server.listen(PORT);
|