tracker/server/announce.go

370 lines
8.5 KiB
Go
Raw Normal View History

// Copyright 2013 The Chihaya Authors. All rights reserved.
// Use of this source code is governed by the BSD 2-Clause license,
// which can be found in the LICENSE file.
2013-06-22 01:31:32 +02:00
package server
import (
2013-11-24 06:49:20 +01:00
"errors"
"log"
"net/http"
"path"
"strconv"
"time"
2013-12-01 04:39:02 +01:00
"github.com/chihaya/chihaya/storage"
2014-02-23 05:47:11 +01:00
"github.com/chihaya/chihaya/storage/backend"
2013-06-22 01:31:32 +02:00
)
func (s Server) serveAnnounce(w http.ResponseWriter, r *http.Request) {
2013-11-24 06:49:20 +01:00
// Parse the required parameters off of a query
compact, numWant, infohash, peerID, event, ip, port, uploaded, downloaded, left, err := s.validateAnnounceQuery(r)
if err != nil {
fail(err, w, r)
return
}
// Get a connection to the tracker db
2014-02-23 05:47:11 +01:00
conn, err := s.trackerPool.Get()
2013-11-24 06:49:20 +01:00
if err != nil {
log.Panicf("server: %s", err)
}
// Validate the user's passkey
passkey, _ := path.Split(r.URL.Path)
user, err := validateUser(conn, passkey)
if err != nil {
fail(err, w, r)
return
}
// Check if the user's client is whitelisted
whitelisted, err := conn.ClientWhitelisted(parsePeerID(peerID))
if err != nil {
log.Panicf("server: %s", err)
}
if !whitelisted {
2014-05-01 06:30:46 +02:00
fail(errors.New("client is not approved"), w, r)
2013-11-24 06:49:20 +01:00
return
}
// Find the specified torrent
torrent, exists, err := conn.FindTorrent(infohash)
if err != nil {
log.Panicf("server: %s", err)
}
if !exists {
2014-05-01 06:30:46 +02:00
fail(errors.New("torrent does not exist"), w, r)
2013-11-24 06:49:20 +01:00
return
}
// If the torrent was pruned and the user is seeding, unprune it
if !torrent.Active && left == 0 {
err := conn.MarkActive(torrent)
if err != nil {
log.Panicf("server: %s", err)
}
}
2014-02-23 05:47:11 +01:00
now := time.Now().Unix()
2013-11-24 06:49:20 +01:00
// Create a new peer object from the request
peer := &storage.Peer{
ID: peerID,
UserID: user.ID,
TorrentID: torrent.ID,
IP: ip,
Port: port,
Uploaded: uploaded,
Downloaded: downloaded,
Left: left,
2014-02-23 05:47:11 +01:00
LastAnnounce: now,
}
delta := &backend.AnnounceDelta{
Peer: peer,
Torrent: torrent,
User: user,
Timestamp: now,
2013-11-24 06:49:20 +01:00
}
// Look for the user in in the pool of seeders and leechers
_, seeder := torrent.Seeders[storage.PeerMapKey(peer)]
_, leecher := torrent.Leechers[storage.PeerMapKey(peer)]
switch {
// Guarantee that no user is in both pools
case seeder && leecher:
if left == 0 {
err := conn.RemoveLeecher(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
leecher = false
} else {
err := conn.RemoveSeeder(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
seeder = false
}
case seeder:
// Update the peer with the stats from the request
err := conn.SetSeeder(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
case leecher:
// Update the peer with the stats from the request
err := conn.SetLeecher(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
default:
if left == 0 {
// Save the peer as a new seeder
err := conn.AddSeeder(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
} else {
err = conn.AddLeecher(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
}
2014-02-23 05:47:11 +01:00
delta.Created = true
2013-11-24 06:49:20 +01:00
}
// Handle any events in the request
switch {
case event == "stopped" || event == "paused":
if seeder {
err := conn.RemoveSeeder(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
}
if leecher {
err := conn.RemoveLeecher(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
}
case event == "completed":
err := conn.RecordSnatch(user, torrent)
if err != nil {
log.Panicf("server: %s", err)
}
2014-02-23 05:47:11 +01:00
delta.Snatched = true
2013-11-24 06:49:20 +01:00
if leecher {
err := conn.LeecherFinished(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
}
case leecher && left == 0:
// A leecher completed but the event was never received
err := conn.LeecherFinished(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
}
if ip != peer.IP || port != peer.Port {
peer.Port = port
peer.IP = ip
}
// Generate the response
seedCount := len(torrent.Seeders)
leechCount := len(torrent.Leechers)
writeBencoded(w, "d")
writeBencoded(w, "complete")
writeBencoded(w, seedCount)
writeBencoded(w, "incomplete")
writeBencoded(w, leechCount)
writeBencoded(w, "interval")
writeBencoded(w, s.conf.Announce.Duration)
writeBencoded(w, "min interval")
writeBencoded(w, s.conf.MinAnnounce.Duration)
if numWant > 0 && event != "stopped" && event != "paused" {
writeBencoded(w, "peers")
var peerCount, count int
if compact {
if left > 0 {
peerCount = minInt(numWant, leechCount)
} else {
peerCount = minInt(numWant, leechCount+seedCount-1)
}
writeBencoded(w, strconv.Itoa(peerCount*6))
writeBencoded(w, ":")
} else {
writeBencoded(w, "l")
}
if left > 0 {
// If they're seeding, give them only leechers
count += writeLeechers(w, user, torrent, numWant, compact)
2013-11-24 06:49:20 +01:00
} else {
// If they're leeching, prioritize giving them seeders
count += writeSeeders(w, user, torrent, numWant, compact)
count += writeLeechers(w, user, torrent, numWant-count, compact)
2013-11-24 06:49:20 +01:00
}
if compact && peerCount != count {
log.Panicf("Calculated peer count (%d) != real count (%d)", peerCount, count)
}
if !compact {
writeBencoded(w, "e")
}
}
writeBencoded(w, "e")
2014-02-23 05:47:11 +01:00
rawDeltaUp := peer.Uploaded - uploaded
rawDeltaDown := peer.Downloaded - downloaded
// Restarting a torrent may cause a delta to be negative.
if rawDeltaUp < 0 {
rawDeltaUp = 0
}
if rawDeltaDown < 0 {
rawDeltaDown = 0
}
delta.Uploaded = uint64(float64(rawDeltaUp) * user.UpMultiplier * torrent.UpMultiplier)
delta.Downloaded = uint64(float64(rawDeltaDown) * user.DownMultiplier * torrent.DownMultiplier)
s.backendConn.RecordAnnounce(delta)
2013-07-12 06:36:24 +02:00
}
func (s Server) validateAnnounceQuery(r *http.Request) (compact bool, numWant int, infohash, peerID, event, ip string, port, uploaded, downloaded, left uint64, err error) {
2013-11-24 06:49:20 +01:00
pq, err := parseQuery(r.URL.RawQuery)
if err != nil {
return false, 0, "", "", "", "", 0, 0, 0, 0, err
}
compact = pq.Params["compact"] == "1"
numWant = requestedPeerCount(s.conf.DefaultNumWant, pq)
infohash, _ = pq.Params["info_hash"]
peerID, _ = pq.Params["peer_id"]
event, _ = pq.Params["event"]
ip, _ = requestedIP(r, pq)
port, portErr := pq.getUint64("port")
uploaded, uploadedErr := pq.getUint64("uploaded")
downloaded, downloadedErr := pq.getUint64("downloaded")
left, leftErr := pq.getUint64("left")
if infohash == "" ||
peerID == "" ||
ip == "" ||
portErr != nil ||
uploadedErr != nil ||
downloadedErr != nil ||
leftErr != nil {
2014-05-01 06:30:46 +02:00
return false, 0, "", "", "", "", 0, 0, 0, 0, errors.New("malformed request")
2013-11-24 06:49:20 +01:00
}
return
2013-07-12 06:36:24 +02:00
}
2013-08-13 08:38:00 +02:00
func requestedPeerCount(fallback int, pq *parsedQuery) int {
2013-11-24 06:49:20 +01:00
if numWantStr, exists := pq.Params["numWant"]; exists {
numWant, err := strconv.Atoi(numWantStr)
if err != nil {
return fallback
}
return numWant
}
return fallback
2013-07-12 06:36:24 +02:00
}
2013-08-13 08:38:00 +02:00
func requestedIP(r *http.Request, pq *parsedQuery) (string, error) {
2013-12-06 02:37:15 +01:00
if ip, ok := pq.Params["ip"]; ok {
2013-11-24 06:49:20 +01:00
return ip, nil
2013-12-06 02:37:15 +01:00
}
if ip, ok := pq.Params["ipv4"]; ok {
return ip, nil
}
if xRealIPs, ok := pq.Params["X-Real-Ip"]; ok {
2013-11-24 06:49:20 +01:00
return string(xRealIPs[0]), nil
2013-12-06 02:37:15 +01:00
}
2013-11-24 06:49:20 +01:00
2013-12-06 02:37:15 +01:00
portIndex := len(r.RemoteAddr) - 1
for ; portIndex >= 0; portIndex-- {
if r.RemoteAddr[portIndex] == ':' {
break
2013-11-24 06:49:20 +01:00
}
}
2013-12-06 02:37:15 +01:00
if portIndex != -1 {
return r.RemoteAddr[0:portIndex], nil
}
2014-05-01 06:30:46 +02:00
return "", errors.New("failed to parse IP address")
2013-08-04 21:56:31 +02:00
}
func minInt(a, b int) int {
2013-11-24 06:49:20 +01:00
if a < b {
return a
}
return b
2013-08-04 21:56:31 +02:00
}
func writeSeeders(w http.ResponseWriter, user *storage.User, t *storage.Torrent, numWant int, compact bool) int {
count := 0
for _, peer := range t.Seeders {
2013-11-24 06:49:20 +01:00
if count >= numWant {
break
}
if peer.UserID == user.ID {
continue
}
2013-11-24 06:49:20 +01:00
if compact {
// TODO writeBencoded(w, compactAddr)
} else {
writeBencoded(w, "d")
writeBencoded(w, "ip")
writeBencoded(w, peer.IP)
2013-11-24 06:49:20 +01:00
writeBencoded(w, "peer id")
writeBencoded(w, peer.ID)
2013-11-24 06:49:20 +01:00
writeBencoded(w, "port")
writeBencoded(w, peer.Port)
2013-11-24 06:49:20 +01:00
writeBencoded(w, "e")
}
count++
}
return count
2013-08-04 21:56:31 +02:00
}
func writeLeechers(w http.ResponseWriter, user *storage.User, t *storage.Torrent, numWant int, compact bool) int {
count := 0
for _, peer := range t.Leechers {
2013-11-24 06:49:20 +01:00
if count >= numWant {
break
}
if peer.UserID == user.ID {
continue
}
2013-11-24 06:49:20 +01:00
if compact {
// TODO writeBencoded(w, compactAddr)
} else {
writeBencoded(w, "d")
writeBencoded(w, "ip")
writeBencoded(w, peer.IP)
2013-11-24 06:49:20 +01:00
writeBencoded(w, "peer id")
writeBencoded(w, peer.ID)
2013-11-24 06:49:20 +01:00
writeBencoded(w, "port")
writeBencoded(w, peer.Port)
2013-11-24 06:49:20 +01:00
writeBencoded(w, "e")
}
count++
}
return count
2013-07-12 06:36:24 +02:00
}