bittorrent-tracker/lib/server/parse-http.js

60 lines
2.0 KiB
JavaScript
Raw Normal View History

2014-12-11 20:53:39 +00:00
module.exports = parseHttpRequest
2015-07-29 07:26:44 +00:00
var common = require('../common')
function parseHttpRequest (req, opts) {
if (!opts) opts = {}
var s = req.url.split('?')
var params = common.querystringParse(s[1])
2016-03-12 01:21:19 +00:00
params.type = 'http'
if (opts.action === 'announce' || s[0] === '/announce') {
params.action = common.ACTIONS.ANNOUNCE
2014-12-11 20:53:39 +00:00
if (typeof params.info_hash !== 'string' || params.info_hash.length !== 20) {
throw new Error('invalid info_hash')
}
params.info_hash = common.binaryToHex(params.info_hash)
if (typeof params.peer_id !== 'string' || params.peer_id.length !== 20) {
throw new Error('invalid peer_id')
}
params.peer_id = common.binaryToHex(params.peer_id)
params.port = Number(params.port)
if (!params.port) throw new Error('invalid port')
2016-12-04 05:07:26 +00:00
params.left = Number(params.left)
2017-02-03 01:23:46 +00:00
if (Number.isNaN(params.left)) params.left = Infinity
2016-12-04 05:07:26 +00:00
params.compact = Number(params.compact) || 0
params.numwant = Math.min(
Number(params.numwant) || common.DEFAULT_ANNOUNCE_PEERS,
common.MAX_ANNOUNCE_PEERS
)
params.ip = opts.trustProxy
? req.headers['x-forwarded-for'] || req.connection.remoteAddress
: req.connection.remoteAddress.replace(common.REMOVE_IPV4_MAPPED_IPV6_RE, '') // force ipv4
2014-12-12 23:09:40 +00:00
params.addr = (common.IPV6_RE.test(params.ip) ? '[' + params.ip + ']' : params.ip) + ':' + params.port
params.headers = req.headers
} else if (opts.action === 'scrape' || s[0] === '/scrape') {
params.action = common.ACTIONS.SCRAPE
if (typeof params.info_hash === 'string') params.info_hash = [ params.info_hash ]
if (Array.isArray(params.info_hash)) {
params.info_hash = params.info_hash.map(function (binaryInfoHash) {
if (typeof binaryInfoHash !== 'string' || binaryInfoHash.length !== 20) {
throw new Error('invalid info_hash')
}
return common.binaryToHex(binaryInfoHash)
})
}
} else {
2016-01-13 20:57:22 +00:00
throw new Error('invalid action in HTTP request: ' + req.url)
}
return params
}