diff --git a/index.js b/index.js index faac34b..3438fd9 100644 --- a/index.js +++ b/index.js @@ -52,9 +52,7 @@ module.exports = metadata => { this._numPieces = Math.ceil(this._metadataSize / PIECE_LENGTH) this._remainingRejects = this._numPieces * 2 - if (this._fetching) { - this._requestPieces() - } + this._requestPieces() } onMessage (buf) { @@ -181,7 +179,7 @@ module.exports = metadata => { } _onData (piece, buf, totalSize) { - if (buf.length > PIECE_LENGTH) { + if (buf.length > PIECE_LENGTH || !this._fetching) { return } buf.copy(this.metadata, piece * PIECE_LENGTH) @@ -201,6 +199,7 @@ module.exports = metadata => { } _requestPieces () { + if (!this._fetching) return this.metadata = Buffer.alloc(this._metadataSize) for (let piece = 0; piece < this._numPieces; piece++) { this._request(piece) diff --git a/test/fetch.js b/test/fetch.js index e9664c2..2363c47 100644 --- a/test/fetch.js +++ b/test/fetch.js @@ -218,3 +218,34 @@ test('discard invalid metadata', t => { wire1.handshake(leavesMetadata.parsedTorrent.infoHash, id1) }) + +test('stop receiving data after cancel', t => { + t.plan(1) + + const wire1 = new Protocol() + const wire2 = new Protocol() + + wire1.pipe(wire2).pipe(wire1) + + wire1.use(utMetadata(sintel.torrent)) + wire2.use(utMetadata()) + + wire2.ut_metadata.once('metadata', () => { + t.fail('No "metadata" event should fire') + }) + + wire2.once('handshake', (infoHash, peerId, extensions) => { + wire2.handshake(sintel.parsedTorrent.infoHash, id2) + wire2.ut_metadata.fetch() + }) + + wire2.on('extended', ext => { + if (ext === 'ut_metadata') { + wire2.ut_metadata.cancel() + } + }) + + wire1.handshake(sintel.parsedTorrent.infoHash, id1) + + process.nextTick(() => t.pass('no metadata received')) +})