1 import * as bitTorrentTracker from 'bittorrent-tracker'
2 import * as express from 'express'
3 import * as http from 'http'
4 import * as proxyAddr from 'proxy-addr'
5 import { Server as WebSocketServer } from 'ws'
6 import { Redis } from '@server/lib/redis'
7 import { logger } from '../helpers/logger'
8 import { CONFIG } from '../initializers/config'
9 import { TRACKER_RATE_LIMITS } from '../initializers/constants'
10 import { VideoFileModel } from '../models/video/video-file'
11 import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist'
13 const TrackerServer = bitTorrentTracker.Server
15 const trackerRouter = express.Router()
18 let peersIpInfoHash = {}
21 const trackerServer = new TrackerServer({
26 filter: async function (infoHash, params, cb) {
27 if (CONFIG.TRACKER.ENABLED === false) {
28 return cb(new Error('Tracker is disabled on this instance.'))
33 if (params.type === 'ws') {
36 ip = params.httpReq.ip
39 const key = ip + '-' + infoHash
41 peersIps[ip] = peersIps[ip] ? peersIps[ip] + 1 : 1
42 peersIpInfoHash[key] = peersIpInfoHash[key] ? peersIpInfoHash[key] + 1 : 1
44 if (CONFIG.TRACKER.REJECT_TOO_MANY_ANNOUNCES && peersIpInfoHash[key] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP_PER_INFOHASH) {
45 return cb(new Error(`Too many requests (${peersIpInfoHash[key]} of ip ${ip} for torrent ${infoHash}`))
49 if (CONFIG.TRACKER.PRIVATE === false) return cb()
51 const videoFileExists = await VideoFileModel.doesInfohashExistCached(infoHash)
52 if (videoFileExists === true) return cb()
54 const playlistExists = await VideoStreamingPlaylistModel.doesInfohashExistCached(infoHash)
55 if (playlistExists === true) return cb()
57 cb(new Error(`Unknown infoHash ${infoHash} requested by ip ${ip}`))
59 // Close socket connection and block IP for a few time
60 if (params.type === 'ws') {
61 Redis.Instance.setTrackerBlockIP(ip)
62 .catch(err => logger.error('Cannot set tracker block ip.', { err }))
64 // setTimeout to wait filter response
65 setTimeout(() => params.socket.close(), 0)
68 logger.error('Error in tracker filter.', { err })
74 if (CONFIG.TRACKER.ENABLED !== false) {
76 trackerServer.on('error', function (err) {
77 logger.error('Error in tracker.', { err })
80 trackerServer.on('warning', function (err) {
81 logger.warn('Warning in tracker.', { err })
85 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
86 trackerRouter.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
87 trackerRouter.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
89 function createWebsocketTrackerServer (app: express.Application) {
90 const server = http.createServer(app)
91 const wss = new WebSocketServer({ noServer: true })
93 wss.on('connection', function (ws, req) {
94 ws['ip'] = proxyAddr(req, CONFIG.TRUST_PROXY)
96 trackerServer.onWebSocketConnection(ws)
99 server.on('upgrade', (request: express.Request, socket, head) => {
100 if (request.url === '/tracker/socket') {
101 const ip = proxyAddr(request, CONFIG.TRUST_PROXY)
103 Redis.Instance.doesTrackerBlockIPExist(ip)
105 if (result === true) {
106 logger.debug('Blocking IP %s from tracker.', ip)
108 socket.write('HTTP/1.1 403 Forbidden\r\n\r\n')
113 return wss.handleUpgrade(request, socket, head, ws => wss.emit('connection', ws, request))
115 .catch(err => logger.error('Cannot check if tracker block ip exists.', { err }))
118 // Don't destroy socket, we have Socket.IO too
124 // ---------------------------------------------------------------------------
128 createWebsocketTrackerServer
131 // ---------------------------------------------------------------------------
133 function runPeersChecker () {
135 logger.debug('Checking peers.')
137 for (const ip of Object.keys(peersIpInfoHash)) {
138 if (peersIps[ip] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP) {
139 logger.warn('Peer %s made abnormal requests (%d).', ip, peersIps[ip])
145 }, TRACKER_RATE_LIMITS.INTERVAL)