1 import { logger } from '../helpers/logger'
2 import * as express from 'express'
3 import * as http from 'http'
4 import * as bitTorrentTracker from 'bittorrent-tracker'
5 import * as proxyAddr from 'proxy-addr'
6 import { Server as WebSocketServer } from 'ws'
7 import { CONFIG, TRACKER_RATE_LIMITS } from '../initializers/constants'
9 const TrackerServer = bitTorrentTracker.Server
11 const trackerRouter = express.Router()
14 let peersIpInfoHash = {}
17 const trackerServer = new TrackerServer({
22 filter: function (infoHash, params, cb) {
25 if (params.type === 'ws') {
28 ip = params.httpReq.ip
31 const key = ip + '-' + infoHash
33 peersIps[ip] = peersIps[ip] ? peersIps[ip] + 1 : 1
34 peersIpInfoHash[key] = peersIpInfoHash[key] ? peersIpInfoHash[key] + 1 : 1
36 if (peersIpInfoHash[key] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP_PER_INFOHASH) {
37 return cb(new Error(`Too many requests (${peersIpInfoHash[ key ]} of ip ${ip} for torrent ${infoHash}`))
44 trackerServer.on('error', function (err) {
45 logger.error('Error in tracker.', { err })
48 trackerServer.on('warning', function (err) {
49 logger.warn('Warning in tracker.', { err })
52 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
53 trackerRouter.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
54 trackerRouter.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
56 function createWebsocketServer (app: express.Application) {
57 const server = http.createServer(app)
58 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
59 wss.on('connection', function (ws, req) {
60 const ip = proxyAddr(req, CONFIG.TRUST_PROXY)
63 trackerServer.onWebSocketConnection(ws)
69 // ---------------------------------------------------------------------------
76 // ---------------------------------------------------------------------------
78 function runPeersChecker () {
80 logger.debug('Checking peers.')
82 for (const ip of Object.keys(peersIpInfoHash)) {
83 if (peersIps[ip] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP) {
84 logger.warn('Peer %s made abnormal requests (%d).', ip, peersIps[ip])
90 }, TRACKER_RATE_LIMITS.INTERVAL)