ut_metadata/index.js

245 lines
6.4 KiB
JavaScript
Raw Normal View History

2018-08-28 10:41:44 +01:00
const { EventEmitter } = require('events')
const bencode = require('bencode')
const BitField = require('bitfield')
const debug = require('debug')('ut_metadata')
const sha1 = require('simple-sha1')
2018-08-28 18:34:08 +01:00
const MAX_METADATA_SIZE = 1E7 // 10 MB
const BITFIELD_GROW = 1E3
const PIECE_LENGTH = 1 << 14 // 16 KiB
2018-08-28 10:41:44 +01:00
module.exports = metadata => {
class utMetadata extends EventEmitter {
constructor (wire) {
super()
this._wire = wire
2018-08-28 18:34:08 +01:00
this._fetching = false
2018-08-28 10:41:44 +01:00
this._metadataComplete = false
this._metadataSize = null
2018-08-28 18:34:08 +01:00
// how many reject messages to tolerate before quitting
this._remainingRejects = null
2018-08-28 10:41:44 +01:00
2018-08-28 18:34:08 +01:00
// The largest torrent file that I know of is ~1-2MB, which is ~100
// pieces. Therefore, cap the bitfield to 10x that (1000 pieces) so a
// malicious peer can't make it grow to fill all memory.
2018-08-28 10:41:44 +01:00
this._bitfield = new BitField(0, { grow: BITFIELD_GROW })
if (Buffer.isBuffer(metadata)) {
this.setMetadata(metadata)
}
}
2014-03-23 03:34:50 +00:00
2018-08-28 10:41:44 +01:00
onHandshake (infoHash, peerId, extensions) {
this._infoHash = infoHash
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
onExtendedHandshake (handshake) {
if (!handshake.m || !handshake.m.ut_metadata) {
return this.emit('warning', new Error('Peer does not support ut_metadata'))
}
if (!handshake.metadata_size) {
return this.emit('warning', new Error('Peer does not have metadata'))
}
if (typeof handshake.metadata_size !== 'number' ||
MAX_METADATA_SIZE < handshake.metadata_size ||
handshake.metadata_size <= 0) {
return this.emit('warning', new Error('Peer gave invalid metadata size'))
}
2014-06-04 07:43:05 +01:00
2018-08-28 10:41:44 +01:00
this._metadataSize = handshake.metadata_size
this._numPieces = Math.ceil(this._metadataSize / PIECE_LENGTH)
this._remainingRejects = this._numPieces * 2
2014-03-23 03:34:50 +00:00
2018-08-28 10:41:44 +01:00
if (this._fetching) {
this._requestPieces()
}
}
2018-08-28 10:41:44 +01:00
onMessage (buf) {
let dict
let trailer
try {
const str = buf.toString()
const trailerIndex = str.indexOf('ee') + 2
dict = bencode.decode(str.substring(0, trailerIndex))
trailer = buf.slice(trailerIndex)
} catch (err) {
// drop invalid messages
return
}
2014-03-23 05:15:57 +00:00
2018-08-28 10:41:44 +01:00
switch (dict.msg_type) {
case 0:
// ut_metadata request (from peer)
// example: { 'msg_type': 0, 'piece': 0 }
this._onRequest(dict.piece)
break
case 1:
// ut_metadata data (in response to our request)
// example: { 'msg_type': 1, 'piece': 0, 'total_size': 3425 }
this._onData(dict.piece, trailer, dict.total_size)
break
case 2:
// ut_metadata reject (peer doesn't have piece we requested)
// { 'msg_type': 2, 'piece': 0 }
this._onReject(dict.piece)
break
}
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
/**
* Ask the peer to send metadata.
* @public
*/
fetch () {
if (this._metadataComplete) {
return
}
this._fetching = true
if (this._metadataSize) {
this._requestPieces()
}
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
/**
* Stop asking the peer to send metadata.
* @public
*/
cancel () {
this._fetching = false
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
setMetadata (metadata) {
if (this._metadataComplete) return true
debug('set metadata')
2014-03-23 03:34:50 +00:00
2018-08-28 10:41:44 +01:00
// if full torrent dictionary was passed in, pull out just `info` key
try {
const info = bencode.decode(metadata).info
if (info) {
metadata = bencode.encode(info)
}
} catch (err) {}
2018-08-28 10:41:44 +01:00
// check hash
if (this._infoHash && this._infoHash !== sha1.sync(metadata)) {
return false
}
2018-08-28 10:41:44 +01:00
this.cancel()
2018-08-28 10:41:44 +01:00
this.metadata = metadata
this._metadataComplete = true
this._metadataSize = this.metadata.length
this._wire.extendedHandshake.metadata_size = this._metadataSize
2018-08-28 18:34:08 +01:00
this.emit('metadata', bencode.encode({
info: bencode.decode(this.metadata)
}))
2014-06-04 05:17:25 +01:00
2018-08-28 10:41:44 +01:00
return true
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
_send (dict, trailer) {
let buf = bencode.encode(dict)
if (Buffer.isBuffer(trailer)) {
buf = Buffer.concat([buf, trailer])
}
this._wire.extended('ut_metadata', buf)
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
_request (piece) {
this._send({ msg_type: 0, piece })
2014-04-23 14:38:50 +01:00
}
2018-08-28 10:41:44 +01:00
_data (piece, buf, totalSize) {
const msg = { msg_type: 1, piece }
if (typeof totalSize === 'number') {
msg.total_size = totalSize
}
this._send(msg, buf)
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
_reject (piece) {
this._send({ msg_type: 2, piece })
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
_onRequest (piece) {
if (!this._metadataComplete) {
this._reject(piece)
return
}
const start = piece * PIECE_LENGTH
let end = start + PIECE_LENGTH
if (end > this._metadataSize) {
end = this._metadataSize
}
const buf = this.metadata.slice(start, end)
this._data(piece, buf, this._metadataSize)
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
_onData (piece, buf, totalSize) {
if (buf.length > PIECE_LENGTH) {
return
}
buf.copy(this.metadata, piece * PIECE_LENGTH)
this._bitfield.set(piece)
this._checkDone()
}
_onReject (piece) {
if (this._remainingRejects > 0 && this._fetching) {
2018-08-28 18:34:08 +01:00
// If we haven't been rejected too much,
// then try to request the piece again
2018-08-28 10:41:44 +01:00
this._request(piece)
this._remainingRejects -= 1
} else {
this.emit('warning', new Error('Peer sent "reject" too much'))
}
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
_requestPieces () {
this.metadata = Buffer.alloc(this._metadataSize)
for (let piece = 0; piece < this._numPieces; piece++) {
this._request(piece)
2014-03-23 03:34:50 +00:00
}
}
2018-08-28 10:41:44 +01:00
_checkDone () {
let done = true
for (let piece = 0; piece < this._numPieces; piece++) {
if (!this._bitfield.get(piece)) {
done = false
break
}
}
if (!done) return
// attempt to set metadata -- may fail sha1 check
const success = this.setMetadata(this.metadata)
2014-05-07 20:09:39 +01:00
2018-08-28 10:41:44 +01:00
if (!success) {
this._failedMetadata()
}
2014-03-23 05:15:57 +00:00
}
2014-03-23 03:34:50 +00:00
2018-08-28 10:41:44 +01:00
_failedMetadata () {
// reset bitfield & try again
this._bitfield = new BitField(0, { grow: BITFIELD_GROW })
this._remainingRejects -= this._numPieces
if (this._remainingRejects > 0) {
this._requestPieces()
} else {
this.emit('warning', new Error('Peer sent invalid metadata'))
}
2014-03-23 05:15:57 +00:00
}
2014-03-23 03:34:50 +00:00
}
2018-08-28 10:41:44 +01:00
// Name of the bittorrent-protocol extension
utMetadata.prototype.name = 'ut_metadata'
2016-04-24 09:03:02 +01:00
return utMetadata
2014-03-23 03:34:50 +00:00
}