2014-04-03 12:16:59 +00:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
2014-11-21 06:04:07 +00:00
|
|
|
"bufio"
|
2015-06-29 09:37:52 +00:00
|
|
|
"bytes"
|
2014-07-16 07:09:30 +00:00
|
|
|
"errors"
|
2014-08-23 17:04:07 +00:00
|
|
|
"expvar"
|
2014-06-26 07:29:12 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2016-09-11 04:32:56 +00:00
|
|
|
"log"
|
2016-05-16 08:46:38 +00:00
|
|
|
"math/rand"
|
2014-04-03 12:16:59 +00:00
|
|
|
"net"
|
2016-02-09 13:45:47 +00:00
|
|
|
"strconv"
|
2016-09-11 04:32:56 +00:00
|
|
|
"strings"
|
2016-05-07 08:56:44 +00:00
|
|
|
"sync"
|
2014-04-03 12:16:59 +00:00
|
|
|
"time"
|
|
|
|
|
2016-02-01 10:08:52 +00:00
|
|
|
"github.com/anacrolix/missinggo"
|
2016-03-22 01:07:03 +00:00
|
|
|
"github.com/anacrolix/missinggo/bitmap"
|
2017-01-14 09:39:48 +00:00
|
|
|
"github.com/anacrolix/missinggo/iter"
|
2016-02-01 10:11:41 +00:00
|
|
|
"github.com/anacrolix/missinggo/prioritybitmap"
|
|
|
|
|
2015-04-27 04:55:01 +00:00
|
|
|
"github.com/anacrolix/torrent/bencode"
|
2015-03-20 05:37:44 +00:00
|
|
|
pp "github.com/anacrolix/torrent/peer_protocol"
|
2014-04-03 12:16:59 +00:00
|
|
|
)
|
|
|
|
|
2014-08-23 17:04:07 +00:00
|
|
|
var optimizedCancels = expvar.NewInt("optimizedCancels")
|
|
|
|
|
2016-11-26 13:05:19 +00:00
|
|
|
type peerSource string
|
2014-07-16 07:06:18 +00:00
|
|
|
|
|
|
|
const (
|
2016-11-26 13:05:19 +00:00
|
|
|
peerSourceTracker = "T" // It's the default.
|
|
|
|
peerSourceIncoming = "I"
|
|
|
|
peerSourceDHTGetPeers = "Hg"
|
|
|
|
peerSourceDHTAnnouncePeer = "Ha"
|
|
|
|
peerSourcePEX = "X"
|
2014-07-16 07:06:18 +00:00
|
|
|
)
|
|
|
|
|
2014-04-03 12:16:59 +00:00
|
|
|
// Maintains the state of a connection with a peer.
|
2014-04-08 16:36:05 +00:00
|
|
|
type connection struct {
|
2016-10-10 05:30:51 +00:00
|
|
|
t *Torrent
|
|
|
|
// The actual Conn, used for closing, and setting socket options.
|
|
|
|
conn net.Conn
|
|
|
|
// The Reader and Writer for this Conn, with hooks installed for stats,
|
|
|
|
// limiting, deadlines etc.
|
|
|
|
w io.Writer
|
|
|
|
r io.Reader
|
|
|
|
// True if the connection is operating over MSE obfuscation.
|
2015-03-18 07:28:13 +00:00
|
|
|
encrypted bool
|
2014-12-03 00:22:38 +00:00
|
|
|
Discovery peerSource
|
|
|
|
uTP bool
|
2016-02-01 10:08:52 +00:00
|
|
|
closed missinggo.Event
|
2014-12-03 00:22:38 +00:00
|
|
|
|
2016-07-05 05:52:33 +00:00
|
|
|
stats ConnStats
|
2014-09-11 10:30:13 +00:00
|
|
|
UnwantedChunksReceived int
|
|
|
|
UsefulChunksReceived int
|
2015-05-14 22:39:53 +00:00
|
|
|
chunksSent int
|
2016-05-23 16:09:47 +00:00
|
|
|
goodPiecesDirtied int
|
|
|
|
badPiecesDirtied int
|
2014-08-27 23:32:49 +00:00
|
|
|
|
|
|
|
lastMessageReceived time.Time
|
|
|
|
completedHandshake time.Time
|
|
|
|
lastUsefulChunkReceived time.Time
|
2015-06-16 06:57:47 +00:00
|
|
|
lastChunkSent time.Time
|
2014-08-27 23:32:49 +00:00
|
|
|
|
2014-04-03 12:16:59 +00:00
|
|
|
// Stuff controlled by the local peer.
|
2014-12-05 06:58:43 +00:00
|
|
|
Interested bool
|
|
|
|
Choked bool
|
2017-08-31 13:48:52 +00:00
|
|
|
requests map[request]struct{}
|
2014-12-05 06:58:43 +00:00
|
|
|
requestsLowWater int
|
2015-03-27 04:36:59 +00:00
|
|
|
// Indexed by metadata piece, set to true if posted and pending a
|
|
|
|
// response.
|
|
|
|
metadataRequests []bool
|
2016-01-04 11:37:49 +00:00
|
|
|
sentHaves []bool
|
2014-04-03 12:16:59 +00:00
|
|
|
|
|
|
|
// Stuff controlled by the remote peer.
|
2014-08-21 08:12:49 +00:00
|
|
|
PeerID [20]byte
|
|
|
|
PeerInterested bool
|
|
|
|
PeerChoked bool
|
|
|
|
PeerRequests map[request]struct{}
|
|
|
|
PeerExtensionBytes peerExtensionBytes
|
2016-03-22 01:07:03 +00:00
|
|
|
// The pieces the peer has claimed to have.
|
|
|
|
peerPieces bitmap.Bitmap
|
|
|
|
// The peer has everything. This can occur due to a special message, when
|
|
|
|
// we may not even know the number of pieces in the torrent yet.
|
2015-03-12 09:06:23 +00:00
|
|
|
peerHasAll bool
|
2016-03-22 01:07:03 +00:00
|
|
|
// The highest possible number of pieces the torrent could have based on
|
|
|
|
// communication with the peer. Generally only useful until we have the
|
|
|
|
// torrent info.
|
|
|
|
peerMinPieces int
|
2015-08-03 15:12:09 +00:00
|
|
|
// Pieces we've accepted chunks for from the peer.
|
|
|
|
peerTouchedPieces map[int]struct{}
|
2015-03-12 09:06:23 +00:00
|
|
|
|
2014-06-26 14:57:07 +00:00
|
|
|
PeerMaxRequests int // Maximum pending requests the peer allows.
|
2015-03-27 04:36:59 +00:00
|
|
|
PeerExtensionIDs map[string]byte
|
2014-06-29 08:57:49 +00:00
|
|
|
PeerClientName string
|
2016-02-01 10:11:41 +00:00
|
|
|
|
|
|
|
pieceInclination []int
|
|
|
|
pieceRequestOrder prioritybitmap.PriorityBitmap
|
2016-05-07 08:56:44 +00:00
|
|
|
|
2017-08-31 06:26:45 +00:00
|
|
|
postedBuffer bytes.Buffer
|
|
|
|
writerCond sync.Cond
|
2016-05-07 08:56:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) mu() sync.Locker {
|
|
|
|
return &cn.t.cl.mu
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
|
2015-03-12 19:21:13 +00:00
|
|
|
func (cn *connection) remoteAddr() net.Addr {
|
|
|
|
return cn.conn.RemoteAddr()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) localAddr() net.Addr {
|
|
|
|
return cn.conn.LocalAddr()
|
|
|
|
}
|
|
|
|
|
2014-12-03 07:07:50 +00:00
|
|
|
func (cn *connection) supportsExtension(ext string) bool {
|
|
|
|
_, ok := cn.PeerExtensionIDs[ext]
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2016-03-22 01:07:03 +00:00
|
|
|
// The best guess at number of pieces in the torrent for this peer.
|
|
|
|
func (cn *connection) bestPeerNumPieces() int {
|
|
|
|
if cn.t.haveInfo() {
|
|
|
|
return cn.t.numPieces()
|
2014-06-26 07:29:12 +00:00
|
|
|
}
|
2016-03-22 01:07:03 +00:00
|
|
|
return cn.peerMinPieces
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) completedString() string {
|
|
|
|
return fmt.Sprintf("%d/%d", cn.peerPieces.Len(), cn.bestPeerNumPieces())
|
2014-06-26 07:29:12 +00:00
|
|
|
}
|
|
|
|
|
2014-07-16 07:09:30 +00:00
|
|
|
// Correct the PeerPieces slice length. Return false if the existing slice is
|
|
|
|
// invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
|
|
|
|
// messages.
|
|
|
|
func (cn *connection) setNumPieces(num int) error {
|
2016-03-22 01:07:03 +00:00
|
|
|
cn.peerPieces.RemoveRange(num, -1)
|
|
|
|
cn.peerPiecesChanged()
|
2014-07-16 07:09:30 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-09-11 10:30:13 +00:00
|
|
|
func eventAgeString(t time.Time) string {
|
|
|
|
if t.IsZero() {
|
|
|
|
return "never"
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%.2fs ago", time.Now().Sub(t).Seconds())
|
|
|
|
}
|
|
|
|
|
2015-08-01 18:06:22 +00:00
|
|
|
func (cn *connection) connectionFlags() (ret string) {
|
2014-06-26 07:29:12 +00:00
|
|
|
c := func(b byte) {
|
2015-03-18 07:38:29 +00:00
|
|
|
ret += string([]byte{b})
|
2014-12-09 06:26:06 +00:00
|
|
|
}
|
2015-03-18 07:38:29 +00:00
|
|
|
if cn.encrypted {
|
|
|
|
c('E')
|
2014-06-26 07:29:12 +00:00
|
|
|
}
|
2016-11-26 13:05:19 +00:00
|
|
|
ret += string(cn.Discovery)
|
2014-11-16 19:29:31 +00:00
|
|
|
if cn.uTP {
|
|
|
|
c('T')
|
|
|
|
}
|
2015-08-01 18:06:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Inspired by https://trac.transmissionbt.com/wiki/PeerStatusText
|
|
|
|
func (cn *connection) statusFlags() (ret string) {
|
|
|
|
c := func(b byte) {
|
|
|
|
ret += string([]byte{b})
|
|
|
|
}
|
|
|
|
if cn.Interested {
|
|
|
|
c('i')
|
|
|
|
}
|
|
|
|
if cn.Choked {
|
|
|
|
c('c')
|
|
|
|
}
|
|
|
|
c('-')
|
|
|
|
ret += cn.connectionFlags()
|
2015-03-18 07:38:29 +00:00
|
|
|
c('-')
|
|
|
|
if cn.PeerInterested {
|
|
|
|
c('i')
|
|
|
|
}
|
|
|
|
if cn.PeerChoked {
|
|
|
|
c('c')
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-29 09:37:52 +00:00
|
|
|
func (cn *connection) String() string {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
cn.WriteStatus(&buf, nil)
|
|
|
|
return buf.String()
|
|
|
|
}
|
|
|
|
|
2016-04-03 08:40:43 +00:00
|
|
|
func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
|
2015-03-18 07:38:29 +00:00
|
|
|
// \t isn't preserved in <pre> blocks?
|
2015-06-22 09:46:26 +00:00
|
|
|
fmt.Fprintf(w, "%+q: %s-%s\n", cn.PeerID, cn.localAddr(), cn.remoteAddr())
|
2015-03-18 07:38:29 +00:00
|
|
|
fmt.Fprintf(w, " last msg: %s, connected: %s, last useful chunk: %s\n",
|
|
|
|
eventAgeString(cn.lastMessageReceived),
|
|
|
|
eventAgeString(cn.completedHandshake),
|
|
|
|
eventAgeString(cn.lastUsefulChunkReceived))
|
2015-05-14 22:39:53 +00:00
|
|
|
fmt.Fprintf(w,
|
2015-08-03 15:12:09 +00:00
|
|
|
" %s completed, %d pieces touched, good chunks: %d/%d-%d reqq: %d-%d, flags: %s\n",
|
2016-03-22 01:07:03 +00:00
|
|
|
cn.completedString(),
|
2015-08-03 15:12:09 +00:00
|
|
|
len(cn.peerTouchedPieces),
|
2015-03-18 07:38:29 +00:00
|
|
|
cn.UsefulChunksReceived,
|
|
|
|
cn.UnwantedChunksReceived+cn.UsefulChunksReceived,
|
2015-05-14 22:39:53 +00:00
|
|
|
cn.chunksSent,
|
2017-08-31 13:48:52 +00:00
|
|
|
cn.numLocalRequests(),
|
2015-03-18 07:38:29 +00:00
|
|
|
len(cn.PeerRequests),
|
2015-05-14 22:39:53 +00:00
|
|
|
cn.statusFlags(),
|
|
|
|
)
|
2017-01-04 07:09:50 +00:00
|
|
|
fmt.Fprintf(w, " next pieces: %v\n", priorityBitmapHeadAsSlice(&cn.pieceRequestOrder, 10))
|
|
|
|
}
|
|
|
|
|
|
|
|
func priorityBitmapHeadAsSlice(pb *prioritybitmap.PriorityBitmap, n int) (ret []int) {
|
|
|
|
pb.IterTyped(func(i int) bool {
|
|
|
|
if len(ret) >= n {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ret = append(ret, i)
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
return
|
2014-06-26 07:29:12 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) Close() {
|
|
|
|
cn.closed.Set()
|
|
|
|
cn.discardPieceInclination()
|
|
|
|
cn.pieceRequestOrder.Clear()
|
2016-05-11 13:50:21 +00:00
|
|
|
if cn.conn != nil {
|
|
|
|
// TODO: This call blocks sometimes, why?
|
|
|
|
go cn.conn.Close()
|
|
|
|
}
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) PeerHasPiece(piece int) bool {
|
|
|
|
return cn.peerHasAll || cn.peerPieces.Contains(piece)
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) Post(msg pp.Message) {
|
2016-05-07 08:56:44 +00:00
|
|
|
postedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
|
2017-08-31 06:26:45 +00:00
|
|
|
cn.postedBuffer.Write(msg.MustMarshalBinary())
|
|
|
|
cn.writerCond.Broadcast()
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) RequestPending(r request) bool {
|
2017-08-31 13:48:52 +00:00
|
|
|
_, ok := cn.requests[r]
|
2014-05-23 11:01:05 +00:00
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) requestMetadataPiece(index int) {
|
|
|
|
eID := cn.PeerExtensionIDs["ut_metadata"]
|
2015-03-27 04:36:59 +00:00
|
|
|
if eID == 0 {
|
|
|
|
return
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
|
2015-03-27 04:36:59 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.Post(pp.Message{
|
2015-03-27 04:36:59 +00:00
|
|
|
Type: pp.Extended,
|
|
|
|
ExtendedID: eID,
|
|
|
|
ExtendedPayload: func() []byte {
|
|
|
|
b, err := bencode.Marshal(map[string]int{
|
|
|
|
"msg_type": pp.RequestMetadataExtensionMsgType,
|
|
|
|
"piece": index,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}(),
|
|
|
|
})
|
2016-04-19 04:11:11 +00:00
|
|
|
for index >= len(cn.metadataRequests) {
|
|
|
|
cn.metadataRequests = append(cn.metadataRequests, false)
|
2015-03-27 04:36:59 +00:00
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.metadataRequests[index] = true
|
2015-03-27 04:36:59 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) requestedMetadataPiece(index int) bool {
|
|
|
|
return index < len(cn.metadataRequests) && cn.metadataRequests[index]
|
2015-03-27 04:36:59 +00:00
|
|
|
}
|
|
|
|
|
2016-02-08 05:09:12 +00:00
|
|
|
// The actual value to use as the maximum outbound requests.
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) nominalMaxRequests() (ret int) {
|
|
|
|
ret = cn.PeerMaxRequests
|
2016-02-08 05:09:12 +00:00
|
|
|
if ret > 64 {
|
|
|
|
ret = 64
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-04-16 07:33:33 +00:00
|
|
|
// Returns true if an unsatisfied request was canceled.
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) PeerCancel(r request) bool {
|
|
|
|
if cn.PeerRequests == nil {
|
2014-04-16 07:33:33 +00:00
|
|
|
return false
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
if _, ok := cn.PeerRequests[r]; !ok {
|
2014-04-16 07:33:33 +00:00
|
|
|
return false
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
delete(cn.PeerRequests, r)
|
2014-04-16 07:33:33 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) Choke() {
|
|
|
|
if cn.Choked {
|
2014-05-21 07:49:28 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.Post(pp.Message{
|
2014-08-21 08:12:49 +00:00
|
|
|
Type: pp.Choke,
|
2014-05-21 07:49:28 +00:00
|
|
|
})
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.PeerRequests = nil
|
|
|
|
cn.Choked = true
|
2014-05-21 07:49:28 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) Unchoke() {
|
|
|
|
if !cn.Choked {
|
2014-04-03 12:16:59 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.Post(pp.Message{
|
2014-08-21 08:12:49 +00:00
|
|
|
Type: pp.Unchoke,
|
2014-04-03 12:16:59 +00:00
|
|
|
})
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.Choked = false
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
|
2017-08-31 13:48:52 +00:00
|
|
|
func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
|
2016-04-19 04:11:11 +00:00
|
|
|
if cn.Interested == interested {
|
2017-08-31 13:48:52 +00:00
|
|
|
return true
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
2017-08-31 13:48:52 +00:00
|
|
|
cn.Interested = interested
|
|
|
|
// log.Printf("%p: setting interest: %v", cn, interested)
|
|
|
|
return msg(pp.Message{
|
2014-08-21 08:12:49 +00:00
|
|
|
Type: func() pp.MessageType {
|
2014-04-03 12:16:59 +00:00
|
|
|
if interested {
|
2014-08-21 08:12:49 +00:00
|
|
|
return pp.Interested
|
2014-04-03 12:16:59 +00:00
|
|
|
} else {
|
2014-08-21 08:12:49 +00:00
|
|
|
return pp.NotInterested
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
}(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2015-08-02 10:39:31 +00:00
|
|
|
var (
|
|
|
|
// Track connection writer buffer writes and flushes, to determine its
|
|
|
|
// efficiency.
|
|
|
|
connectionWriterFlush = expvar.NewInt("connectionWriterFlush")
|
|
|
|
connectionWriterWrite = expvar.NewInt("connectionWriterWrite")
|
|
|
|
)
|
2015-08-02 04:30:33 +00:00
|
|
|
|
2017-08-31 13:48:52 +00:00
|
|
|
func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
|
|
|
|
rs, i := cn.desiredRequestState()
|
|
|
|
if !cn.SetInterested(i, msg) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for r := range cn.requests {
|
|
|
|
if _, ok := rs[r]; !ok {
|
|
|
|
delete(cn.requests, r)
|
|
|
|
// log.Printf("%p: cancelling request: %v", cn, r)
|
|
|
|
if !msg(pp.Message{
|
|
|
|
Type: pp.Cancel,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
|
|
|
Length: r.Length,
|
|
|
|
}) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for r := range rs {
|
|
|
|
if _, ok := cn.requests[r]; !ok {
|
|
|
|
if cn.requests == nil {
|
|
|
|
cn.requests = make(map[request]struct{}, cn.nominalMaxRequests())
|
|
|
|
}
|
|
|
|
cn.requests[r] = struct{}{}
|
|
|
|
// log.Printf("%p: requesting %v", cn, r)
|
|
|
|
if !msg(pp.Message{
|
|
|
|
Type: pp.Request,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
|
|
|
Length: r.Length,
|
|
|
|
}) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-28 15:27:48 +00:00
|
|
|
// Writes buffers to the socket from the write channel.
|
2016-05-07 08:56:44 +00:00
|
|
|
func (cn *connection) writer(keepAliveTimeout time.Duration) {
|
2017-08-31 06:26:45 +00:00
|
|
|
var (
|
|
|
|
buf bytes.Buffer
|
|
|
|
lastWrite time.Time = time.Now()
|
|
|
|
)
|
|
|
|
var keepAliveTimer *time.Timer
|
|
|
|
keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
|
2016-05-07 08:56:44 +00:00
|
|
|
cn.mu().Lock()
|
|
|
|
defer cn.mu().Unlock()
|
2017-08-31 06:26:45 +00:00
|
|
|
if time.Since(lastWrite) >= keepAliveTimeout {
|
|
|
|
cn.writerCond.Broadcast()
|
|
|
|
}
|
|
|
|
keepAliveTimer.Reset(keepAliveTimeout)
|
|
|
|
})
|
|
|
|
cn.mu().Lock()
|
|
|
|
defer cn.mu().Unlock()
|
|
|
|
defer cn.Close()
|
|
|
|
defer keepAliveTimer.Stop()
|
2014-08-21 08:12:49 +00:00
|
|
|
for {
|
2017-08-31 06:26:45 +00:00
|
|
|
buf.Write(cn.postedBuffer.Bytes())
|
|
|
|
cn.postedBuffer.Reset()
|
2017-08-31 13:48:52 +00:00
|
|
|
if buf.Len() == 0 {
|
|
|
|
cn.fillWriteBuffer(func(msg pp.Message) bool {
|
|
|
|
buf.Write(msg.MustMarshalBinary())
|
|
|
|
return buf.Len() < 1<<16
|
|
|
|
})
|
|
|
|
}
|
2017-08-31 06:26:45 +00:00
|
|
|
if buf.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
|
|
|
|
buf.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
|
|
|
|
postedKeepalives.Add(1)
|
|
|
|
}
|
|
|
|
if buf.Len() == 0 {
|
|
|
|
cn.writerCond.Wait()
|
|
|
|
continue
|
2016-05-07 08:56:44 +00:00
|
|
|
}
|
|
|
|
cn.mu().Unlock()
|
2017-08-31 06:26:45 +00:00
|
|
|
// log.Printf("writing %d bytes", buf.Len())
|
|
|
|
n, err := cn.w.Write(buf.Bytes())
|
|
|
|
cn.mu().Lock()
|
|
|
|
if n != 0 {
|
|
|
|
lastWrite = time.Now()
|
2016-05-07 08:56:44 +00:00
|
|
|
keepAliveTimer.Reset(keepAliveTimeout)
|
|
|
|
}
|
2017-08-31 06:26:45 +00:00
|
|
|
if err != nil {
|
2014-08-21 08:12:49 +00:00
|
|
|
return
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
2017-08-31 06:26:45 +00:00
|
|
|
if n != buf.Len() {
|
|
|
|
panic("short write")
|
|
|
|
}
|
|
|
|
buf.Reset()
|
2014-04-03 12:16:59 +00:00
|
|
|
}
|
|
|
|
}
|
2016-01-04 11:37:49 +00:00
|
|
|
|
|
|
|
func (cn *connection) Have(piece int) {
|
|
|
|
for piece >= len(cn.sentHaves) {
|
|
|
|
cn.sentHaves = append(cn.sentHaves, false)
|
|
|
|
}
|
|
|
|
if cn.sentHaves[piece] {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
cn.Post(pp.Message{
|
|
|
|
Type: pp.Have,
|
|
|
|
Index: pp.Integer(piece),
|
|
|
|
})
|
|
|
|
cn.sentHaves[piece] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) Bitfield(haves []bool) {
|
2016-01-04 11:56:36 +00:00
|
|
|
if cn.sentHaves != nil {
|
2016-01-04 11:37:49 +00:00
|
|
|
panic("bitfield must be first have-related message sent")
|
|
|
|
}
|
|
|
|
cn.Post(pp.Message{
|
|
|
|
Type: pp.Bitfield,
|
|
|
|
Bitfield: haves,
|
|
|
|
})
|
2016-05-11 13:50:21 +00:00
|
|
|
// Make a copy of haves, as that's read when the message is marshalled
|
|
|
|
// without the lock. Also it obviously shouldn't change in the Msg due to
|
|
|
|
// changes in .sentHaves.
|
|
|
|
cn.sentHaves = append([]bool(nil), haves...)
|
2016-01-04 11:37:49 +00:00
|
|
|
}
|
2016-01-24 04:21:17 +00:00
|
|
|
|
2017-08-17 15:51:02 +00:00
|
|
|
func nextRequestState(
|
|
|
|
networkingEnabled bool,
|
|
|
|
currentRequests map[request]struct{},
|
|
|
|
peerChoking bool,
|
2017-08-25 06:36:34 +00:00
|
|
|
nextPieces *prioritybitmap.PriorityBitmap,
|
2017-08-17 15:51:02 +00:00
|
|
|
pendingChunks func(piece int, f func(chunkSpec) bool) bool,
|
|
|
|
requestsLowWater int,
|
|
|
|
requestsHighWater int,
|
|
|
|
) (
|
|
|
|
requests map[request]struct{},
|
|
|
|
interested bool,
|
|
|
|
) {
|
|
|
|
if !networkingEnabled || nextPieces.IsEmpty() {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
if peerChoking || len(currentRequests) > requestsLowWater {
|
|
|
|
return currentRequests, true
|
|
|
|
}
|
|
|
|
requests = make(map[request]struct{}, requestsHighWater)
|
|
|
|
for r := range currentRequests {
|
|
|
|
requests[r] = struct{}{}
|
|
|
|
}
|
|
|
|
nextPieces.IterTyped(func(piece int) bool {
|
|
|
|
return pendingChunks(piece, func(cs chunkSpec) bool {
|
|
|
|
if len(requests) >= requestsHighWater {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
r := request{pp.Integer(piece), cs}
|
|
|
|
requests[r] = struct{}{}
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
})
|
|
|
|
return requests, true
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) updateRequests() {
|
2017-08-31 13:48:52 +00:00
|
|
|
cn.writerCond.Broadcast()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) desiredRequestState() (map[request]struct{}, bool) {
|
|
|
|
return nextRequestState(
|
2017-08-17 15:51:02 +00:00
|
|
|
cn.t.networkingEnabled,
|
2017-08-31 13:48:52 +00:00
|
|
|
cn.requests,
|
2017-08-17 15:51:02 +00:00
|
|
|
cn.PeerChoked,
|
2017-08-25 06:36:34 +00:00
|
|
|
&cn.pieceRequestOrder,
|
2017-08-17 15:51:02 +00:00
|
|
|
func(piece int, f func(chunkSpec) bool) bool {
|
|
|
|
return undirtiedChunks(piece, cn.t, f)
|
|
|
|
},
|
|
|
|
cn.requestsLowWater,
|
2017-08-31 13:48:52 +00:00
|
|
|
cn.nominalMaxRequests(),
|
|
|
|
)
|
2016-01-24 04:21:17 +00:00
|
|
|
}
|
|
|
|
|
2017-08-17 15:51:02 +00:00
|
|
|
func undirtiedChunks(piece int, t *Torrent, f func(chunkSpec) bool) bool {
|
|
|
|
chunkIndices := t.pieces[piece].undirtiedChunkIndices().ToSortedSlice()
|
|
|
|
return iter.ForPerm(len(chunkIndices), func(i int) bool {
|
|
|
|
return f(t.chunkIndexSpec(chunkIndices[i], piece))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) stopRequestingPiece(piece int) {
|
|
|
|
cn.pieceRequestOrder.Remove(piece)
|
2017-08-31 13:48:52 +00:00
|
|
|
cn.writerCond.Broadcast()
|
2016-02-01 10:11:41 +00:00
|
|
|
}
|
|
|
|
|
2016-10-31 05:22:07 +00:00
|
|
|
// This is distinct from Torrent piece priority, which is the user's
|
|
|
|
// preference. Connection piece priority is specific to a connection,
|
|
|
|
// pseudorandomly avoids connections always requesting the same pieces and
|
|
|
|
// thus wasting effort.
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) updatePiecePriority(piece int) {
|
|
|
|
tpp := cn.t.piecePriority(piece)
|
|
|
|
if !cn.PeerHasPiece(piece) {
|
2016-02-09 13:47:53 +00:00
|
|
|
tpp = PiecePriorityNone
|
2016-01-24 04:21:17 +00:00
|
|
|
}
|
2016-02-01 10:11:41 +00:00
|
|
|
if tpp == PiecePriorityNone {
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.stopRequestingPiece(piece)
|
2016-02-01 10:11:41 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
prio := cn.getPieceInclination()[piece]
|
2016-02-01 10:11:41 +00:00
|
|
|
switch tpp {
|
|
|
|
case PiecePriorityNormal:
|
|
|
|
case PiecePriorityReadahead:
|
2016-04-19 04:11:11 +00:00
|
|
|
prio -= cn.t.numPieces()
|
2016-02-01 10:11:41 +00:00
|
|
|
case PiecePriorityNext, PiecePriorityNow:
|
2016-04-19 04:11:11 +00:00
|
|
|
prio -= 2 * cn.t.numPieces()
|
2016-02-01 10:11:41 +00:00
|
|
|
default:
|
|
|
|
panic(tpp)
|
|
|
|
}
|
2017-01-04 07:08:29 +00:00
|
|
|
prio += piece / 3
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.pieceRequestOrder.Set(piece, prio)
|
|
|
|
cn.updateRequests()
|
2016-02-01 10:11:41 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) getPieceInclination() []int {
|
|
|
|
if cn.pieceInclination == nil {
|
|
|
|
cn.pieceInclination = cn.t.getConnPieceInclination()
|
2016-02-01 10:11:41 +00:00
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
return cn.pieceInclination
|
2016-02-01 10:11:41 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) discardPieceInclination() {
|
|
|
|
if cn.pieceInclination == nil {
|
2016-02-01 10:11:41 +00:00
|
|
|
return
|
2016-01-24 04:21:17 +00:00
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.t.putPieceInclination(cn.pieceInclination)
|
|
|
|
cn.pieceInclination = nil
|
2016-01-24 04:21:17 +00:00
|
|
|
}
|
2016-03-21 03:17:15 +00:00
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) peerHasPieceChanged(piece int) {
|
|
|
|
cn.updatePiecePriority(piece)
|
2016-03-22 01:07:03 +00:00
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) peerPiecesChanged() {
|
|
|
|
if cn.t.haveInfo() {
|
|
|
|
for i := range iter.N(cn.t.numPieces()) {
|
|
|
|
cn.peerHasPieceChanged(i)
|
2016-03-21 03:17:15 +00:00
|
|
|
}
|
2016-03-22 01:07:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) raisePeerMinPieces(newMin int) {
|
|
|
|
if newMin > cn.peerMinPieces {
|
|
|
|
cn.peerMinPieces = newMin
|
2016-03-22 01:07:03 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) peerSentHave(piece int) error {
|
|
|
|
if cn.t.haveInfo() && piece >= cn.t.numPieces() {
|
2016-03-22 01:07:03 +00:00
|
|
|
return errors.New("invalid piece")
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
if cn.PeerHasPiece(piece) {
|
2016-03-22 01:07:03 +00:00
|
|
|
return nil
|
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.raisePeerMinPieces(piece + 1)
|
|
|
|
cn.peerPieces.Set(piece, true)
|
|
|
|
cn.peerHasPieceChanged(piece)
|
2016-03-22 01:07:03 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) peerSentBitfield(bf []bool) error {
|
|
|
|
cn.peerHasAll = false
|
2016-03-22 01:07:03 +00:00
|
|
|
if len(bf)%8 != 0 {
|
|
|
|
panic("expected bitfield length divisible by 8")
|
|
|
|
}
|
|
|
|
// We know that the last byte means that at most the last 7 bits are
|
|
|
|
// wasted.
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.raisePeerMinPieces(len(bf) - 7)
|
2016-04-29 18:08:02 +00:00
|
|
|
if cn.t.haveInfo() && len(bf) > cn.t.numPieces() {
|
2016-03-22 01:07:03 +00:00
|
|
|
// Ignore known excess pieces.
|
2016-04-19 04:11:11 +00:00
|
|
|
bf = bf[:cn.t.numPieces()]
|
2016-03-22 01:07:03 +00:00
|
|
|
}
|
|
|
|
for i, have := range bf {
|
|
|
|
if have {
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.raisePeerMinPieces(i + 1)
|
2016-03-21 03:17:15 +00:00
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.peerPieces.Set(i, have)
|
2016-03-21 03:17:15 +00:00
|
|
|
}
|
2016-04-19 04:11:11 +00:00
|
|
|
cn.peerPiecesChanged()
|
2016-03-22 01:07:03 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) peerSentHaveAll() error {
|
|
|
|
cn.peerHasAll = true
|
|
|
|
cn.peerPieces.Clear()
|
|
|
|
cn.peerPiecesChanged()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (cn *connection) peerSentHaveNone() error {
|
|
|
|
cn.peerPieces.Clear()
|
|
|
|
cn.peerHasAll = false
|
|
|
|
cn.peerPiecesChanged()
|
2016-03-21 03:17:15 +00:00
|
|
|
return nil
|
|
|
|
}
|
2016-05-16 08:46:38 +00:00
|
|
|
|
|
|
|
func (c *connection) requestPendingMetadata() {
|
|
|
|
if c.t.haveInfo() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if c.PeerExtensionIDs["ut_metadata"] == 0 {
|
|
|
|
// Peer doesn't support this.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Request metadata pieces that we don't have in a random order.
|
|
|
|
var pending []int
|
|
|
|
for index := 0; index < c.t.metadataPieceCount(); index++ {
|
|
|
|
if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
|
|
|
|
pending = append(pending, index)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, i := range rand.Perm(len(pending)) {
|
|
|
|
c.requestMetadataPiece(pending[i])
|
|
|
|
}
|
|
|
|
}
|
2016-07-05 05:52:33 +00:00
|
|
|
|
2016-07-12 06:42:04 +00:00
|
|
|
func (cn *connection) wroteMsg(msg *pp.Message) {
|
2016-07-05 05:52:33 +00:00
|
|
|
cn.stats.wroteMsg(msg)
|
|
|
|
cn.t.stats.wroteMsg(msg)
|
|
|
|
}
|
|
|
|
|
2016-07-12 06:42:04 +00:00
|
|
|
func (cn *connection) readMsg(msg *pp.Message) {
|
|
|
|
cn.stats.readMsg(msg)
|
|
|
|
cn.t.stats.readMsg(msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) wroteBytes(n int64) {
|
|
|
|
cn.stats.wroteBytes(n)
|
|
|
|
if cn.t != nil {
|
|
|
|
cn.t.stats.wroteBytes(n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *connection) readBytes(n int64) {
|
|
|
|
cn.stats.readBytes(n)
|
|
|
|
if cn.t != nil {
|
|
|
|
cn.t.stats.readBytes(n)
|
|
|
|
}
|
2016-07-05 05:52:33 +00:00
|
|
|
}
|
2016-07-05 06:23:17 +00:00
|
|
|
|
|
|
|
// Returns whether the connection is currently useful to us. We're seeding and
|
|
|
|
// they want data, we don't have metainfo and they can provide it, etc.
|
|
|
|
func (c *connection) useful() bool {
|
|
|
|
t := c.t
|
|
|
|
if c.closed.IsSet() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if !t.haveInfo() {
|
|
|
|
return c.supportsExtension("ut_metadata")
|
|
|
|
}
|
|
|
|
if t.seeding() {
|
|
|
|
return c.PeerInterested
|
|
|
|
}
|
2017-08-17 15:48:19 +00:00
|
|
|
return c.peerHasWantedPieces()
|
2016-07-05 06:23:17 +00:00
|
|
|
}
|
2016-07-05 14:42:16 +00:00
|
|
|
|
2016-08-14 12:39:23 +00:00
|
|
|
func (c *connection) lastHelpful() (ret time.Time) {
|
|
|
|
ret = c.lastUsefulChunkReceived
|
|
|
|
if c.t.seeding() && c.lastChunkSent.After(ret) {
|
|
|
|
ret = c.lastChunkSent
|
2016-07-05 14:42:16 +00:00
|
|
|
}
|
2016-08-14 12:39:23 +00:00
|
|
|
return
|
2016-07-05 14:42:16 +00:00
|
|
|
}
|
2016-09-11 04:32:56 +00:00
|
|
|
|
|
|
|
// Processes incoming bittorrent messages. The client lock is held upon entry
|
|
|
|
// and exit. Returning will end the connection.
|
|
|
|
func (c *connection) mainReadLoop() error {
|
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
2016-09-12 07:10:11 +00:00
|
|
|
|
2016-09-11 04:32:56 +00:00
|
|
|
decoder := pp.Decoder{
|
2016-10-10 05:30:51 +00:00
|
|
|
R: bufio.NewReader(c.r),
|
2016-09-11 04:32:56 +00:00
|
|
|
MaxLength: 256 * 1024,
|
2016-10-05 04:57:00 +00:00
|
|
|
Pool: t.chunkPool,
|
2016-09-11 04:32:56 +00:00
|
|
|
}
|
|
|
|
for {
|
2017-08-31 06:25:49 +00:00
|
|
|
var (
|
|
|
|
msg pp.Message
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
func() {
|
|
|
|
cl.mu.Unlock()
|
|
|
|
defer cl.mu.Lock()
|
|
|
|
err = decoder.Decode(&msg)
|
|
|
|
}()
|
2016-09-11 04:32:56 +00:00
|
|
|
if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.readMsg(&msg)
|
|
|
|
c.lastMessageReceived = time.Now()
|
|
|
|
if msg.Keepalive {
|
|
|
|
receivedKeepalives.Add(1)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
|
|
|
|
switch msg.Type {
|
|
|
|
case pp.Choke:
|
|
|
|
c.PeerChoked = true
|
2017-08-31 13:48:52 +00:00
|
|
|
c.requests = nil
|
2016-09-11 04:32:56 +00:00
|
|
|
// We can then reset our interest.
|
|
|
|
c.updateRequests()
|
|
|
|
case pp.Reject:
|
|
|
|
cl.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
|
|
|
|
c.updateRequests()
|
|
|
|
case pp.Unchoke:
|
|
|
|
c.PeerChoked = false
|
2017-08-31 13:48:52 +00:00
|
|
|
c.writerCond.Broadcast()
|
2016-09-11 04:32:56 +00:00
|
|
|
case pp.Interested:
|
|
|
|
c.PeerInterested = true
|
2016-11-22 10:12:53 +00:00
|
|
|
c.upload()
|
2016-09-11 04:32:56 +00:00
|
|
|
case pp.NotInterested:
|
|
|
|
c.PeerInterested = false
|
|
|
|
c.Choke()
|
|
|
|
case pp.Have:
|
|
|
|
err = c.peerSentHave(int(msg.Index))
|
|
|
|
case pp.Request:
|
|
|
|
if c.Choked {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if !c.PeerInterested {
|
|
|
|
err = errors.New("peer sent request but isn't interested")
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if !t.havePiece(msg.Index.Int()) {
|
|
|
|
// This isn't necessarily them screwing up. We can drop pieces
|
|
|
|
// from our storage, and can't communicate this to peers
|
|
|
|
// except by reconnecting.
|
|
|
|
requestsReceivedForMissingPieces.Add(1)
|
|
|
|
err = errors.New("peer requested piece we don't have")
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if c.PeerRequests == nil {
|
|
|
|
c.PeerRequests = make(map[request]struct{}, maxRequests)
|
|
|
|
}
|
|
|
|
c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
|
2016-11-22 10:12:53 +00:00
|
|
|
c.upload()
|
2016-09-11 04:32:56 +00:00
|
|
|
case pp.Cancel:
|
|
|
|
req := newRequest(msg.Index, msg.Begin, msg.Length)
|
|
|
|
if !c.PeerCancel(req) {
|
|
|
|
unexpectedCancels.Add(1)
|
|
|
|
}
|
|
|
|
case pp.Bitfield:
|
|
|
|
err = c.peerSentBitfield(msg.Bitfield)
|
|
|
|
case pp.HaveAll:
|
|
|
|
err = c.peerSentHaveAll()
|
|
|
|
case pp.HaveNone:
|
|
|
|
err = c.peerSentHaveNone()
|
|
|
|
case pp.Piece:
|
2016-11-22 03:18:09 +00:00
|
|
|
c.receiveChunk(&msg)
|
2016-09-12 07:10:11 +00:00
|
|
|
if len(msg.Piece) == int(t.chunkSize) {
|
2016-10-05 04:57:00 +00:00
|
|
|
t.chunkPool.Put(msg.Piece)
|
2016-09-12 07:10:11 +00:00
|
|
|
}
|
2016-09-11 04:32:56 +00:00
|
|
|
case pp.Extended:
|
|
|
|
switch msg.ExtendedID {
|
|
|
|
case pp.HandshakeExtendedID:
|
|
|
|
// TODO: Create a bencode struct for this.
|
|
|
|
var d map[string]interface{}
|
|
|
|
err = bencode.Unmarshal(msg.ExtendedPayload, &d)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error decoding extended message payload: %s", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
// log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
|
|
|
|
if reqq, ok := d["reqq"]; ok {
|
|
|
|
if i, ok := reqq.(int64); ok {
|
|
|
|
c.PeerMaxRequests = int(i)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if v, ok := d["v"]; ok {
|
|
|
|
c.PeerClientName = v.(string)
|
|
|
|
}
|
|
|
|
m, ok := d["m"]
|
|
|
|
if !ok {
|
|
|
|
err = errors.New("handshake missing m item")
|
|
|
|
break
|
|
|
|
}
|
|
|
|
mTyped, ok := m.(map[string]interface{})
|
|
|
|
if !ok {
|
|
|
|
err = errors.New("handshake m value is not dict")
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if c.PeerExtensionIDs == nil {
|
|
|
|
c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
|
|
|
|
}
|
|
|
|
for name, v := range mTyped {
|
|
|
|
id, ok := v.(int64)
|
|
|
|
if !ok {
|
|
|
|
log.Printf("bad handshake m item extension ID type: %T", v)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if id == 0 {
|
|
|
|
delete(c.PeerExtensionIDs, name)
|
|
|
|
} else {
|
|
|
|
if c.PeerExtensionIDs[name] == 0 {
|
|
|
|
supportedExtensionMessages.Add(name, 1)
|
|
|
|
}
|
|
|
|
c.PeerExtensionIDs[name] = byte(id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
metadata_sizeUntyped, ok := d["metadata_size"]
|
|
|
|
if ok {
|
|
|
|
metadata_size, ok := metadata_sizeUntyped.(int64)
|
|
|
|
if !ok {
|
|
|
|
log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
|
|
|
|
} else {
|
|
|
|
err = t.setMetadataSize(metadata_size)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error setting metadata size to %d", metadata_size)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
|
|
|
|
c.requestPendingMetadata()
|
|
|
|
}
|
|
|
|
case metadataExtendedId:
|
|
|
|
err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error handling metadata extension message: %s", err)
|
|
|
|
}
|
|
|
|
case pexExtendedId:
|
|
|
|
if cl.config.DisablePEX {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
var pexMsg peerExchangeMessage
|
|
|
|
err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("error unmarshalling PEX message: %s", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
cl.mu.Lock()
|
|
|
|
t.addPeers(func() (ret []Peer) {
|
|
|
|
for i, cp := range pexMsg.Added {
|
|
|
|
p := Peer{
|
|
|
|
IP: make([]byte, 4),
|
|
|
|
Port: cp.Port,
|
|
|
|
Source: peerSourcePEX,
|
|
|
|
}
|
|
|
|
if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
|
|
|
|
p.SupportsEncryption = true
|
|
|
|
}
|
|
|
|
missinggo.CopyExact(p.IP, cp.IP[:])
|
|
|
|
ret = append(ret, p)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}())
|
|
|
|
cl.mu.Unlock()
|
|
|
|
}()
|
|
|
|
default:
|
|
|
|
err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
// That client uses its own extension IDs for outgoing message
|
|
|
|
// types, which is incorrect.
|
|
|
|
if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
|
|
|
|
strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case pp.Port:
|
|
|
|
if cl.dHT == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if msg.Port != 0 {
|
|
|
|
pingAddr.Port = int(msg.Port)
|
|
|
|
}
|
2017-07-20 14:40:49 +00:00
|
|
|
go cl.dHT.Ping(pingAddr, nil)
|
2016-09-11 04:32:56 +00:00
|
|
|
default:
|
|
|
|
err = fmt.Errorf("received unknown message type: %#v", msg.Type)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-10-10 05:30:51 +00:00
|
|
|
|
|
|
|
// Set both the Reader and Writer for the connection from a single ReadWriter.
|
|
|
|
func (cn *connection) setRW(rw io.ReadWriter) {
|
|
|
|
cn.r = rw
|
|
|
|
cn.w = rw
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns the Reader and Writer as a combined ReadWriter.
|
|
|
|
func (cn *connection) rw() io.ReadWriter {
|
|
|
|
return struct {
|
|
|
|
io.Reader
|
|
|
|
io.Writer
|
|
|
|
}{cn.r, cn.w}
|
|
|
|
}
|
2016-11-22 03:16:18 +00:00
|
|
|
|
|
|
|
// Handle a received chunk from a peer.
|
2016-11-22 03:18:09 +00:00
|
|
|
func (c *connection) receiveChunk(msg *pp.Message) {
|
2016-11-22 03:17:30 +00:00
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
2016-11-22 03:16:18 +00:00
|
|
|
chunksReceived.Add(1)
|
|
|
|
|
|
|
|
req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
|
|
|
|
|
|
|
|
// Request has been satisfied.
|
|
|
|
if cl.connDeleteRequest(t, c, req) {
|
|
|
|
defer c.updateRequests()
|
|
|
|
} else {
|
|
|
|
unexpectedChunksReceived.Add(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do we actually want this chunk?
|
|
|
|
if !t.wantPiece(req) {
|
|
|
|
unwantedChunksReceived.Add(1)
|
|
|
|
c.UnwantedChunksReceived++
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-11-22 03:20:48 +00:00
|
|
|
index := int(req.Index)
|
|
|
|
piece := &t.pieces[index]
|
|
|
|
|
2016-11-22 03:16:18 +00:00
|
|
|
c.UsefulChunksReceived++
|
|
|
|
c.lastUsefulChunkReceived = time.Now()
|
|
|
|
|
2016-11-22 10:12:53 +00:00
|
|
|
c.upload()
|
2016-11-22 03:16:18 +00:00
|
|
|
|
|
|
|
// Need to record that it hasn't been written yet, before we attempt to do
|
|
|
|
// anything with it.
|
|
|
|
piece.incrementPendingWrites()
|
|
|
|
// Record that we have the chunk.
|
|
|
|
piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
|
|
|
|
|
|
|
|
// Cancel pending requests for this chunk.
|
2016-11-23 00:48:44 +00:00
|
|
|
for c := range t.conns {
|
2017-08-31 13:48:52 +00:00
|
|
|
c.updateRequests()
|
2016-11-22 03:16:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
cl.mu.Unlock()
|
|
|
|
// Write the chunk out. Note that the upper bound on chunk writing
|
|
|
|
// concurrency will be the number of connections.
|
|
|
|
err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
|
|
|
|
cl.mu.Lock()
|
|
|
|
|
|
|
|
piece.decrementPendingWrites()
|
|
|
|
|
|
|
|
if err != nil {
|
2017-02-02 05:53:19 +00:00
|
|
|
log.Printf("%s (%x): error writing chunk %v: %s", t, t.infoHash, req, err)
|
2016-11-22 03:16:18 +00:00
|
|
|
t.pendRequest(req)
|
|
|
|
t.updatePieceCompletion(int(msg.Index))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// It's important that the piece is potentially queued before we check if
|
|
|
|
// the piece is still wanted, because if it is queued, it won't be wanted.
|
|
|
|
if t.pieceAllDirty(index) {
|
2017-01-01 00:02:37 +00:00
|
|
|
t.queuePieceCheck(int(req.Index))
|
2016-11-22 03:16:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if c.peerTouchedPieces == nil {
|
|
|
|
c.peerTouchedPieces = make(map[int]struct{})
|
|
|
|
}
|
|
|
|
c.peerTouchedPieces[index] = struct{}{}
|
|
|
|
|
|
|
|
cl.event.Broadcast()
|
|
|
|
t.publishPieceChange(int(req.Index))
|
|
|
|
return
|
|
|
|
}
|
2016-11-22 10:12:53 +00:00
|
|
|
|
|
|
|
// Also handles choking and unchoking of the remote peer.
|
|
|
|
func (c *connection) upload() {
|
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
|
|
|
if cl.config.NoUpload {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if !c.PeerInterested {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
seeding := t.seeding()
|
2017-08-17 15:48:19 +00:00
|
|
|
if !seeding && !c.peerHasWantedPieces() {
|
2016-11-22 10:12:53 +00:00
|
|
|
// There's no reason to upload to this peer.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Breaking or completing this loop means we don't want to upload to the
|
|
|
|
// peer anymore, and we choke them.
|
|
|
|
another:
|
|
|
|
for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
|
|
|
|
// We want to upload to the peer.
|
|
|
|
c.Unchoke()
|
|
|
|
for r := range c.PeerRequests {
|
|
|
|
res := cl.uploadLimit.ReserveN(time.Now(), int(r.Length))
|
|
|
|
delay := res.Delay()
|
|
|
|
if delay > 0 {
|
|
|
|
res.Cancel()
|
|
|
|
go func() {
|
|
|
|
time.Sleep(delay)
|
|
|
|
cl.mu.Lock()
|
|
|
|
defer cl.mu.Unlock()
|
|
|
|
c.upload()
|
|
|
|
}()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err := cl.sendChunk(t, c, r)
|
|
|
|
if err != nil {
|
|
|
|
i := int(r.Index)
|
|
|
|
if t.pieceComplete(i) {
|
|
|
|
t.updatePieceCompletion(i)
|
|
|
|
if !t.pieceComplete(i) {
|
|
|
|
// We had the piece, but not anymore.
|
|
|
|
break another
|
|
|
|
}
|
|
|
|
}
|
|
|
|
log.Printf("error sending chunk %+v to peer: %s", r, err)
|
|
|
|
// If we failed to send a chunk, choke the peer to ensure they
|
|
|
|
// flush all their requests. We've probably dropped a piece,
|
|
|
|
// but there's no way to communicate this to the peer. If they
|
|
|
|
// ask for it again, we'll kick them to allow us to send them
|
|
|
|
// an updated bitfield.
|
|
|
|
break another
|
|
|
|
}
|
|
|
|
delete(c.PeerRequests, r)
|
|
|
|
goto another
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.Choke()
|
|
|
|
}
|
2016-11-23 00:52:41 +00:00
|
|
|
|
|
|
|
func (cn *connection) Drop() {
|
|
|
|
cn.t.dropConnection(cn)
|
|
|
|
}
|
|
|
|
|
2016-11-23 01:59:23 +00:00
|
|
|
func (cn *connection) netGoodPiecesDirtied() int {
|
|
|
|
return cn.goodPiecesDirtied - cn.badPiecesDirtied
|
|
|
|
}
|
2017-08-17 15:48:19 +00:00
|
|
|
|
|
|
|
func (c *connection) peerHasWantedPieces() bool {
|
|
|
|
return !c.pieceRequestOrder.IsEmpty()
|
|
|
|
}
|
2017-08-31 13:48:52 +00:00
|
|
|
|
|
|
|
func (c *connection) numLocalRequests() int {
|
|
|
|
return len(c.requests)
|
|
|
|
}
|