17 "github.com/RoaringBitmap/roaring"
18 "github.com/anacrolix/log"
19 "github.com/anacrolix/missinggo/iter"
20 "github.com/anacrolix/missinggo/v2/bitmap"
21 "github.com/anacrolix/multiless"
23 "github.com/anacrolix/chansync"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/metainfo"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
28 request_strategy "github.com/anacrolix/torrent/request-strategy"
31 type PeerSource string
34 PeerSourceTracker = "Tr"
35 PeerSourceIncoming = "I"
36 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
37 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
39 // The peer was given directly, such as through a magnet link.
40 PeerSourceDirect = "M"
43 type peerRequestState struct {
47 type PeerRemoteAddr interface {
51 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
52 // indexable with the memory space available.
55 requestState = request_strategy.PeerRequestState
59 // First to ensure 64-bit alignment for atomics. See #262.
69 RemoteAddr PeerRemoteAddr
70 // True if the connection is operating over MSE obfuscation.
72 cryptoMethod mse.CryptoMethod
75 closed chansync.SetOnce
76 // Set true after we've added our ConnStats generated during handshake to
77 // other ConnStat instances as determined when the *Torrent became known.
78 reconciledHandshakeStats bool
80 lastMessageReceived time.Time
81 completedHandshake time.Time
82 lastUsefulChunkReceived time.Time
83 lastChunkSent time.Time
85 // Stuff controlled by the local peer.
86 needRequestUpdate string
87 requestState requestState
88 updateRequestsTimer *time.Timer
89 lastBecameInterested time.Time
90 priorInterest time.Duration
92 lastStartedExpectingToReceiveChunks time.Time
93 cumulativeExpectedToReceiveChunks time.Duration
94 _chunksReceivedWhileExpecting int64
97 piecesReceivedSinceLastRequestUpdate maxRequests
98 maxPiecesReceivedBetweenRequestUpdates maxRequests
99 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
100 // and implementation differences, we may receive chunks that are no longer in the set of
101 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
102 validReceiveChunks map[RequestIndex]int
103 // Indexed by metadata piece, set to true if posted and pending a
105 metadataRequests []bool
106 sentHaves bitmap.Bitmap
108 // Stuff controlled by the remote peer.
111 peerRequests map[Request]*peerRequestState
112 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
114 // The highest possible number of pieces the torrent could have based on
115 // communication with the peer. Generally only useful until we have the
117 peerMinPieces pieceIndex
118 // Pieces we've accepted chunks for from the peer.
119 peerTouchedPieces map[pieceIndex]struct{}
120 peerAllowedFast roaring.Bitmap
122 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
123 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
124 PeerClientName atomic.Value
129 // Maintains the state of a BitTorrent-protocol based connection with a peer.
130 type PeerConn struct {
133 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
134 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
139 PeerExtensionBytes pp.PeerExtensionBits
141 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
142 // while holding any mutexes.
144 // The Reader and Writer for this Conn, with hooks installed for stats,
145 // limiting, deadlines etc.
149 messageWriter peerConnMsgWriter
151 uploadTimer *time.Timer
154 // The pieces the peer has claimed to have.
155 _peerPieces roaring.Bitmap
156 // The peer has everything. This can occur due to a special message, when
157 // we may not even know the number of pieces in the torrent yet.
161 func (cn *PeerConn) connStatusString() string {
162 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
165 func (cn *Peer) updateExpectingChunks() {
166 if cn.expectingChunks() {
167 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
168 cn.lastStartedExpectingToReceiveChunks = time.Now()
171 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
172 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
173 cn.lastStartedExpectingToReceiveChunks = time.Time{}
178 func (cn *Peer) expectingChunks() bool {
179 if cn.requestState.Requests.IsEmpty() {
182 if !cn.requestState.Interested {
188 haveAllowedFastRequests := false
189 cn.peerAllowedFast.Iterate(func(i uint32) bool {
190 haveAllowedFastRequests = roaringBitmapRangeCardinality(
191 &cn.requestState.Requests,
192 cn.t.pieceRequestIndexOffset(pieceIndex(i)),
193 cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
195 return !haveAllowedFastRequests
197 return haveAllowedFastRequests
200 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
201 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
204 // Returns true if the connection is over IPv6.
205 func (cn *PeerConn) ipv6() bool {
210 return len(ip) == net.IPv6len
213 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
214 // specification for this.
215 func (cn *PeerConn) isPreferredDirection() bool {
216 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
219 // Returns whether the left connection should be preferred over the right one,
220 // considering only their networking properties. If ok is false, we can't
222 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
224 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
225 ml.NextBool(!l.utp(), !r.utp())
226 ml.NextBool(l.ipv6(), r.ipv6())
230 func (cn *Peer) cumInterest() time.Duration {
231 ret := cn.priorInterest
232 if cn.requestState.Interested {
233 ret += time.Since(cn.lastBecameInterested)
238 func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
239 if cn.peerSentHaveAll {
242 if !cn.t.haveInfo() {
245 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
248 func (cn *Peer) locker() *lockWithDeferreds {
249 return cn.t.cl.locker()
252 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
253 _, ok := cn.PeerExtensionIDs[ext]
257 // The best guess at number of pieces in the torrent for this peer.
258 func (cn *Peer) bestPeerNumPieces() pieceIndex {
260 return cn.t.numPieces()
262 return cn.peerMinPieces
265 func (cn *Peer) completedString() string {
266 have := pieceIndex(cn.peerPieces().GetCardinality())
267 if all, _ := cn.peerHasAllPieces(); all {
268 have = cn.bestPeerNumPieces()
270 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
273 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
274 cn.setNumPieces(info.NumPieces())
277 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
278 // receiving badly sized BITFIELD, or invalid HAVE messages.
279 func (cn *PeerConn) setNumPieces(num pieceIndex) {
280 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
281 cn.peerPiecesChanged()
284 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
285 return &cn._peerPieces
288 func eventAgeString(t time.Time) string {
292 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
295 func (cn *PeerConn) connectionFlags() (ret string) {
297 ret += string([]byte{b})
299 if cn.cryptoMethod == mse.CryptoMethodRC4 {
301 } else if cn.headerEncrypted {
304 ret += string(cn.Discovery)
311 func (cn *PeerConn) utp() bool {
312 return parseNetworkString(cn.Network).Udp
315 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
316 func (cn *Peer) statusFlags() (ret string) {
318 ret += string([]byte{b})
320 if cn.requestState.Interested {
327 ret += cn.connectionFlags()
329 if cn.peerInterested {
338 func (cn *Peer) downloadRate() float64 {
339 num := cn._stats.BytesReadUsefulData.Int64()
343 return float64(num) / cn.totalExpectingTime().Seconds()
346 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
347 ret = make(map[pieceIndex]int)
348 cn.requestState.Requests.Iterate(func(x uint32) bool {
349 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
355 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
356 // \t isn't preserved in <pre> blocks?
357 if cn.closed.IsSet() {
358 fmt.Fprint(w, "CLOSED: ")
360 fmt.Fprintln(w, cn.connStatusString())
361 prio, err := cn.peerPriority()
362 prioStr := fmt.Sprintf("%08x", prio)
364 prioStr += ": " + err.Error()
366 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
367 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
368 eventAgeString(cn.lastMessageReceived),
369 eventAgeString(cn.completedHandshake),
370 eventAgeString(cn.lastHelpful()),
372 cn.totalExpectingTime(),
375 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
376 cn.completedString(),
377 len(cn.peerTouchedPieces),
378 &cn._stats.ChunksReadUseful,
379 &cn._stats.ChunksRead,
380 &cn._stats.ChunksWritten,
381 cn.requestState.Requests.GetCardinality(),
382 cn.requestState.Cancelled.GetCardinality(),
383 cn.nominalMaxRequests(),
385 len(cn.peerRequests),
388 cn.downloadRate()/(1<<10),
390 fmt.Fprintf(w, " requested pieces:")
391 type pieceNumRequestsType struct {
395 var pieceNumRequests []pieceNumRequestsType
396 for piece, count := range cn.numRequestsByPiece() {
397 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
399 sort.Slice(pieceNumRequests, func(i, j int) bool {
400 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
402 for _, elem := range pieceNumRequests {
403 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
408 func (p *Peer) close() {
412 if p.updateRequestsTimer != nil {
413 p.updateRequestsTimer.Stop()
417 p.t.decPeerPieceAvailability(p)
419 for _, f := range p.callbacks.PeerClosed {
424 func (cn *PeerConn) onClose() {
425 if cn.pex.IsEnabled() {
432 if cb := cn.callbacks.PeerConnClosed; cb != nil {
437 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
438 // they do (known=true).
439 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
440 if all, known := cn.peerHasAllPieces(); all && known {
443 return cn.peerPieces().ContainsInt(piece)
446 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
447 // https://github.com/pion/datachannel/issues/59 is fixed.
448 const writeBufferHighWaterLen = 1 << 15
450 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
451 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
452 func (cn *PeerConn) write(msg pp.Message) bool {
453 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
454 // We don't need to track bytes here because the connection's Writer has that behaviour injected
455 // (although there's some delay between us buffering the message, and the connection writer
456 // flushing it out.).
457 notFull := cn.messageWriter.write(msg)
458 // Last I checked only Piece messages affect stats, and we don't write those.
464 func (cn *PeerConn) requestMetadataPiece(index int) {
465 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
466 if eID == pp.ExtensionDeleteNumber {
469 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
472 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
473 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
474 for index >= len(cn.metadataRequests) {
475 cn.metadataRequests = append(cn.metadataRequests, false)
477 cn.metadataRequests[index] = true
480 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
481 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
484 // The actual value to use as the maximum outbound requests.
485 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
486 return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 2048))
489 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
490 ret = cn.cumulativeExpectedToReceiveChunks
491 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
492 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
497 func (cn *PeerConn) onPeerSentCancel(r Request) {
498 if _, ok := cn.peerRequests[r]; !ok {
499 torrent.Add("unexpected cancels received", 1)
502 if cn.fastEnabled() {
505 delete(cn.peerRequests, r)
509 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
514 more = msg(pp.Message{
517 if cn.fastEnabled() {
518 for r := range cn.peerRequests {
519 // TODO: Don't reject pieces in allowed fast set.
523 cn.peerRequests = nil
528 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
533 return msg(pp.Message{
538 func (cn *Peer) setInterested(interested bool) bool {
539 if cn.requestState.Interested == interested {
542 cn.requestState.Interested = interested
544 cn.lastBecameInterested = time.Now()
545 } else if !cn.lastBecameInterested.IsZero() {
546 cn.priorInterest += time.Since(cn.lastBecameInterested)
548 cn.updateExpectingChunks()
549 // log.Printf("%p: setting interest: %v", cn, interested)
550 return cn.writeInterested(interested)
553 func (pc *PeerConn) writeInterested(interested bool) bool {
554 return pc.write(pp.Message{
555 Type: func() pp.MessageType {
559 return pp.NotInterested
565 // The function takes a message to be sent, and returns true if more messages
567 type messageWriter func(pp.Message) bool
569 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
570 // when we want to go fast.
571 func (cn *Peer) shouldRequest(r RequestIndex) error {
572 pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
573 if cn.requestState.Cancelled.Contains(r) {
574 return errors.New("request is cancelled and waiting acknowledgement")
576 if !cn.peerHasPiece(pi) {
577 return errors.New("requesting piece peer doesn't have")
579 if !cn.t.peerIsActive(cn) {
580 panic("requesting but not in active conns")
582 if cn.closed.IsSet() {
583 panic("requesting when connection is closed")
585 if cn.t.hashingPiece(pi) {
586 panic("piece is being hashed")
588 if cn.t.pieceQueuedForHash(pi) {
589 panic("piece is queued for hash")
591 if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
592 // This could occur if we made a request with the fast extension, and then got choked and
593 // haven't had the request rejected yet.
594 if !cn.requestState.Requests.Contains(r) {
595 panic("peer choking and piece not allowed fast")
601 func (cn *Peer) mustRequest(r RequestIndex) bool {
602 more, err := cn.request(r)
609 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
610 if err := cn.shouldRequest(r); err != nil {
613 if cn.requestState.Requests.Contains(r) {
616 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
617 return true, errors.New("too many outstanding requests")
619 cn.requestState.Requests.Add(r)
620 if cn.validReceiveChunks == nil {
621 cn.validReceiveChunks = make(map[RequestIndex]int)
623 cn.validReceiveChunks[r]++
624 cn.t.pendingRequests[r] = cn
625 cn.t.lastRequested[r] = time.Now()
626 cn.updateExpectingChunks()
627 ppReq := cn.t.requestIndexToRequest(r)
628 for _, f := range cn.callbacks.SentRequest {
629 f(PeerRequestEvent{cn, ppReq})
631 return cn.peerImpl._request(ppReq), nil
634 func (me *PeerConn) _request(r Request) bool {
635 return me.write(pp.Message{
643 func (me *Peer) cancel(r RequestIndex) {
644 if !me.deleteRequest(r) {
645 panic("request not existing should have been guarded")
648 if !me.requestState.Cancelled.CheckedAdd(r) {
649 panic("request already cancelled")
652 if me.isLowOnRequests() {
653 me.updateRequests("Peer.cancel")
657 func (me *PeerConn) _cancel(r RequestIndex) bool {
658 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
659 // Transmission does not send rejects for received cancels. See
660 // https://github.com/transmission/transmission/pull/2275.
661 return me.fastEnabled() && !me.remoteIsTransmission()
664 func (cn *PeerConn) fillWriteBuffer() {
665 if !cn.maybeUpdateActualRequestState() {
668 if cn.pex.IsEnabled() {
669 if flow := cn.pex.Share(cn.write); !flow {
676 func (cn *PeerConn) have(piece pieceIndex) {
677 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
682 Index: pp.Integer(piece),
684 cn.sentHaves.Add(bitmap.BitIndex(piece))
687 func (cn *PeerConn) postBitfield() {
688 if cn.sentHaves.Len() != 0 {
689 panic("bitfield must be first have-related message sent")
691 if !cn.t.haveAnyPieces() {
696 Bitfield: cn.t.bitfield(),
698 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
701 // Sets a reason to update requests, and if there wasn't already one, handle it.
702 func (cn *Peer) updateRequests(reason string) {
703 if cn.needRequestUpdate != "" {
706 cn.needRequestUpdate = reason
707 cn.handleUpdateRequests()
710 func (cn *PeerConn) handleUpdateRequests() {
711 // The writer determines the request state as needed when it can write.
715 // Emits the indices in the Bitmaps bms in order, never repeating any index.
716 // skip is mutated during execution, and its initial values will never be
718 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
719 return func(cb iter.Callback) {
720 for _, bm := range bms {
722 func(_i interface{}) bool {
724 if skip.Contains(bitmap.BitIndex(i)) {
727 skip.Add(bitmap.BitIndex(i))
738 func (cn *Peer) peerPiecesChanged() {
739 cn.t.maybeDropMutuallyCompletePeer(cn)
742 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
743 if newMin > cn.peerMinPieces {
744 cn.peerMinPieces = newMin
748 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
749 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
750 return errors.New("invalid piece")
752 if cn.peerHasPiece(piece) {
755 cn.raisePeerMinPieces(piece + 1)
756 if !cn.peerHasPiece(piece) {
757 cn.t.incPieceAvailability(piece)
759 cn._peerPieces.Add(uint32(piece))
760 if cn.t.wantPieceIndex(piece) {
761 cn.updateRequests("have")
763 cn.peerPiecesChanged()
767 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
769 panic("expected bitfield length divisible by 8")
771 // We know that the last byte means that at most the last 7 bits are wasted.
772 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
773 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
774 // Ignore known excess pieces.
775 bf = bf[:cn.t.numPieces()]
777 pp := cn.newPeerPieces()
778 cn.peerSentHaveAll = false
779 for i, have := range bf {
781 cn.raisePeerMinPieces(pieceIndex(i) + 1)
782 if !pp.Contains(bitmap.BitIndex(i)) {
783 cn.t.incPieceAvailability(i)
786 if pp.Contains(bitmap.BitIndex(i)) {
787 cn.t.decPieceAvailability(i)
791 cn._peerPieces.Add(uint32(i))
792 if cn.t.wantPieceIndex(i) {
793 cn.updateRequests("bitfield")
796 cn._peerPieces.Remove(uint32(i))
799 cn.peerPiecesChanged()
803 func (cn *PeerConn) onPeerHasAllPieces() {
806 npp, pc := cn.newPeerPieces(), t.numPieces()
807 for i := 0; i < pc; i += 1 {
808 if !npp.Contains(bitmap.BitIndex(i)) {
809 t.incPieceAvailability(i)
813 cn.peerSentHaveAll = true
814 cn._peerPieces.Clear()
815 if !cn.t._pendingPieces.IsEmpty() {
816 cn.updateRequests("Peer.onPeerHasAllPieces")
818 cn.peerPiecesChanged()
821 func (cn *PeerConn) onPeerSentHaveAll() error {
822 cn.onPeerHasAllPieces()
826 func (cn *PeerConn) peerSentHaveNone() error {
827 cn.t.decPeerPieceAvailability(&cn.Peer)
828 cn._peerPieces.Clear()
829 cn.peerSentHaveAll = false
830 cn.peerPiecesChanged()
834 func (c *PeerConn) requestPendingMetadata() {
838 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
839 // Peer doesn't support this.
842 // Request metadata pieces that we don't have in a random order.
844 for index := 0; index < c.t.metadataPieceCount(); index++ {
845 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
846 pending = append(pending, index)
849 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
850 for _, i := range pending {
851 c.requestMetadataPiece(i)
855 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
856 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
857 if msg.Type == pp.Extended {
858 for name, id := range cn.PeerExtensionIDs {
859 if id != msg.ExtendedID {
862 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
865 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
868 // After handshake, we know what Torrent and Client stats to include for a
870 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
876 // All ConnStats that include this connection. Some objects are not known
877 // until the handshake is complete, after which it's expected to reconcile the
879 func (cn *Peer) allStats(f func(*ConnStats)) {
881 if cn.reconciledHandshakeStats {
882 cn.postHandshakeStats(f)
886 func (cn *PeerConn) wroteBytes(n int64) {
887 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
890 func (cn *Peer) readBytes(n int64) {
891 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
894 // Returns whether the connection could be useful to us. We're seeding and
895 // they want data, we don't have metainfo and they can provide it, etc.
896 func (c *Peer) useful() bool {
898 if c.closed.IsSet() {
902 return c.supportsExtension("ut_metadata")
904 if t.seeding() && c.peerInterested {
907 if c.peerHasWantedPieces() {
913 func (c *Peer) lastHelpful() (ret time.Time) {
914 ret = c.lastUsefulChunkReceived
915 if c.t.seeding() && c.lastChunkSent.After(ret) {
916 ret = c.lastChunkSent
921 func (c *PeerConn) fastEnabled() bool {
922 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
925 func (c *PeerConn) reject(r Request) {
926 if !c.fastEnabled() {
927 panic("fast not enabled")
929 c.write(r.ToMsg(pp.Reject))
930 delete(c.peerRequests, r)
933 func (c *PeerConn) onReadRequest(r Request) error {
934 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
935 if _, ok := c.peerRequests[r]; ok {
936 torrent.Add("duplicate requests received", 1)
940 torrent.Add("requests received while choking", 1)
942 torrent.Add("requests rejected while choking", 1)
947 // TODO: What if they've already requested this?
948 if len(c.peerRequests) >= localClientReqq {
949 torrent.Add("requests received while queue full", 1)
953 // BEP 6 says we may close here if we choose.
956 if !c.t.havePiece(pieceIndex(r.Index)) {
957 // This isn't necessarily them screwing up. We can drop pieces
958 // from our storage, and can't communicate this to peers
959 // except by reconnecting.
960 requestsReceivedForMissingPieces.Add(1)
961 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
963 // Check this after we know we have the piece, so that the piece length will be known.
964 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
965 torrent.Add("bad requests received", 1)
966 return errors.New("bad Request")
968 if c.peerRequests == nil {
969 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
971 value := &peerRequestState{}
972 c.peerRequests[r] = value
973 go c.peerRequestDataReader(r, value)
978 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
979 b, err := readPeerRequestData(r, c)
981 defer c.locker().Unlock()
983 c.peerRequestDataReadFailed(err, r)
986 panic("data must be non-nil to trigger send")
993 // If this is maintained correctly, we might be able to support optional synchronous reading for
994 // chunk sending, the way it used to work.
995 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
996 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
997 if c.t.closed.IsSet() {
1000 i := pieceIndex(r.Index)
1001 if c.t.pieceComplete(i) {
1002 // There used to be more code here that just duplicated the following break. Piece
1003 // completions are currently cached, so I'm not sure how helpful this update is, except to
1004 // pull any completion changes pushed to the storage backend in failed reads that got us
1006 c.t.updatePieceCompletion(i)
1008 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1009 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1010 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1011 // next connect. TODO: Support rejecting here too.
1013 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1018 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1019 b := make([]byte, r.Length)
1020 p := c.t.info.Piece(int(r.Index))
1021 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1028 panic("expected error")
1034 func runSafeExtraneous(f func()) {
1042 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1043 c.logger.WithLevel(level).WithContextText(fmt.Sprintf(
1044 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1045 )).SkipCallers(1).Printf(format, arg...)
1048 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1049 // exit. Returning will end the connection.
1050 func (c *PeerConn) mainReadLoop() (err error) {
1053 torrent.Add("connection.mainReadLoop returned with error", 1)
1055 torrent.Add("connection.mainReadLoop returned with no error", 1)
1061 decoder := pp.Decoder{
1062 R: bufio.NewReaderSize(c.r, 1<<17),
1063 MaxLength: 256 * 1024,
1071 err = decoder.Decode(&msg)
1073 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1076 if t.closed.IsSet() || c.closed.IsSet() {
1082 c.lastMessageReceived = time.Now()
1084 receivedKeepalives.Add(1)
1087 messageTypesReceived.Add(msg.Type.String(), 1)
1088 if msg.Type.FastExtension() && !c.fastEnabled() {
1089 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1090 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1097 if !c.fastEnabled() {
1098 if !c.deleteAllRequests().IsEmpty() {
1099 c.t.iterPeers(func(p *Peer) {
1100 if p.isLowOnRequests() {
1101 p.updateRequests("choked by non-fast PeerConn")
1106 // We don't decrement pending requests here, let's wait for the peer to either
1107 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1108 // us and resume where they left off, we don't want to have piled on to those chunks
1109 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1110 // could let us request a lot of stuff, then choke us and never reject, but they're
1111 // only a single peer, our chunk balancing should smooth over this abuse.
1113 c.peerChoking = true
1114 c.updateExpectingChunks()
1117 // Some clients do this for some reason. Transmission doesn't error on this, so we
1118 // won't for consistency.
1119 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1122 c.peerChoking = false
1124 c.requestState.Requests.Iterate(func(x uint32) bool {
1125 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1130 if preservedCount != 0 {
1131 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1133 c.logger.WithLevel(log.Debug).Printf(
1134 "%v requests were preserved while being choked (fast=%v)",
1137 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1139 if !c.t._pendingPieces.IsEmpty() {
1140 c.updateRequests("unchoked")
1142 c.updateExpectingChunks()
1144 c.peerInterested = true
1146 case pp.NotInterested:
1147 c.peerInterested = false
1148 // We don't clear their requests since it isn't clear in the spec.
1149 // We'll probably choke them for this, which will clear them if
1150 // appropriate, and is clearly specified.
1152 err = c.peerSentHave(pieceIndex(msg.Index))
1154 err = c.peerSentBitfield(msg.Bitfield)
1156 r := newRequestFromMessage(&msg)
1157 err = c.onReadRequest(r)
1159 c.doChunkReadStats(int64(len(msg.Piece)))
1160 err = c.receiveChunk(&msg)
1161 if len(msg.Piece) == int(t.chunkSize) {
1162 t.chunkPool.Put(&msg.Piece)
1165 err = fmt.Errorf("receiving chunk: %w", err)
1168 req := newRequestFromMessage(&msg)
1169 c.onPeerSentCancel(req)
1171 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1175 pingAddr := net.UDPAddr{
1180 pingAddr.Port = int(msg.Port)
1182 cl.eachDhtServer(func(s DhtServer) {
1183 go s.Ping(&pingAddr)
1186 torrent.Add("suggests received", 1)
1187 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1188 c.updateRequests("suggested")
1190 err = c.onPeerSentHaveAll()
1192 err = c.peerSentHaveNone()
1194 req := newRequestFromMessage(&msg)
1195 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1196 log.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1197 err = fmt.Errorf("received invalid reject [request=%v]", req)
1199 case pp.AllowedFast:
1200 torrent.Add("allowed fasts received", 1)
1201 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1202 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1204 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1206 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1214 // Returns true if it was valid to reject the request.
1215 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1216 if !c.deleteRequest(r) && !c.requestState.Cancelled.CheckedRemove(r) {
1219 if c.isLowOnRequests() {
1220 c.updateRequests("Peer.remoteRejectedRequest")
1222 c.decExpectedChunkReceive(r)
1226 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1227 count := c.validReceiveChunks[r]
1229 delete(c.validReceiveChunks, r)
1230 } else if count > 1 {
1231 c.validReceiveChunks[r] = count - 1
1237 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1239 // TODO: Should we still do this?
1241 // These clients use their own extension IDs for outgoing message
1242 // types, which is incorrect.
1243 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1251 case pp.HandshakeExtendedID:
1252 var d pp.ExtendedHandshakeMessage
1253 if err := bencode.Unmarshal(payload, &d); err != nil {
1254 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1255 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1257 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1260 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1262 c.PeerMaxRequests = d.Reqq
1264 c.PeerClientName.Store(d.V)
1265 if c.PeerExtensionIDs == nil {
1266 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1268 c.PeerListenPort = d.Port
1269 c.PeerPrefersEncryption = d.Encryption
1270 for name, id := range d.M {
1271 if _, ok := c.PeerExtensionIDs[name]; !ok {
1272 peersSupportingExtension.Add(
1273 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1274 // entered here which caused problems later when unmarshalling.
1275 strconv.Quote(string(name)),
1278 c.PeerExtensionIDs[name] = id
1280 if d.MetadataSize != 0 {
1281 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1282 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1285 c.requestPendingMetadata()
1286 if !t.cl.config.DisablePEX {
1287 t.pex.Add(c) // we learnt enough now
1291 case metadataExtendedId:
1292 err := cl.gotMetadataExtensionMsg(payload, t, c)
1294 return fmt.Errorf("handling metadata extension message: %w", err)
1298 if !c.pex.IsEnabled() {
1299 return nil // or hang-up maybe?
1301 return c.pex.Recv(payload)
1303 return fmt.Errorf("unexpected extended message ID: %v", id)
1307 // Set both the Reader and Writer for the connection from a single ReadWriter.
1308 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1313 // Returns the Reader and Writer as a combined ReadWriter.
1314 func (cn *PeerConn) rw() io.ReadWriter {
1321 func (c *Peer) doChunkReadStats(size int64) {
1322 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1325 // Handle a received chunk from a peer.
1326 func (c *Peer) receiveChunk(msg *pp.Message) error {
1327 chunksReceived.Add("total", 1)
1329 ppReq := newRequestFromMessage(msg)
1330 req := c.t.requestIndexFromRequest(ppReq)
1333 chunksReceived.Add("while choked", 1)
1336 if c.validReceiveChunks[req] <= 0 {
1337 chunksReceived.Add("unexpected", 1)
1338 return errors.New("received unexpected chunk")
1340 c.decExpectedChunkReceive(req)
1342 if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1343 chunksReceived.Add("due to allowed fast", 1)
1346 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1347 // have actually already received the piece, while we have the Client unlocked to write the data
1351 if c.requestState.Requests.Contains(req) {
1352 for _, f := range c.callbacks.ReceivedRequested {
1353 f(PeerMessageEvent{c, msg})
1356 // Request has been satisfied.
1357 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1360 c._chunksReceivedWhileExpecting++
1362 if c.isLowOnRequests() {
1363 c.updateRequests("Peer.receiveChunk deleted request")
1366 chunksReceived.Add("unintended", 1)
1373 // Do we actually want this chunk?
1374 if t.haveChunk(ppReq) {
1375 // panic(fmt.Sprintf("%+v", ppReq))
1376 chunksReceived.Add("redundant", 1)
1377 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1381 piece := &t.pieces[ppReq.Index]
1383 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1384 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1386 c.piecesReceivedSinceLastRequestUpdate++
1387 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1389 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1390 f(ReceivedUsefulDataEvent{c, msg})
1392 c.lastUsefulChunkReceived = time.Now()
1394 // Need to record that it hasn't been written yet, before we attempt to do
1395 // anything with it.
1396 piece.incrementPendingWrites()
1397 // Record that we have the chunk, so we aren't trying to download it while
1398 // waiting for it to be written to storage.
1399 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1401 // Cancel pending requests for this chunk from *other* peers.
1402 if p := t.pendingRequests[req]; p != nil {
1404 panic("should not be pending request from conn that just received it")
1409 err := func() error {
1412 concurrentChunkWrites.Add(1)
1413 defer concurrentChunkWrites.Add(-1)
1414 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1415 // number of connections. We write inline with receiving the chunk (with this lock dance),
1416 // because we want to handle errors synchronously and I haven't thought of a nice way to
1417 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1419 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1422 piece.decrementPendingWrites()
1425 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1427 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1428 // request update runs while we're writing the chunk that just failed. Then we never do a
1429 // fresh update after pending the failed request.
1430 c.updateRequests("Peer.receiveChunk error writing chunk")
1431 t.onWriteChunkErr(err)
1435 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1437 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1438 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1439 t.queuePieceCheck(pieceIndex(ppReq.Index))
1440 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1441 // chunk status (such as the haveChunk call above) to have to check all the various other
1442 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1443 // that chunk pieces are pended at an appropriate time later however.
1446 cl.event.Broadcast()
1447 // We do this because we've written a chunk, and may change PieceState.Partial.
1448 t.publishPieceChange(pieceIndex(ppReq.Index))
1453 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1454 if c.peerTouchedPieces == nil {
1455 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1457 c.peerTouchedPieces[piece] = struct{}{}
1458 ds := &c.t.pieces[piece].dirtiers
1460 *ds = make(map[*Peer]struct{})
1462 (*ds)[c] = struct{}{}
1465 func (c *PeerConn) uploadAllowed() bool {
1466 if c.t.cl.config.NoUpload {
1469 if c.t.dataUploadDisallowed {
1475 if !c.peerHasWantedPieces() {
1478 // Don't upload more than 100 KiB more than we download.
1479 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1485 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1486 if c.uploadTimer == nil {
1487 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1489 c.uploadTimer.Reset(delay)
1493 // Also handles choking and unchoking of the remote peer.
1494 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1495 // Breaking or completing this loop means we don't want to upload to the
1496 // peer anymore, and we choke them.
1498 for c.uploadAllowed() {
1499 // We want to upload to the peer.
1500 if !c.unchoke(msg) {
1503 for r, state := range c.peerRequests {
1504 if state.data == nil {
1507 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1509 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1511 delay := res.Delay()
1514 c.setRetryUploadTimer(delay)
1515 // Hard to say what to return here.
1518 more := c.sendChunk(r, msg, state)
1519 delete(c.peerRequests, r)
1530 func (cn *PeerConn) drop() {
1531 cn.t.dropConnection(cn)
1534 func (cn *Peer) netGoodPiecesDirtied() int64 {
1535 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1538 func (c *Peer) peerHasWantedPieces() bool {
1539 if all, _ := c.peerHasAllPieces(); all {
1540 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1542 if !c.t.haveInfo() {
1543 return !c.peerPieces().IsEmpty()
1545 return c.peerPieces().Intersects(&c.t._pendingPieces)
1548 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1550 func (c *Peer) deleteRequest(r RequestIndex) bool {
1551 if !c.requestState.Requests.CheckedRemove(r) {
1554 for _, f := range c.callbacks.DeletedRequest {
1555 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1557 c.updateExpectingChunks()
1558 if c.t.requestingPeer(r) != c {
1559 panic("only one peer should have a given request at a time")
1561 delete(c.t.pendingRequests, r)
1562 delete(c.t.lastRequested, r)
1563 // c.t.iterPeers(func(p *Peer) {
1564 // if p.isLowOnRequests() {
1565 // p.updateRequests("Peer.deleteRequest")
1571 func (c *Peer) deleteAllRequests() (deleted *roaring.Bitmap) {
1572 deleted = c.requestState.Requests.Clone()
1573 deleted.Iterate(func(x uint32) bool {
1574 if !c.deleteRequest(x) {
1575 panic("request should exist")
1579 c.assertNoRequests()
1583 func (c *Peer) assertNoRequests() {
1584 if !c.requestState.Requests.IsEmpty() {
1585 panic(c.requestState.Requests.GetCardinality())
1589 func (c *Peer) cancelAllRequests() (cancelled *roaring.Bitmap) {
1590 cancelled = c.requestState.Requests.Clone()
1591 cancelled.Iterate(func(x uint32) bool {
1595 c.assertNoRequests()
1599 // This is called when something has changed that should wake the writer, such as putting stuff into
1600 // the writeBuffer, or changing some state that the writer can act on.
1601 func (c *PeerConn) tickleWriter() {
1602 c.messageWriter.writeCond.Broadcast()
1605 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1606 c.lastChunkSent = time.Now()
1607 return msg(pp.Message{
1615 func (c *PeerConn) setTorrent(t *Torrent) {
1617 panic("connection already associated with a torrent")
1620 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1621 t.reconcileHandshakeStats(c)
1624 func (c *Peer) peerPriority() (peerPriority, error) {
1625 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1628 func (c *Peer) remoteIp() net.IP {
1629 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1630 return net.ParseIP(host)
1633 func (c *Peer) remoteIpPort() IpPort {
1634 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1635 return IpPort{ipa.IP, uint16(ipa.Port)}
1638 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1639 f := pp.PexPeerFlags(0)
1640 if c.PeerPrefersEncryption {
1641 f |= pp.PexPrefersEncryption
1644 f |= pp.PexOutgoingConn
1647 f |= pp.PexSupportsUtp
1652 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1653 // advertised listen port.
1654 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1655 if !c.outgoing && c.PeerListenPort != 0 {
1656 switch addr := c.RemoteAddr.(type) {
1659 dialAddr.Port = c.PeerListenPort
1663 dialAddr.Port = c.PeerListenPort
1670 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1671 f := c.pexPeerFlags()
1672 addr := c.dialAddr()
1673 return pexEvent{t, addr, f, nil}
1676 func (c *PeerConn) String() string {
1677 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1680 func (c *Peer) trust() connectionTrust {
1681 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1684 type connectionTrust struct {
1686 NetGoodPiecesDirted int64
1689 func (l connectionTrust) Less(r connectionTrust) bool {
1690 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1693 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1694 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1695 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1697 defer cn.locker().RUnlock()
1698 return cn.newPeerPieces()
1701 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1702 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1703 // TODO: Can we use copy on write?
1704 ret := cn.peerPieces().Clone()
1705 if all, _ := cn.peerHasAllPieces(); all {
1706 if cn.t.haveInfo() {
1707 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1709 ret.AddRange(0, bitmap.ToEnd)
1715 func (cn *Peer) stats() *ConnStats {
1719 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1720 pc, ok := p.peerImpl.(*PeerConn)
1724 func (pc *PeerConn) isLowOnRequests() bool {
1725 return pc.requestState.Requests.IsEmpty() && pc.requestState.Cancelled.IsEmpty()
1728 func (p *Peer) uncancelledRequests() uint64 {
1729 return p.requestState.Requests.GetCardinality()
1732 func (pc *PeerConn) remoteIsTransmission() bool {
1733 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'