forked from webtorrent/bittorrent-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
316 lines (278 loc) · 9.24 KB
/
server.js
File metadata and controls
316 lines (278 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
module.exports = Server
var bencode = require('bencode')
var debug = require('debug')('bittorrent-tracker')
var dgram = require('dgram')
var EventEmitter = require('events').EventEmitter
var http = require('http')
var inherits = require('inherits')
var portfinder = require('portfinder')
var series = require('run-series')
var string2compact = require('string2compact')
var common = require('./lib/common')
var Swarm = require('./lib/swarm')
var parseHttpRequest = require('./lib/parse_http')
var parseUdpRequest = require('./lib/parse_udp')
// Use random port above 1024
portfinder.basePort = Math.floor(Math.random() * 60000) + 1025
inherits(Server, EventEmitter)
/**
* A BitTorrent tracker server.
*
* A "BitTorrent tracker" is an HTTP service which responds to GET requests from
* BitTorrent clients. The requests include metrics from clients that help the tracker
* keep overall statistics about the torrent. The response includes a peer list that
* helps the client participate in the torrent.
*
* @param {Object} opts options
* @param {Number} opts.interval interval in ms that clients should announce on
* @param {Number} opts.trustProxy Trust 'x-forwarded-for' header from reverse proxy
* @param {boolean} opts.http Start an http server? (default: true)
* @param {boolean} opts.udp Start a udp server? (default: true)
*/
function Server (opts) {
var self = this
if (!(self instanceof Server)) return new Server(opts)
EventEmitter.call(self)
opts = opts || {}
self._intervalMs = opts.interval
? opts.interval / 1000
: 10 * 60 // 10 min (in secs)
self._trustProxy = !!opts.trustProxy
self.listening = false
self.port = null
self.torrents = {}
// default to starting an http server unless the user explictly says no
if (opts.http !== false) {
self._httpServer = http.createServer()
self._httpServer.on('request', self.onHttpRequest.bind(self))
self._httpServer.on('error', self._onError.bind(self))
self._httpServer.on('listening', onListening)
}
// default to starting a udp server unless the user explicitly says no
if (opts.udp !== false) {
self._udpSocket = dgram.createSocket('udp4')
self._udpSocket.on('message', self.onUdpRequest.bind(self))
self._udpSocket.on('error', self._onError.bind(self))
self._udpSocket.on('listening', onListening)
}
var num = !!self._httpServer + !!self._udpSocket
function onListening () {
num -= 1
if (num === 0) {
self.listening = true
self.emit('listening', self.port)
}
}
}
Server.prototype._onError = function (err) {
var self = this
self.emit('error', err)
}
Server.prototype.listen = function (port, onlistening) {
var self = this
if (typeof port === 'function') {
onlistening = port
port = undefined
}
if (self.listening) throw new Error('server already listening')
if (onlistening) self.once('listening', onlistening)
function onPort (err, port) {
if (err) return self.emit('error', err)
self.port = port
// ATTENTION:
// binding to :: only receives IPv4 connections if the bindv6only
// sysctl is set 0, which is the default on many operating systems.
self._httpServer && self._httpServer.listen(port.http || port, '::')
self._udpSocket && self._udpSocket.bind(port.udp || port)
}
if (port) onPort(null, port)
else portfinder.getPort(onPort)
}
Server.prototype.close = function (cb) {
var self = this
cb = cb || function () {}
if (self._udpSocket) {
self._udpSocket.close()
}
if (self._httpServer) {
self._httpServer.close(cb)
} else {
cb(null)
}
}
Server.prototype.getSwarm = function (infoHash) {
var self = this
if (Buffer.isBuffer(infoHash)) infoHash = infoHash.toString('hex')
var swarm = self.torrents[infoHash]
if (!swarm) swarm = self.torrents[infoHash] = new Swarm(infoHash, this)
return swarm
}
Server.prototype.onHttpRequest = function (req, res) {
var self = this
var params
try {
params = parseHttpRequest(req, { trustProxy: self._trustProxy })
} catch (err) {
debug('sent error %s', err.message)
res.end(bencode.encode({
'failure reason': err.message
}))
// 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 :)
self.emit('warning', err)
return
}
this._onRequest(params, function (err, response) {
if (err) {
self.emit('warning', err)
response = {
'failure reason': err.message
}
}
delete response.action // only needed for UDP encoding
res.end(bencode.encode(response))
})
}
Server.prototype.onUdpRequest = function (msg, rinfo) {
var self = this
var params
try {
params = parseUdpRequest(msg, rinfo)
} catch (err) {
self.emit('warning', err)
// Do not reply for parsing errors
return
}
// Handle
this._onRequest(params, function (err, response) {
if (err) {
self.emit('warning', err)
response = {
action: common.ACTIONS.ERRROR,
'failure reason': err.message
}
}
response.transactionId = params.transactionId
response.connectionId = params.connectionId
var buf = makeUdpPacket(response)
self._udpSocket.send(buf, 0, buf.length, rinfo.port, rinfo.address, function () {
try {
socket.close()
} catch (err) {}
})
})
}
Server.prototype._onRequest = function (params, cb) {
if (params && params.action === common.ACTIONS.CONNECT) {
cb(null, { action: common.ACTIONS.CONNECT })
} else if (params && params.action === common.ACTIONS.ANNOUNCE) {
this._onAnnounce(params, cb)
} else if (params && params.action === common.ACTIONS.SCRAPE) {
this._onScrape(params, cb)
} else {
cb(new Error('Invalid action'))
}
}
Server.prototype._onAnnounce = function (params, cb) {
var self = this
var swarm = self.getSwarm(params.info_hash)
swarm.announce(params, function (err, response) {
if (response) {
if (!response.action) response.action = common.ACTIONS.ANNOUNCE
if (!response.intervalMs) response.intervalMs = self._intervalMs
if (params.compact === 1) {
var peers = response.peers
// Find IPv4 peers
response.peers = string2compact(peers.filter(function (peer) {
return common.IPV4_RE.test(peer.ip)
}).map(function (peer) {
return peer.ip + ':' + peer.port
}))
// Find IPv6 peers
response.peers6 = string2compact(peers.filter(function (peer) {
return common.IPV6_RE.test(peer.ip)
}).map(function (peer) {
return '[' + peer.ip + ']:' + peer.port
}))
}
// IPv6 peers are not separate for non-compact responses
}
cb(err, response)
})
}
Server.prototype._onScrape = function (params, cb) {
var self = this
if (params.info_hash == null) {
// if info_hash param is omitted, stats for all torrents are returned
// TODO: make this configurable!
params.info_hash = Object.keys(self.torrents)
}
series(params.info_hash.map(function (infoHash) {
var swarm = self.getSwarm(infoHash)
return function (cb) {
swarm.scrape(params, function (err, scrapeInfo) {
cb(err, scrapeInfo && {
infoHash: infoHash,
complete: scrapeInfo.complete || 0,
incomplete: scrapeInfo.incomplete || 0
})
})
}
}), function (err, results) {
if (err) return cb(err)
var response = {
action: common.ACTIONS.SCRAPE,
files: {},
flags: { min_request_interval: self._intervalMs }
}
results.forEach(function (result) {
response.files[common.hexToBinary(result.infoHash)] = {
complete: result.complete,
incomplete: result.incomplete,
downloaded: result.complete // TODO: this only provides a lower-bound
}
})
cb(null, response)
})
}
function makeUdpPacket (params) {
switch (params.action) {
case common.ACTIONS.CONNECT:
return Buffer.concat([
common.toUInt32(common.ACTIONS.CONNECT),
common.toUInt32(params.transactionId),
params.connectionId
])
case common.ACTIONS.ANNOUNCE:
return Buffer.concat([
common.toUInt32(common.ACTIONS.ANNOUNCE),
common.toUInt32(params.transactionId),
common.toUInt32(params.intervalMs),
common.toUInt32(params.incomplete),
common.toUInt32(params.complete),
params.peers
])
case common.ACTIONS.SCRAPE:
var firstInfoHash = Object.keys(params.files)[0]
var scrapeInfo = firstInfoHash ? {
complete: params.files[firstInfoHash].complete,
incomplete: params.files[firstInfoHash].incomplete,
completed: params.files[firstInfoHash].complete // TODO: this only provides a lower-bound
} : {}
return Buffer.concat([
common.toUInt32(common.ACTIONS.SCRAPE),
common.toUInt32(params.transactionId),
common.toUInt32(scrapeInfo.complete),
common.toUInt32(scrapeInfo.completed),
common.toUInt32(scrapeInfo.incomplete)
])
case common.ACTIONS.ERROR:
return Buffer.concat([
common.toUInt32(common.ACTIONS.ERROR),
common.toUInt32(params.transactionId || 0),
new Buffer(params.message, 'utf8')
])
default:
throw new Error('Action not implemented: ' + params.action)
}
}