2014-04-03 20:16:59 +08:00
|
|
|
package torrent
|
|
|
|
|
|
|
|
import (
|
2014-11-21 14:04:07 +08:00
|
|
|
"bufio"
|
2015-06-29 17:37:52 +08:00
|
|
|
"bytes"
|
2014-06-26 15:29:12 +08:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2016-05-16 16:46:38 +08:00
|
|
|
"math/rand"
|
2014-04-03 20:16:59 +08:00
|
|
|
"net"
|
2016-02-09 21:45:47 +08:00
|
|
|
"strconv"
|
2016-09-11 12:32:56 +08:00
|
|
|
"strings"
|
2016-05-07 16:56:44 +08:00
|
|
|
"sync"
|
2014-04-03 20:16:59 +08:00
|
|
|
"time"
|
|
|
|
|
2018-02-03 09:06:52 +08:00
|
|
|
"github.com/anacrolix/log"
|
2016-02-01 18:08:52 +08:00
|
|
|
"github.com/anacrolix/missinggo"
|
2017-01-14 17:39:48 +08:00
|
|
|
"github.com/anacrolix/missinggo/iter"
|
2020-01-10 12:09:21 +08:00
|
|
|
"github.com/anacrolix/missinggo/v2/bitmap"
|
|
|
|
"github.com/anacrolix/missinggo/v2/prioritybitmap"
|
2019-12-23 11:04:07 +08:00
|
|
|
"github.com/anacrolix/multiless"
|
2020-06-02 14:18:25 +08:00
|
|
|
"github.com/anacrolix/torrent/metainfo"
|
2019-08-21 18:58:40 +08:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2015-04-27 12:55:01 +08:00
|
|
|
"github.com/anacrolix/torrent/bencode"
|
2017-12-01 15:12:29 +08:00
|
|
|
"github.com/anacrolix/torrent/mse"
|
2015-03-20 13:37:44 +08:00
|
|
|
pp "github.com/anacrolix/torrent/peer_protocol"
|
2014-04-03 20:16:59 +08:00
|
|
|
)
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
type PeerSource string
|
2014-07-16 15:06:18 +08:00
|
|
|
|
|
|
|
const (
|
2020-02-21 08:07:50 +08:00
|
|
|
PeerSourceTracker = "Tr"
|
|
|
|
PeerSourceIncoming = "I"
|
|
|
|
PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
|
|
|
|
PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
|
|
|
|
PeerSourcePex = "X"
|
2014-07-16 15:06:18 +08:00
|
|
|
)
|
|
|
|
|
2020-05-30 08:14:20 +08:00
|
|
|
type peer struct {
|
2018-06-23 16:33:56 +08:00
|
|
|
// First to ensure 64-bit alignment for atomics. See #262.
|
2020-01-10 12:09:21 +08:00
|
|
|
_stats ConnStats
|
2018-06-23 16:33:56 +08:00
|
|
|
|
2016-10-10 13:30:51 +08:00
|
|
|
t *Torrent
|
2020-05-30 13:18:28 +08:00
|
|
|
|
2020-06-02 15:41:59 +08:00
|
|
|
peerImpl
|
2020-05-30 13:18:28 +08:00
|
|
|
|
2018-11-04 13:56:55 +08:00
|
|
|
outgoing bool
|
|
|
|
network string
|
2020-07-15 14:15:38 +08:00
|
|
|
RemoteAddr net.Addr
|
2016-10-10 13:30:51 +08:00
|
|
|
// True if the connection is operating over MSE obfuscation.
|
2017-09-13 16:20:20 +08:00
|
|
|
headerEncrypted bool
|
2018-02-16 07:36:29 +08:00
|
|
|
cryptoMethod mse.CryptoMethod
|
2020-02-21 08:07:50 +08:00
|
|
|
Discovery PeerSource
|
2019-12-18 10:52:00 +08:00
|
|
|
trusted bool
|
2017-09-13 16:20:20 +08:00
|
|
|
closed missinggo.Event
|
2018-06-10 07:18:52 +08:00
|
|
|
// Set true after we've added our ConnStats generated during handshake to
|
|
|
|
// other ConnStat instances as determined when the *Torrent became known.
|
|
|
|
reconciledHandshakeStats bool
|
2014-12-03 08:22:38 +08:00
|
|
|
|
2014-08-28 07:32:49 +08:00
|
|
|
lastMessageReceived time.Time
|
|
|
|
completedHandshake time.Time
|
|
|
|
lastUsefulChunkReceived time.Time
|
2015-06-16 14:57:47 +08:00
|
|
|
lastChunkSent time.Time
|
2014-08-28 07:32:49 +08:00
|
|
|
|
2014-04-03 20:16:59 +08:00
|
|
|
// Stuff controlled by the local peer.
|
2020-02-21 08:07:50 +08:00
|
|
|
interested bool
|
2018-02-05 14:47:47 +08:00
|
|
|
lastBecameInterested time.Time
|
|
|
|
priorInterest time.Duration
|
|
|
|
|
2018-06-24 18:04:31 +08:00
|
|
|
lastStartedExpectingToReceiveChunks time.Time
|
|
|
|
cumulativeExpectedToReceiveChunks time.Duration
|
2020-01-10 12:09:21 +08:00
|
|
|
_chunksReceivedWhileExpecting int64
|
2018-06-24 18:04:31 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
choking bool
|
2017-08-31 21:48:52 +08:00
|
|
|
requests map[request]struct{}
|
2014-12-05 14:58:43 +08:00
|
|
|
requestsLowWater int
|
2018-06-24 18:35:46 +08:00
|
|
|
// Chunks that we might reasonably expect to receive from the peer. Due to
|
|
|
|
// latency, buffering, and implementation differences, we may receive
|
|
|
|
// chunks that are no longer in the set of requests actually want.
|
2020-04-23 10:34:43 +08:00
|
|
|
validReceiveChunks map[request]int
|
2015-03-27 12:36:59 +08:00
|
|
|
// Indexed by metadata piece, set to true if posted and pending a
|
|
|
|
// response.
|
|
|
|
metadataRequests []bool
|
2018-02-04 16:10:25 +08:00
|
|
|
sentHaves bitmap.Bitmap
|
2020-04-09 00:03:29 +08:00
|
|
|
pex pexConnState
|
2014-04-03 20:16:59 +08:00
|
|
|
|
|
|
|
// Stuff controlled by the remote peer.
|
2020-04-01 04:14:43 +08:00
|
|
|
peerInterested bool
|
|
|
|
peerChoking bool
|
|
|
|
peerRequests map[request]struct{}
|
2019-12-11 19:45:04 +08:00
|
|
|
PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
|
|
|
|
PeerListenPort int
|
2016-03-22 09:07:03 +08:00
|
|
|
// The pieces the peer has claimed to have.
|
2020-01-10 12:09:21 +08:00
|
|
|
_peerPieces bitmap.Bitmap
|
2016-03-22 09:07:03 +08:00
|
|
|
// 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.
|
2018-01-29 15:18:08 +08:00
|
|
|
peerSentHaveAll bool
|
2016-03-22 09:07:03 +08: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.
|
2018-07-12 07:15:15 +08:00
|
|
|
peerMinPieces pieceIndex
|
2015-08-03 23:12:09 +08:00
|
|
|
// Pieces we've accepted chunks for from the peer.
|
2018-07-12 07:15:15 +08:00
|
|
|
peerTouchedPieces map[pieceIndex]struct{}
|
2018-02-04 21:18:38 +08:00
|
|
|
peerAllowedFast bitmap.Bitmap
|
2015-03-12 17:06:23 +08:00
|
|
|
|
2014-06-26 22:57:07 +08:00
|
|
|
PeerMaxRequests int // Maximum pending requests the peer allows.
|
2018-07-10 10:20:36 +08:00
|
|
|
PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
|
2014-06-29 16:57:49 +08:00
|
|
|
PeerClientName string
|
2016-02-01 18:11:41 +08:00
|
|
|
|
2020-01-10 12:09:21 +08:00
|
|
|
pieceInclination []int
|
|
|
|
_pieceRequestOrder prioritybitmap.PriorityBitmap
|
2016-05-07 16:56:44 +08:00
|
|
|
|
2020-05-30 08:14:20 +08:00
|
|
|
logger log.Logger
|
|
|
|
}
|
|
|
|
|
2020-09-29 14:21:54 +08:00
|
|
|
// Maintains the state of a BitTorrent-protocol based connection with a peer.
|
2020-05-30 08:14:20 +08:00
|
|
|
type PeerConn struct {
|
|
|
|
peer
|
|
|
|
|
2020-09-29 14:21:54 +08:00
|
|
|
// A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
|
|
|
|
// be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
|
|
|
|
connString string
|
|
|
|
|
|
|
|
// See BEP 3 etc.
|
|
|
|
PeerID PeerID
|
|
|
|
PeerExtensionBytes pp.PeerExtensionBits
|
|
|
|
|
2020-05-30 08:14:20 +08:00
|
|
|
// 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
|
|
|
|
|
2018-02-03 12:09:38 +08:00
|
|
|
writeBuffer *bytes.Buffer
|
2018-02-03 11:40:03 +08:00
|
|
|
uploadTimer *time.Timer
|
|
|
|
writerCond sync.Cond
|
2016-05-07 16:56:44 +08:00
|
|
|
}
|
|
|
|
|
2020-09-29 14:21:54 +08:00
|
|
|
func (cn *PeerConn) connStatusString() string {
|
|
|
|
return fmt.Sprintf("%+-55q %s %s\n", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) updateExpectingChunks() {
|
2018-06-24 18:04:31 +08:00
|
|
|
if cn.expectingChunks() {
|
|
|
|
if cn.lastStartedExpectingToReceiveChunks.IsZero() {
|
|
|
|
cn.lastStartedExpectingToReceiveChunks = time.Now()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
|
|
|
|
cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
|
|
|
|
cn.lastStartedExpectingToReceiveChunks = time.Time{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) expectingChunks() bool {
|
2020-02-21 08:07:50 +08:00
|
|
|
return cn.interested && !cn.peerChoking
|
2018-06-24 18:04:31 +08:00
|
|
|
}
|
|
|
|
|
2018-06-16 15:14:47 +08:00
|
|
|
// Returns true if the connection is over IPv6.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) ipv6() bool {
|
2020-07-15 14:15:38 +08:00
|
|
|
ip := addrIpOrNil(cn.RemoteAddr)
|
2018-06-16 15:14:47 +08:00
|
|
|
if ip.To4() != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return len(ip) == net.IPv6len
|
|
|
|
}
|
|
|
|
|
2020-02-20 13:47:37 +08:00
|
|
|
// Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
|
2018-06-16 15:14:47 +08:00
|
|
|
// specification for this.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) isPreferredDirection() bool {
|
2018-06-16 15:14:47 +08:00
|
|
|
return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns whether the left connection should be preferred over the right one,
|
|
|
|
// considering only their networking properties. If ok is false, we can't
|
|
|
|
// decide.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
|
2018-06-16 15:14:47 +08:00
|
|
|
var ml multiLess
|
|
|
|
ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
|
|
|
|
ml.NextBool(!l.utp(), !r.utp())
|
|
|
|
ml.NextBool(l.ipv6(), r.ipv6())
|
|
|
|
return ml.FinalOk()
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) cumInterest() time.Duration {
|
2018-02-05 14:47:47 +08:00
|
|
|
ret := cn.priorInterest
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.interested {
|
2018-02-05 14:47:47 +08:00
|
|
|
ret += time.Since(cn.lastBecameInterested)
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
|
2018-01-29 15:18:08 +08:00
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
return true, true
|
|
|
|
}
|
|
|
|
if !cn.t.haveInfo() {
|
|
|
|
return false, false
|
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
|
2018-01-29 15:18:08 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:51:24 +08:00
|
|
|
func (cn *PeerConn) locker() *lockWithDeferreds {
|
2018-07-25 11:41:50 +08:00
|
|
|
return cn.t.cl.locker()
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) localAddr() net.Addr {
|
2015-03-13 03:21:13 +08:00
|
|
|
return cn.conn.LocalAddr()
|
|
|
|
}
|
|
|
|
|
2020-06-01 16:25:45 +08:00
|
|
|
func (cn *peer) supportsExtension(ext pp.ExtensionName) bool {
|
2014-12-03 15:07:50 +08:00
|
|
|
_, ok := cn.PeerExtensionIDs[ext]
|
|
|
|
return ok
|
|
|
|
}
|
|
|
|
|
2016-03-22 09:07:03 +08:00
|
|
|
// The best guess at number of pieces in the torrent for this peer.
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) bestPeerNumPieces() pieceIndex {
|
2016-03-22 09:07:03 +08:00
|
|
|
if cn.t.haveInfo() {
|
|
|
|
return cn.t.numPieces()
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
2016-03-22 09:07:03 +08:00
|
|
|
return cn.peerMinPieces
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) completedString() string {
|
2020-01-10 12:09:21 +08:00
|
|
|
have := pieceIndex(cn._peerPieces.Len())
|
2018-02-04 19:43:28 +08:00
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
have = cn.bestPeerNumPieces()
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
|
|
|
|
2020-06-02 14:18:25 +08:00
|
|
|
func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
|
|
|
|
cn.setNumPieces(info.NumPieces())
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 *PeerConn) setNumPieces(num pieceIndex) {
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
|
2016-03-22 09:07:03 +08:00
|
|
|
cn.peerPiecesChanged()
|
2014-07-16 15:09:30 +08:00
|
|
|
}
|
|
|
|
|
2014-09-11 18:30:13 +08:00
|
|
|
func eventAgeString(t time.Time) string {
|
|
|
|
if t.IsZero() {
|
|
|
|
return "never"
|
|
|
|
}
|
2017-11-07 13:11:59 +08:00
|
|
|
return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
|
2014-09-11 18:30:13 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) connectionFlags() (ret string) {
|
2014-06-26 15:29:12 +08:00
|
|
|
c := func(b byte) {
|
2015-03-18 15:38:29 +08:00
|
|
|
ret += string([]byte{b})
|
2014-12-09 14:26:06 +08:00
|
|
|
}
|
2017-09-13 16:20:20 +08:00
|
|
|
if cn.cryptoMethod == mse.CryptoMethodRC4 {
|
2015-03-18 15:38:29 +08:00
|
|
|
c('E')
|
2017-09-13 16:20:20 +08:00
|
|
|
} else if cn.headerEncrypted {
|
|
|
|
c('e')
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
2016-11-26 21:05:19 +08:00
|
|
|
ret += string(cn.Discovery)
|
2018-04-12 09:41:07 +08:00
|
|
|
if cn.utp() {
|
2018-02-15 13:04:42 +08:00
|
|
|
c('U')
|
2014-11-17 03:29:31 +08:00
|
|
|
}
|
2015-08-02 02:06:22 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) utp() bool {
|
2018-11-28 07:30:21 +08:00
|
|
|
return parseNetworkString(cn.network).Udp
|
2018-04-12 09:41:07 +08:00
|
|
|
}
|
|
|
|
|
2018-06-09 20:08:24 +08:00
|
|
|
// Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) statusFlags() (ret string) {
|
2015-08-02 02:06:22 +08:00
|
|
|
c := func(b byte) {
|
|
|
|
ret += string([]byte{b})
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.interested {
|
2015-08-02 02:06:22 +08:00
|
|
|
c('i')
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.choking {
|
2015-08-02 02:06:22 +08:00
|
|
|
c('c')
|
|
|
|
}
|
|
|
|
c('-')
|
|
|
|
ret += cn.connectionFlags()
|
2015-03-18 15:38:29 +08:00
|
|
|
c('-')
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.peerInterested {
|
2015-03-18 15:38:29 +08:00
|
|
|
c('i')
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.peerChoking {
|
2015-03-18 15:38:29 +08:00
|
|
|
c('c')
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-02-05 14:47:47 +08:00
|
|
|
// func (cn *connection) String() string {
|
|
|
|
// var buf bytes.Buffer
|
2020-02-21 08:07:50 +08:00
|
|
|
// cn.writeStatus(&buf, nil)
|
2018-02-05 14:47:47 +08:00
|
|
|
// return buf.String()
|
|
|
|
// }
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) downloadRate() float64 {
|
2020-01-10 12:09:21 +08:00
|
|
|
return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
|
2015-06-29 17:37:52 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) writeStatus(w io.Writer, t *Torrent) {
|
2015-03-18 15:38:29 +08:00
|
|
|
// \t isn't preserved in <pre> blocks?
|
2020-09-29 14:21:54 +08:00
|
|
|
fmt.Fprintln(w, cn.connStatusString())
|
2018-06-24 18:04:31 +08:00
|
|
|
fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
|
2015-03-18 15:38:29 +08:00
|
|
|
eventAgeString(cn.lastMessageReceived),
|
|
|
|
eventAgeString(cn.completedHandshake),
|
2018-02-05 14:47:47 +08:00
|
|
|
eventAgeString(cn.lastHelpful()),
|
|
|
|
cn.cumInterest(),
|
2018-06-24 18:04:31 +08:00
|
|
|
cn.totalExpectingTime(),
|
2018-02-05 14:47:47 +08:00
|
|
|
)
|
2015-05-15 06:39:53 +08:00
|
|
|
fmt.Fprintf(w,
|
2018-06-16 15:10:56 +08:00
|
|
|
" %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
|
2016-03-22 09:07:03 +08:00
|
|
|
cn.completedString(),
|
2015-08-03 23:12:09 +08:00
|
|
|
len(cn.peerTouchedPieces),
|
2020-01-10 12:09:21 +08:00
|
|
|
&cn._stats.ChunksReadUseful,
|
|
|
|
&cn._stats.ChunksRead,
|
|
|
|
&cn._stats.ChunksWritten,
|
2018-02-05 14:47:47 +08:00
|
|
|
cn.requestsLowWater,
|
2017-08-31 21:48:52 +08:00
|
|
|
cn.numLocalRequests(),
|
2018-02-05 14:47:47 +08:00
|
|
|
cn.nominalMaxRequests(),
|
2020-02-21 08:07:50 +08:00
|
|
|
len(cn.peerRequests),
|
2015-05-15 06:39:53 +08:00
|
|
|
cn.statusFlags(),
|
2018-02-05 14:47:47 +08:00
|
|
|
cn.downloadRate()/(1<<10),
|
2015-05-15 06:39:53 +08:00
|
|
|
)
|
2017-09-23 13:25:47 +08:00
|
|
|
fmt.Fprintf(w, " next pieces: %v%s\n",
|
2018-06-26 12:51:55 +08:00
|
|
|
iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
|
2017-09-23 13:25:47 +08:00
|
|
|
func() string {
|
2020-06-01 17:09:17 +08:00
|
|
|
if cn == t.fastestPeer {
|
2017-09-23 13:25:47 +08:00
|
|
|
return " (fastest)"
|
|
|
|
} else {
|
|
|
|
return ""
|
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
}(),
|
|
|
|
)
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 15:52:27 +08:00
|
|
|
func (cn *peer) close() {
|
2017-09-18 11:40:36 +08:00
|
|
|
if !cn.closed.Set() {
|
|
|
|
return
|
|
|
|
}
|
2020-05-30 15:52:27 +08:00
|
|
|
cn.discardPieceInclination()
|
|
|
|
cn._pieceRequestOrder.Clear()
|
2020-06-02 15:41:59 +08:00
|
|
|
cn.peerImpl._close()
|
2020-05-30 15:52:27 +08:00
|
|
|
}
|
|
|
|
|
2020-06-02 15:41:59 +08:00
|
|
|
func (cn *PeerConn) _close() {
|
2020-04-09 00:03:29 +08:00
|
|
|
if cn.pex.IsEnabled() {
|
|
|
|
cn.pex.Close()
|
|
|
|
}
|
2018-02-03 12:44:03 +08:00
|
|
|
cn.tickleWriter()
|
2016-05-11 21:50:21 +08:00
|
|
|
if cn.conn != nil {
|
2020-05-03 16:40:40 +08:00
|
|
|
cn.conn.Close()
|
2016-05-11 21:50:21 +08:00
|
|
|
}
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) peerHasPiece(piece pieceIndex) bool {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2018-02-03 12:29:06 +08:00
|
|
|
// Writes a message into the write buffer.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) post(msg pp.Message) {
|
2018-06-29 20:10:21 +08:00
|
|
|
torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
|
2018-02-03 12:29:06 +08:00
|
|
|
// We don't need to track bytes here because a connection.w Writer wrapper
|
|
|
|
// takes care of that (although there's some delay between us recording
|
|
|
|
// the message, and the connection writer flushing it out.).
|
2018-02-03 11:40:03 +08:00
|
|
|
cn.writeBuffer.Write(msg.MustMarshalBinary())
|
2018-02-03 12:29:06 +08:00
|
|
|
// Last I checked only Piece messages affect stats, and we don't post
|
|
|
|
// those.
|
|
|
|
cn.wroteMsg(&msg)
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.tickleWriter()
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2020-06-01 16:25:45 +08:00
|
|
|
// Returns true if there's room to write more.
|
2020-05-30 15:52:27 +08:00
|
|
|
func (cn *PeerConn) write(msg pp.Message) bool {
|
|
|
|
cn.wroteMsg(&msg)
|
|
|
|
cn.writeBuffer.Write(msg.MustMarshalBinary())
|
|
|
|
torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
|
|
|
|
// 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update
|
|
|
|
// when https://github.com/pion/datachannel/issues/59 is fixed.
|
|
|
|
return cn.writeBuffer.Len() < 1<<15
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) requestMetadataPiece(index int) {
|
2018-07-10 10:20:36 +08:00
|
|
|
eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
|
2015-03-27 12:36:59 +08:00
|
|
|
if eID == 0 {
|
|
|
|
return
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
|
2015-03-27 12:36:59 +08:00
|
|
|
return
|
|
|
|
}
|
2019-10-03 17:09:55 +08:00
|
|
|
cn.logger.Printf("requesting metadata piece %d", index)
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.post(pp.Message{
|
2015-03-27 12:36:59 +08: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 12:11:11 +08:00
|
|
|
for index >= len(cn.metadataRequests) {
|
|
|
|
cn.metadataRequests = append(cn.metadataRequests, false)
|
2015-03-27 12:36:59 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.metadataRequests[index] = true
|
2015-03-27 12:36:59 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) requestedMetadataPiece(index int) bool {
|
2016-04-19 12:11:11 +08:00
|
|
|
return index < len(cn.metadataRequests) && cn.metadataRequests[index]
|
2015-03-27 12:36:59 +08:00
|
|
|
}
|
|
|
|
|
2016-02-08 13:09:12 +08:00
|
|
|
// The actual value to use as the maximum outbound requests.
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) nominalMaxRequests() (ret int) {
|
2018-07-07 09:33:48 +08:00
|
|
|
return int(clamp(
|
|
|
|
1,
|
|
|
|
int64(cn.PeerMaxRequests),
|
2020-01-10 12:09:21 +08:00
|
|
|
int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) totalExpectingTime() (ret time.Duration) {
|
2018-06-24 18:04:31 +08:00
|
|
|
ret = cn.cumulativeExpectedToReceiveChunks
|
|
|
|
if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
|
|
|
|
ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) onPeerSentCancel(r request) {
|
|
|
|
if _, ok := cn.peerRequests[r]; !ok {
|
2018-02-04 21:18:38 +08:00
|
|
|
torrent.Add("unexpected cancels received", 1)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if cn.fastEnabled() {
|
|
|
|
cn.reject(r)
|
|
|
|
} else {
|
2020-02-21 08:07:50 +08:00
|
|
|
delete(cn.peerRequests, r)
|
2014-04-16 15:33:33 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) choke(msg messageWriter) (more bool) {
|
|
|
|
if cn.choking {
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2014-05-21 15:49:28 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.choking = true
|
2018-02-04 21:18:38 +08:00
|
|
|
more = msg(pp.Message{
|
2017-09-18 10:09:08 +08:00
|
|
|
Type: pp.Choke,
|
|
|
|
})
|
2018-02-04 21:18:38 +08:00
|
|
|
if cn.fastEnabled() {
|
2020-02-21 08:07:50 +08:00
|
|
|
for r := range cn.peerRequests {
|
2018-02-04 21:18:38 +08:00
|
|
|
// TODO: Don't reject pieces in allowed fast set.
|
|
|
|
cn.reject(r)
|
|
|
|
}
|
|
|
|
} else {
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.peerRequests = nil
|
2018-02-04 21:18:38 +08:00
|
|
|
}
|
|
|
|
return
|
2014-05-21 15:49:28 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
|
|
|
|
if !cn.choking {
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.choking = false
|
2017-09-18 10:09:08 +08:00
|
|
|
return msg(pp.Message{
|
2014-08-21 16:12:49 +08:00
|
|
|
Type: pp.Unchoke,
|
2014-04-03 20:16:59 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) setInterested(interested bool) bool {
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.interested == interested {
|
2017-08-31 21:48:52 +08:00
|
|
|
return true
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.interested = interested
|
2018-02-05 14:47:47 +08:00
|
|
|
if interested {
|
|
|
|
cn.lastBecameInterested = time.Now()
|
|
|
|
} else if !cn.lastBecameInterested.IsZero() {
|
|
|
|
cn.priorInterest += time.Since(cn.lastBecameInterested)
|
|
|
|
}
|
2018-06-24 18:04:31 +08:00
|
|
|
cn.updateExpectingChunks()
|
2017-08-31 21:48:52 +08:00
|
|
|
// log.Printf("%p: setting interest: %v", cn, interested)
|
2020-06-02 15:41:59 +08:00
|
|
|
return cn.writeInterested(interested)
|
2020-05-30 13:18:28 +08:00
|
|
|
}
|
|
|
|
|
2020-06-02 15:41:59 +08:00
|
|
|
func (pc *PeerConn) writeInterested(interested bool) bool {
|
2020-05-30 13:18:28 +08:00
|
|
|
return pc.write(pp.Message{
|
2014-08-21 16:12:49 +08:00
|
|
|
Type: func() pp.MessageType {
|
2014-04-03 20:16:59 +08:00
|
|
|
if interested {
|
2014-08-21 16:12:49 +08:00
|
|
|
return pp.Interested
|
2014-04-03 20:16:59 +08:00
|
|
|
} else {
|
2014-08-21 16:12:49 +08:00
|
|
|
return pp.NotInterested
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
}(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-11-06 11:53:00 +08:00
|
|
|
// The function takes a message to be sent, and returns true if more messages
|
|
|
|
// are okay.
|
|
|
|
type messageWriter func(pp.Message) bool
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) request(r request) bool {
|
2017-11-06 11:53:00 +08:00
|
|
|
if _, ok := cn.requests[r]; ok {
|
|
|
|
panic("chunk already requested")
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if !cn.peerHasPiece(pieceIndex(r.Index)) {
|
2017-11-06 11:53:00 +08:00
|
|
|
panic("requesting piece peer doesn't have")
|
|
|
|
}
|
2020-05-30 13:18:28 +08:00
|
|
|
if !cn.t.peerIsActive(cn) {
|
2018-02-02 10:36:18 +08:00
|
|
|
panic("requesting but not in active conns")
|
|
|
|
}
|
2018-02-15 12:21:51 +08:00
|
|
|
if cn.closed.IsSet() {
|
|
|
|
panic("requesting when connection is closed")
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.peerChoking {
|
2018-02-04 21:18:38 +08:00
|
|
|
if cn.peerAllowedFast.Get(int(r.Index)) {
|
|
|
|
torrent.Add("allowed fast requests sent", 1)
|
|
|
|
} else {
|
2020-02-21 08:07:50 +08:00
|
|
|
panic("requesting while choking and not allowed fast")
|
2018-02-04 21:18:38 +08:00
|
|
|
}
|
|
|
|
}
|
2018-06-26 11:04:15 +08:00
|
|
|
if cn.t.hashingPiece(pieceIndex(r.Index)) {
|
|
|
|
panic("piece is being hashed")
|
|
|
|
}
|
|
|
|
if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
|
|
|
|
panic("piece is queued for hash")
|
|
|
|
}
|
2018-06-24 18:35:46 +08:00
|
|
|
if cn.requests == nil {
|
|
|
|
cn.requests = make(map[request]struct{})
|
|
|
|
}
|
2018-02-15 12:21:51 +08:00
|
|
|
cn.requests[r] = struct{}{}
|
2018-06-24 18:35:46 +08:00
|
|
|
if cn.validReceiveChunks == nil {
|
2020-04-23 10:34:43 +08:00
|
|
|
cn.validReceiveChunks = make(map[request]int)
|
2018-06-24 18:35:46 +08:00
|
|
|
}
|
2020-04-23 10:34:43 +08:00
|
|
|
cn.validReceiveChunks[r]++
|
2018-02-01 11:46:03 +08:00
|
|
|
cn.t.pendingRequests[r]++
|
2020-01-10 13:18:55 +08:00
|
|
|
cn.t.requestStrategy.hooks().sentRequest(r)
|
2018-06-24 18:04:31 +08:00
|
|
|
cn.updateExpectingChunks()
|
2020-06-02 15:41:59 +08:00
|
|
|
return cn.peerImpl.request(r)
|
2020-05-30 13:18:28 +08:00
|
|
|
}
|
|
|
|
|
2020-06-02 15:41:59 +08:00
|
|
|
func (me *PeerConn) request(r request) bool {
|
2020-05-30 13:18:28 +08:00
|
|
|
return me.write(pp.Message{
|
2017-11-06 11:53:00 +08:00
|
|
|
Type: pp.Request,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
|
|
|
Length: r.Length,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-06-02 15:41:59 +08:00
|
|
|
func (me *PeerConn) cancel(r request) bool {
|
2020-05-30 13:18:28 +08:00
|
|
|
return me.write(makeCancelMessage(r))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *peer) doRequestState() bool {
|
2020-02-22 16:40:50 +08:00
|
|
|
if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
|
2020-05-30 13:18:28 +08:00
|
|
|
if !cn.setInterested(false) {
|
|
|
|
return false
|
2018-06-26 12:51:55 +08:00
|
|
|
}
|
|
|
|
if len(cn.requests) != 0 {
|
|
|
|
for r := range cn.requests {
|
|
|
|
cn.deleteRequest(r)
|
|
|
|
// log.Printf("%p: cancelling request: %v", cn, r)
|
2020-06-02 15:41:59 +08:00
|
|
|
if !cn.peerImpl.cancel(r) {
|
2020-05-30 13:18:28 +08:00
|
|
|
return false
|
2018-06-26 12:51:55 +08:00
|
|
|
}
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
|
|
|
}
|
2020-02-22 16:38:56 +08:00
|
|
|
} else if len(cn.requests) <= cn.requestsLowWater {
|
2018-06-26 12:51:55 +08:00
|
|
|
filledBuffer := false
|
2018-07-12 07:15:15 +08:00
|
|
|
cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
|
2018-06-26 12:51:55 +08:00
|
|
|
cn.iterPendingRequests(pieceIndex, func(r request) bool {
|
2020-05-30 13:18:28 +08:00
|
|
|
if !cn.setInterested(true) {
|
2018-06-26 12:51:55 +08:00
|
|
|
filledBuffer = true
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if len(cn.requests) >= cn.nominalMaxRequests() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// Choking is looked at here because our interest is dependent
|
|
|
|
// on whether we'd make requests in its absence.
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.peerChoking {
|
2018-06-26 12:51:55 +08:00
|
|
|
if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if _, ok := cn.requests[r]; ok {
|
|
|
|
return true
|
|
|
|
}
|
2020-05-30 13:18:28 +08:00
|
|
|
filledBuffer = !cn.request(r)
|
2018-06-26 12:51:55 +08:00
|
|
|
return !filledBuffer
|
|
|
|
})
|
|
|
|
return !filledBuffer
|
|
|
|
})
|
|
|
|
if filledBuffer {
|
|
|
|
// If we didn't completely top up the requests, we shouldn't mark
|
|
|
|
// the low water, since we'll want to top up the requests as soon
|
|
|
|
// as we have more write buffer space.
|
2020-05-30 13:18:28 +08:00
|
|
|
return false
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
2017-09-02 08:36:43 +08:00
|
|
|
cn.requestsLowWater = len(cn.requests) / 2
|
2017-09-01 08:36:43 +08:00
|
|
|
}
|
2020-05-30 13:18:28 +08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *PeerConn) fillWriteBuffer() {
|
|
|
|
if !cn.doRequestState() {
|
|
|
|
return
|
|
|
|
}
|
2020-04-09 00:03:29 +08:00
|
|
|
if cn.pex.IsEnabled() {
|
2020-05-30 13:18:28 +08:00
|
|
|
if flow := cn.pex.Share(cn.write); !flow {
|
2020-04-15 20:02:34 +08:00
|
|
|
return
|
|
|
|
}
|
2020-04-09 00:03:29 +08:00
|
|
|
}
|
2020-05-30 13:18:28 +08:00
|
|
|
cn.upload(cn.write)
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
|
|
|
|
2017-12-02 21:35:09 +08:00
|
|
|
// Routine that writes to the peer. Some of what to write is buffered by
|
|
|
|
// activity elsewhere in the Client, and some is determined locally when the
|
|
|
|
// connection is writable.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
|
2017-08-31 14:26:45 +08:00
|
|
|
var (
|
2018-02-03 12:09:38 +08:00
|
|
|
lastWrite time.Time = time.Now()
|
|
|
|
keepAliveTimer *time.Timer
|
2017-08-31 14:26:45 +08:00
|
|
|
)
|
|
|
|
keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
|
2020-02-21 08:51:24 +08:00
|
|
|
cn.locker().Lock()
|
|
|
|
defer cn.locker().Unlock()
|
2017-08-31 14:26:45 +08:00
|
|
|
if time.Since(lastWrite) >= keepAliveTimeout {
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.tickleWriter()
|
2017-08-31 14:26:45 +08:00
|
|
|
}
|
|
|
|
keepAliveTimer.Reset(keepAliveTimeout)
|
|
|
|
})
|
2020-02-21 08:51:24 +08:00
|
|
|
cn.locker().Lock()
|
|
|
|
defer cn.locker().Unlock()
|
2020-02-21 08:07:50 +08:00
|
|
|
defer cn.close()
|
2017-08-31 14:26:45 +08:00
|
|
|
defer keepAliveTimer.Stop()
|
2018-02-03 12:09:38 +08:00
|
|
|
frontBuf := new(bytes.Buffer)
|
2014-08-21 16:12:49 +08:00
|
|
|
for {
|
2018-02-02 10:36:18 +08:00
|
|
|
if cn.closed.IsSet() {
|
|
|
|
return
|
|
|
|
}
|
2018-02-03 11:40:03 +08:00
|
|
|
if cn.writeBuffer.Len() == 0 {
|
2020-05-30 13:18:28 +08:00
|
|
|
cn.fillWriteBuffer()
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
2018-02-03 11:40:03 +08:00
|
|
|
if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
|
|
|
|
cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
|
2017-08-31 14:26:45 +08:00
|
|
|
postedKeepalives.Add(1)
|
|
|
|
}
|
2018-02-03 11:40:03 +08:00
|
|
|
if cn.writeBuffer.Len() == 0 {
|
2017-11-05 12:26:23 +08:00
|
|
|
// TODO: Minimize wakeups....
|
2017-08-31 14:26:45 +08:00
|
|
|
cn.writerCond.Wait()
|
|
|
|
continue
|
2016-05-07 16:56:44 +08:00
|
|
|
}
|
2018-02-03 12:09:38 +08:00
|
|
|
// Flip the buffers.
|
|
|
|
frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
|
2020-02-21 08:51:24 +08:00
|
|
|
cn.locker().Unlock()
|
2018-02-03 12:09:38 +08:00
|
|
|
n, err := cn.w.Write(frontBuf.Bytes())
|
2020-02-21 08:51:24 +08:00
|
|
|
cn.locker().Lock()
|
2017-08-31 14:26:45 +08:00
|
|
|
if n != 0 {
|
|
|
|
lastWrite = time.Now()
|
2016-05-07 16:56:44 +08:00
|
|
|
keepAliveTimer.Reset(keepAliveTimeout)
|
|
|
|
}
|
2017-08-31 14:26:45 +08:00
|
|
|
if err != nil {
|
2020-05-03 16:40:09 +08:00
|
|
|
cn.logger.Printf("error writing: %v", err)
|
2014-08-21 16:12:49 +08:00
|
|
|
return
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2018-02-03 12:09:38 +08:00
|
|
|
if n != frontBuf.Len() {
|
2017-08-31 14:26:45 +08:00
|
|
|
panic("short write")
|
|
|
|
}
|
2018-02-03 12:09:38 +08:00
|
|
|
frontBuf.Reset()
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
}
|
2016-01-04 19:37:49 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) have(piece pieceIndex) {
|
2018-07-12 07:15:15 +08:00
|
|
|
if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
|
2016-01-04 19:37:49 +08:00
|
|
|
return
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.post(pp.Message{
|
2016-01-04 19:37:49 +08:00
|
|
|
Type: pp.Have,
|
|
|
|
Index: pp.Integer(piece),
|
|
|
|
})
|
2018-07-12 07:15:15 +08:00
|
|
|
cn.sentHaves.Add(bitmap.BitIndex(piece))
|
2016-01-04 19:37:49 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) postBitfield() {
|
2018-02-04 16:10:25 +08:00
|
|
|
if cn.sentHaves.Len() != 0 {
|
2016-01-04 19:37:49 +08:00
|
|
|
panic("bitfield must be first have-related message sent")
|
|
|
|
}
|
2018-02-04 16:10:25 +08:00
|
|
|
if !cn.t.haveAnyPieces() {
|
|
|
|
return
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
cn.post(pp.Message{
|
2016-01-04 19:37:49 +08:00
|
|
|
Type: pp.Bitfield,
|
2018-02-04 16:10:25 +08:00
|
|
|
Bitfield: cn.t.bitfield(),
|
2016-01-04 19:37:49 +08:00
|
|
|
})
|
2020-01-10 12:09:21 +08:00
|
|
|
cn.sentHaves = cn.t._completedPieces.Copy()
|
2016-01-04 19:37:49 +08:00
|
|
|
}
|
2016-01-24 12:21:17 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) updateRequests() {
|
2018-01-25 14:18:36 +08:00
|
|
|
// log.Print("update requests")
|
2017-09-01 13:26:50 +08:00
|
|
|
cn.tickleWriter()
|
2017-08-31 21:48:52 +08:00
|
|
|
}
|
|
|
|
|
2017-11-06 11:53:00 +08:00
|
|
|
// Emits the indices in the Bitmaps bms in order, never repeating any index.
|
|
|
|
// skip is mutated during execution, and its initial values will never be
|
|
|
|
// emitted.
|
2018-02-08 12:08:33 +08:00
|
|
|
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
|
2017-09-23 13:25:47 +08:00
|
|
|
return func(cb iter.Callback) {
|
|
|
|
for _, bm := range bms {
|
2020-01-10 07:27:05 +08:00
|
|
|
if !iter.All(
|
|
|
|
func(i interface{}) bool {
|
|
|
|
skip.Add(i.(int))
|
|
|
|
return cb(i)
|
|
|
|
},
|
|
|
|
bitmap.Sub(bm, *skip).Iter,
|
|
|
|
) {
|
2017-09-23 13:25:47 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-10 12:09:21 +08:00
|
|
|
func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
|
|
|
|
now, readahead := cn.torrent().readerPiecePriorities()
|
|
|
|
skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
|
|
|
|
skip.Union(cn.torrent().ignorePieces())
|
2020-01-10 07:27:05 +08:00
|
|
|
// Return an iterator over the different priority classes, minus the skip pieces.
|
2018-06-26 12:51:55 +08:00
|
|
|
return iter.All(
|
|
|
|
func(_piece interface{}) bool {
|
2020-01-10 12:09:21 +08:00
|
|
|
return f(pieceIndex(_piece.(bitmap.BitIndex)))
|
2018-06-26 12:51:55 +08:00
|
|
|
},
|
2018-02-08 12:08:33 +08:00
|
|
|
iterBitmapsDistinct(&skip, now, readahead),
|
2020-01-10 12:09:21 +08:00
|
|
|
// We have to iterate _pendingPieces separately because it isn't a Bitmap.
|
2018-01-12 09:24:37 +08:00
|
|
|
func(cb iter.Callback) {
|
2020-01-10 12:09:21 +08:00
|
|
|
cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
|
2018-01-12 09:24:37 +08:00
|
|
|
if skip.Contains(piece) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
more := cb(piece)
|
|
|
|
skip.Add(piece)
|
|
|
|
return more
|
|
|
|
})
|
|
|
|
},
|
|
|
|
)
|
2017-09-23 13:25:47 +08:00
|
|
|
}
|
|
|
|
|
2020-01-10 07:27:05 +08:00
|
|
|
// The connection should download highest priority pieces first, without any inclination toward
|
|
|
|
// avoiding wastage. Generally we might do this if there's a single connection, or this is the
|
|
|
|
// fastest connection, and we have active readers that signal an ordering preference. It's
|
|
|
|
// conceivable that the best connection should do this, since it's least likely to waste our time if
|
|
|
|
// assigned to the highest priority pieces, and assigning more than one this role would cause
|
|
|
|
// significant wasted bandwidth.
|
2020-05-31 11:09:56 +08:00
|
|
|
func (cn *peer) shouldRequestWithoutBias() bool {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) iterPendingPieces(f func(pieceIndex) bool) bool {
|
2018-06-28 09:12:49 +08:00
|
|
|
if !cn.t.haveInfo() {
|
|
|
|
return false
|
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn.t.requestStrategy.iterPendingPieces(cn, f)
|
|
|
|
}
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) iterPendingPiecesUntyped(f iter.Callback) {
|
2018-07-12 07:15:15 +08:00
|
|
|
cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
|
2018-06-26 12:51:55 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
|
2020-01-10 13:18:55 +08:00
|
|
|
return cn.t.requestStrategy.iterUndirtiedChunks(
|
|
|
|
cn.t.piece(piece).requestStrategyPiece(),
|
2020-01-10 12:09:21 +08:00
|
|
|
func(cs chunkSpec) bool {
|
|
|
|
return f(request{pp.Integer(piece), cs})
|
2020-01-10 13:18:55 +08:00
|
|
|
},
|
|
|
|
)
|
2018-02-01 13:14:13 +08:00
|
|
|
}
|
|
|
|
|
2017-09-01 13:26:50 +08:00
|
|
|
// check callers updaterequests
|
2020-05-31 11:09:56 +08:00
|
|
|
func (cn *peer) stopRequestingPiece(piece pieceIndex) bool {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
|
|
|
|
2016-10-31 13:22:07 +08:00
|
|
|
// This is distinct from Torrent piece priority, which is the user's
|
2018-01-25 14:02:52 +08:00
|
|
|
// preference. Connection piece priority is specific to a connection and is
|
|
|
|
// used to pseudorandomly avoid connections always requesting the same pieces
|
|
|
|
// and thus wasting effort.
|
2020-05-31 11:09:56 +08:00
|
|
|
func (cn *peer) updatePiecePriority(piece pieceIndex) bool {
|
2016-04-19 12:11:11 +08:00
|
|
|
tpp := cn.t.piecePriority(piece)
|
2020-02-21 08:07:50 +08:00
|
|
|
if !cn.peerHasPiece(piece) {
|
2016-02-09 21:47:53 +08:00
|
|
|
tpp = PiecePriorityNone
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
2016-02-01 18:11:41 +08:00
|
|
|
if tpp == PiecePriorityNone {
|
2017-09-01 13:26:50 +08:00
|
|
|
return cn.stopRequestingPiece(piece)
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
prio := cn.getPieceInclination()[piece]
|
2020-01-10 12:09:21 +08:00
|
|
|
prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
|
|
|
|
return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
|
|
|
|
}
|
|
|
|
|
2020-05-31 11:09:56 +08:00
|
|
|
func (cn *peer) getPieceInclination() []int {
|
2016-04-19 12:11:11 +08:00
|
|
|
if cn.pieceInclination == nil {
|
|
|
|
cn.pieceInclination = cn.t.getConnPieceInclination()
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
return cn.pieceInclination
|
2016-02-01 18:11:41 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 15:52:27 +08:00
|
|
|
func (cn *peer) discardPieceInclination() {
|
2016-04-19 12:11:11 +08:00
|
|
|
if cn.pieceInclination == nil {
|
2016-02-01 18:11:41 +08:00
|
|
|
return
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.t.putPieceInclination(cn.pieceInclination)
|
|
|
|
cn.pieceInclination = nil
|
2016-01-24 12:21:17 +08:00
|
|
|
}
|
2016-03-21 11:17:15 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) peerPiecesChanged() {
|
2016-04-19 12:11:11 +08:00
|
|
|
if cn.t.haveInfo() {
|
2017-09-01 13:26:50 +08:00
|
|
|
prioritiesChanged := false
|
2018-07-12 07:15:15 +08:00
|
|
|
for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
|
2017-09-01 13:26:50 +08:00
|
|
|
if cn.updatePiecePriority(i) {
|
|
|
|
prioritiesChanged = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if prioritiesChanged {
|
|
|
|
cn.updateRequests()
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2016-03-22 09:07:03 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
|
2016-04-19 12:11:11 +08:00
|
|
|
if newMin > cn.peerMinPieces {
|
|
|
|
cn.peerMinPieces = newMin
|
2016-03-22 09:07:03 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
|
2018-01-09 14:26:01 +08:00
|
|
|
if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
|
2016-03-22 09:07:03 +08:00
|
|
|
return errors.New("invalid piece")
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if cn.peerHasPiece(piece) {
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.raisePeerMinPieces(piece + 1)
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.Set(bitmap.BitIndex(piece), true)
|
2017-09-01 13:26:50 +08:00
|
|
|
if cn.updatePiecePriority(piece) {
|
|
|
|
cn.updateRequests()
|
|
|
|
}
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) peerSentBitfield(bf []bool) error {
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = false
|
2016-03-22 09:07:03 +08: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.
|
2018-07-12 07:15:15 +08:00
|
|
|
cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
|
|
|
|
if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
|
2016-03-22 09:07:03 +08:00
|
|
|
// Ignore known excess pieces.
|
2016-04-19 12:11:11 +08:00
|
|
|
bf = bf[:cn.t.numPieces()]
|
2016-03-22 09:07:03 +08:00
|
|
|
}
|
|
|
|
for i, have := range bf {
|
|
|
|
if have {
|
2018-07-12 07:15:15 +08:00
|
|
|
cn.raisePeerMinPieces(pieceIndex(i) + 1)
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.Set(i, have)
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.peerPiecesChanged()
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) onPeerSentHaveAll() error {
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = true
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.Clear()
|
2016-03-22 09:07:03 +08:00
|
|
|
cn.peerPiecesChanged()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) peerSentHaveNone() error {
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.Clear()
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = false
|
2016-04-19 12:11:11 +08:00
|
|
|
cn.peerPiecesChanged()
|
2016-03-21 11:17:15 +08:00
|
|
|
return nil
|
|
|
|
}
|
2016-05-16 16:46:38 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) requestPendingMetadata() {
|
2016-05-16 16:46:38 +08:00
|
|
|
if c.t.haveInfo() {
|
|
|
|
return
|
|
|
|
}
|
2018-07-10 10:20:36 +08:00
|
|
|
if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
|
2016-05-16 16:46:38 +08:00
|
|
|
// 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)
|
|
|
|
}
|
|
|
|
}
|
2019-10-01 16:45:36 +08:00
|
|
|
rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
|
|
|
|
for _, i := range pending {
|
|
|
|
c.requestMetadataPiece(i)
|
2016-05-16 16:46:38 +08:00
|
|
|
}
|
|
|
|
}
|
2016-07-05 13:52:33 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) wroteMsg(msg *pp.Message) {
|
2018-06-29 20:10:21 +08:00
|
|
|
torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
|
2020-04-15 16:09:15 +08:00
|
|
|
if msg.Type == pp.Extended {
|
|
|
|
for name, id := range cn.PeerExtensionIDs {
|
|
|
|
if id != msg.ExtendedID {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
|
|
|
|
}
|
|
|
|
}
|
2018-06-10 07:18:52 +08:00
|
|
|
cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
|
2016-07-05 13:52:33 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) readMsg(msg *pp.Message) {
|
2018-06-10 07:18:52 +08:00
|
|
|
cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
|
2016-07-12 14:42:04 +08:00
|
|
|
}
|
|
|
|
|
2018-06-10 07:18:52 +08:00
|
|
|
// After handshake, we know what Torrent and Client stats to include for a
|
|
|
|
// connection.
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) postHandshakeStats(f func(*ConnStats)) {
|
2018-06-10 07:18:52 +08:00
|
|
|
t := cn.t
|
2018-06-12 18:21:53 +08:00
|
|
|
f(&t.stats)
|
2018-06-10 07:18:52 +08:00
|
|
|
f(&t.cl.stats)
|
|
|
|
}
|
|
|
|
|
|
|
|
// All ConnStats that include this connection. Some objects are not known
|
|
|
|
// until the handshake is complete, after which it's expected to reconcile the
|
|
|
|
// differences.
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) allStats(f func(*ConnStats)) {
|
2020-01-10 12:09:21 +08:00
|
|
|
f(&cn._stats)
|
2018-06-10 07:18:52 +08:00
|
|
|
if cn.reconciledHandshakeStats {
|
|
|
|
cn.postHandshakeStats(f)
|
2016-07-12 14:42:04 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) wroteBytes(n int64) {
|
2018-06-12 18:21:53 +08:00
|
|
|
cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
|
2018-06-10 07:18:52 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) readBytes(n int64) {
|
2018-06-12 18:21:53 +08:00
|
|
|
cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
|
2016-07-05 13:52:33 +08:00
|
|
|
}
|
2016-07-05 14:23:17 +08:00
|
|
|
|
2018-02-01 15:49:53 +08:00
|
|
|
// Returns whether the connection could be useful to us. We're seeding and
|
2016-07-05 14:23:17 +08:00
|
|
|
// they want data, we don't have metainfo and they can provide it, etc.
|
2020-06-01 16:25:45 +08:00
|
|
|
func (c *peer) useful() bool {
|
2016-07-05 14:23:17 +08:00
|
|
|
t := c.t
|
|
|
|
if c.closed.IsSet() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if !t.haveInfo() {
|
|
|
|
return c.supportsExtension("ut_metadata")
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if t.seeding() && c.peerInterested {
|
2018-02-01 15:49:53 +08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
if c.peerHasWantedPieces() {
|
|
|
|
return true
|
2016-07-05 14:23:17 +08:00
|
|
|
}
|
2018-02-01 15:49:53 +08:00
|
|
|
return false
|
2016-07-05 14:23:17 +08:00
|
|
|
}
|
2016-07-05 22:42:16 +08:00
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) lastHelpful() (ret time.Time) {
|
2016-08-14 20:39:23 +08:00
|
|
|
ret = c.lastUsefulChunkReceived
|
|
|
|
if c.t.seeding() && c.lastChunkSent.After(ret) {
|
|
|
|
ret = c.lastChunkSent
|
2016-07-05 22:42:16 +08:00
|
|
|
}
|
2016-08-14 20:39:23 +08:00
|
|
|
return
|
2016-07-05 22:42:16 +08:00
|
|
|
}
|
2016-09-11 12:32:56 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) fastEnabled() bool {
|
2020-04-23 11:03:35 +08:00
|
|
|
return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
|
2018-02-03 10:35:09 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) reject(r request) {
|
2018-02-03 10:35:09 +08:00
|
|
|
if !c.fastEnabled() {
|
2018-02-04 21:18:38 +08:00
|
|
|
panic("fast not enabled")
|
2018-02-03 10:35:09 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
c.post(r.ToMsg(pp.Reject))
|
|
|
|
delete(c.peerRequests, r)
|
2018-02-03 10:35:09 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) onReadRequest(r request) error {
|
2018-02-02 16:19:14 +08:00
|
|
|
requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
|
2020-02-21 08:07:50 +08:00
|
|
|
if _, ok := c.peerRequests[r]; ok {
|
2018-02-04 21:18:38 +08:00
|
|
|
torrent.Add("duplicate requests received", 1)
|
2018-02-03 10:35:09 +08:00
|
|
|
return nil
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if c.choking {
|
2018-02-04 21:18:38 +08:00
|
|
|
torrent.Add("requests received while choking", 1)
|
|
|
|
if c.fastEnabled() {
|
|
|
|
torrent.Add("requests rejected while choking", 1)
|
|
|
|
c.reject(r)
|
|
|
|
}
|
2018-02-02 16:19:14 +08:00
|
|
|
return nil
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if len(c.peerRequests) >= maxRequests {
|
2018-02-04 21:18:38 +08:00
|
|
|
torrent.Add("requests received while queue full", 1)
|
|
|
|
if c.fastEnabled() {
|
|
|
|
c.reject(r)
|
|
|
|
}
|
|
|
|
// BEP 6 says we may close here if we choose.
|
2018-02-02 16:19:14 +08:00
|
|
|
return nil
|
|
|
|
}
|
2018-07-17 19:28:01 +08:00
|
|
|
if !c.t.havePiece(pieceIndex(r.Index)) {
|
2018-02-02 16:19:14 +08:00
|
|
|
// 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)
|
|
|
|
return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
|
|
|
|
}
|
2019-08-23 10:19:28 +08:00
|
|
|
// Check this after we know we have the piece, so that the piece length will be known.
|
|
|
|
if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
|
|
|
|
torrent.Add("bad requests received", 1)
|
|
|
|
return errors.New("bad request")
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if c.peerRequests == nil {
|
|
|
|
c.peerRequests = make(map[request]struct{}, maxRequests)
|
2018-02-02 16:19:14 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
c.peerRequests[r] = struct{}{}
|
2018-02-02 16:19:14 +08:00
|
|
|
c.tickleWriter()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-04-23 10:34:43 +08:00
|
|
|
func runSafeExtraneous(f func()) {
|
|
|
|
if true {
|
|
|
|
go f()
|
|
|
|
} else {
|
|
|
|
f()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-01 16:13:55 +08:00
|
|
|
// Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
|
|
|
|
// exit. Returning will end the connection.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) mainReadLoop() (err error) {
|
2018-02-12 21:56:21 +08:00
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
torrent.Add("connection.mainReadLoop returned with error", 1)
|
|
|
|
} else {
|
|
|
|
torrent.Add("connection.mainReadLoop returned with no error", 1)
|
|
|
|
}
|
|
|
|
}()
|
2016-09-11 12:32:56 +08:00
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
2016-09-12 15:10:11 +08:00
|
|
|
|
2016-09-11 12:32:56 +08:00
|
|
|
decoder := pp.Decoder{
|
2017-09-21 17:29:56 +08:00
|
|
|
R: bufio.NewReaderSize(c.r, 1<<17),
|
2016-09-11 12:32:56 +08:00
|
|
|
MaxLength: 256 * 1024,
|
2016-10-05 12:57:00 +08:00
|
|
|
Pool: t.chunkPool,
|
2016-09-11 12:32:56 +08:00
|
|
|
}
|
|
|
|
for {
|
2018-02-12 21:56:21 +08:00
|
|
|
var msg pp.Message
|
2017-08-31 14:25:49 +08:00
|
|
|
func() {
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.unlock()
|
|
|
|
defer cl.lock()
|
2017-08-31 14:25:49 +08:00
|
|
|
err = decoder.Decode(&msg)
|
|
|
|
}()
|
2020-07-15 12:00:47 +08:00
|
|
|
if cb := cl.config.Callbacks.ReadMessage; cb != nil && err == nil {
|
|
|
|
cb(c, &msg)
|
|
|
|
}
|
2020-05-03 16:40:09 +08:00
|
|
|
if t.closed.IsSet() || c.closed.IsSet() {
|
2016-09-11 12:32:56 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.readMsg(&msg)
|
|
|
|
c.lastMessageReceived = time.Now()
|
|
|
|
if msg.Keepalive {
|
|
|
|
receivedKeepalives.Add(1)
|
|
|
|
continue
|
|
|
|
}
|
2018-02-05 12:30:35 +08:00
|
|
|
messageTypesReceived.Add(msg.Type.String(), 1)
|
2018-02-04 21:18:38 +08:00
|
|
|
if msg.Type.FastExtension() && !c.fastEnabled() {
|
2020-04-23 10:34:43 +08:00
|
|
|
runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
|
2018-02-04 21:18:38 +08:00
|
|
|
return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
|
|
|
|
}
|
2016-09-11 12:32:56 +08:00
|
|
|
switch msg.Type {
|
|
|
|
case pp.Choke:
|
2020-02-21 08:07:50 +08:00
|
|
|
c.peerChoking = true
|
2020-04-23 10:36:19 +08:00
|
|
|
if !c.fastEnabled() {
|
|
|
|
c.deleteAllRequests()
|
|
|
|
}
|
2016-09-11 12:32:56 +08:00
|
|
|
// We can then reset our interest.
|
|
|
|
c.updateRequests()
|
2018-06-24 18:04:31 +08:00
|
|
|
c.updateExpectingChunks()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Unchoke:
|
2020-02-21 08:07:50 +08:00
|
|
|
c.peerChoking = false
|
2017-09-01 13:26:50 +08:00
|
|
|
c.tickleWriter()
|
2018-06-24 18:04:31 +08:00
|
|
|
c.updateExpectingChunks()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Interested:
|
2020-02-21 08:07:50 +08:00
|
|
|
c.peerInterested = true
|
2017-09-18 10:09:08 +08:00
|
|
|
c.tickleWriter()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.NotInterested:
|
2020-02-21 08:07:50 +08:00
|
|
|
c.peerInterested = false
|
2018-06-23 20:32:11 +08:00
|
|
|
// We don't clear their requests since it isn't clear in the spec.
|
|
|
|
// We'll probably choke them for this, which will clear them if
|
|
|
|
// appropriate, and is clearly specified.
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Have:
|
2018-07-17 19:28:01 +08:00
|
|
|
err = c.peerSentHave(pieceIndex(msg.Index))
|
2019-10-01 16:13:16 +08:00
|
|
|
case pp.Bitfield:
|
|
|
|
err = c.peerSentBitfield(msg.Bitfield)
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Request:
|
2018-02-02 16:19:14 +08:00
|
|
|
r := newRequestFromMessage(&msg)
|
|
|
|
err = c.onReadRequest(r)
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Piece:
|
2018-06-24 18:35:46 +08:00
|
|
|
err = c.receiveChunk(&msg)
|
2016-09-12 15:10:11 +08:00
|
|
|
if len(msg.Piece) == int(t.chunkSize) {
|
2017-11-07 13:11:59 +08:00
|
|
|
t.chunkPool.Put(&msg.Piece)
|
2016-09-12 15:10:11 +08:00
|
|
|
}
|
2018-06-26 18:24:39 +08:00
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("receiving chunk: %s", err)
|
|
|
|
}
|
2019-10-01 16:13:16 +08:00
|
|
|
case pp.Cancel:
|
|
|
|
req := newRequestFromMessage(&msg)
|
|
|
|
c.onPeerSentCancel(req)
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Port:
|
2020-07-15 14:15:38 +08:00
|
|
|
ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
|
2020-02-20 13:47:37 +08:00
|
|
|
if !ok {
|
|
|
|
break
|
|
|
|
}
|
2018-11-04 13:56:55 +08:00
|
|
|
pingAddr := net.UDPAddr{
|
2020-02-20 13:47:37 +08:00
|
|
|
IP: ipa.IP,
|
|
|
|
Port: ipa.Port,
|
2016-09-11 12:32:56 +08:00
|
|
|
}
|
|
|
|
if msg.Port != 0 {
|
|
|
|
pingAddr.Port = int(msg.Port)
|
|
|
|
}
|
2020-02-20 14:46:29 +08:00
|
|
|
cl.eachDhtServer(func(s DhtServer) {
|
|
|
|
go s.Ping(&pingAddr)
|
2018-04-12 09:41:07 +08:00
|
|
|
})
|
2019-10-01 16:13:16 +08:00
|
|
|
case pp.Suggest:
|
|
|
|
torrent.Add("suggests received", 1)
|
2020-04-16 15:20:58 +08:00
|
|
|
log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
|
2019-10-01 16:13:16 +08:00
|
|
|
c.updateRequests()
|
|
|
|
case pp.HaveAll:
|
|
|
|
err = c.onPeerSentHaveAll()
|
|
|
|
case pp.HaveNone:
|
|
|
|
err = c.peerSentHaveNone()
|
|
|
|
case pp.Reject:
|
2020-06-02 14:41:49 +08:00
|
|
|
c.remoteRejectedRequest(newRequestFromMessage(&msg))
|
2018-02-04 21:18:38 +08:00
|
|
|
case pp.AllowedFast:
|
|
|
|
torrent.Add("allowed fasts received", 1)
|
2020-04-16 15:20:58 +08:00
|
|
|
log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
|
2018-02-04 21:18:38 +08:00
|
|
|
c.peerAllowedFast.Add(int(msg.Index))
|
|
|
|
c.updateRequests()
|
2019-10-01 16:13:16 +08:00
|
|
|
case pp.Extended:
|
|
|
|
err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
|
2016-09-11 12:32:56 +08:00
|
|
|
default:
|
|
|
|
err = fmt.Errorf("received unknown message type: %#v", msg.Type)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-10-10 13:30:51 +08:00
|
|
|
|
2020-06-02 14:41:49 +08:00
|
|
|
func (c *peer) remoteRejectedRequest(r request) {
|
2020-09-03 12:34:06 +08:00
|
|
|
if c.deleteRequest(r) {
|
|
|
|
c.decExpectedChunkReceive(r)
|
|
|
|
}
|
2020-06-02 14:41:49 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) decExpectedChunkReceive(r request) {
|
2020-04-23 10:34:43 +08:00
|
|
|
count := c.validReceiveChunks[r]
|
|
|
|
if count == 1 {
|
|
|
|
delete(c.validReceiveChunks, r)
|
|
|
|
} else if count > 1 {
|
|
|
|
c.validReceiveChunks[r] = count - 1
|
|
|
|
} else {
|
|
|
|
panic(r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
|
2018-02-03 11:06:10 +08:00
|
|
|
defer func() {
|
|
|
|
// TODO: Should we still do this?
|
|
|
|
if err != nil {
|
|
|
|
// These clients use their own extension IDs for outgoing message
|
|
|
|
// types, which is incorrect.
|
|
|
|
if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
|
|
|
switch id {
|
|
|
|
case pp.HandshakeExtendedID:
|
2018-07-10 10:20:36 +08:00
|
|
|
var d pp.ExtendedHandshakeMessage
|
|
|
|
if err := bencode.Unmarshal(payload, &d); err != nil {
|
2020-04-18 15:45:01 +08:00
|
|
|
c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
|
2018-07-10 10:20:36 +08:00
|
|
|
return errors.Wrap(err, "unmarshalling extended handshake payload")
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2020-07-15 14:16:09 +08:00
|
|
|
if cb := cl.config.Callbacks.ReadExtendedHandshake; cb != nil {
|
|
|
|
cb(c, &d)
|
|
|
|
}
|
2020-04-18 15:45:01 +08:00
|
|
|
//c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
|
2018-07-10 10:20:36 +08:00
|
|
|
if d.Reqq != 0 {
|
|
|
|
c.PeerMaxRequests = d.Reqq
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2018-07-10 10:20:36 +08:00
|
|
|
c.PeerClientName = d.V
|
|
|
|
if c.PeerExtensionIDs == nil {
|
|
|
|
c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2019-12-11 19:45:04 +08:00
|
|
|
c.PeerListenPort = d.Port
|
|
|
|
c.PeerPrefersEncryption = d.Encryption
|
2018-07-10 10:20:36 +08:00
|
|
|
for name, id := range d.M {
|
|
|
|
if _, ok := c.PeerExtensionIDs[name]; !ok {
|
|
|
|
torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2018-07-10 10:20:36 +08:00
|
|
|
c.PeerExtensionIDs[name] = id
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2018-07-10 10:20:36 +08:00
|
|
|
if d.MetadataSize != 0 {
|
|
|
|
if err = t.setMetadataSize(d.MetadataSize); err != nil {
|
|
|
|
return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
|
|
|
}
|
2019-10-01 16:46:10 +08:00
|
|
|
c.requestPendingMetadata()
|
2020-04-09 00:03:29 +08:00
|
|
|
if !t.cl.config.DisablePEX {
|
|
|
|
t.pex.Add(c) // we learnt enough now
|
|
|
|
c.pex.Init(c)
|
2019-12-11 19:45:04 +08:00
|
|
|
}
|
2018-02-03 11:06:10 +08:00
|
|
|
return nil
|
|
|
|
case metadataExtendedId:
|
|
|
|
err := cl.gotMetadataExtensionMsg(payload, t, c)
|
|
|
|
if err != nil {
|
2019-10-03 17:09:55 +08:00
|
|
|
return fmt.Errorf("handling metadata extension message: %w", err)
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
case pexExtendedId:
|
2020-04-09 00:03:29 +08:00
|
|
|
if !c.pex.IsEnabled() {
|
|
|
|
return nil // or hang-up maybe?
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2020-04-09 00:03:29 +08:00
|
|
|
return c.pex.Recv(payload)
|
2018-02-03 11:06:10 +08:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("unexpected extended message ID: %v", id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-10 13:30:51 +08:00
|
|
|
// Set both the Reader and Writer for the connection from a single ReadWriter.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) setRW(rw io.ReadWriter) {
|
2016-10-10 13:30:51 +08:00
|
|
|
cn.r = rw
|
|
|
|
cn.w = rw
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns the Reader and Writer as a combined ReadWriter.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) rw() io.ReadWriter {
|
2016-10-10 13:30:51 +08:00
|
|
|
return struct {
|
|
|
|
io.Reader
|
|
|
|
io.Writer
|
|
|
|
}{cn.r, cn.w}
|
|
|
|
}
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
// Handle a received chunk from a peer.
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) receiveChunk(msg *pp.Message) error {
|
2016-11-22 11:17:30 +08:00
|
|
|
t := c.t
|
|
|
|
cl := t.cl
|
2018-06-17 14:18:22 +08:00
|
|
|
torrent.Add("chunks received", 1)
|
2016-11-22 11:16:18 +08:00
|
|
|
|
2018-02-02 16:19:14 +08:00
|
|
|
req := newRequestFromMessage(msg)
|
2016-11-22 11:16:18 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
if c.peerChoking {
|
|
|
|
torrent.Add("chunks received while choking", 1)
|
2018-06-25 12:06:30 +08:00
|
|
|
}
|
|
|
|
|
2020-04-23 10:34:43 +08:00
|
|
|
if c.validReceiveChunks[req] <= 0 {
|
2018-06-25 12:06:30 +08:00
|
|
|
torrent.Add("chunks received unexpected", 1)
|
2018-06-24 18:35:46 +08:00
|
|
|
return errors.New("received unexpected chunk")
|
|
|
|
}
|
2020-04-23 10:34:43 +08:00
|
|
|
c.decExpectedChunkReceive(req)
|
2018-06-24 18:35:46 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
|
2018-06-25 12:06:30 +08:00
|
|
|
torrent.Add("chunks received due to allowed fast", 1)
|
|
|
|
}
|
|
|
|
|
2016-11-22 11:16:18 +08:00
|
|
|
// Request has been satisfied.
|
2017-09-01 13:26:50 +08:00
|
|
|
if c.deleteRequest(req) {
|
2018-06-24 18:04:31 +08:00
|
|
|
if c.expectingChunks() {
|
2020-01-10 12:09:21 +08:00
|
|
|
c._chunksReceivedWhileExpecting++
|
2018-06-24 18:04:31 +08:00
|
|
|
}
|
2017-09-01 13:26:50 +08:00
|
|
|
} else {
|
2018-06-25 12:06:30 +08:00
|
|
|
torrent.Add("chunks received unwanted", 1)
|
2018-02-04 21:18:38 +08:00
|
|
|
}
|
|
|
|
|
2016-11-22 11:16:18 +08:00
|
|
|
// Do we actually want this chunk?
|
2018-06-24 17:40:53 +08:00
|
|
|
if t.haveChunk(req) {
|
2018-06-25 12:06:30 +08:00
|
|
|
torrent.Add("chunks received wasted", 1)
|
|
|
|
c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
|
2018-06-24 18:35:46 +08:00
|
|
|
return nil
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
2018-07-12 07:15:15 +08:00
|
|
|
piece := &t.pieces[req.Index]
|
2016-11-22 11:20:48 +08:00
|
|
|
|
2018-06-12 18:21:53 +08:00
|
|
|
c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
|
|
|
|
c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
|
2016-11-22 11:16:18 +08:00
|
|
|
c.lastUsefulChunkReceived = time.Now()
|
2020-06-01 17:09:17 +08:00
|
|
|
// if t.fastestPeer != c {
|
2017-11-07 13:11:59 +08:00
|
|
|
// log.Printf("setting fastest connection %p", c)
|
|
|
|
// }
|
2020-06-01 17:09:17 +08:00
|
|
|
t.fastestPeer = c
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
// Need to record that it hasn't been written yet, before we attempt to do
|
|
|
|
// anything with it.
|
|
|
|
piece.incrementPendingWrites()
|
2017-12-29 09:16:05 +08:00
|
|
|
// Record that we have the chunk, so we aren't trying to download it while
|
|
|
|
// waiting for it to be written to storage.
|
2016-11-22 11:16:18 +08:00
|
|
|
piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
|
|
|
|
|
|
|
|
// Cancel pending requests for this chunk.
|
2016-11-23 08:48:44 +08:00
|
|
|
for c := range t.conns {
|
2020-06-02 15:41:59 +08:00
|
|
|
c._postCancel(req)
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
2017-12-29 09:15:33 +08:00
|
|
|
err := func() error {
|
2018-07-25 11:41:50 +08:00
|
|
|
cl.unlock()
|
|
|
|
defer cl.lock()
|
2019-06-13 10:18:08 +08:00
|
|
|
concurrentChunkWrites.Add(1)
|
|
|
|
defer concurrentChunkWrites.Add(-1)
|
2020-02-22 16:38:56 +08:00
|
|
|
// Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
|
|
|
|
// number of connections. We write inline with receiving the chunk (with this lock dance),
|
|
|
|
// because we want to handle errors synchronously and I haven't thought of a nice way to
|
|
|
|
// defer any concurrency to the storage and have that notify the client of errors. TODO: Do
|
|
|
|
// that instead.
|
2017-12-29 09:15:33 +08:00
|
|
|
return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
|
|
|
|
}()
|
2016-11-22 11:16:18 +08:00
|
|
|
|
|
|
|
piece.decrementPendingWrites()
|
|
|
|
|
|
|
|
if err != nil {
|
2020-02-22 16:40:50 +08:00
|
|
|
c.logger.Printf("error writing received chunk %v: %v", req, err)
|
2016-11-22 11:16:18 +08:00
|
|
|
t.pendRequest(req)
|
2020-02-22 16:40:50 +08:00
|
|
|
//t.updatePieceCompletion(pieceIndex(msg.Index))
|
|
|
|
t.onWriteChunkErr(err)
|
2018-06-24 18:35:46 +08:00
|
|
|
return nil
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
2020-01-23 10:52:17 +08:00
|
|
|
c.onDirtiedPiece(pieceIndex(req.Index))
|
|
|
|
|
2018-07-17 19:28:01 +08:00
|
|
|
if t.pieceAllDirty(pieceIndex(req.Index)) {
|
|
|
|
t.queuePieceCheck(pieceIndex(req.Index))
|
2020-01-23 10:54:37 +08:00
|
|
|
// We don't pend all chunks here anymore because we don't want code dependent on the dirty
|
|
|
|
// chunk status (such as the haveChunk call above) to have to check all the various other
|
|
|
|
// piece states like queued for hash, hashing etc. This does mean that we need to be sure
|
|
|
|
// that chunk pieces are pended at an appropriate time later however.
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
cl.event.Broadcast()
|
2020-01-23 10:51:14 +08:00
|
|
|
// We do this because we've written a chunk, and may change PieceState.Partial.
|
2018-07-17 19:28:01 +08:00
|
|
|
t.publishPieceChange(pieceIndex(req.Index))
|
2018-06-24 18:35:46 +08:00
|
|
|
|
|
|
|
return nil
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) onDirtiedPiece(piece pieceIndex) {
|
2018-02-03 09:08:16 +08:00
|
|
|
if c.peerTouchedPieces == nil {
|
2018-07-12 07:15:15 +08:00
|
|
|
c.peerTouchedPieces = make(map[pieceIndex]struct{})
|
2018-02-03 09:08:16 +08:00
|
|
|
}
|
|
|
|
c.peerTouchedPieces[piece] = struct{}{}
|
|
|
|
ds := &c.t.pieces[piece].dirtiers
|
|
|
|
if *ds == nil {
|
2020-05-30 13:18:28 +08:00
|
|
|
*ds = make(map[*peer]struct{})
|
2018-02-03 09:08:16 +08:00
|
|
|
}
|
|
|
|
(*ds)[c] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) uploadAllowed() bool {
|
2018-02-02 16:04:56 +08:00
|
|
|
if c.t.cl.config.NoUpload {
|
|
|
|
return false
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2020-05-31 03:42:51 +08:00
|
|
|
if c.t.dataUploadDisallowed {
|
|
|
|
return false
|
|
|
|
}
|
2018-02-02 16:04:56 +08:00
|
|
|
if c.t.seeding() {
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 16:04:56 +08:00
|
|
|
if !c.peerHasWantedPieces() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// Don't upload more than 100 KiB more than we download.
|
2020-01-10 12:09:21 +08:00
|
|
|
if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
|
2018-02-02 16:04:56 +08:00
|
|
|
return false
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 16:04:56 +08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
|
2018-02-02 16:04:56 +08:00
|
|
|
if c.uploadTimer == nil {
|
|
|
|
c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
|
|
|
|
} else {
|
|
|
|
c.uploadTimer.Reset(delay)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Also handles choking and unchoking of the remote peer.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
|
2016-11-22 18:12:53 +08:00
|
|
|
// Breaking or completing this loop means we don't want to upload to the
|
|
|
|
// peer anymore, and we choke them.
|
|
|
|
another:
|
2018-02-02 16:04:56 +08:00
|
|
|
for c.uploadAllowed() {
|
2016-11-22 18:12:53 +08:00
|
|
|
// We want to upload to the peer.
|
2020-02-21 08:07:50 +08:00
|
|
|
if !c.unchoke(msg) {
|
2017-09-18 10:09:08 +08:00
|
|
|
return false
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
for r := range c.peerRequests {
|
2018-06-16 14:30:04 +08:00
|
|
|
res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
|
2017-09-18 10:09:08 +08:00
|
|
|
if !res.OK() {
|
2017-11-04 13:58:38 +08:00
|
|
|
panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
|
2017-09-18 10:09:08 +08:00
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
delay := res.Delay()
|
|
|
|
if delay > 0 {
|
|
|
|
res.Cancel()
|
2018-02-02 16:04:56 +08:00
|
|
|
c.setRetryUploadTimer(delay)
|
2017-09-18 10:09:08 +08:00
|
|
|
// Hard to say what to return here.
|
|
|
|
return true
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2018-02-02 10:34:35 +08:00
|
|
|
more, err := c.sendChunk(r, msg)
|
2016-11-22 18:12:53 +08:00
|
|
|
if err != nil {
|
2018-07-17 19:28:01 +08:00
|
|
|
i := pieceIndex(r.Index)
|
2018-02-02 16:04:56 +08:00
|
|
|
if c.t.pieceComplete(i) {
|
|
|
|
c.t.updatePieceCompletion(i)
|
|
|
|
if !c.t.pieceComplete(i) {
|
2016-11-22 18:12:53 +08:00
|
|
|
// We had the piece, but not anymore.
|
|
|
|
break another
|
|
|
|
}
|
|
|
|
}
|
2018-02-03 09:06:52 +08:00
|
|
|
log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
|
2016-11-22 18:12:53 +08:00
|
|
|
// 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
|
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
delete(c.peerRequests, r)
|
2017-09-18 10:09:08 +08:00
|
|
|
if !more {
|
|
|
|
return false
|
|
|
|
}
|
2016-11-22 18:12:53 +08:00
|
|
|
goto another
|
|
|
|
}
|
2017-09-18 10:09:08 +08:00
|
|
|
return true
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
return c.choke(msg)
|
2016-11-22 18:12:53 +08:00
|
|
|
}
|
2016-11-23 08:52:41 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) drop() {
|
2016-11-23 08:52:41 +08:00
|
|
|
cn.t.dropConnection(cn)
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) netGoodPiecesDirtied() int64 {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
|
2016-11-23 09:59:23 +08:00
|
|
|
}
|
2017-08-17 23:48:19 +08:00
|
|
|
|
2020-06-01 16:25:45 +08:00
|
|
|
func (c *peer) peerHasWantedPieces() bool {
|
2020-01-10 12:09:21 +08:00
|
|
|
return !c._pieceRequestOrder.IsEmpty()
|
2017-08-17 23:48:19 +08:00
|
|
|
}
|
2017-08-31 21:48:52 +08:00
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) numLocalRequests() int {
|
2017-08-31 21:48:52 +08:00
|
|
|
return len(c.requests)
|
|
|
|
}
|
2017-09-01 10:09:41 +08:00
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) deleteRequest(r request) bool {
|
2017-09-01 10:09:41 +08:00
|
|
|
if _, ok := c.requests[r]; !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
delete(c.requests, r)
|
2018-06-24 18:04:31 +08:00
|
|
|
c.updateExpectingChunks()
|
2020-01-10 13:18:55 +08:00
|
|
|
c.t.requestStrategy.hooks().deletedRequest(r)
|
2018-06-16 15:00:50 +08:00
|
|
|
pr := c.t.pendingRequests
|
|
|
|
pr[r]--
|
|
|
|
n := pr[r]
|
|
|
|
if n == 0 {
|
|
|
|
delete(pr, r)
|
|
|
|
}
|
|
|
|
if n < 0 {
|
|
|
|
panic(n)
|
|
|
|
}
|
2018-02-03 10:35:09 +08:00
|
|
|
c.updateRequests()
|
2020-05-30 13:18:28 +08:00
|
|
|
c.t.iterPeers(func(_c *peer) {
|
2020-02-21 08:07:50 +08:00
|
|
|
if !_c.interested && _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
|
2018-07-17 19:29:54 +08:00
|
|
|
_c.updateRequests()
|
|
|
|
}
|
2020-05-30 13:18:28 +08:00
|
|
|
})
|
2017-09-01 10:09:41 +08:00
|
|
|
return true
|
|
|
|
}
|
2017-11-04 14:08:02 +08:00
|
|
|
|
2020-05-30 15:52:27 +08:00
|
|
|
func (c *peer) deleteAllRequests() {
|
2018-02-01 11:46:03 +08:00
|
|
|
for r := range c.requests {
|
|
|
|
c.deleteRequest(r)
|
|
|
|
}
|
2018-02-15 12:21:51 +08:00
|
|
|
if len(c.requests) != 0 {
|
|
|
|
panic(len(c.requests))
|
|
|
|
}
|
2018-02-01 11:46:03 +08:00
|
|
|
// for c := range c.t.conns {
|
|
|
|
// c.tickleWriter()
|
|
|
|
// }
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) tickleWriter() {
|
2017-09-01 13:26:50 +08:00
|
|
|
c.writerCond.Broadcast()
|
|
|
|
}
|
2017-09-18 11:47:49 +08:00
|
|
|
|
2020-05-30 15:52:27 +08:00
|
|
|
func (c *peer) postCancel(r request) bool {
|
2017-09-18 11:47:49 +08:00
|
|
|
if !c.deleteRequest(r) {
|
|
|
|
return false
|
|
|
|
}
|
2020-06-02 15:41:59 +08:00
|
|
|
c.peerImpl._postCancel(r)
|
2017-09-18 11:47:49 +08:00
|
|
|
return true
|
|
|
|
}
|
2018-02-02 10:26:04 +08:00
|
|
|
|
2020-06-02 15:41:59 +08:00
|
|
|
func (c *PeerConn) _postCancel(r request) {
|
2020-05-30 15:52:27 +08:00
|
|
|
c.post(makeCancelMessage(r))
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
|
2018-02-02 10:26:04 +08:00
|
|
|
// Count the chunk being sent, even if it isn't.
|
|
|
|
b := make([]byte, r.Length)
|
|
|
|
p := c.t.info.Piece(int(r.Index))
|
|
|
|
n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
|
|
|
|
if n != len(b) {
|
|
|
|
if err == nil {
|
|
|
|
panic("expected error")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
} else if err == io.EOF {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
more = msg(pp.Message{
|
|
|
|
Type: pp.Piece,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
|
|
|
Piece: b,
|
|
|
|
})
|
|
|
|
c.lastChunkSent = time.Now()
|
|
|
|
return
|
|
|
|
}
|
2018-02-02 16:07:20 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) setTorrent(t *Torrent) {
|
2018-02-02 16:07:20 +08:00
|
|
|
if c.t != nil {
|
|
|
|
panic("connection already associated with a torrent")
|
|
|
|
}
|
|
|
|
c.t = t
|
2019-10-03 17:09:55 +08:00
|
|
|
c.logger.Printf("torrent=%v", t)
|
2018-06-10 07:18:52 +08:00
|
|
|
t.reconcileHandshakeStats(c)
|
2018-02-02 16:07:20 +08:00
|
|
|
}
|
2018-07-10 07:50:39 +08:00
|
|
|
|
2020-06-01 16:25:45 +08:00
|
|
|
func (c *peer) peerPriority() (peerPriority, error) {
|
2020-04-13 12:08:32 +08:00
|
|
|
return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
|
2018-07-10 07:50:39 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) remoteIp() net.IP {
|
2020-07-15 14:15:38 +08:00
|
|
|
return addrIpOrNil(c.RemoteAddr)
|
2018-07-10 07:50:39 +08:00
|
|
|
}
|
|
|
|
|
2020-06-01 16:25:45 +08:00
|
|
|
func (c *peer) remoteIpPort() IpPort {
|
2020-07-15 14:15:38 +08:00
|
|
|
ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
|
2020-02-20 13:47:37 +08:00
|
|
|
return IpPort{ipa.IP, uint16(ipa.Port)}
|
2018-07-10 07:50:39 +08:00
|
|
|
}
|
2019-10-01 19:16:18 +08:00
|
|
|
|
2019-12-11 19:45:04 +08:00
|
|
|
func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
|
|
|
|
f := pp.PexPeerFlags(0)
|
|
|
|
if c.PeerPrefersEncryption {
|
|
|
|
f |= pp.PexPrefersEncryption
|
|
|
|
}
|
|
|
|
if c.outgoing {
|
|
|
|
f |= pp.PexOutgoingConn
|
|
|
|
}
|
2020-07-15 14:15:38 +08:00
|
|
|
if c.RemoteAddr != nil && strings.Contains(c.RemoteAddr.Network(), "udp") {
|
2019-12-11 19:45:04 +08:00
|
|
|
f |= pp.PexSupportsUtp
|
|
|
|
}
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
|
2020-04-09 00:03:29 +08:00
|
|
|
func (c *PeerConn) dialAddr() net.Addr {
|
|
|
|
if !c.outgoing && c.PeerListenPort != 0 {
|
2020-07-15 14:15:38 +08:00
|
|
|
switch addr := c.RemoteAddr.(type) {
|
2020-04-09 00:03:29 +08:00
|
|
|
case *net.TCPAddr:
|
|
|
|
dialAddr := *addr
|
|
|
|
dialAddr.Port = c.PeerListenPort
|
|
|
|
return &dialAddr
|
|
|
|
case *net.UDPAddr:
|
|
|
|
dialAddr := *addr
|
|
|
|
dialAddr.Port = c.PeerListenPort
|
|
|
|
return &dialAddr
|
|
|
|
}
|
|
|
|
}
|
2020-07-15 14:15:38 +08:00
|
|
|
return c.RemoteAddr
|
2020-04-09 00:03:29 +08:00
|
|
|
}
|
|
|
|
|
2020-04-01 04:14:43 +08:00
|
|
|
func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
|
|
|
|
f := c.pexPeerFlags()
|
2020-04-09 00:03:29 +08:00
|
|
|
addr := c.dialAddr()
|
|
|
|
return pexEvent{t, addr, f}
|
2020-04-01 04:14:43 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) String() string {
|
2019-10-03 17:09:55 +08:00
|
|
|
return fmt.Sprintf("connection %p", c)
|
2019-10-01 19:16:18 +08:00
|
|
|
}
|
2019-12-18 10:52:00 +08:00
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (c *peer) trust() connectionTrust {
|
2019-12-18 10:52:00 +08:00
|
|
|
return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
|
|
|
|
}
|
|
|
|
|
|
|
|
type connectionTrust struct {
|
|
|
|
Implicit bool
|
|
|
|
NetGoodPiecesDirted int64
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l connectionTrust) Less(r connectionTrust) bool {
|
2019-12-23 11:04:07 +08:00
|
|
|
return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
|
2019-12-18 10:52:00 +08:00
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) requestStrategyConnection() requestStrategyConnection {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) chunksReceivedWhileExpecting() int64 {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn._chunksReceivedWhileExpecting
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) fastest() bool {
|
2020-06-01 17:09:17 +08:00
|
|
|
return cn == cn.t.fastestPeer
|
2020-01-10 12:09:21 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) peerMaxRequests() int {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn.PeerMaxRequests
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:51:24 +08:00
|
|
|
// Returns the pieces the peer has claimed to have.
|
|
|
|
func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
|
|
|
|
cn.locker().RLock()
|
|
|
|
defer cn.locker().RUnlock()
|
|
|
|
return cn.peerPieces()
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) peerPieces() bitmap.Bitmap {
|
2020-01-10 12:09:21 +08:00
|
|
|
ret := cn._peerPieces.Copy()
|
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
ret.AddRange(0, cn.t.numPieces())
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
|
2020-01-10 12:09:21 +08:00
|
|
|
return &cn._pieceRequestOrder
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) stats() *ConnStats {
|
2020-01-10 12:09:21 +08:00
|
|
|
return &cn._stats
|
|
|
|
}
|
|
|
|
|
2020-05-30 13:18:28 +08:00
|
|
|
func (cn *peer) torrent() requestStrategyTorrent {
|
2020-01-10 12:09:21 +08:00
|
|
|
return cn.t.requestStrategyTorrent()
|
|
|
|
}
|