-
Notifications
You must be signed in to change notification settings - Fork 0
/
torrent.ts
245 lines (215 loc) · 5.8 KB
/
torrent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright (C) 2020-2022 Russell Clarey. All rights reserved. MIT license.
import {
Deferred,
deferred,
} from "https://deno.land/[email protected]/async/deferred.ts#^";
import { Storage } from "./storage.ts";
import { Metainfo } from "./metainfo.ts";
import { announce } from "./tracker.ts";
import {
AnnounceEvent,
AnnounceInfo,
AnnouncePeer,
CompactValue,
} from "./types.ts";
import { Peer } from "./peer.ts";
import {
Connection,
endReceiveHandshake,
MsgId,
readMessage,
sendBitfield,
sendHandshake,
sendPiece,
startReceiveHandshake,
} from "./protocol.ts";
import { equals } from "./_bytes.ts";
import { validateReceivedBlock, validateRequestedBlock } from "./piece.ts";
export interface TorrentParams {
ip: string;
metainfo: Metainfo;
peerId: Uint8Array;
port: number;
storage: Storage;
}
const enum TorrentState {
starting,
downloading,
seeding,
}
export class Torrent {
#announceSignal!: Deferred<void>;
#announceInfo: AnnounceInfo;
state = TorrentState.starting;
metainfo: Metainfo;
peerId: Uint8Array;
storage: Storage;
bitfield: Uint8Array;
peers = new Map<string, Peer>();
constructor({ ip, metainfo, peerId, port, storage }: TorrentParams) {
this.metainfo = metainfo;
this.peerId = peerId;
this.storage = storage;
this.bitfield = new Uint8Array(Math.ceil(metainfo.info.pieces.length / 8));
this.#announceInfo = {
infoHash: metainfo.infoHash,
peerId,
ip,
port,
uploaded: 0,
downloaded: 0,
left: metainfo.info.length,
event: AnnounceEvent.started,
numWant: 50,
compact: CompactValue.compact,
key: crypto.getRandomValues(new Uint8Array(20)),
};
this.run();
}
addPeer(buffId: Uint8Array, conn: Connection) {
const id = new TextDecoder().decode(buffId);
const peer = new Peer({
id,
conn,
metainfo: this.metainfo,
});
this.peers.set(id, peer);
this.handleMessages(peer)
.catch((e) => {
console.error(`peer ${peer.id} threw ${e}`);
})
.then(() => {
try {
peer.conn.close();
} catch {
// do nothing
}
this.peers.delete(peer.id);
});
sendBitfield(conn, this.bitfield);
}
requestPeers() {
this.#announceInfo.numWant = 50;
this.#announceSignal.resolve();
}
private run() {
// start announcer
this.doAnnounce();
}
private async handleMessages(peer: Peer) {
while (true) {
const msg = await readMessage(peer.conn);
if (!msg) {
return;
}
switch (msg.id) {
case MsgId.choke: {
peer.isChoking = true;
break;
}
case MsgId.unchoke: {
peer.isChoking = false;
break;
}
case MsgId.interested: {
peer.isInterested = true;
break;
}
case MsgId.uninterested: {
peer.isInterested = false;
break;
}
case MsgId.have: {
if (msg.index >= this.metainfo.info.pieces.length) {
throw new Error(`have message with invalid index ${msg.index}`);
}
const byte = msg.index >> 3;
const bit = msg.index % 8;
peer.bitfield[byte] |= 128 >> bit;
break;
}
case MsgId.bitfield: {
peer.bitfield.set(msg.bitfield);
break;
}
case MsgId.request: {
validateRequestedBlock(this.metainfo.info, msg);
if (peer.amChoking) {
// TODO log request from chocked peer. should we drop peer?
break;
}
const block = await this.storage.get(
msg.index * this.metainfo.info.pieceLength + msg.offset,
msg.length,
);
if (!block) {
// TODO log request for piece we don't have. should we drop peer?
break;
}
sendPiece(peer.conn, msg.index, msg.offset, block).catch(() => {
// TODO log error
});
break;
}
case MsgId.cancel: {
// TODO
break;
}
case MsgId.piece: {
validateReceivedBlock(this.metainfo.info, msg);
const success = await this.storage.set(
msg.index * this.metainfo.info.pieceLength + msg.offset,
msg.block,
);
if (!success) {
// TODO log error
}
break;
}
}
}
}
private handleNewPeers(peers: AnnouncePeer[]) {
for (const peer of peers) {
let conn: Deno.Conn;
(async () => {
conn = await Deno.connect({ hostname: peer.ip, port: peer.port });
await sendHandshake(conn, this.metainfo.infoHash, this.peerId);
const infoHash = await startReceiveHandshake(conn);
const peerId = await endReceiveHandshake(conn);
if (
!equals(infoHash, this.metainfo.infoHash) ||
(peer.id && !equals(peerId, peer.id))
) {
throw new Error("info hash or peer id does not match expected value");
}
this.addPeer(peerId, conn);
})().catch(() => {
try {
conn.close();
} catch {
// do nothing
}
});
}
}
private async doAnnounce() {
let interval = 0;
while (true) {
try {
const res = await announce(this.metainfo.announce, this.#announceInfo);
interval = res.interval;
this.#announceInfo.numWant = 0;
this.#announceInfo.event = AnnounceEvent.empty;
this.handleNewPeers(res.peers);
} catch {
// TODO: log error
}
this.#announceSignal = deferred();
const to = setTimeout(this.#announceSignal.resolve, interval * 1000);
await this.#announceSignal;
// clear timeout in case announceSignal was resolved early
clearTimeout(to);
}
}
}