tracker.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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'
  12. const TrackerServer = bitTorrentTracker.Server
  13. const trackerRouter = express.Router()
  14. let peersIps = {}
  15. let peersIpInfoHash = {}
  16. runPeersChecker()
  17. const trackerServer = new TrackerServer({
  18. http: false,
  19. udp: false,
  20. ws: false,
  21. filter: async function (infoHash, params, cb) {
  22. if (CONFIG.TRACKER.ENABLED === false) {
  23. return cb(new Error('Tracker is disabled on this instance.'))
  24. }
  25. let ip: string
  26. if (params.type === 'ws') {
  27. ip = params.ip
  28. } else {
  29. ip = params.httpReq.ip
  30. }
  31. const key = ip + '-' + infoHash
  32. peersIps[ip] = peersIps[ip] ? peersIps[ip] + 1 : 1
  33. peersIpInfoHash[key] = peersIpInfoHash[key] ? peersIpInfoHash[key] + 1 : 1
  34. if (CONFIG.TRACKER.REJECT_TOO_MANY_ANNOUNCES && peersIpInfoHash[key] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP_PER_INFOHASH) {
  35. return cb(new Error(`Too many requests (${peersIpInfoHash[key]} of ip ${ip} for torrent ${infoHash}`))
  36. }
  37. try {
  38. if (CONFIG.TRACKER.PRIVATE === false) return cb()
  39. const videoFileExists = await VideoFileModel.doesInfohashExistCached(infoHash)
  40. if (videoFileExists === true) return cb()
  41. const playlistExists = await VideoStreamingPlaylistModel.doesInfohashExistCached(infoHash)
  42. if (playlistExists === true) return cb()
  43. cb(new Error(`Unknown infoHash ${infoHash} requested by ip ${ip}`))
  44. // Close socket connection and block IP for a few time
  45. if (params.type === 'ws') {
  46. Redis.Instance.setTrackerBlockIP(ip)
  47. .catch(err => logger.error('Cannot set tracker block ip.', { err }))
  48. // setTimeout to wait filter response
  49. setTimeout(() => params.socket.close(), 0)
  50. }
  51. } catch (err) {
  52. logger.error('Error in tracker filter.', { err })
  53. return cb(err)
  54. }
  55. }
  56. })
  57. if (CONFIG.TRACKER.ENABLED !== false) {
  58. trackerServer.on('error', function (err) {
  59. logger.error('Error in tracker.', { err })
  60. })
  61. trackerServer.on('warning', function (err) {
  62. logger.warn('Warning in tracker.', { err })
  63. })
  64. }
  65. const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
  66. trackerRouter.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
  67. trackerRouter.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
  68. function createWebsocketTrackerServer (app: express.Application) {
  69. const server = http.createServer(app)
  70. const wss = new WebSocketServer({ noServer: true })
  71. wss.on('connection', function (ws, req) {
  72. ws['ip'] = proxyAddr(req, CONFIG.TRUST_PROXY)
  73. trackerServer.onWebSocketConnection(ws)
  74. })
  75. server.on('upgrade', (request: express.Request, socket, head) => {
  76. if (request.url === '/tracker/socket') {
  77. const ip = proxyAddr(request, CONFIG.TRUST_PROXY)
  78. Redis.Instance.doesTrackerBlockIPExist(ip)
  79. .then(result => {
  80. if (result === true) {
  81. logger.debug('Blocking IP %s from tracker.', ip)
  82. socket.write('HTTP/1.1 403 Forbidden\r\n\r\n')
  83. socket.destroy()
  84. return
  85. }
  86. return wss.handleUpgrade(request, socket, head, ws => wss.emit('connection', ws, request))
  87. })
  88. .catch(err => logger.error('Cannot check if tracker block ip exists.', { err }))
  89. }
  90. // Don't destroy socket, we have Socket.IO too
  91. })
  92. return server
  93. }
  94. // ---------------------------------------------------------------------------
  95. export {
  96. trackerRouter,
  97. createWebsocketTrackerServer
  98. }
  99. // ---------------------------------------------------------------------------
  100. function runPeersChecker () {
  101. setInterval(() => {
  102. logger.debug('Checking peers.')
  103. for (const ip of Object.keys(peersIpInfoHash)) {
  104. if (peersIps[ip] > TRACKER_RATE_LIMITS.ANNOUNCES_PER_IP) {
  105. logger.warn('Peer %s made abnormal requests (%d).', ip, peersIps[ip])
  106. }
  107. }
  108. peersIpInfoHash = {}
  109. peersIps = {}
  110. }, TRACKER_RATE_LIMITS.INTERVAL)
  111. }