From bc3d1ea668e912505ec8356df9a78f2d83e3fcdb Mon Sep 17 00:00:00 2001 From: fisch0920 Date: Fri, 9 May 2014 07:11:14 -0400 Subject: [PATCH] fixed buggy metadata vs metadata.info --- index.js | 16 +++++++++++++--- test/basic.js | 3 ++- test/fetch.js | 3 ++- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index 40c27a4..b44892d 100644 --- a/index.js +++ b/index.js @@ -31,7 +31,17 @@ module.exports = function (metadata) { this._bitfield = new BitField(0, { grow: BITFIELD_GROW }) if (Buffer.isBuffer(metadata)) { - this._gotMetadata(metadata) + var info = null + try { + // if buffer fails to decode or there is no info key, then metadata is corrupt + info = bncode.encode(bncode.decode(metadata).info) + } catch (err) { + // TODO: throw or disregard invalid metadata? + //throw new Error('ut_metadata constructed with invalid metadata') + } + + if (info) + this._gotMetadata(info) } } @@ -185,7 +195,7 @@ module.exports = function (metadata) { // check hash if (sha1(this.metadata) === this._infoHash.toString('hex')) { - this._gotMetadata(bncode.encode({ info: bncode.decode(this.metadata) })) + this._gotMetadata(this.metadata) } else { this._failedMetadata() } @@ -197,7 +207,7 @@ module.exports = function (metadata) { this._metadataComplete = true this._metadataSize = this.metadata.length this._wire.extendedHandshake.metadata_size = this._metadataSize - this.emit('metadata', this.metadata) + this.emit('metadata', bncode.encode({ info: bncode.decode(this.metadata) })) } ut_metadata.prototype._failedMetadata = function () { diff --git a/test/basic.js b/test/basic.js index 55f156e..174f96b 100644 --- a/test/basic.js +++ b/test/basic.js @@ -1,6 +1,7 @@ var fs = require('fs') var Protocol = require('bittorrent-protocol') var ut_metadata = require('../') +var bncode = require('bncode') var test = require('tape') // Used in multiple tests @@ -28,6 +29,6 @@ test('wire.use(ut_metadata(metadata))', function (t) { t.ok(wire.ut_metadata) t.ok(wire.ut_metadata.fetch) t.ok(wire.ut_metadata.cancel) - t.equal(wire.ut_metadata.metadata, metadata) + t.equal(wire.ut_metadata.metadata.toString('hex'), bncode.encode(bncode.decode(metadata).info).toString('hex')) t.end() }) diff --git a/test/fetch.js b/test/fetch.js index 9a9d66d..52e9217 100644 --- a/test/fetch.js +++ b/test/fetch.js @@ -2,6 +2,7 @@ var fs = require('fs') var parseTorrent = require('parse-torrent') var Protocol = require('bittorrent-protocol') var ut_metadata = require('../') +var bncode = require('bncode') var test = require('tape') // Used in multiple tests @@ -24,7 +25,7 @@ test('fetch()', function (t) { wire2.ut_metadata.on('metadata', function (_metadata) { // got metadata! - t.deepEqual(_metadata, metadata) + t.equal(_metadata.toString('hex'), bncode.encode({ info: bncode.decode(metadata).info }).toString('hex')) }) wire2.on('handshake', function (infoHash, peerId, extensions) {