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"
|
2021-05-11 15:14:02 +08:00
|
|
|
"errors"
|
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"
|
2021-05-12 19:48:23 +08:00
|
|
|
"sort"
|
2016-02-09 21:45:47 +08:00
|
|
|
"strconv"
|
2016-09-11 12:32:56 +08:00
|
|
|
"strings"
|
2021-12-06 16:02:55 +08:00
|
|
|
"sync/atomic"
|
2014-04-03 20:16:59 +08:00
|
|
|
"time"
|
|
|
|
|
2021-10-05 14:48:34 +08:00
|
|
|
"github.com/RoaringBitmap/roaring"
|
2022-01-21 19:28:15 +08:00
|
|
|
"github.com/anacrolix/chansync"
|
|
|
|
. "github.com/anacrolix/generics"
|
2018-02-03 09:06:52 +08:00
|
|
|
"github.com/anacrolix/log"
|
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"
|
2019-12-23 11:04:07 +08:00
|
|
|
"github.com/anacrolix/multiless"
|
2015-04-27 12:55:01 +08:00
|
|
|
"github.com/anacrolix/torrent/bencode"
|
2021-05-20 16:51:08 +08:00
|
|
|
"github.com/anacrolix/torrent/metainfo"
|
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"
|
2021-05-20 18:23:45 +08:00
|
|
|
request_strategy "github.com/anacrolix/torrent/request-strategy"
|
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"
|
2020-11-12 12:25:06 +08:00
|
|
|
// The peer was given directly, such as through a magnet link.
|
|
|
|
PeerSourceDirect = "M"
|
2014-07-16 15:06:18 +08:00
|
|
|
)
|
|
|
|
|
2020-11-13 12:50:08 +08:00
|
|
|
type peerRequestState struct {
|
|
|
|
data []byte
|
|
|
|
}
|
|
|
|
|
2021-01-25 11:22:24 +08:00
|
|
|
type PeerRemoteAddr interface {
|
|
|
|
String() string
|
|
|
|
}
|
|
|
|
|
2021-05-20 06:56:53 +08:00
|
|
|
// Since we have to store all the requests in memory, we can't reasonably exceed what would be
|
|
|
|
// indexable with the memory space available.
|
2021-05-20 18:23:45 +08:00
|
|
|
type (
|
|
|
|
maxRequests = int
|
2021-12-11 21:04:06 +08:00
|
|
|
requestState = request_strategy.PeerRequestState
|
2021-05-20 18:23:45 +08:00
|
|
|
)
|
2021-05-20 06:56:53 +08:00
|
|
|
|
2021-01-20 10:10:32 +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
|
2021-01-28 11:23:22 +08:00
|
|
|
callbacks *Callbacks
|
2020-05-30 13:18:28 +08:00
|
|
|
|
2022-01-12 11:23:30 +08:00
|
|
|
outgoing bool
|
|
|
|
Network string
|
|
|
|
RemoteAddr PeerRemoteAddr
|
2022-01-21 19:28:15 +08:00
|
|
|
bannableAddr Option[bannableAddr]
|
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
|
2021-05-20 16:51:08 +08:00
|
|
|
closed chansync.SetOnce
|
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.
|
2021-10-08 10:53:36 +08:00
|
|
|
needRequestUpdate string
|
2021-12-11 21:04:06 +08:00
|
|
|
requestState requestState
|
2021-10-18 15:40:33 +08:00
|
|
|
updateRequestsTimer *time.Timer
|
2021-12-24 05:55:57 +08:00
|
|
|
lastRequestUpdate time.Time
|
|
|
|
peakRequests maxRequests
|
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
|
|
|
|
2021-05-20 06:56:53 +08:00
|
|
|
choking bool
|
|
|
|
piecesReceivedSinceLastRequestUpdate maxRequests
|
|
|
|
maxPiecesReceivedBetweenRequestUpdates maxRequests
|
2021-12-11 21:04:06 +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. This could use a roaring.BSI if the memory use becomes noticeable.
|
2021-09-19 13:16:37 +08:00
|
|
|
validReceiveChunks map[RequestIndex]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
|
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
|
2021-01-28 11:23:22 +08:00
|
|
|
peerRequests map[Request]*peerRequestState
|
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 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{}
|
2021-10-05 17:06:23 +08:00
|
|
|
peerAllowedFast roaring.Bitmap
|
2015-03-12 17:06:23 +08:00
|
|
|
|
2021-05-20 06:56:53 +08:00
|
|
|
PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
|
2018-07-10 10:20:36 +08:00
|
|
|
PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
|
2021-12-06 16:02:55 +08:00
|
|
|
PeerClientName atomic.Value
|
2016-02-01 18:11:41 +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 {
|
2021-01-20 10:10:32 +08:00
|
|
|
Peer
|
2020-05-30 08:14:20 +08:00
|
|
|
|
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
|
|
|
|
|
2021-11-17 11:00:50 +08:00
|
|
|
// The actual Conn, used for closing, and setting socket options. Do not use methods on this
|
|
|
|
// while holding any mutexes.
|
2020-05-30 08:14:20 +08:00
|
|
|
conn net.Conn
|
|
|
|
// The Reader and Writer for this Conn, with hooks installed for stats,
|
|
|
|
// limiting, deadlines etc.
|
|
|
|
w io.Writer
|
|
|
|
r io.Reader
|
|
|
|
|
2021-05-20 16:55:23 +08:00
|
|
|
messageWriter peerConnMsgWriter
|
2020-10-13 10:33:22 +08:00
|
|
|
|
2021-05-20 16:51:08 +08:00
|
|
|
uploadTimer *time.Timer
|
|
|
|
pex pexConnState
|
2021-11-12 09:37:40 +08:00
|
|
|
|
|
|
|
// The pieces the peer has claimed to have.
|
|
|
|
_peerPieces roaring.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.
|
|
|
|
peerSentHaveAll bool
|
2016-05-07 16:56:44 +08:00
|
|
|
}
|
|
|
|
|
2020-09-29 14:21:54 +08:00
|
|
|
func (cn *PeerConn) connStatusString() string {
|
2020-10-06 06:50:47 +08:00
|
|
|
return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
|
2020-09-29 14:21:54 +08:00
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +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{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) expectingChunks() bool {
|
2021-12-11 21:04:06 +08:00
|
|
|
if cn.requestState.Requests.IsEmpty() {
|
2021-05-09 22:53:32 +08:00
|
|
|
return false
|
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
if !cn.requestState.Interested {
|
2021-05-09 22:53:32 +08:00
|
|
|
return false
|
|
|
|
}
|
2021-10-05 17:06:23 +08:00
|
|
|
if !cn.peerChoking {
|
2021-09-19 13:16:37 +08:00
|
|
|
return true
|
2021-05-09 22:53:32 +08:00
|
|
|
}
|
2021-10-05 17:06:23 +08:00
|
|
|
haveAllowedFastRequests := false
|
|
|
|
cn.peerAllowedFast.Iterate(func(i uint32) bool {
|
|
|
|
haveAllowedFastRequests = roaringBitmapRangeCardinality(
|
2021-12-11 21:04:06 +08:00
|
|
|
&cn.requestState.Requests,
|
2021-10-05 17:06:23 +08:00
|
|
|
cn.t.pieceRequestIndexOffset(pieceIndex(i)),
|
|
|
|
cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
|
|
|
|
) == 0
|
|
|
|
return !haveAllowedFastRequests
|
|
|
|
})
|
|
|
|
return haveAllowedFastRequests
|
2018-06-24 18:04:31 +08:00
|
|
|
}
|
|
|
|
|
2021-05-12 15:45:36 +08:00
|
|
|
func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
|
|
|
|
return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
|
|
|
|
}
|
|
|
|
|
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 {
|
2021-01-25 11:22:24 +08:00
|
|
|
ip := cn.remoteIp()
|
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.
|
2022-01-12 12:01:33 +08:00
|
|
|
func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
|
2022-01-12 12:07:26 +08:00
|
|
|
var ml multiless.Computation
|
|
|
|
ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
|
|
|
|
ml = ml.Bool(l.utp(), r.utp())
|
|
|
|
ml = ml.Bool(r.ipv6(), l.ipv6())
|
2022-01-12 12:01:33 +08:00
|
|
|
return ml.Less()
|
2018-06-16 15:14:47 +08:00
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) cumInterest() time.Duration {
|
2018-02-05 14:47:47 +08:00
|
|
|
ret := cn.priorInterest
|
2021-12-11 21:04:06 +08:00
|
|
|
if cn.requestState.Interested {
|
2018-02-05 14:47:47 +08:00
|
|
|
ret += time.Since(cn.lastBecameInterested)
|
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2021-12-18 05:58:56 +08:00
|
|
|
func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
|
2018-01-29 15:18:08 +08:00
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
return true, true
|
|
|
|
}
|
|
|
|
if !cn.t.haveInfo() {
|
|
|
|
return false, false
|
|
|
|
}
|
2021-11-17 11:01:11 +08:00
|
|
|
return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
|
2018-01-29 15:18:08 +08:00
|
|
|
}
|
|
|
|
|
2021-10-21 07:28:57 +08:00
|
|
|
func (cn *Peer) locker() *lockWithDeferreds {
|
2018-07-25 11:41:50 +08:00
|
|
|
return cn.t.cl.locker()
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +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.
|
2021-01-20 10:10:32 +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
|
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) completedString() string {
|
2021-11-12 09:37:40 +08:00
|
|
|
have := pieceIndex(cn.peerPieces().GetCardinality())
|
|
|
|
if all, _ := cn.peerHasAllPieces(); all {
|
2018-02-04 19:43:28 +08:00
|
|
|
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) {
|
2021-05-20 09:16:54 +08:00
|
|
|
cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
|
2021-10-11 12:45:55 +08:00
|
|
|
cn.peerPiecesChanged()
|
2014-07-16 15:09:30 +08:00
|
|
|
}
|
|
|
|
|
2021-11-12 09:37:40 +08:00
|
|
|
func (cn *PeerConn) peerPieces() *roaring.Bitmap {
|
|
|
|
return &cn._peerPieces
|
|
|
|
}
|
|
|
|
|
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 {
|
2021-01-25 12:43:28 +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.
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) statusFlags() (ret string) {
|
2015-08-02 02:06:22 +08:00
|
|
|
c := func(b byte) {
|
|
|
|
ret += string([]byte{b})
|
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
if cn.requestState.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
|
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) downloadRate() float64 {
|
2021-05-09 22:53:32 +08:00
|
|
|
num := cn._stats.BytesReadUsefulData.Int64()
|
|
|
|
if num == 0 {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return float64(num) / cn.totalExpectingTime().Seconds()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
|
|
|
|
ret = make(map[pieceIndex]int)
|
2021-12-11 21:04:06 +08:00
|
|
|
cn.requestState.Requests.Iterate(func(x uint32) bool {
|
2021-09-19 13:16:37 +08:00
|
|
|
ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
|
|
|
|
return true
|
|
|
|
})
|
2021-05-09 22:53:32 +08:00
|
|
|
return
|
2015-06-29 17:37:52 +08:00
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +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?
|
2021-02-09 16:21:54 +08:00
|
|
|
if cn.closed.IsSet() {
|
|
|
|
fmt.Fprint(w, "CLOSED: ")
|
|
|
|
}
|
2020-09-29 14:21:54 +08:00
|
|
|
fmt.Fprintln(w, cn.connStatusString())
|
2021-05-09 22:53:32 +08:00
|
|
|
prio, err := cn.peerPriority()
|
|
|
|
prioStr := fmt.Sprintf("%08x", prio)
|
|
|
|
if err != nil {
|
|
|
|
prioStr += ": " + err.Error()
|
|
|
|
}
|
|
|
|
fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
|
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,
|
2021-12-11 21:04:06 +08:00
|
|
|
" %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%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,
|
2021-12-11 21:04:06 +08:00
|
|
|
cn.requestState.Requests.GetCardinality(),
|
|
|
|
cn.requestState.Cancelled.GetCardinality(),
|
2018-02-05 14:47:47 +08:00
|
|
|
cn.nominalMaxRequests(),
|
2021-05-09 22:53:32 +08:00
|
|
|
cn.PeerMaxRequests,
|
2020-02-21 08:07:50 +08:00
|
|
|
len(cn.peerRequests),
|
2021-05-09 22:53:32 +08:00
|
|
|
localClientReqq,
|
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
|
|
|
)
|
2021-05-09 22:53:32 +08:00
|
|
|
fmt.Fprintf(w, " requested pieces:")
|
2021-05-12 19:48:23 +08:00
|
|
|
type pieceNumRequestsType struct {
|
|
|
|
piece pieceIndex
|
|
|
|
numRequests int
|
|
|
|
}
|
|
|
|
var pieceNumRequests []pieceNumRequestsType
|
2021-05-09 22:53:32 +08:00
|
|
|
for piece, count := range cn.numRequestsByPiece() {
|
2021-05-12 19:48:23 +08:00
|
|
|
pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
|
|
|
|
}
|
|
|
|
sort.Slice(pieceNumRequests, func(i, j int) bool {
|
|
|
|
return pieceNumRequests[i].piece < pieceNumRequests[j].piece
|
|
|
|
})
|
|
|
|
for _, elem := range pieceNumRequests {
|
|
|
|
fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
|
2021-05-09 22:53:32 +08:00
|
|
|
}
|
|
|
|
fmt.Fprintf(w, "\n")
|
2014-06-26 15:29:12 +08:00
|
|
|
}
|
|
|
|
|
2021-05-10 15:02:17 +08:00
|
|
|
func (p *Peer) close() {
|
|
|
|
if !p.closed.Set() {
|
2017-09-18 11:40:36 +08:00
|
|
|
return
|
|
|
|
}
|
2021-10-21 07:28:57 +08:00
|
|
|
if p.updateRequestsTimer != nil {
|
|
|
|
p.updateRequestsTimer.Stop()
|
|
|
|
}
|
2021-05-10 15:02:17 +08:00
|
|
|
p.peerImpl.onClose()
|
2021-05-20 12:01:31 +08:00
|
|
|
if p.t != nil {
|
|
|
|
p.t.decPeerPieceAvailability(p)
|
|
|
|
}
|
2021-05-10 15:02:17 +08:00
|
|
|
for _, f := range p.callbacks.PeerClosed {
|
|
|
|
f(p)
|
2021-01-28 11:23:22 +08:00
|
|
|
}
|
2020-05-30 15:52:27 +08:00
|
|
|
}
|
|
|
|
|
2021-01-04 12:51:23 +08:00
|
|
|
func (cn *PeerConn) onClose() {
|
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 {
|
2021-11-17 11:00:50 +08:00
|
|
|
go cn.conn.Close()
|
2016-05-11 21:50:21 +08:00
|
|
|
}
|
2020-10-14 12:11:45 +08:00
|
|
|
if cb := cn.callbacks.PeerConnClosed; cb != nil {
|
2020-10-13 10:02:39 +08:00
|
|
|
cb(cn)
|
|
|
|
}
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2021-11-12 09:37:40 +08:00
|
|
|
// Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
|
|
|
|
// they do (known=true).
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
|
2021-11-12 09:37:40 +08:00
|
|
|
if all, known := cn.peerHasAllPieces(); all && known {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return cn.peerPieces().ContainsInt(piece)
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
|
|
|
|
2020-11-13 12:50:08 +08:00
|
|
|
// 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
|
|
|
|
// https://github.com/pion/datachannel/issues/59 is fixed.
|
2021-12-24 05:55:57 +08:00
|
|
|
const (
|
|
|
|
writeBufferHighWaterLen = 1 << 15
|
|
|
|
writeBufferLowWaterLen = writeBufferHighWaterLen / 2
|
|
|
|
)
|
2020-11-13 12:50:08 +08:00
|
|
|
|
2021-05-10 10:29:47 +08:00
|
|
|
// Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
|
|
|
|
// done asynchronously, so it may be that we're not able to honour backpressure from this method.
|
|
|
|
func (cn *PeerConn) write(msg pp.Message) bool {
|
|
|
|
torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
|
2021-05-20 16:51:08 +08:00
|
|
|
// We don't need to track bytes here because the connection's Writer has that behaviour injected
|
|
|
|
// (although there's some delay between us buffering the message, and the connection writer
|
2020-11-13 12:50:08 +08:00
|
|
|
// flushing it out.).
|
2021-05-20 16:51:08 +08:00
|
|
|
notFull := cn.messageWriter.write(msg)
|
2021-05-10 10:29:47 +08:00
|
|
|
// Last I checked only Piece messages affect stats, and we don't write those.
|
2020-05-30 15:52:27 +08:00
|
|
|
cn.wroteMsg(&msg)
|
2021-05-09 12:14:11 +08:00
|
|
|
cn.tickleWriter()
|
2021-05-20 16:51:08 +08:00
|
|
|
return notFull
|
|
|
|
}
|
|
|
|
|
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]
|
2021-06-18 13:04:07 +08:00
|
|
|
if eID == pp.ExtensionDeleteNumber {
|
2015-03-27 12:36:59 +08:00
|
|
|
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
|
|
|
|
}
|
2020-10-12 14:12:34 +08:00
|
|
|
cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
|
2021-06-18 13:04:07 +08:00
|
|
|
cn.write(pp.MetadataExtensionRequestMsg(eID, index))
|
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
|
|
|
}
|
|
|
|
|
2021-12-24 05:55:57 +08:00
|
|
|
var (
|
|
|
|
interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
|
|
|
|
requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
|
|
|
|
// This is the maximum request count that could fit in the write buffer if it's at or below the
|
|
|
|
// low water mark when we run maybeUpdateActualRequestState.
|
|
|
|
maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
|
|
|
|
)
|
|
|
|
|
2016-02-08 13:09:12 +08:00
|
|
|
// The actual value to use as the maximum outbound requests.
|
2021-12-24 05:55:57 +08:00
|
|
|
func (cn *Peer) nominalMaxRequests() maxRequests {
|
|
|
|
return maxRequests(maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests)))
|
2020-01-10 12:09:21 +08:00
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +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
|
|
|
|
}
|
|
|
|
|
2021-01-28 11:23:22 +08:00
|
|
|
func (cn *PeerConn) onPeerSentCancel(r Request) {
|
2020-02-21 08:07:50 +08:00
|
|
|
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,
|
|
|
|
})
|
2021-12-27 19:19:04 +08:00
|
|
|
if !cn.fastEnabled() {
|
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
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) setInterested(interested bool) bool {
|
2021-12-11 21:04:06 +08:00
|
|
|
if cn.requestState.Interested == interested {
|
2017-08-31 21:48:52 +08:00
|
|
|
return true
|
2014-04-03 20:16:59 +08:00
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
cn.requestState.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
|
|
|
|
|
2021-10-25 10:00:56 +08:00
|
|
|
// This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
|
|
|
|
// when we want to go fast.
|
2021-09-19 13:16:37 +08:00
|
|
|
func (cn *Peer) shouldRequest(r RequestIndex) error {
|
|
|
|
pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
|
2021-12-13 08:56:57 +08:00
|
|
|
if cn.requestState.Cancelled.Contains(r) {
|
|
|
|
return errors.New("request is cancelled and waiting acknowledgement")
|
|
|
|
}
|
2021-09-19 13:16:37 +08:00
|
|
|
if !cn.peerHasPiece(pi) {
|
2021-05-09 21:38:38 +08:00
|
|
|
return errors.New("requesting piece peer doesn't have")
|
2017-11-06 11:53:00 +08:00
|
|
|
}
|
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")
|
|
|
|
}
|
2021-09-19 13:16:37 +08:00
|
|
|
if cn.t.hashingPiece(pi) {
|
2018-06-26 11:04:15 +08:00
|
|
|
panic("piece is being hashed")
|
|
|
|
}
|
2021-09-19 13:16:37 +08:00
|
|
|
if cn.t.pieceQueuedForHash(pi) {
|
2018-06-26 11:04:15 +08:00
|
|
|
panic("piece is queued for hash")
|
|
|
|
}
|
2021-09-19 13:16:37 +08:00
|
|
|
if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
|
2021-10-25 10:00:56 +08:00
|
|
|
// This could occur if we made a request with the fast extension, and then got choked and
|
|
|
|
// haven't had the request rejected yet.
|
2021-12-11 21:04:06 +08:00
|
|
|
if !cn.requestState.Requests.Contains(r) {
|
2021-10-25 10:00:56 +08:00
|
|
|
panic("peer choking and piece not allowed fast")
|
|
|
|
}
|
2021-09-18 17:00:21 +08:00
|
|
|
}
|
2021-05-12 15:45:36 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-26 12:03:04 +08:00
|
|
|
func (cn *Peer) mustRequest(r RequestIndex) bool {
|
|
|
|
more, err := cn.request(r)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return more
|
|
|
|
}
|
|
|
|
|
2021-09-19 13:16:37 +08:00
|
|
|
func (cn *Peer) request(r RequestIndex) (more bool, err error) {
|
2021-05-12 15:45:36 +08:00
|
|
|
if err := cn.shouldRequest(r); err != nil {
|
|
|
|
panic(err)
|
2021-05-09 21:38:38 +08:00
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
if cn.requestState.Requests.Contains(r) {
|
2021-05-20 18:23:45 +08:00
|
|
|
return true, nil
|
2021-05-12 15:45:36 +08:00
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
|
2021-05-20 18:23:45 +08:00
|
|
|
return true, errors.New("too many outstanding requests")
|
2021-05-09 21:38:38 +08:00
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
cn.requestState.Requests.Add(r)
|
2018-06-24 18:35:46 +08:00
|
|
|
if cn.validReceiveChunks == nil {
|
2021-09-19 13:16:37 +08:00
|
|
|
cn.validReceiveChunks = make(map[RequestIndex]int)
|
2018-06-24 18:35:46 +08:00
|
|
|
}
|
2020-04-23 10:34:43 +08:00
|
|
|
cn.validReceiveChunks[r]++
|
2021-12-03 18:30:41 +08:00
|
|
|
cn.t.pendingRequests[r] = cn
|
2021-12-02 10:10:02 +08:00
|
|
|
cn.t.lastRequested[r] = time.Now()
|
2018-06-24 18:04:31 +08:00
|
|
|
cn.updateExpectingChunks()
|
2021-09-19 13:16:37 +08:00
|
|
|
ppReq := cn.t.requestIndexToRequest(r)
|
2021-01-28 11:23:22 +08:00
|
|
|
for _, f := range cn.callbacks.SentRequest {
|
2021-09-19 13:16:37 +08:00
|
|
|
f(PeerRequestEvent{cn, ppReq})
|
2021-01-28 11:23:22 +08:00
|
|
|
}
|
2021-09-19 13:16:37 +08:00
|
|
|
return cn.peerImpl._request(ppReq), nil
|
2020-05-30 13:18:28 +08:00
|
|
|
}
|
|
|
|
|
2021-05-20 18:23:45 +08:00
|
|
|
func (me *PeerConn) _request(r Request) bool {
|
|
|
|
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,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-12-06 16:02:29 +08:00
|
|
|
func (me *Peer) cancel(r RequestIndex) {
|
2021-12-11 21:04:06 +08:00
|
|
|
if !me.deleteRequest(r) {
|
|
|
|
panic("request not existing should have been guarded")
|
|
|
|
}
|
|
|
|
if me._cancel(r) {
|
|
|
|
if !me.requestState.Cancelled.CheckedAdd(r) {
|
|
|
|
panic("request already cancelled")
|
|
|
|
}
|
|
|
|
}
|
2021-12-24 05:55:57 +08:00
|
|
|
me.decPeakRequests()
|
2021-12-11 21:04:06 +08:00
|
|
|
if me.isLowOnRequests() {
|
|
|
|
me.updateRequests("Peer.cancel")
|
2021-10-13 07:16:56 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-11 21:04:06 +08:00
|
|
|
func (me *PeerConn) _cancel(r RequestIndex) bool {
|
|
|
|
me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
|
2021-12-07 11:16:02 +08:00
|
|
|
// Transmission does not send rejects for received cancels. See
|
|
|
|
// https://github.com/transmission/transmission/pull/2275.
|
2021-12-11 21:04:06 +08:00
|
|
|
return me.fastEnabled() && !me.remoteIsTransmission()
|
2020-05-30 13:18:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *PeerConn) fillWriteBuffer() {
|
2021-12-24 05:55:57 +08:00
|
|
|
if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
|
|
|
|
// Fully committing to our max requests requires sufficient space (see
|
|
|
|
// maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
|
|
|
|
// requests than to do PEX or upload, so we short-circuit before handling those. Any update
|
|
|
|
// request reason will not be cleared, so we'll come right back here when there's space. We
|
|
|
|
// can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
|
|
|
|
// knowledge of write buffers.
|
|
|
|
}
|
|
|
|
cn.maybeUpdateActualRequestState()
|
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
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
2021-05-10 10:29:47 +08:00
|
|
|
cn.write(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
|
|
|
|
}
|
2021-05-10 10:29:47 +08:00
|
|
|
cn.write(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
|
|
|
})
|
2021-08-16 09:07:10 +08:00
|
|
|
cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
|
2016-01-04 19:37:49 +08:00
|
|
|
}
|
2016-01-24 12:21:17 +08:00
|
|
|
|
2021-10-21 07:28:57 +08:00
|
|
|
// Sets a reason to update requests, and if there wasn't already one, handle it.
|
|
|
|
func (cn *Peer) updateRequests(reason string) {
|
2021-10-08 10:53:36 +08:00
|
|
|
if cn.needRequestUpdate != "" {
|
2021-09-18 19:01:06 +08:00
|
|
|
return
|
|
|
|
}
|
2021-12-24 05:55:57 +08:00
|
|
|
if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
|
|
|
|
return
|
|
|
|
}
|
2021-10-08 10:53:36 +08:00
|
|
|
cn.needRequestUpdate = reason
|
2021-10-21 07:28:57 +08:00
|
|
|
cn.handleUpdateRequests()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *PeerConn) handleUpdateRequests() {
|
|
|
|
// The writer determines the request state as needed when it can write.
|
2021-10-08 10:53:36 +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(
|
2021-05-09 12:14:11 +08:00
|
|
|
func(_i interface{}) bool {
|
|
|
|
i := _i.(int)
|
2021-05-20 09:16:54 +08:00
|
|
|
if skip.Contains(bitmap.BitIndex(i)) {
|
2021-05-09 12:14:11 +08:00
|
|
|
return true
|
|
|
|
}
|
2021-05-20 09:16:54 +08:00
|
|
|
skip.Add(bitmap.BitIndex(i))
|
2020-01-10 07:27:05 +08:00
|
|
|
return cb(i)
|
|
|
|
},
|
2021-05-08 08:35:23 +08:00
|
|
|
bm.Iter,
|
2020-01-10 07:27:05 +08:00
|
|
|
) {
|
2017-09-23 13:25:47 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-11 12:45:55 +08:00
|
|
|
func (cn *Peer) peerPiecesChanged() {
|
2021-05-10 15:02:17 +08:00
|
|
|
cn.t.maybeDropMutuallyCompletePeer(cn)
|
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)
|
2021-05-10 15:02:17 +08:00
|
|
|
if !cn.peerHasPiece(piece) {
|
|
|
|
cn.t.incPieceAvailability(piece)
|
|
|
|
}
|
2021-10-05 14:48:34 +08:00
|
|
|
cn._peerPieces.Add(uint32(piece))
|
2021-10-11 12:45:55 +08:00
|
|
|
if cn.t.wantPieceIndex(piece) {
|
|
|
|
cn.updateRequests("have")
|
|
|
|
}
|
|
|
|
cn.peerPiecesChanged()
|
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 {
|
2016-03-22 09:07:03 +08:00
|
|
|
if len(bf)%8 != 0 {
|
|
|
|
panic("expected bitfield length divisible by 8")
|
|
|
|
}
|
2021-05-10 15:02:17 +08:00
|
|
|
// 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
|
|
|
}
|
2021-12-17 19:06:21 +08:00
|
|
|
bm := boolSliceToBitmap(bf)
|
|
|
|
if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
|
|
|
|
cn.onPeerHasAllPieces()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if !bm.IsEmpty() {
|
|
|
|
cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
|
|
|
|
}
|
|
|
|
shouldUpdateRequests := false
|
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
|
|
|
|
panic(cn)
|
|
|
|
}
|
|
|
|
cn.peerSentHaveAll = false
|
|
|
|
if !cn._peerPieces.IsEmpty() {
|
|
|
|
panic("if peer has all, we expect no individual peer pieces to be set")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
bm.Xor(&cn._peerPieces)
|
|
|
|
}
|
2021-05-10 15:02:17 +08:00
|
|
|
cn.peerSentHaveAll = false
|
2021-12-17 19:06:21 +08:00
|
|
|
// bm is now 'on' for pieces that are changing
|
|
|
|
bm.Iterate(func(x uint32) bool {
|
|
|
|
pi := pieceIndex(x)
|
|
|
|
if cn._peerPieces.Contains(x) {
|
|
|
|
// Then we must be losing this piece
|
|
|
|
cn.t.decPieceAvailability(pi)
|
2021-05-10 15:02:17 +08:00
|
|
|
} else {
|
2021-12-17 19:06:21 +08:00
|
|
|
if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
|
|
|
|
shouldUpdateRequests = true
|
2021-05-10 15:02:17 +08:00
|
|
|
}
|
2021-12-17 19:06:21 +08:00
|
|
|
// We must be gaining this piece
|
|
|
|
cn.t.incPieceAvailability(pieceIndex(x))
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2021-12-17 19:06:21 +08:00
|
|
|
return true
|
|
|
|
})
|
|
|
|
// Apply the changes. If we had everything previously, this should be empty, so xor is the same
|
|
|
|
// as or.
|
|
|
|
cn._peerPieces.Xor(&bm)
|
|
|
|
if shouldUpdateRequests {
|
|
|
|
cn.updateRequests("bitfield")
|
2016-03-21 11:17:15 +08:00
|
|
|
}
|
2021-12-17 19:06:21 +08:00
|
|
|
// We didn't guard this before, I see no reason to do it now.
|
2021-10-11 12:45:55 +08:00
|
|
|
cn.peerPiecesChanged()
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-11-12 09:37:40 +08:00
|
|
|
func (cn *PeerConn) onPeerHasAllPieces() {
|
2021-05-10 15:02:17 +08:00
|
|
|
t := cn.t
|
|
|
|
if t.haveInfo() {
|
2021-12-17 19:06:21 +08:00
|
|
|
cn._peerPieces.Iterate(func(x uint32) bool {
|
|
|
|
t.decPieceAvailability(pieceIndex(x))
|
|
|
|
return true
|
|
|
|
})
|
2021-05-10 15:02:17 +08:00
|
|
|
}
|
2021-12-17 19:06:21 +08:00
|
|
|
t.addConnWithAllPieces(&cn.Peer)
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = true
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.Clear()
|
2021-10-13 12:16:53 +08:00
|
|
|
if !cn.t._pendingPieces.IsEmpty() {
|
|
|
|
cn.updateRequests("Peer.onPeerHasAllPieces")
|
2021-10-11 12:45:55 +08:00
|
|
|
}
|
|
|
|
cn.peerPiecesChanged()
|
2021-05-10 15:02:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cn *PeerConn) onPeerSentHaveAll() error {
|
|
|
|
cn.onPeerHasAllPieces()
|
2016-03-22 09:07:03 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (cn *PeerConn) peerSentHaveNone() error {
|
2021-12-17 19:06:21 +08:00
|
|
|
if cn.peerSentHaveAll {
|
|
|
|
cn.t.decPeerPieceAvailability(&cn.Peer)
|
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
cn._peerPieces.Clear()
|
2018-01-29 15:18:08 +08:00
|
|
|
cn.peerSentHaveAll = false
|
2021-10-11 12:45:55 +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
|
|
|
}
|
|
|
|
|
2018-06-10 07:18:52 +08:00
|
|
|
// After handshake, we know what Torrent and Client stats to include for a
|
|
|
|
// connection.
|
2021-01-20 10:10:32 +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.
|
2021-01-20 10:10:32 +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
|
|
|
}
|
|
|
|
|
2021-10-25 13:17:55 +08:00
|
|
|
func (cn *Peer) 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.
|
2021-01-20 10:10:32 +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
|
|
|
|
2021-01-20 10:10:32 +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
|
|
|
}
|
|
|
|
|
2021-01-28 11:23:22 +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
|
|
|
}
|
2021-05-10 10:29:47 +08:00
|
|
|
c.write(r.ToMsg(pp.Reject))
|
2020-02-21 08:07:50 +08:00
|
|
|
delete(c.peerRequests, r)
|
2018-02-03 10:35:09 +08:00
|
|
|
}
|
|
|
|
|
2021-01-28 11:23:22 +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
|
|
|
|
}
|
2021-05-20 06:34:20 +08:00
|
|
|
// TODO: What if they've already requested this?
|
|
|
|
if len(c.peerRequests) >= localClientReqq {
|
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)
|
2021-01-28 11:23:22 +08:00
|
|
|
return errors.New("bad Request")
|
2019-08-23 10:19:28 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
if c.peerRequests == nil {
|
2021-05-20 06:34:20 +08:00
|
|
|
c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
|
2018-02-02 16:19:14 +08:00
|
|
|
}
|
2020-11-13 12:50:08 +08:00
|
|
|
value := &peerRequestState{}
|
|
|
|
c.peerRequests[r] = value
|
|
|
|
go c.peerRequestDataReader(r, value)
|
2018-02-02 16:19:14 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-28 11:23:22 +08:00
|
|
|
func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
|
2020-11-13 12:50:08 +08:00
|
|
|
b, err := readPeerRequestData(r, c)
|
|
|
|
c.locker().Lock()
|
|
|
|
defer c.locker().Unlock()
|
|
|
|
if err != nil {
|
|
|
|
c.peerRequestDataReadFailed(err, r)
|
|
|
|
} else {
|
|
|
|
if b == nil {
|
|
|
|
panic("data must be non-nil to trigger send")
|
|
|
|
}
|
2021-12-27 19:06:52 +08:00
|
|
|
torrent.Add("peer request data read successes", 1)
|
2020-11-13 12:50:08 +08:00
|
|
|
prs.data = b
|
|
|
|
c.tickleWriter()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If this is maintained correctly, we might be able to support optional synchronous reading for
|
|
|
|
// chunk sending, the way it used to work.
|
2021-01-28 11:23:22 +08:00
|
|
|
func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
|
2021-12-27 19:06:52 +08:00
|
|
|
torrent.Add("peer request data read failures", 1)
|
|
|
|
logLevel := log.Warning
|
|
|
|
if c.t.hasStorageCap() {
|
|
|
|
// It's expected that pieces might drop. See
|
|
|
|
// https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
|
|
|
|
logLevel = log.Debug
|
|
|
|
}
|
|
|
|
c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
|
2021-10-27 12:14:11 +08:00
|
|
|
if c.t.closed.IsSet() {
|
|
|
|
return
|
|
|
|
}
|
2020-11-13 12:50:08 +08:00
|
|
|
i := pieceIndex(r.Index)
|
|
|
|
if c.t.pieceComplete(i) {
|
|
|
|
// There used to be more code here that just duplicated the following break. Piece
|
|
|
|
// completions are currently cached, so I'm not sure how helpful this update is, except to
|
|
|
|
// pull any completion changes pushed to the storage backend in failed reads that got us
|
|
|
|
// here.
|
|
|
|
c.t.updatePieceCompletion(i)
|
|
|
|
}
|
2021-12-27 19:19:04 +08:00
|
|
|
// We've probably dropped a piece from storage, but there's no way to communicate this to the
|
|
|
|
// peer. If they ask for it again, we kick them allowing us to send them updated piece states if
|
|
|
|
// we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
|
|
|
|
// if they kick us for breaking protocol, on reconnect we will be compliant again (at least
|
|
|
|
// initially).
|
|
|
|
if c.fastEnabled() {
|
|
|
|
c.reject(r)
|
|
|
|
} else {
|
|
|
|
if c.choking {
|
|
|
|
// If fast isn't enabled, I think we would have wiped all peer requests when we last
|
|
|
|
// choked, and requests while we're choking would be ignored. It could be possible that
|
|
|
|
// a peer request data read completed concurrently to it being deleted elsewhere.
|
|
|
|
c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
|
|
|
|
}
|
|
|
|
// Choking a non-fast peer should cause them to flush all their requests.
|
|
|
|
c.choke(c.write)
|
2020-11-13 12:50:08 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-28 11:23:22 +08:00
|
|
|
func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
|
2020-11-13 12:50:08 +08:00
|
|
|
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 == io.EOF {
|
|
|
|
err = nil
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if err == nil {
|
|
|
|
panic("expected error")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return b, err
|
|
|
|
}
|
|
|
|
|
2020-04-23 10:34:43 +08:00
|
|
|
func runSafeExtraneous(f func()) {
|
|
|
|
if true {
|
|
|
|
go f()
|
|
|
|
} else {
|
|
|
|
f()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-19 10:36:37 +08:00
|
|
|
func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
|
2022-01-23 06:37:11 +08:00
|
|
|
c.logger.WithContextText(fmt.Sprintf(
|
2021-12-06 16:02:55 +08:00
|
|
|
"peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
|
2022-01-23 06:37:11 +08:00
|
|
|
)).SkipCallers(1).Levelf(level, format, arg...)
|
2021-10-19 10:36:37 +08:00
|
|
|
}
|
|
|
|
|
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,
|
2021-09-09 20:27:16 +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-10-14 12:11:45 +08:00
|
|
|
if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
|
2020-07-15 12:00:47 +08:00
|
|
|
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.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:
|
2021-10-12 08:58:46 +08:00
|
|
|
if c.peerChoking {
|
|
|
|
break
|
|
|
|
}
|
2020-04-23 10:36:19 +08:00
|
|
|
if !c.fastEnabled() {
|
2021-12-13 09:09:12 +08:00
|
|
|
if !c.deleteAllRequests().IsEmpty() {
|
|
|
|
c.t.iterPeers(func(p *Peer) {
|
|
|
|
if p.isLowOnRequests() {
|
|
|
|
p.updateRequests("choked by non-fast PeerConn")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2021-10-11 15:21:24 +08:00
|
|
|
} else {
|
2021-10-25 13:36:58 +08:00
|
|
|
// We don't decrement pending requests here, let's wait for the peer to either
|
2021-12-11 21:04:06 +08:00
|
|
|
// reject or satisfy the outstanding requests. Additionally, some peers may unchoke
|
2021-10-25 13:36:58 +08:00
|
|
|
// us and resume where they left off, we don't want to have piled on to those chunks
|
2021-12-11 21:04:06 +08:00
|
|
|
// in the meanwhile. I think a peer's ability to abuse this should be limited: they
|
2021-10-25 13:36:58 +08:00
|
|
|
// could let us request a lot of stuff, then choke us and never reject, but they're
|
|
|
|
// only a single peer, our chunk balancing should smooth over this abuse.
|
2020-04-23 10:36:19 +08:00
|
|
|
}
|
2021-10-12 08:58:46 +08:00
|
|
|
c.peerChoking = true
|
2018-06-24 18:04:31 +08:00
|
|
|
c.updateExpectingChunks()
|
2016-09-11 12:32:56 +08:00
|
|
|
case pp.Unchoke:
|
2021-10-11 15:21:24 +08:00
|
|
|
if !c.peerChoking {
|
2021-10-19 10:36:37 +08:00
|
|
|
// Some clients do this for some reason. Transmission doesn't error on this, so we
|
|
|
|
// won't for consistency.
|
2021-10-20 08:22:35 +08:00
|
|
|
c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
|
2021-10-19 10:36:37 +08:00
|
|
|
break
|
2021-10-11 15:21:24 +08:00
|
|
|
}
|
2020-02-21 08:07:50 +08:00
|
|
|
c.peerChoking = false
|
2021-10-12 10:06:11 +08:00
|
|
|
preservedCount := 0
|
2021-12-11 21:04:06 +08:00
|
|
|
c.requestState.Requests.Iterate(func(x uint32) bool {
|
2021-10-11 15:21:24 +08:00
|
|
|
if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
|
2021-10-12 10:06:11 +08:00
|
|
|
preservedCount++
|
2021-10-11 15:21:24 +08:00
|
|
|
}
|
|
|
|
return true
|
|
|
|
})
|
2021-10-12 10:06:11 +08:00
|
|
|
if preservedCount != 0 {
|
|
|
|
// TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
|
|
|
|
// right now.
|
2022-01-23 06:37:11 +08:00
|
|
|
c.logger.Levelf(log.Debug,
|
2021-10-18 16:06:33 +08:00
|
|
|
"%v requests were preserved while being choked (fast=%v)",
|
|
|
|
preservedCount,
|
|
|
|
c.fastEnabled())
|
2022-01-23 06:37:11 +08:00
|
|
|
|
2021-10-12 10:06:11 +08:00
|
|
|
torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
|
|
|
|
}
|
2021-11-29 09:12:30 +08:00
|
|
|
if !c.t._pendingPieces.IsEmpty() {
|
|
|
|
c.updateRequests("unchoked")
|
|
|
|
}
|
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:
|
2021-05-21 09:49:57 +08:00
|
|
|
c.doChunkReadStats(int64(len(msg.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 {
|
2021-09-30 10:01:56 +08:00
|
|
|
err = fmt.Errorf("receiving chunk: %w", err)
|
2018-06-26 18:24:39 +08:00
|
|
|
}
|
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)
|
2022-01-23 06:37:11 +08:00
|
|
|
log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
|
2021-10-08 10:53:36 +08:00
|
|
|
c.updateRequests("suggested")
|
2019-10-01 16:13:16 +08:00
|
|
|
case pp.HaveAll:
|
|
|
|
err = c.onPeerSentHaveAll()
|
|
|
|
case pp.HaveNone:
|
|
|
|
err = c.peerSentHaveNone()
|
|
|
|
case pp.Reject:
|
2021-12-11 21:04:06 +08:00
|
|
|
req := newRequestFromMessage(&msg)
|
|
|
|
if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
|
|
|
|
log.Printf("received invalid reject [request=%v, peer=%v]", req, c)
|
|
|
|
err = fmt.Errorf("received invalid reject [request=%v]", req)
|
|
|
|
}
|
2018-02-04 21:18:38 +08:00
|
|
|
case pp.AllowedFast:
|
|
|
|
torrent.Add("allowed fasts received", 1)
|
2022-01-23 06:37:11 +08:00
|
|
|
log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
|
2021-10-11 19:04:53 +08:00
|
|
|
c.updateRequests("PeerConn.mainReadLoop allowed fast")
|
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
|
|
|
|
2021-12-11 21:04:06 +08:00
|
|
|
// Returns true if it was valid to reject the request.
|
|
|
|
func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
|
2021-12-24 05:55:57 +08:00
|
|
|
if c.deleteRequest(r) {
|
|
|
|
c.decPeakRequests()
|
|
|
|
} else if !c.requestState.Cancelled.CheckedRemove(r) {
|
2021-12-11 21:04:06 +08:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if c.isLowOnRequests() {
|
|
|
|
c.updateRequests("Peer.remoteRejectedRequest")
|
2020-09-03 12:34:06 +08:00
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
c.decExpectedChunkReceive(r)
|
|
|
|
return true
|
2020-06-02 14:41:49 +08:00
|
|
|
}
|
|
|
|
|
2021-09-19 13:16:37 +08:00
|
|
|
func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
|
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)
|
2021-05-11 15:14:02 +08:00
|
|
|
return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
|
2018-02-03 11:06:10 +08:00
|
|
|
}
|
2020-10-14 12:11:45 +08:00
|
|
|
if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
|
2020-07-15 14:16:09 +08:00
|
|
|
cb(c, &d)
|
|
|
|
}
|
2021-11-08 11:47: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
|
|
|
}
|
2021-12-06 16:02:55 +08:00
|
|
|
c.PeerClientName.Store(d.V)
|
2018-07-10 10:20:36 +08:00
|
|
|
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 {
|
2021-11-19 10:02:42 +08:00
|
|
|
peersSupportingExtension.Add(
|
|
|
|
// expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
|
|
|
|
// entered here which caused problems later when unmarshalling.
|
|
|
|
strconv.Quote(string(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 {
|
2021-05-11 15:14:02 +08:00
|
|
|
return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
|
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
|
|
|
|
2021-05-21 09:49:57 +08:00
|
|
|
func (c *Peer) doChunkReadStats(size int64) {
|
|
|
|
c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
|
|
|
|
}
|
|
|
|
|
2016-11-22 11:16:18 +08:00
|
|
|
// Handle a received chunk from a peer.
|
2021-01-20 10:10:32 +08:00
|
|
|
func (c *Peer) receiveChunk(msg *pp.Message) error {
|
2021-05-11 15:13:03 +08:00
|
|
|
chunksReceived.Add("total", 1)
|
2016-11-22 11:16:18 +08:00
|
|
|
|
2021-09-19 13:16:37 +08:00
|
|
|
ppReq := newRequestFromMessage(msg)
|
|
|
|
req := c.t.requestIndexFromRequest(ppReq)
|
2022-01-10 13:19:16 +08:00
|
|
|
t := c.t
|
|
|
|
|
2022-01-12 11:23:30 +08:00
|
|
|
if c.bannableAddr.Ok() {
|
|
|
|
t.smartBanCache.RecordBlock(c.bannableAddr.Value(), req, msg.Piece)
|
2022-01-10 13:19:16 +08:00
|
|
|
}
|
2016-11-22 11:16:18 +08:00
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
if c.peerChoking {
|
2021-05-11 15:13:03 +08:00
|
|
|
chunksReceived.Add("while choked", 1)
|
2018-06-25 12:06:30 +08:00
|
|
|
}
|
|
|
|
|
2020-04-23 10:34:43 +08:00
|
|
|
if c.validReceiveChunks[req] <= 0 {
|
2021-05-11 15:13:03 +08:00
|
|
|
chunksReceived.Add("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
|
|
|
|
2021-10-05 17:06:23 +08:00
|
|
|
if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
|
2021-05-11 15:13:03 +08:00
|
|
|
chunksReceived.Add("due to allowed fast", 1)
|
2018-06-25 12:06:30 +08:00
|
|
|
}
|
|
|
|
|
2021-05-09 22:53:32 +08:00
|
|
|
// The request needs to be deleted immediately to prevent cancels occurring asynchronously when
|
|
|
|
// have actually already received the piece, while we have the Client unlocked to write the data
|
|
|
|
// out.
|
2021-12-11 21:04:06 +08:00
|
|
|
intended := false
|
2021-01-28 13:36:35 +08:00
|
|
|
{
|
2021-12-11 21:04:06 +08:00
|
|
|
if c.requestState.Requests.Contains(req) {
|
2021-01-28 13:36:35 +08:00
|
|
|
for _, f := range c.callbacks.ReceivedRequested {
|
|
|
|
f(PeerMessageEvent{c, msg})
|
|
|
|
}
|
|
|
|
}
|
2020-10-30 09:19:53 +08:00
|
|
|
// Request has been satisfied.
|
2021-12-11 21:04:06 +08:00
|
|
|
if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
|
|
|
|
intended = true
|
2021-05-09 22:53:32 +08:00
|
|
|
if !c.peerChoking {
|
2020-10-30 09:19:53 +08:00
|
|
|
c._chunksReceivedWhileExpecting++
|
|
|
|
}
|
2021-10-21 07:48:43 +08:00
|
|
|
if c.isLowOnRequests() {
|
2021-10-13 07:16:56 +08:00
|
|
|
c.updateRequests("Peer.receiveChunk deleted request")
|
|
|
|
}
|
2020-10-30 09:19:53 +08:00
|
|
|
} else {
|
2021-12-11 21:04:06 +08:00
|
|
|
chunksReceived.Add("unintended", 1)
|
2018-06-24 18:04:31 +08:00
|
|
|
}
|
2021-01-28 13:36:35 +08:00
|
|
|
}
|
2018-02-04 21:18:38 +08:00
|
|
|
|
2021-05-21 09:49:57 +08:00
|
|
|
cl := t.cl
|
|
|
|
|
2016-11-22 11:16:18 +08:00
|
|
|
// Do we actually want this chunk?
|
2021-09-19 13:16:37 +08:00
|
|
|
if t.haveChunk(ppReq) {
|
2021-11-08 11:47:01 +08:00
|
|
|
// panic(fmt.Sprintf("%+v", ppReq))
|
2021-12-11 21:04:06 +08:00
|
|
|
chunksReceived.Add("redundant", 1)
|
2018-06-25 12:06:30 +08:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-09-19 13:16:37 +08:00
|
|
|
piece := &t.pieces[ppReq.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 }))
|
2021-12-11 21:04:06 +08:00
|
|
|
if intended {
|
2021-05-20 06:56:53 +08:00
|
|
|
c.piecesReceivedSinceLastRequestUpdate++
|
2021-05-09 22:53:32 +08:00
|
|
|
c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
|
|
|
|
}
|
2021-01-20 11:22:44 +08:00
|
|
|
for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
|
|
|
|
f(ReceivedUsefulDataEvent{c, msg})
|
|
|
|
}
|
2016-11-22 11:16:18 +08:00
|
|
|
c.lastUsefulChunkReceived = time.Now()
|
|
|
|
|
|
|
|
// 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.
|
2021-09-19 13:16:37 +08:00
|
|
|
piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
|
2016-11-22 11:16:18 +08:00
|
|
|
|
2021-01-28 11:26:10 +08:00
|
|
|
// Cancel pending requests for this chunk from *other* peers.
|
2021-12-06 16:02:29 +08:00
|
|
|
if p := t.pendingRequests[req]; p != nil {
|
2021-01-28 11:26:10 +08:00
|
|
|
if p == c {
|
2021-12-06 16:02:29 +08:00
|
|
|
panic("should not be pending request from conn that just received it")
|
2021-01-28 11:26:10 +08:00
|
|
|
}
|
2021-05-09 21:38:38 +08:00
|
|
|
p.cancel(req)
|
2021-12-06 16:02:29 +08:00
|
|
|
}
|
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-10-10 07:24:58 +08:00
|
|
|
c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
|
2016-11-22 11:16:18 +08:00
|
|
|
t.pendRequest(req)
|
2021-10-08 10:53:36 +08:00
|
|
|
// Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
|
|
|
|
// request update runs while we're writing the chunk that just failed. Then we never do a
|
|
|
|
// fresh update after pending the failed request.
|
2021-10-11 15:22:02 +08:00
|
|
|
c.updateRequests("Peer.receiveChunk error writing chunk")
|
2020-02-22 16:40:50 +08:00
|
|
|
t.onWriteChunkErr(err)
|
2018-06-24 18:35:46 +08:00
|
|
|
return nil
|
2016-11-22 11:16:18 +08:00
|
|
|
}
|
|
|
|
|
2021-09-19 13:16:37 +08:00
|
|
|
c.onDirtiedPiece(pieceIndex(ppReq.Index))
|
2020-01-23 10:52:17 +08:00
|
|
|
|
2020-11-06 05:39:56 +08:00
|
|
|
// We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
|
2021-09-19 13:16:37 +08:00
|
|
|
if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
|
|
|
|
t.queuePieceCheck(pieceIndex(ppReq.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.
|
2021-09-19 13:16:37 +08:00
|
|
|
t.publishPieceChange(pieceIndex(ppReq.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
|
|
|
|
2021-01-20 10:10:32 +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 {
|
2021-01-20 10:10:32 +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 {
|
2021-05-20 16:51:08 +08:00
|
|
|
c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
|
2018-02-02 16:04:56 +08:00
|
|
|
} 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-11-13 12:50:08 +08:00
|
|
|
for r, state := range c.peerRequests {
|
|
|
|
if state.data == nil {
|
|
|
|
continue
|
|
|
|
}
|
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
|
|
|
}
|
2020-11-13 12:50:08 +08:00
|
|
|
more := c.sendChunk(r, msg, state)
|
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)
|
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +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
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (c *Peer) peerHasWantedPieces() bool {
|
2021-11-12 09:37:40 +08:00
|
|
|
if all, _ := c.peerHasAllPieces(); all {
|
2021-11-28 19:36:19 +08:00
|
|
|
return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
|
2021-10-11 12:46:40 +08:00
|
|
|
}
|
|
|
|
if !c.t.haveInfo() {
|
2021-11-12 09:37:40 +08:00
|
|
|
return !c.peerPieces().IsEmpty()
|
2021-10-11 12:46:40 +08:00
|
|
|
}
|
2021-11-12 09:37:40 +08:00
|
|
|
return c.peerPieces().Intersects(&c.t._pendingPieces)
|
2017-08-17 23:48:19 +08:00
|
|
|
}
|
2017-08-31 21:48:52 +08:00
|
|
|
|
2021-12-11 21:04:06 +08:00
|
|
|
// Returns true if an outstanding request is removed. Cancelled requests should be handled
|
|
|
|
// separately.
|
2021-09-19 13:16:37 +08:00
|
|
|
func (c *Peer) deleteRequest(r RequestIndex) bool {
|
2021-12-11 21:04:06 +08:00
|
|
|
if !c.requestState.Requests.CheckedRemove(r) {
|
2017-09-01 10:09:41 +08:00
|
|
|
return false
|
|
|
|
}
|
2021-01-28 11:23:22 +08:00
|
|
|
for _, f := range c.callbacks.DeletedRequest {
|
2021-09-19 13:16:37 +08:00
|
|
|
f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
|
2021-01-28 11:23:22 +08:00
|
|
|
}
|
2018-06-24 18:04:31 +08:00
|
|
|
c.updateExpectingChunks()
|
2021-12-11 21:04:06 +08:00
|
|
|
if c.t.requestingPeer(r) != c {
|
|
|
|
panic("only one peer should have a given request at a time")
|
2021-12-10 15:04:45 +08:00
|
|
|
}
|
2021-12-11 21:04:06 +08:00
|
|
|
delete(c.t.pendingRequests, r)
|
|
|
|
delete(c.t.lastRequested, r)
|
2021-12-13 09:09:12 +08:00
|
|
|
// c.t.iterPeers(func(p *Peer) {
|
|
|
|
// if p.isLowOnRequests() {
|
|
|
|
// p.updateRequests("Peer.deleteRequest")
|
|
|
|
// }
|
|
|
|
// })
|
2017-09-01 10:09:41 +08:00
|
|
|
return true
|
|
|
|
}
|
2017-11-04 14:08:02 +08:00
|
|
|
|
2021-12-13 09:09:12 +08:00
|
|
|
func (c *Peer) deleteAllRequests() (deleted *roaring.Bitmap) {
|
|
|
|
deleted = c.requestState.Requests.Clone()
|
|
|
|
deleted.Iterate(func(x uint32) bool {
|
2021-12-11 21:04:06 +08:00
|
|
|
if !c.deleteRequest(x) {
|
|
|
|
panic("request should exist")
|
|
|
|
}
|
2021-09-19 13:16:37 +08:00
|
|
|
return true
|
|
|
|
})
|
2021-12-13 09:09:12 +08:00
|
|
|
c.assertNoRequests()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Peer) assertNoRequests() {
|
2021-12-11 21:04:06 +08:00
|
|
|
if !c.requestState.Requests.IsEmpty() {
|
|
|
|
panic(c.requestState.Requests.GetCardinality())
|
2018-02-15 12:21:51 +08:00
|
|
|
}
|
2018-02-01 11:46:03 +08:00
|
|
|
}
|
|
|
|
|
2021-12-13 09:11:38 +08:00
|
|
|
func (c *Peer) cancelAllRequests() (cancelled *roaring.Bitmap) {
|
|
|
|
cancelled = c.requestState.Requests.Clone()
|
|
|
|
cancelled.Iterate(func(x uint32) bool {
|
|
|
|
c.cancel(x)
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
c.assertNoRequests()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-11-13 12:50:08 +08:00
|
|
|
// This is called when something has changed that should wake the writer, such as putting stuff into
|
|
|
|
// the writeBuffer, or changing some state that the writer can act on.
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) tickleWriter() {
|
2021-05-20 16:51:08 +08:00
|
|
|
c.messageWriter.writeCond.Broadcast()
|
2017-09-01 13:26:50 +08:00
|
|
|
}
|
2017-09-18 11:47:49 +08:00
|
|
|
|
2021-01-28 11:23:22 +08:00
|
|
|
func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
|
2020-11-13 12:50:08 +08:00
|
|
|
c.lastChunkSent = time.Now()
|
|
|
|
return msg(pp.Message{
|
2018-02-02 10:26:04 +08:00
|
|
|
Type: pp.Piece,
|
|
|
|
Index: r.Index,
|
|
|
|
Begin: r.Begin,
|
2020-11-13 12:50:08 +08:00
|
|
|
Piece: state.data,
|
2018-02-02 10:26:04 +08:00
|
|
|
})
|
|
|
|
}
|
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
|
2020-10-10 07:24:58 +08:00
|
|
|
c.logger.WithDefaultLevel(log.Debug).Printf("set 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
|
|
|
|
2021-01-20 10:10:32 +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
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (c *Peer) remoteIp() net.IP {
|
2021-01-25 11:22:24 +08:00
|
|
|
host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
|
|
|
|
return net.ParseIP(host)
|
2018-07-10 07:50:39 +08:00
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +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
|
|
|
|
}
|
2021-01-25 11:22:24 +08:00
|
|
|
if c.utp() {
|
2019-12-11 19:45:04 +08:00
|
|
|
f |= pp.PexSupportsUtp
|
|
|
|
}
|
|
|
|
return f
|
|
|
|
}
|
|
|
|
|
2020-10-23 05:58:55 +08:00
|
|
|
// This returns the address to use if we want to dial the peer again. It incorporates the peer's
|
|
|
|
// advertised listen port.
|
2021-01-25 11:22:24 +08:00
|
|
|
func (c *PeerConn) dialAddr() PeerRemoteAddr {
|
2020-04-09 00:03:29 +08:00
|
|
|
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()
|
2021-12-07 02:46:25 +08:00
|
|
|
return pexEvent{t, addr, f, nil}
|
2020-04-01 04:14:43 +08:00
|
|
|
}
|
|
|
|
|
2020-02-21 08:07:50 +08:00
|
|
|
func (c *PeerConn) String() string {
|
2021-12-06 16:02:55 +08:00
|
|
|
return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
|
2019-10-01 19:16:18 +08:00
|
|
|
}
|
2019-12-18 10:52:00 +08:00
|
|
|
|
2021-01-20 10:10:32 +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
|
|
|
|
2021-05-20 12:01:31 +08:00
|
|
|
// Returns the pieces the peer could have based on their claims. If we don't know how many pieces
|
|
|
|
// are in the torrent, it could be a very large range the peer has sent HaveAll.
|
2021-10-05 14:48:34 +08:00
|
|
|
func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
|
2020-02-21 08:51:24 +08:00
|
|
|
cn.locker().RLock()
|
|
|
|
defer cn.locker().RUnlock()
|
2021-05-10 15:02:17 +08:00
|
|
|
return cn.newPeerPieces()
|
2020-02-21 08:51:24 +08:00
|
|
|
}
|
|
|
|
|
2021-05-20 12:01:31 +08:00
|
|
|
// Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
|
2021-10-05 14:48:34 +08:00
|
|
|
func (cn *Peer) newPeerPieces() *roaring.Bitmap {
|
|
|
|
// TODO: Can we use copy on write?
|
2021-11-12 09:37:40 +08:00
|
|
|
ret := cn.peerPieces().Clone()
|
|
|
|
if all, _ := cn.peerHasAllPieces(); all {
|
2021-05-20 12:01:31 +08:00
|
|
|
if cn.t.haveInfo() {
|
|
|
|
ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
|
|
|
|
} else {
|
|
|
|
ret.AddRange(0, bitmap.ToEnd)
|
|
|
|
}
|
2020-01-10 12:09:21 +08:00
|
|
|
}
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
2021-01-20 10:10:32 +08:00
|
|
|
func (cn *Peer) stats() *ConnStats {
|
2020-01-10 12:09:21 +08:00
|
|
|
return &cn._stats
|
|
|
|
}
|
|
|
|
|
2021-01-28 13:31:13 +08:00
|
|
|
func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
|
|
|
|
pc, ok := p.peerImpl.(*PeerConn)
|
|
|
|
return pc, ok
|
|
|
|
}
|
2021-10-21 07:48:43 +08:00
|
|
|
|
2021-12-10 15:04:45 +08:00
|
|
|
func (p *Peer) uncancelledRequests() uint64 {
|
2021-12-11 21:04:06 +08:00
|
|
|
return p.requestState.Requests.GetCardinality()
|
2021-12-10 15:04:45 +08:00
|
|
|
}
|
|
|
|
|
2021-12-07 11:16:02 +08:00
|
|
|
func (pc *PeerConn) remoteIsTransmission() bool {
|
|
|
|
return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
|
|
|
|
}
|