tracker/server/serve_announce.go

399 lines
9 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"
2014-05-07 11:19:36 +02:00
"github.com/chihaya/chihaya/config"
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
)
2014-05-07 11:19:36 +02:00
// announce represents all of the data from an announce request.
type announce struct {
Compact bool
Downloaded uint64
Event string
IP string
Infohash string
Left uint64
NumWant int
Passkey string
PeerID string
Port uint64
Uploaded uint64
}
// newAnnounce parses an HTTP request and generates an Announce.
func newAnnounce(r *http.Request, conf *config.Config) (*announce, error) {
pq, err := parseQuery(r.URL.RawQuery)
if err != nil {
return nil, err
}
compact := pq.Params["compact"] == "1"
downloaded, downloadedErr := pq.getUint64("downloaded")
event, _ := pq.Params["event"]
infohash, _ := pq.Params["info_hash"]
ip, _ := requestedIP(r, pq)
left, leftErr := pq.getUint64("left")
numWant := requestedPeerCount(conf.DefaultNumWant, pq)
passkey, _ := path.Split(r.URL.Path)
peerID, _ := pq.Params["peer_id"]
port, portErr := pq.getUint64("port")
uploaded, uploadedErr := pq.getUint64("uploaded")
if downloadedErr != nil ||
infohash == "" ||
leftErr != nil ||
peerID == "" ||
portErr != nil ||
uploadedErr != nil ||
ip == "" {
return nil, errors.New("malformed request")
}
return &announce{
Compact: compact,
Downloaded: downloaded,
Event: event,
IP: ip,
Left: left,
NumWant: numWant,
Passkey: passkey,
PeerID: peerID,
Port: port,
Uploaded: uploaded,
}, nil
}
func (s Server) serveAnnounce(w http.ResponseWriter, r *http.Request) {
2014-05-07 11:19:36 +02:00
// Parse the required data from a request
ann, err := newAnnounce(r, s.conf)
2013-11-24 06:49:20 +01:00
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
2014-05-07 11:19:36 +02:00
user, err := validateUser(conn, ann.Passkey)
2013-11-24 06:49:20 +01:00
if err != nil {
fail(err, w, r)
return
}
// Check if the user's client is whitelisted
2014-05-07 11:19:36 +02:00
whitelisted, err := conn.ClientWhitelisted(parsePeerID(ann.PeerID))
2013-11-24 06:49:20 +01:00
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
2014-05-07 11:19:36 +02:00
torrent, exists, err := conn.FindTorrent(ann.Infohash)
2013-11-24 06:49:20 +01:00
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
2014-05-07 11:19:36 +02:00
if !torrent.Active && ann.Left == 0 {
2013-11-24 06:49:20 +01:00
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{
2014-05-07 11:19:36 +02:00
ID: ann.PeerID,
2013-11-24 06:49:20 +01:00
UserID: user.ID,
TorrentID: torrent.ID,
2014-05-07 11:19:36 +02:00
IP: ann.IP,
Port: ann.Port,
Uploaded: ann.Uploaded,
Downloaded: ann.Downloaded,
Left: ann.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:
2014-05-07 11:19:36 +02:00
if ann.Left == 0 {
2013-11-24 06:49:20 +01:00
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:
2014-05-07 11:19:36 +02:00
if ann.Left == 0 {
2013-11-24 06:49:20 +01:00
// 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 {
2014-05-07 11:19:36 +02:00
case ann.Event == "stopped" || ann.Event == "paused":
2013-11-24 06:49:20 +01:00
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)
}
}
2014-05-07 11:19:36 +02:00
case ann.Event == "completed":
2013-11-24 06:49:20 +01:00
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)
}
}
2014-05-07 11:19:36 +02:00
case leecher && ann.Left == 0:
2013-11-24 06:49:20 +01:00
// A leecher completed but the event was never received
err := conn.LeecherFinished(torrent, peer)
if err != nil {
log.Panicf("server: %s", err)
}
}
2014-05-07 11:19:36 +02:00
if ann.IP != peer.IP || ann.Port != peer.Port {
peer.Port = ann.Port
peer.IP = ann.IP
2013-11-24 06:49:20 +01:00
}
// 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)
2014-05-07 11:19:36 +02:00
if ann.NumWant > 0 && ann.Event != "stopped" && ann.Event != "paused" {
2013-11-24 06:49:20 +01:00
writeBencoded(w, "peers")
var peerCount, count int
2014-05-07 11:19:36 +02:00
if ann.Compact {
if ann.Left > 0 {
peerCount = minInt(ann.NumWant, leechCount)
2013-11-24 06:49:20 +01:00
} else {
2014-05-07 11:19:36 +02:00
peerCount = minInt(ann.NumWant, leechCount+seedCount-1)
2013-11-24 06:49:20 +01:00
}
writeBencoded(w, strconv.Itoa(peerCount*6))
writeBencoded(w, ":")
} else {
writeBencoded(w, "l")
}
2014-05-07 11:19:36 +02:00
if ann.Left > 0 {
2013-11-24 06:49:20 +01:00
// If they're seeding, give them only leechers
2014-05-07 11:19:36 +02:00
count += writeLeechers(w, user, torrent, ann.NumWant, ann.Compact)
2013-11-24 06:49:20 +01:00
} else {
// If they're leeching, prioritize giving them seeders
2014-05-07 11:19:36 +02:00
count += writeSeeders(w, user, torrent, ann.NumWant, ann.Compact)
count += writeLeechers(w, user, torrent, ann.NumWant-count, ann.Compact)
2013-11-24 06:49:20 +01:00
}
2014-05-07 11:19:36 +02:00
if ann.Compact && peerCount != count {
2013-11-24 06:49:20 +01:00
log.Panicf("Calculated peer count (%d) != real count (%d)", peerCount, count)
}
2014-05-07 11:19:36 +02:00
if !ann.Compact {
2013-11-24 06:49:20 +01:00
writeBencoded(w, "e")
}
}
writeBencoded(w, "e")
2014-02-23 05:47:11 +01:00
2014-05-07 11:19:36 +02:00
rawDeltaUp := peer.Uploaded - ann.Uploaded
rawDeltaDown := peer.Downloaded - ann.Downloaded
2014-02-23 05:47:11 +01:00
// 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
}
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
}