Merge pull request #295 from jimmywarting/modernize_server.js

Modernize server.js
This commit is contained in:
Diego Rodríguez Baquero 2018-11-22 11:05:04 -05:00 committed by GitHub
commit e21a3809f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

530
server.js
View File

@ -1,24 +1,19 @@
module.exports = Server const { Buffer } = require('safe-buffer')
const bencode = require('bencode')
const debug = require('debug')('bittorrent-tracker:server')
const dgram = require('dgram')
const EventEmitter = require('events')
const http = require('http')
const peerid = require('bittorrent-peerid')
const series = require('run-series')
const string2compact = require('string2compact')
const WebSocketServer = require('ws').Server
var Buffer = require('safe-buffer').Buffer const common = require('./lib/common')
var bencode = require('bencode') const Swarm = require('./lib/server/swarm')
var debug = require('debug')('bittorrent-tracker:server') const parseHttpRequest = require('./lib/server/parse-http')
var dgram = require('dgram') const parseUdpRequest = require('./lib/server/parse-udp')
var EventEmitter = require('events').EventEmitter const parseWebSocketRequest = require('./lib/server/parse-websocket')
var http = require('http')
var inherits = require('inherits')
var peerid = require('bittorrent-peerid')
var series = require('run-series')
var string2compact = require('string2compact')
var WebSocketServer = require('ws').Server
var common = require('./lib/common')
var Swarm = require('./lib/server/swarm')
var parseHttpRequest = require('./lib/server/parse-http')
var parseUdpRequest = require('./lib/server/parse-udp')
var parseWebSocketRequest = require('./lib/server/parse-websocket')
inherits(Server, EventEmitter)
/** /**
* BitTorrent tracker server. * BitTorrent tracker server.
@ -36,80 +31,77 @@ inherits(Server, EventEmitter)
* @param {boolean} opts.stats enable web-based statistics? (default: true) * @param {boolean} opts.stats enable web-based statistics? (default: true)
* @param {function} opts.filter black/whitelist fn for disallowing/allowing torrents * @param {function} opts.filter black/whitelist fn for disallowing/allowing torrents
*/ */
function Server (opts) { class Server extends EventEmitter {
var self = this constructor (opts = {}) {
if (!(self instanceof Server)) return new Server(opts) super()
EventEmitter.call(self)
if (!opts) opts = {}
debug('new server %s', JSON.stringify(opts)) debug('new server %s', JSON.stringify(opts))
self.intervalMs = opts.interval this.intervalMs = opts.interval
? opts.interval ? opts.interval
: 10 * 60 * 1000 // 10 min : 10 * 60 * 1000 // 10 min
self._trustProxy = !!opts.trustProxy this._trustProxy = !!opts.trustProxy
if (typeof opts.filter === 'function') self._filter = opts.filter if (typeof opts.filter === 'function') this._filter = opts.filter
self.peersCacheLength = opts.peersCacheLength this.peersCacheLength = opts.peersCacheLength
self.peersCacheTtl = opts.peersCacheTtl this.peersCacheTtl = opts.peersCacheTtl
self._listenCalled = false this._listenCalled = false
self.listening = false this.listening = false
self.destroyed = false this.destroyed = false
self.torrents = {} this.torrents = {}
self.http = null this.http = null
self.udp4 = null this.udp4 = null
self.udp6 = null this.udp6 = null
self.ws = null this.ws = null
// start an http tracker unless the user explictly says no // start an http tracker unless the user explictly says no
if (opts.http !== false) { if (opts.http !== false) {
self.http = http.createServer() this.http = http.createServer()
self.http.on('error', function (err) { self._onError(err) }) this.http.on('error', err => { this._onError(err) })
self.http.on('listening', onListening) this.http.on('listening', onListening)
// Add default http request handler on next tick to give user the chance to add // Add default http request handler on next tick to give user the chance to add
// their own handler first. Handle requests untouched by user's handler. // their own handler first. Handle requests untouched by user's handler.
process.nextTick(function () { process.nextTick(() => {
self.http.on('request', function (req, res) { this.http.on('request', (req, res) => {
if (res.headersSent) return if (res.headersSent) return
self.onHttpRequest(req, res) this.onHttpRequest(req, res)
}) })
}) })
} }
// start a udp tracker unless the user explicitly says no // start a udp tracker unless the user explicitly says no
if (opts.udp !== false) { if (opts.udp !== false) {
var isNode10 = /^v0.10./.test(process.version) const isNode10 = /^v0.10./.test(process.version)
self.udp4 = self.udp = dgram.createSocket( this.udp4 = this.udp = dgram.createSocket(
isNode10 ? 'udp4' : { type: 'udp4', reuseAddr: true } isNode10 ? 'udp4' : { type: 'udp4', reuseAddr: true }
) )
self.udp4.on('message', function (msg, rinfo) { self.onUdpRequest(msg, rinfo) }) this.udp4.on('message', (msg, rinfo) => { this.onUdpRequest(msg, rinfo) })
self.udp4.on('error', function (err) { self._onError(err) }) this.udp4.on('error', err => { this._onError(err) })
self.udp4.on('listening', onListening) this.udp4.on('listening', onListening)
self.udp6 = dgram.createSocket( this.udp6 = dgram.createSocket(
isNode10 ? 'udp6' : { type: 'udp6', reuseAddr: true } isNode10 ? 'udp6' : { type: 'udp6', reuseAddr: true }
) )
self.udp6.on('message', function (msg, rinfo) { self.onUdpRequest(msg, rinfo) }) this.udp6.on('message', (msg, rinfo) => { this.onUdpRequest(msg, rinfo) })
self.udp6.on('error', function (err) { self._onError(err) }) this.udp6.on('error', err => { this._onError(err) })
self.udp6.on('listening', onListening) this.udp6.on('listening', onListening)
} }
// start a websocket tracker (for WebTorrent) unless the user explicitly says no // start a websocket tracker (for WebTorrent) unless the user explicitly says no
if (opts.ws !== false) { if (opts.ws !== false) {
if (!self.http) { if (!this.http) {
self.http = http.createServer() this.http = http.createServer()
self.http.on('error', function (err) { self._onError(err) }) this.http.on('error', err => { this._onError(err) })
self.http.on('listening', onListening) this.http.on('listening', onListening)
// Add default http request handler on next tick to give user the chance to add // Add default http request handler on next tick to give user the chance to add
// their own handler first. Handle requests untouched by user's handler. // their own handler first. Handle requests untouched by user's handler.
process.nextTick(function () { process.nextTick(() => {
self.http.on('request', function (req, res) { this.http.on('request', (req, res) => {
if (res.headersSent) return if (res.headersSent) return
// For websocket trackers, we only need to handle the UPGRADE http method. // For websocket trackers, we only need to handle the UPGRADE http method.
// Return 404 for all other request types. // Return 404 for all other request types.
@ -118,41 +110,41 @@ function Server (opts) {
}) })
}) })
} }
self.ws = new WebSocketServer({ this.ws = new WebSocketServer({
server: self.http, server: this.http,
perMessageDeflate: false, perMessageDeflate: false,
clientTracking: false clientTracking: false
}) })
self.ws.address = function () { this.ws.address = () => {
return self.http.address() return this.http.address()
} }
self.ws.on('error', function (err) { self._onError(err) }) this.ws.on('error', err => { this._onError(err) })
self.ws.on('connection', function (socket, req) { this.ws.on('connection', (socket, req) => {
// Note: socket.upgradeReq was removed in ws@3.0.0, so re-add it. // Note: socket.upgradeReq was removed in ws@3.0.0, so re-add it.
// https://github.com/websockets/ws/pull/1099 // https://github.com/websockets/ws/pull/1099
socket.upgradeReq = req socket.upgradeReq = req
self.onWebSocketConnection(socket) this.onWebSocketConnection(socket)
}) })
} }
if (opts.stats !== false) { if (opts.stats !== false) {
if (!self.http) { if (!this.http) {
self.http = http.createServer() this.http = http.createServer()
self.http.on('error', function (err) { self._onError(err) }) this.http.on('error', err => { this._onError(err) })
self.http.on('listening', onListening) this.http.on('listening', onListening)
} }
// Http handler for '/stats' route // Http handler for '/stats' route
self.http.on('request', function (req, res) { this.http.on('request', (req, res) => {
if (res.headersSent) return if (res.headersSent) return
var infoHashes = Object.keys(self.torrents) const infoHashes = Object.keys(this.torrents)
var activeTorrents = 0 let activeTorrents = 0
var allPeers = {} const allPeers = {}
function countPeers (filterFunction) { function countPeers (filterFunction) {
var count = 0 let count = 0
var key let key
for (key in allPeers) { for (key in allPeers) {
if (allPeers.hasOwnProperty(key) && filterFunction(allPeers[key])) { if (allPeers.hasOwnProperty(key) && filterFunction(allPeers[key])) {
@ -164,17 +156,17 @@ function Server (opts) {
} }
function groupByClient () { function groupByClient () {
var clients = {} const clients = {}
for (var key in allPeers) { for (const key in allPeers) {
if (allPeers.hasOwnProperty(key)) { if (allPeers.hasOwnProperty(key)) {
var peer = allPeers[key] const peer = allPeers[key]
if (!clients[peer.client.client]) { if (!clients[peer.client.client]) {
clients[peer.client.client] = {} clients[peer.client.client] = {}
} }
var client = clients[peer.client.client] const client = clients[peer.client.client]
// If the client is not known show 8 chars from peerId as version // If the client is not known show 8 chars from peerId as version
var version = peer.client.version || Buffer.from(peer.peerId, 'hex').toString().substring(0, 8) const version = peer.client.version || Buffer.from(peer.peerId, 'hex').toString().substring(0, 8)
if (!client[version]) { if (!client[version]) {
client[version] = 0 client[version] = 0
} }
@ -185,13 +177,13 @@ function Server (opts) {
} }
function printClients (clients) { function printClients (clients) {
var html = '<ul>\n' let html = '<ul>\n'
for (var name in clients) { for (const name in clients) {
if (clients.hasOwnProperty(name)) { if (clients.hasOwnProperty(name)) {
var client = clients[name] const client = clients[name]
for (var version in client) { for (const version in client) {
if (client.hasOwnProperty(version)) { if (client.hasOwnProperty(version)) {
html += '<li><strong>' + name + '</strong> ' + version + ' : ' + client[version] + '</li>\n' html += `<li><strong>${name}</strong> ${version} : ${client[version]}</li>\n`
} }
} }
} }
@ -201,14 +193,14 @@ function Server (opts) {
} }
if (req.method === 'GET' && (req.url === '/stats' || req.url === '/stats.json')) { if (req.method === 'GET' && (req.url === '/stats' || req.url === '/stats.json')) {
infoHashes.forEach(function (infoHash) { infoHashes.forEach(infoHash => {
var peers = self.torrents[infoHash].peers const peers = this.torrents[infoHash].peers
var keys = peers.keys const keys = peers.keys
if (keys.length > 0) activeTorrents++ if (keys.length > 0) activeTorrents++
keys.forEach(function (peerId) { keys.forEach(peerId => {
// Don't mark the peer as most recently used for stats // Don't mark the peer as most recently used for stats
var peer = peers.peek(peerId) const peer = peers.peek(peerId)
if (peer == null) return // peers.peek() can evict the peer if (peer == null) return // peers.peek() can evict the peer
if (!allPeers.hasOwnProperty(peerId)) { if (!allPeers.hasOwnProperty(peerId)) {
@ -220,7 +212,7 @@ function Server (opts) {
} }
} }
if (peer.ip.indexOf(':') >= 0) { if (peer.ip.includes(':')) {
allPeers[peerId].ipv6 = true allPeers[peerId].ipv6 = true
} else { } else {
allPeers[peerId].ipv4 = true allPeers[peerId].ipv4 = true
@ -237,15 +229,15 @@ function Server (opts) {
}) })
}) })
var isSeederOnly = function (peer) { return peer.seeder && peer.leecher === false } const isSeederOnly = peer => { return peer.seeder && peer.leecher === false }
var isLeecherOnly = function (peer) { return peer.leecher && peer.seeder === false } const isLeecherOnly = peer => { return peer.leecher && peer.seeder === false }
var isSeederAndLeecher = function (peer) { return peer.seeder && peer.leecher } const isSeederAndLeecher = peer => { return peer.seeder && peer.leecher }
var isIPv4 = function (peer) { return peer.ipv4 } const isIPv4 = peer => { return peer.ipv4 }
var isIPv6 = function (peer) { return peer.ipv6 } const isIPv6 = peer => { return peer.ipv6 }
var stats = { const stats = {
torrents: infoHashes.length, torrents: infoHashes.length,
activeTorrents: activeTorrents, activeTorrents,
peersAll: Object.keys(allPeers).length, peersAll: Object.keys(allPeers).length,
peersSeederOnly: countPeers(isSeederOnly), peersSeederOnly: countPeers(isSeederOnly),
peersLeecherOnly: countPeers(isLeecherOnly), peersLeecherOnly: countPeers(isLeecherOnly),
@ -259,22 +251,24 @@ function Server (opts) {
res.write(JSON.stringify(stats)) res.write(JSON.stringify(stats))
res.end() res.end()
} else if (req.url === '/stats') { } else if (req.url === '/stats') {
res.end('<h1>' + stats.torrents + ' torrents (' + stats.activeTorrents + ' active)</h1>\n' + res.end(`
'<h2>Connected Peers: ' + stats.peersAll + '</h2>\n' + <h1>${stats.torrents} torrents (${stats.activeTorrents} active)</h1>
'<h3>Peers Seeding Only: ' + stats.peersSeederOnly + '</h3>\n' + <h2>Connected Peers: ${stats.peersAll}</h2>
'<h3>Peers Leeching Only: ' + stats.peersLeecherOnly + '</h3>\n' + <h3>Peers Seeding Only: ${stats.peersSeederOnly}</h3>
'<h3>Peers Seeding & Leeching: ' + stats.peersSeederAndLeecher + '</h3>\n' + <h3>Peers Leeching Only: ${stats.peersLeecherOnly}</h3>
'<h3>IPv4 Peers: ' + stats.peersIPv4 + '</h3>\n' + <h3>Peers Seeding & Leeching: ${stats.peersSeederAndLeecher}</h3>
'<h3>IPv6 Peers: ' + stats.peersIPv6 + '</h3>\n' + <h3>IPv4 Peers: ${stats.peersIPv4}</h3>
'<h3>Clients:</h3>\n' + <h3>IPv6 Peers: ${stats.peersIPv6}</h3>
printClients(stats.clients) <h3>Clients:</h3>
) ${printClients(stats.clients)}
`.replace(/^\s+/gm, '')) // trim left
} }
} }
}) })
} }
var num = !!self.http + !!self.udp4 + !!self.udp6 let num = !!this.http + !!this.udp4 + !!this.udp6
const self = this
function onListening () { function onListening () {
num -= 1 num -= 1
if (num === 0) { if (num === 0) {
@ -283,26 +277,21 @@ function Server (opts) {
self.emit('listening') self.emit('listening')
} }
} }
} }
Server.Swarm = Swarm _onError (err) {
this.emit('error', err)
}
Server.prototype._onError = function (err) { listen (...args) /* port, hostname, onlistening */{
var self = this if (this._listenCalled || this.listening) throw new Error('server already listening')
self.emit('error', err) this._listenCalled = true
}
Server.prototype.listen = function (/* port, hostname, onlistening */) { const lastArg = args[args.length - 1]
var self = this if (typeof lastArg === 'function') this.once('listening', lastArg)
if (self._listenCalled || self.listening) throw new Error('server already listening') const port = toNumber(args[0]) || args[0] || 0
self._listenCalled = true const hostname = typeof args[1] !== 'function' ? args[1] : undefined
var lastArg = arguments[arguments.length - 1]
if (typeof lastArg === 'function') self.once('listening', lastArg)
var port = toNumber(arguments[0]) || arguments[0] || 0
var hostname = typeof arguments[1] !== 'function' ? arguments[1] : undefined
debug('listen (port: %o hostname: %o)', port, hostname) debug('listen (port: %o hostname: %o)', port, hostname)
@ -310,75 +299,69 @@ Server.prototype.listen = function (/* port, hostname, onlistening */) {
return typeof obj === 'object' && obj !== null return typeof obj === 'object' && obj !== null
} }
var httpPort = isObject(port) ? (port.http || 0) : port const httpPort = isObject(port) ? (port.http || 0) : port
var udpPort = isObject(port) ? (port.udp || 0) : port const udpPort = isObject(port) ? (port.udp || 0) : port
// binding to :: only receives IPv4 connections if the bindv6only sysctl is set 0, // binding to :: only receives IPv4 connections if the bindv6only sysctl is set 0,
// which is the default on many operating systems // which is the default on many operating systems
var httpHostname = isObject(hostname) ? hostname.http : hostname const httpHostname = isObject(hostname) ? hostname.http : hostname
var udp4Hostname = isObject(hostname) ? hostname.udp : hostname const udp4Hostname = isObject(hostname) ? hostname.udp : hostname
var udp6Hostname = isObject(hostname) ? hostname.udp6 : hostname const udp6Hostname = isObject(hostname) ? hostname.udp6 : hostname
if (self.http) self.http.listen(httpPort, httpHostname) if (this.http) this.http.listen(httpPort, httpHostname)
if (self.udp4) self.udp4.bind(udpPort, udp4Hostname) if (this.udp4) this.udp4.bind(udpPort, udp4Hostname)
if (self.udp6) self.udp6.bind(udpPort, udp6Hostname) if (this.udp6) this.udp6.bind(udpPort, udp6Hostname)
} }
Server.prototype.close = function (cb) { close (cb = noop) {
var self = this
if (!cb) cb = noop
debug('close') debug('close')
self.listening = false this.listening = false
self.destroyed = true this.destroyed = true
if (self.udp4) { if (this.udp4) {
try { try {
self.udp4.close() this.udp4.close()
} catch (err) {} } catch (err) {}
} }
if (self.udp6) { if (this.udp6) {
try { try {
self.udp6.close() this.udp6.close()
} catch (err) {} } catch (err) {}
} }
if (self.ws) { if (this.ws) {
try { try {
self.ws.close() this.ws.close()
} catch (err) {} } catch (err) {}
} }
if (self.http) self.http.close(cb) if (this.http) this.http.close(cb)
else cb(null) else cb(null)
} }
Server.prototype.createSwarm = function (infoHash, cb) { createSwarm (infoHash, cb) {
var self = this
if (Buffer.isBuffer(infoHash)) infoHash = infoHash.toString('hex') if (Buffer.isBuffer(infoHash)) infoHash = infoHash.toString('hex')
process.nextTick(function () { process.nextTick(() => {
var swarm = self.torrents[infoHash] = new Server.Swarm(infoHash, self) const swarm = this.torrents[infoHash] = new Server.Swarm(infoHash, this)
cb(null, swarm) cb(null, swarm)
}) })
} }
Server.prototype.getSwarm = function (infoHash, cb) { getSwarm (infoHash, cb) {
var self = this
if (Buffer.isBuffer(infoHash)) infoHash = infoHash.toString('hex') if (Buffer.isBuffer(infoHash)) infoHash = infoHash.toString('hex')
process.nextTick(function () { process.nextTick(() => {
cb(null, self.torrents[infoHash]) cb(null, this.torrents[infoHash])
}) })
} }
Server.prototype.onHttpRequest = function (req, res, opts) { onHttpRequest (req, res, opts = {}) {
var self = this opts.trustProxy = opts.trustProxy || this._trustProxy
if (!opts) opts = {}
opts.trustProxy = opts.trustProxy || self._trustProxy
var params let params
try { try {
params = parseHttpRequest(req, opts) params = parseHttpRequest(req, opts)
params.httpReq = req params.httpReq = req
@ -390,98 +373,92 @@ Server.prototype.onHttpRequest = function (req, res, opts) {
// even though it's an error for the client, it's just a warning for the server. // even though it's an error for the client, it's just a warning for the server.
// don't crash the server because a client sent bad data :) // don't crash the server because a client sent bad data :)
self.emit('warning', err) this.emit('warning', err)
return return
} }
self._onRequest(params, function (err, response) { this._onRequest(params, (err, response) => {
if (err) { if (err) {
self.emit('warning', err) this.emit('warning', err)
response = { response = {
'failure reason': err.message 'failure reason': err.message
} }
} }
if (self.destroyed) return res.end() if (this.destroyed) return res.end()
delete response.action // only needed for UDP encoding delete response.action // only needed for UDP encoding
res.end(bencode.encode(response)) res.end(bencode.encode(response))
if (params.action === common.ACTIONS.ANNOUNCE) { if (params.action === common.ACTIONS.ANNOUNCE) {
self.emit(common.EVENT_NAMES[params.event], params.addr, params) this.emit(common.EVENT_NAMES[params.event], params.addr, params)
} }
}) })
} }
Server.prototype.onUdpRequest = function (msg, rinfo) { onUdpRequest (msg, rinfo) {
var self = this let params
var params
try { try {
params = parseUdpRequest(msg, rinfo) params = parseUdpRequest(msg, rinfo)
} catch (err) { } catch (err) {
self.emit('warning', err) this.emit('warning', err)
// Do not reply for parsing errors // Do not reply for parsing errors
return return
} }
self._onRequest(params, function (err, response) { this._onRequest(params, (err, response) => {
if (err) { if (err) {
self.emit('warning', err) this.emit('warning', err)
response = { response = {
action: common.ACTIONS.ERROR, action: common.ACTIONS.ERROR,
'failure reason': err.message 'failure reason': err.message
} }
} }
if (self.destroyed) return if (this.destroyed) return
response.transactionId = params.transactionId response.transactionId = params.transactionId
response.connectionId = params.connectionId response.connectionId = params.connectionId
var buf = makeUdpPacket(response) const buf = makeUdpPacket(response)
try { try {
var udp = (rinfo.family === 'IPv4') ? self.udp4 : self.udp6 const udp = (rinfo.family === 'IPv4') ? this.udp4 : this.udp6
udp.send(buf, 0, buf.length, rinfo.port, rinfo.address) udp.send(buf, 0, buf.length, rinfo.port, rinfo.address)
} catch (err) { } catch (err) {
self.emit('warning', err) this.emit('warning', err)
} }
if (params.action === common.ACTIONS.ANNOUNCE) { if (params.action === common.ACTIONS.ANNOUNCE) {
self.emit(common.EVENT_NAMES[params.event], params.addr, params) this.emit(common.EVENT_NAMES[params.event], params.addr, params)
} }
}) })
} }
Server.prototype.onWebSocketConnection = function (socket, opts) { onWebSocketConnection (socket, opts = {}) {
var self = this opts.trustProxy = opts.trustProxy || this._trustProxy
if (!opts) opts = {}
opts.trustProxy = opts.trustProxy || self._trustProxy
socket.peerId = null // as hex socket.peerId = null // as hex
socket.infoHashes = [] // swarms that this socket is participating in socket.infoHashes = [] // swarms that this socket is participating in
socket.onSend = function (err) { socket.onSend = err => {
self._onWebSocketSend(socket, err) this._onWebSocketSend(socket, err)
} }
socket.onMessageBound = function (params) { socket.onMessageBound = params => {
self._onWebSocketRequest(socket, opts, params) this._onWebSocketRequest(socket, opts, params)
} }
socket.on('message', socket.onMessageBound) socket.on('message', socket.onMessageBound)
socket.onErrorBound = function (err) { socket.onErrorBound = err => {
self._onWebSocketError(socket, err) this._onWebSocketError(socket, err)
} }
socket.on('error', socket.onErrorBound) socket.on('error', socket.onErrorBound)
socket.onCloseBound = function () { socket.onCloseBound = () => {
self._onWebSocketClose(socket) this._onWebSocketClose(socket)
} }
socket.on('close', socket.onCloseBound) socket.on('close', socket.onCloseBound)
} }
Server.prototype._onWebSocketRequest = function (socket, opts, params) {
var self = this
_onWebSocketRequest (socket, opts, params) {
try { try {
params = parseWebSocketRequest(socket, opts, params) params = parseWebSocketRequest(socket, opts, params)
} catch (err) { } catch (err) {
@ -491,14 +468,14 @@ Server.prototype._onWebSocketRequest = function (socket, opts, params) {
// even though it's an error for the client, it's just a warning for the server. // even though it's an error for the client, it's just a warning for the server.
// don't crash the server because a client sent bad data :) // don't crash the server because a client sent bad data :)
self.emit('warning', err) this.emit('warning', err)
return return
} }
if (!socket.peerId) socket.peerId = params.peer_id // as hex if (!socket.peerId) socket.peerId = params.peer_id // as hex
self._onRequest(params, function (err, response) { this._onRequest(params, (err, response) => {
if (self.destroyed || socket.destroyed) return if (this.destroyed || socket.destroyed) return
if (err) { if (err) {
socket.send(JSON.stringify({ socket.send(JSON.stringify({
action: params.action === common.ACTIONS.ANNOUNCE ? 'announce' : 'scrape', action: params.action === common.ACTIONS.ANNOUNCE ? 'announce' : 'scrape',
@ -506,25 +483,25 @@ Server.prototype._onWebSocketRequest = function (socket, opts, params) {
info_hash: common.hexToBinary(params.info_hash) info_hash: common.hexToBinary(params.info_hash)
}), socket.onSend) }), socket.onSend)
self.emit('warning', err) this.emit('warning', err)
return return
} }
response.action = params.action === common.ACTIONS.ANNOUNCE ? 'announce' : 'scrape' response.action = params.action === common.ACTIONS.ANNOUNCE ? 'announce' : 'scrape'
var peers let peers
if (response.action === 'announce') { if (response.action === 'announce') {
peers = response.peers peers = response.peers
delete response.peers delete response.peers
if (socket.infoHashes.indexOf(params.info_hash) === -1) { if (!socket.infoHashes.includes(params.info_hash)) {
socket.infoHashes.push(params.info_hash) socket.infoHashes.push(params.info_hash)
} }
response.info_hash = common.hexToBinary(params.info_hash) response.info_hash = common.hexToBinary(params.info_hash)
// WebSocket tracker should have a shorter interval default: 2 minutes // WebSocket tracker should have a shorter interval default: 2 minutes
response.interval = Math.ceil(self.intervalMs / 1000 / 5) response.interval = Math.ceil(this.intervalMs / 1000 / 5)
} }
// Skip sending update back for 'answer' announce messages not needed // Skip sending update back for 'answer' announce messages not needed
@ -536,7 +513,7 @@ Server.prototype._onWebSocketRequest = function (socket, opts, params) {
if (Array.isArray(params.offers)) { if (Array.isArray(params.offers)) {
debug('got %s offers from %s', params.offers.length, params.peer_id) debug('got %s offers from %s', params.offers.length, params.peer_id)
debug('got %s peers from swarm %s', peers.length, params.info_hash) debug('got %s peers from swarm %s', peers.length, params.info_hash)
peers.forEach(function (peer, i) { peers.forEach((peer, i) => {
peer.socket.send(JSON.stringify({ peer.socket.send(JSON.stringify({
action: 'announce', action: 'announce',
offer: params.offers[i].offer, offer: params.offers[i].offer,
@ -548,19 +525,26 @@ Server.prototype._onWebSocketRequest = function (socket, opts, params) {
}) })
} }
const done = () => {
// emit event once the announce is fully "processed"
if (params.action === common.ACTIONS.ANNOUNCE) {
this.emit(common.EVENT_NAMES[params.event], params.peer_id, params)
}
}
if (params.answer) { if (params.answer) {
debug('got answer %s from %s', JSON.stringify(params.answer), params.peer_id) debug('got answer %s from %s', JSON.stringify(params.answer), params.peer_id)
self.getSwarm(params.info_hash, function (err, swarm) { this.getSwarm(params.info_hash, (err, swarm) => {
if (self.destroyed) return if (this.destroyed) return
if (err) return self.emit('warning', err) if (err) return this.emit('warning', err)
if (!swarm) { if (!swarm) {
return self.emit('warning', new Error('no swarm with that `info_hash`')) return this.emit('warning', new Error('no swarm with that `info_hash`'))
} }
// Mark the destination peer as recently used in cache // Mark the destination peer as recently used in cache
var toPeer = swarm.peers.get(params.to_peer_id) const toPeer = swarm.peers.get(params.to_peer_id)
if (!toPeer) { if (!toPeer) {
return self.emit('warning', new Error('no peer with that `to_peer_id`')) return this.emit('warning', new Error('no peer with that `to_peer_id`'))
} }
toPeer.socket.send(JSON.stringify({ toPeer.socket.send(JSON.stringify({
@ -577,29 +561,20 @@ Server.prototype._onWebSocketRequest = function (socket, opts, params) {
} else { } else {
done() done()
} }
function done () {
// emit event once the announce is fully "processed"
if (params.action === common.ACTIONS.ANNOUNCE) {
self.emit(common.EVENT_NAMES[params.event], params.peer_id, params)
}
}
}) })
} }
Server.prototype._onWebSocketSend = function (socket, err) { _onWebSocketSend (socket, err) {
var self = this if (err) this._onWebSocketError(socket, err)
if (err) self._onWebSocketError(socket, err) }
}
Server.prototype._onWebSocketClose = function (socket) { _onWebSocketClose (socket) {
var self = this
debug('websocket close %s', socket.peerId) debug('websocket close %s', socket.peerId)
socket.destroyed = true socket.destroyed = true
if (socket.peerId) { if (socket.peerId) {
socket.infoHashes.slice(0).forEach(function (infoHash) { socket.infoHashes.slice(0).forEach(infoHash => {
var swarm = self.torrents[infoHash] const swarm = this.torrents[infoHash]
if (swarm) { if (swarm) {
swarm.announce({ swarm.announce({
type: 'ws', type: 'ws',
@ -632,43 +607,41 @@ Server.prototype._onWebSocketClose = function (socket) {
socket.removeListener('close', socket.onCloseBound) socket.removeListener('close', socket.onCloseBound)
} }
socket.onCloseBound = null socket.onCloseBound = null
} }
Server.prototype._onWebSocketError = function (socket, err) { _onWebSocketError (socket, err) {
var self = this
debug('websocket error %s', err.message || err) debug('websocket error %s', err.message || err)
self.emit('warning', err) this.emit('warning', err)
self._onWebSocketClose(socket) this._onWebSocketClose(socket)
} }
Server.prototype._onRequest = function (params, cb) { _onRequest (params, cb) {
var self = this
if (params && params.action === common.ACTIONS.CONNECT) { if (params && params.action === common.ACTIONS.CONNECT) {
cb(null, { action: common.ACTIONS.CONNECT }) cb(null, { action: common.ACTIONS.CONNECT })
} else if (params && params.action === common.ACTIONS.ANNOUNCE) { } else if (params && params.action === common.ACTIONS.ANNOUNCE) {
self._onAnnounce(params, cb) this._onAnnounce(params, cb)
} else if (params && params.action === common.ACTIONS.SCRAPE) { } else if (params && params.action === common.ACTIONS.SCRAPE) {
self._onScrape(params, cb) this._onScrape(params, cb)
} else { } else {
cb(new Error('Invalid action')) cb(new Error('Invalid action'))
} }
} }
Server.prototype._onAnnounce = function (params, cb) { _onAnnounce (params, cb) {
var self = this const self = this
if (self._filter) { if (this._filter) {
self._filter(params.info_hash, params, function (err) { this._filter(params.info_hash, params, err => {
// Presence of `err` means that this announce request is disallowed // Presence of `err` means that this announce request is disallowed
if (err) return cb(err) if (err) return cb(err)
getOrCreateSwarm(function (err, swarm) { getOrCreateSwarm((err, swarm) => {
if (err) return cb(err) if (err) return cb(err)
announce(swarm) announce(swarm)
}) })
}) })
} else { } else {
getOrCreateSwarm(function (err, swarm) { getOrCreateSwarm((err, swarm) => {
if (err) return cb(err) if (err) return cb(err)
announce(swarm) announce(swarm)
}) })
@ -676,10 +649,10 @@ Server.prototype._onAnnounce = function (params, cb) {
// Get existing swarm, or create one if one does not exist // Get existing swarm, or create one if one does not exist
function getOrCreateSwarm (cb) { function getOrCreateSwarm (cb) {
self.getSwarm(params.info_hash, function (err, swarm) { self.getSwarm(params.info_hash, (err, swarm) => {
if (err) return cb(err) if (err) return cb(err)
if (swarm) return cb(null, swarm) if (swarm) return cb(null, swarm)
self.createSwarm(params.info_hash, function (err, swarm) { self.createSwarm(params.info_hash, (err, swarm) => {
if (err) return cb(err) if (err) return cb(err)
cb(null, swarm) cb(null, swarm)
}) })
@ -688,30 +661,30 @@ Server.prototype._onAnnounce = function (params, cb) {
function announce (swarm) { function announce (swarm) {
if (!params.event || params.event === 'empty') params.event = 'update' if (!params.event || params.event === 'empty') params.event = 'update'
swarm.announce(params, function (err, response) { swarm.announce(params, (err, response) => {
if (err) return cb(err) if (err) return cb(err)
if (!response.action) response.action = common.ACTIONS.ANNOUNCE if (!response.action) response.action = common.ACTIONS.ANNOUNCE
if (!response.interval) response.interval = Math.ceil(self.intervalMs / 1000) if (!response.interval) response.interval = Math.ceil(self.intervalMs / 1000)
if (params.compact === 1) { if (params.compact === 1) {
var peers = response.peers const peers = response.peers
// Find IPv4 peers // Find IPv4 peers
response.peers = string2compact(peers.filter(function (peer) { response.peers = string2compact(peers.filter(peer => {
return common.IPV4_RE.test(peer.ip) return common.IPV4_RE.test(peer.ip)
}).map(function (peer) { }).map(peer => {
return peer.ip + ':' + peer.port return `${peer.ip}:${peer.port}`
})) }))
// Find IPv6 peers // Find IPv6 peers
response.peers6 = string2compact(peers.filter(function (peer) { response.peers6 = string2compact(peers.filter(peer => {
return common.IPV6_RE.test(peer.ip) return common.IPV6_RE.test(peer.ip)
}).map(function (peer) { }).map(peer => {
return '[' + peer.ip + ']:' + peer.port return `[${peer.ip}]:${peer.port}`
})) }))
} else if (params.compact === 0) { } else if (params.compact === 0) {
// IPv6 peers are not separate for non-compact responses // IPv6 peers are not separate for non-compact responses
response.peers = response.peers.map(function (peer) { response.peers = response.peers.map(peer => {
return { return {
'peer id': common.hexToBinary(peer.peerId), 'peer id': common.hexToBinary(peer.peerId),
ip: peer.ip, ip: peer.ip,
@ -723,45 +696,43 @@ Server.prototype._onAnnounce = function (params, cb) {
cb(null, response) cb(null, response)
}) })
} }
} }
Server.prototype._onScrape = function (params, cb) {
var self = this
_onScrape (params, cb) {
if (params.info_hash == null) { if (params.info_hash == null) {
// if info_hash param is omitted, stats for all torrents are returned // if info_hash param is omitted, stats for all torrents are returned
// TODO: make this configurable! // TODO: make this configurable!
params.info_hash = Object.keys(self.torrents) params.info_hash = Object.keys(this.torrents)
} }
series(params.info_hash.map(function (infoHash) { series(params.info_hash.map(infoHash => {
return function (cb) { return cb => {
self.getSwarm(infoHash, function (err, swarm) { this.getSwarm(infoHash, (err, swarm) => {
if (err) return cb(err) if (err) return cb(err)
if (swarm) { if (swarm) {
swarm.scrape(params, function (err, scrapeInfo) { swarm.scrape(params, (err, scrapeInfo) => {
if (err) return cb(err) if (err) return cb(err)
cb(null, { cb(null, {
infoHash: infoHash, infoHash,
complete: (scrapeInfo && scrapeInfo.complete) || 0, complete: (scrapeInfo && scrapeInfo.complete) || 0,
incomplete: (scrapeInfo && scrapeInfo.incomplete) || 0 incomplete: (scrapeInfo && scrapeInfo.incomplete) || 0
}) })
}) })
} else { } else {
cb(null, { infoHash: infoHash, complete: 0, incomplete: 0 }) cb(null, { infoHash, complete: 0, incomplete: 0 })
} }
}) })
} }
}), function (err, results) { }), (err, results) => {
if (err) return cb(err) if (err) return cb(err)
var response = { const response = {
action: common.ACTIONS.SCRAPE, action: common.ACTIONS.SCRAPE,
files: {}, files: {},
flags: { min_request_interval: Math.ceil(self.intervalMs / 1000) } flags: { min_request_interval: Math.ceil(this.intervalMs / 1000) }
} }
results.forEach(function (result) { results.forEach(result => {
response.files[common.hexToBinary(result.infoHash)] = { response.files[common.hexToBinary(result.infoHash)] = {
complete: result.complete || 0, complete: result.complete || 0,
incomplete: result.incomplete || 0, incomplete: result.incomplete || 0,
@ -771,10 +742,13 @@ Server.prototype._onScrape = function (params, cb) {
cb(null, response) cb(null, response)
}) })
}
} }
Server.Swarm = Swarm
function makeUdpPacket (params) { function makeUdpPacket (params) {
var packet let packet
switch (params.action) { switch (params.action) {
case common.ACTIONS.CONNECT: case common.ACTIONS.CONNECT:
packet = Buffer.concat([ packet = Buffer.concat([
@ -794,12 +768,12 @@ function makeUdpPacket (params) {
]) ])
break break
case common.ACTIONS.SCRAPE: case common.ACTIONS.SCRAPE:
var scrapeResponse = [ const scrapeResponse = [
common.toUInt32(common.ACTIONS.SCRAPE), common.toUInt32(common.ACTIONS.SCRAPE),
common.toUInt32(params.transactionId) common.toUInt32(params.transactionId)
] ]
for (var infoHash in params.files) { for (const infoHash in params.files) {
var file = params.files[infoHash] const file = params.files[infoHash]
scrapeResponse.push( scrapeResponse.push(
common.toUInt32(file.complete), common.toUInt32(file.complete),
common.toUInt32(file.downloaded), // TODO: this only provides a lower-bound common.toUInt32(file.downloaded), // TODO: this only provides a lower-bound
@ -816,7 +790,7 @@ function makeUdpPacket (params) {
]) ])
break break
default: default:
throw new Error('Action not implemented: ' + params.action) throw new Error(`Action not implemented: ${params.action}`)
} }
return packet return packet
} }
@ -827,3 +801,5 @@ function toNumber (x) {
} }
function noop () {} function noop () {}
module.exports = Server