forked from Onek8/LNXSDK
425 lines
12 KiB
Haxe
425 lines
12 KiB
Haxe
package leenkx.network.torrent.peer;
|
|
|
|
import haxe.io.Bytes;
|
|
import leenkx.network.torrent.Bencode;
|
|
|
|
class WireProtocol {
|
|
static inline var PSTR = "BitTorrent protocol";
|
|
static inline var BLOCK_SIZE = 16384;
|
|
static inline var MAX_MSG_LEN = 256 * 1024;
|
|
|
|
public static inline var MSG_CHOKE = 0;
|
|
public static inline var MSG_UNCHOKE = 1;
|
|
public static inline var MSG_INTERESTED = 2;
|
|
public static inline var MSG_NOT_INTERESTED = 3;
|
|
public static inline var MSG_HAVE = 4;
|
|
public static inline var MSG_BITFIELD = 5;
|
|
public static inline var MSG_REQUEST = 6;
|
|
public static inline var MSG_PIECE = 7;
|
|
public static inline var MSG_CANCEL = 8;
|
|
public static inline var MSG_PORT = 9;
|
|
public static inline var MSG_EXTENDED = 20;
|
|
public static inline var MSG_HASH_REQUEST = 21;
|
|
public static inline var MSG_HASHES = 22;
|
|
public static inline var MSG_HASH_REJECT = 23;
|
|
|
|
var channel:IPeerChannel;
|
|
var infoHash:Bytes;
|
|
var peerId:Bytes;
|
|
var buffer:haxe.io.BytesBuffer = new haxe.io.BytesBuffer();
|
|
var handshakeDone = false;
|
|
var handshakeSent = false;
|
|
var started = false;
|
|
var closed = false;
|
|
|
|
public var extIds:Map<String, Int> = [];
|
|
public var peerExtendedHandshake:Dynamic = null;
|
|
public var remotePeerId:String = null;
|
|
public var peerChoking = true;
|
|
public var peerInterested = false;
|
|
public var amChoking = true;
|
|
public var amInterested = false;
|
|
|
|
var localExtNames:Array<String> = [];
|
|
var localExtIds:Map<Int, String> = [];
|
|
|
|
public var onHandshake:String -> Void;
|
|
public var onExtendedHandshake:Dynamic -> Void;
|
|
public var onChoke:Void -> Void;
|
|
public var onUnchoke:Void -> Void;
|
|
public var onInterested:Void -> Void;
|
|
public var onNotInterested:Void -> Void;
|
|
public var onHave:Int -> Void;
|
|
public var onBitfield:Bytes -> Void;
|
|
public var onRequest:Int -> Int -> Int -> Void;
|
|
public var onPiece:Int -> Int -> Bytes -> Void;
|
|
public var onCancel:Int -> Int -> Int -> Void;
|
|
public var onExtended:String -> Bytes -> Void;
|
|
public var onHashRequest:Bytes -> Void;
|
|
public var onHashes:Bytes -> Void;
|
|
public var onHashReject:Bytes -> Void;
|
|
public var onClose:Void -> Void;
|
|
public var onError:String -> Void;
|
|
|
|
public function new(channel:IPeerChannel, infoHash:Bytes, peerId:Bytes) {
|
|
this.channel = channel;
|
|
this.infoHash = infoHash;
|
|
this.peerId = peerId;
|
|
channel.onData = onChannelData;
|
|
var prevClose = channel.onClose;
|
|
channel.onClose = function() {
|
|
if (prevClose != null) prevClose();
|
|
closed = true;
|
|
if (onClose != null) onClose();
|
|
};
|
|
}
|
|
|
|
public function start(extNames:Array<String>):Void {
|
|
localExtNames = extNames;
|
|
started = true;
|
|
sendHandshake();
|
|
pump();
|
|
}
|
|
|
|
function sendHandshake():Void {
|
|
if (handshakeSent) return;
|
|
handshakeSent = true;
|
|
var out = new haxe.io.BytesBuffer();
|
|
out.addByte(PSTR.length);
|
|
out.addString(PSTR);
|
|
var reserved = Bytes.alloc(8);
|
|
reserved.set(5, 0x10);
|
|
out.addBytes(reserved, 0, 8);
|
|
out.addBytes(infoHash, 0, 20);
|
|
out.addBytes(peerId, 0, 20);
|
|
channel.send(out.getBytes());
|
|
}
|
|
|
|
var parsing = false;
|
|
|
|
function onChannelData(data:Bytes):Void {
|
|
if (closed) return;
|
|
buffer.addBytes(data, 0, data.length);
|
|
if (!started) return;
|
|
pump();
|
|
}
|
|
|
|
function pump():Void {
|
|
if (parsing) return;
|
|
parsing = true;
|
|
while (!closed) {
|
|
var bytes = buffer.getBytes();
|
|
buffer = new haxe.io.BytesBuffer();
|
|
if (bytes.length == 0) break;
|
|
var consumed = parse(bytes);
|
|
if (consumed < bytes.length) {
|
|
var nested = buffer.getBytes();
|
|
buffer = new haxe.io.BytesBuffer();
|
|
buffer.addBytes(bytes, consumed, bytes.length - consumed);
|
|
buffer.addBytes(nested, 0, nested.length);
|
|
if (consumed == 0 && nested.length == 0) break;
|
|
}
|
|
}
|
|
parsing = false;
|
|
}
|
|
|
|
function parse(data:Bytes):Int {
|
|
var pos = 0;
|
|
if (!handshakeDone) {
|
|
if (data.length < 68) return 0;
|
|
var pstrLen = data.get(0);
|
|
if (pstrLen != PSTR.length) {
|
|
fail("bad pstr length");
|
|
return data.length;
|
|
}
|
|
var pstr = data.sub(1, pstrLen).toString();
|
|
if (pstr != PSTR) {
|
|
fail("bad pstr");
|
|
return data.length;
|
|
}
|
|
var ihOff = 1 + pstrLen + 8;
|
|
var remoteHash = data.sub(ihOff, 20);
|
|
if (!bytesEqual(remoteHash, infoHash)) {
|
|
fail("info_hash mismatch");
|
|
return data.length;
|
|
}
|
|
remotePeerId = leenkx.network.torrent.Crypto.toHex(
|
|
data.sub(ihOff + 20, 20));
|
|
handshakeDone = true;
|
|
pos = ihOff + 40;
|
|
sendHandshake();
|
|
sendExtendedHandshake();
|
|
if (onHandshake != null) onHandshake(remotePeerId);
|
|
}
|
|
while (pos + 4 <= data.length) {
|
|
var len = (data.get(pos) << 24) | (data.get(pos + 1) << 16)
|
|
| (data.get(pos + 2) << 8) | data.get(pos + 3);
|
|
if (len < 0 || len > MAX_MSG_LEN || pos + 4 + len > data.length) break;
|
|
var msgStart = pos;
|
|
pos += 4;
|
|
if (len > 0) {
|
|
var mid = data.get(pos);
|
|
handleMessage(mid, data.sub(pos + 1, len - 1));
|
|
}
|
|
pos += len;
|
|
}
|
|
return pos;
|
|
}
|
|
|
|
function handleMessage(id:Int, payload:Bytes):Void {
|
|
switch (id) {
|
|
case MSG_CHOKE:
|
|
peerChoking = true;
|
|
if (onChoke != null) onChoke();
|
|
case MSG_UNCHOKE:
|
|
peerChoking = false;
|
|
if (onUnchoke != null) onUnchoke();
|
|
case MSG_INTERESTED:
|
|
peerInterested = true;
|
|
if (onInterested != null) onInterested();
|
|
case MSG_NOT_INTERESTED:
|
|
peerInterested = false;
|
|
if (onNotInterested != null) onNotInterested();
|
|
case MSG_HAVE:
|
|
if (payload.length >= 4 && onHave != null) {
|
|
onHave(readInt32(payload, 0));
|
|
}
|
|
case MSG_BITFIELD:
|
|
if (onBitfield != null) onBitfield(payload);
|
|
case MSG_REQUEST:
|
|
if (payload.length >= 12 && onRequest != null) {
|
|
onRequest(readInt32(payload, 0), readInt32(payload, 4),
|
|
readInt32(payload, 8));
|
|
}
|
|
case MSG_PIECE:
|
|
if (payload.length >= 8 && onPiece != null) {
|
|
onPiece(readInt32(payload, 0), readInt32(payload, 4),
|
|
payload.sub(8, payload.length - 8));
|
|
}
|
|
case MSG_CANCEL:
|
|
if (payload.length >= 12 && onCancel != null) {
|
|
onCancel(readInt32(payload, 0), readInt32(payload, 4),
|
|
readInt32(payload, 8));
|
|
}
|
|
case MSG_EXTENDED:
|
|
handleExtended(payload);
|
|
case MSG_HASH_REQUEST:
|
|
if (payload.length >= 48 && onHashRequest != null) {
|
|
onHashRequest(payload);
|
|
}
|
|
case MSG_HASHES:
|
|
if (payload.length >= 48 && onHashes != null) {
|
|
onHashes(payload);
|
|
}
|
|
case MSG_HASH_REJECT:
|
|
if (payload.length >= 48 && onHashReject != null) {
|
|
onHashReject(payload);
|
|
}
|
|
default:
|
|
}
|
|
}
|
|
|
|
function handleExtended(payload:Bytes):Void {
|
|
if (payload.length < 1) return;
|
|
var extId = payload.get(0);
|
|
var body = payload.sub(1, payload.length - 1);
|
|
if (extId == 0) {
|
|
var dict:Dynamic = null;
|
|
try {
|
|
dict = Bencode.decode(body);
|
|
} catch(e:Dynamic) {
|
|
return;
|
|
}
|
|
peerExtendedHandshake = dict;
|
|
var m:Dynamic = Reflect.field(dict, "m");
|
|
if (m != null) {
|
|
for (name in Reflect.fields(m)) {
|
|
extIds.set(name, Std.int(Reflect.field(m, name)));
|
|
}
|
|
}
|
|
if (onExtendedHandshake != null) onExtendedHandshake(dict);
|
|
} else {
|
|
var name = localExtIds.get(extId);
|
|
if (name != null) {
|
|
if (onExtended != null) onExtended(name, body);
|
|
}
|
|
}
|
|
}
|
|
|
|
function sendExtendedHandshake():Void {
|
|
var m:Dynamic = {};
|
|
var id = 1;
|
|
for (name in localExtNames) {
|
|
Reflect.setField(m, name, id);
|
|
localExtIds.set(id, name);
|
|
id++;
|
|
}
|
|
var dict:Dynamic = {m: m, v: "Leenkx 0.1"};
|
|
if (metaSize > 0) Reflect.setField(dict, "metadata_size", metaSize);
|
|
if (extHandshakeFields != null) {
|
|
for (f in Reflect.fields(extHandshakeFields)) {
|
|
Reflect.setField(dict, f, Reflect.field(extHandshakeFields, f));
|
|
}
|
|
}
|
|
sendExtendedMessage(0, Bencode.encode(dict));
|
|
}
|
|
|
|
public var metaSize:Int = 0;
|
|
public var extHandshakeFields:Dynamic = null;
|
|
|
|
public function sendExtended(name:String, payload:Bytes):Bool {
|
|
var id = extIds.get(name);
|
|
if (id == null) return false;
|
|
var out = new haxe.io.BytesBuffer();
|
|
out.addByte(id);
|
|
out.addBytes(payload, 0, payload.length);
|
|
sendExtendedMessage(-1, out.getBytes());
|
|
return true;
|
|
}
|
|
|
|
function sendExtendedMessage(id:Int, payload:Bytes):Void {
|
|
var out = new haxe.io.BytesBuffer();
|
|
if (id >= 0) out.addByte(id);
|
|
out.addBytes(payload, 0, payload.length);
|
|
sendMessage(MSG_EXTENDED, out.getBytes());
|
|
}
|
|
|
|
var keepAliveBuf:Bytes = Bytes.alloc(4);
|
|
|
|
public function sendKeepAlive():Void {
|
|
channel.send(keepAliveBuf);
|
|
}
|
|
|
|
public function sendChoke():Void {
|
|
amChoking = true;
|
|
sendMessage(MSG_CHOKE, null);
|
|
}
|
|
public function sendUnchoke():Void {
|
|
amChoking = false;
|
|
sendMessage(MSG_UNCHOKE, null);
|
|
}
|
|
public function sendInterested():Void {
|
|
amInterested = true;
|
|
sendMessage(MSG_INTERESTED, null);
|
|
}
|
|
public function sendNotInterested():Void {
|
|
amInterested = false;
|
|
sendMessage(MSG_NOT_INTERESTED, null);
|
|
}
|
|
|
|
public function sendHave(index:Int):Void {
|
|
var out = Bytes.alloc(9);
|
|
writeInt32(out, 0, 5);
|
|
out.set(4, MSG_HAVE);
|
|
writeInt32(out, 5, index);
|
|
channel.send(out);
|
|
}
|
|
|
|
public function sendBitfield(bitfield:Bytes):Void {
|
|
sendMessage(MSG_BITFIELD, bitfield);
|
|
}
|
|
|
|
public function sendRequest(index:Int, begin:Int, length:Int):Void {
|
|
var out = Bytes.alloc(17);
|
|
writeInt32(out, 0, 13);
|
|
out.set(4, MSG_REQUEST);
|
|
writeInt32(out, 5, index);
|
|
writeInt32(out, 9, begin);
|
|
writeInt32(out, 13, length);
|
|
channel.send(out);
|
|
}
|
|
|
|
public function sendPiece(index:Int, begin:Int, data:Bytes):Void {
|
|
var total = 13 + data.length;
|
|
var out = Bytes.alloc(total);
|
|
writeInt32(out, 0, total - 4);
|
|
out.set(4, MSG_PIECE);
|
|
writeInt32(out, 5, index);
|
|
writeInt32(out, 9, begin);
|
|
out.blit(13, data, 0, data.length);
|
|
channel.send(out);
|
|
}
|
|
|
|
static function hashMsg(root:Bytes, base:Int, index:Int, length:Int, proofs:Int, ?hashes:Bytes):Bytes {
|
|
var n = 48 + (hashes != null ? hashes.length : 0);
|
|
var out = Bytes.alloc(n);
|
|
out.blit(0, root, 0, 32);
|
|
writeInt32(out, 32, base);
|
|
writeInt32(out, 36, index);
|
|
writeInt32(out, 40, length);
|
|
writeInt32(out, 44, proofs);
|
|
if (hashes != null) out.blit(48, hashes, 0, hashes.length);
|
|
return out;
|
|
}
|
|
|
|
public function sendHashRequest(root:Bytes, base:Int, index:Int, length:Int, proofs:Int):Void {
|
|
sendMessage(MSG_HASH_REQUEST,
|
|
hashMsg(root, base, index, length, proofs));
|
|
}
|
|
|
|
public function sendHashes(root:Bytes, base:Int, index:Int, length:Int, proofs:Int, hashes:Bytes):Void {
|
|
sendMessage(MSG_HASHES,
|
|
hashMsg(root, base, index, length, proofs, hashes));
|
|
}
|
|
|
|
public function sendHashReject(root:Bytes, base:Int, index:Int, length:Int, proofs:Int):Void {
|
|
sendMessage(MSG_HASH_REJECT,
|
|
hashMsg(root, base, index, length, proofs));
|
|
}
|
|
|
|
public function sendCancel(index:Int, begin:Int, length:Int):Void {
|
|
var out = Bytes.alloc(17);
|
|
writeInt32(out, 0, 13);
|
|
out.set(4, MSG_CANCEL);
|
|
writeInt32(out, 5, index);
|
|
writeInt32(out, 9, begin);
|
|
writeInt32(out, 13, length);
|
|
channel.send(out);
|
|
}
|
|
|
|
function sendMessage(id:Int, payload:Bytes):Void {
|
|
if (closed) return;
|
|
var len = 1 + (payload != null ? payload.length : 0);
|
|
var total = 4 + 1 + (payload != null ? payload.length : 0);
|
|
var out = Bytes.alloc(total);
|
|
writeInt32(out, 0, len);
|
|
out.set(4, id);
|
|
if (payload != null) out.blit(5, payload, 0, payload.length);
|
|
channel.send(out);
|
|
}
|
|
|
|
public function close():Void {
|
|
closed = true;
|
|
channel.close();
|
|
}
|
|
|
|
function fail(reason:String):Void {
|
|
if (onError != null) onError(reason);
|
|
close();
|
|
}
|
|
|
|
static function bytesEqual(a:Bytes, b:Bytes):Bool {
|
|
if (a.length != b.length) return false;
|
|
for (i in 0...a.length) {
|
|
if (a.get(i) != b.get(i)) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static function readInt32(b:Bytes, off:Int):Int {
|
|
return (b.get(off) << 24) | (b.get(off + 1) << 16)
|
|
| (b.get(off + 2) << 8) | b.get(off + 3);
|
|
}
|
|
|
|
static public function readU32(b:Bytes, off:Int):Int {
|
|
return readInt32(b, off);
|
|
}
|
|
|
|
static function writeInt32(b:Bytes, off:Int, v:Int):Void {
|
|
b.set(off, (v >> 24) & 0xFF);
|
|
b.set(off + 1, (v >> 16) & 0xFF);
|
|
b.set(off + 2, (v >> 8) & 0xFF);
|
|
b.set(off + 3, v & 0xFF);
|
|
}
|
|
}
|