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'
8 import { VideoFileModel } from '../models/video/video-file'
10 const TrackerServer = bitTorrentTracker.Server
12 const trackerRouter = express.Router()
15 let peersIpInfoHash = {}
18 const trackerServer = new TrackerServer({
23 filter: function (infoHash, params, cb) {
26 if (params.type === 'ws') {
29 ip = params.httpReq.ip
32 const key = ip + '-' + infoHash
34 peersIps[ip] = peersIps[ip] ? peersIps[ip] + 1 : 1
35 peersIpInfoHash[key] = peersIpInfoHash[key] ? peersIpInfoHash[key] + 1 : 1
37 if (peersIpInfoHash[key] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP_PER_INFOHASH) {
38 return cb(new Error(`Too many requests (${peersIpInfoHash[ key ]} of ip ${ip} for torrent ${infoHash}`))
41 VideoFileModel.isInfohashExists(infoHash)
43 if (exists === false) return cb(new Error(`Unknown infoHash ${infoHash}`))
50 trackerServer.on('error', function (err) {
51 logger.error('Error in tracker.', { err })
54 trackerServer.on('warning', function (err) {
55 logger.warn('Warning in tracker.', { err })
58 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
59 trackerRouter.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
60 trackerRouter.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
62 function createWebsocketServer (app: express.Application) {
63 const server = http.createServer(app)
64 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
65 wss.on('connection', function (ws, req) {
66 const ip = proxyAddr(req, CONFIG.TRUST_PROXY)
69 trackerServer.onWebSocketConnection(ws)
75 // ---------------------------------------------------------------------------
82 // ---------------------------------------------------------------------------
84 function runPeersChecker () {
86 logger.debug('Checking peers.')
88 for (const ip of Object.keys(peersIpInfoHash)) {
89 if (peersIps[ip] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP) {
90 logger.warn('Peer %s made abnormal requests (%d).', ip, peersIps[ip])
96 }, TRACKER_RATE_LIMITS.INTERVAL)