8 "golang.org/x/time/rate"
17 "github.com/RoaringBitmap/roaring"
18 "github.com/anacrolix/chansync"
19 . "github.com/anacrolix/generics"
20 "github.com/anacrolix/log"
21 "github.com/anacrolix/missinggo/iter"
22 "github.com/anacrolix/missinggo/v2/bitmap"
23 "github.com/anacrolix/multiless"
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"
29 "github.com/anacrolix/torrent/typed-roaring"
32 type PeerSource string
35 PeerSourceTracker = "Tr"
36 PeerSourceIncoming = "I"
37 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
38 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
40 // The peer was given directly, such as through a magnet link.
41 PeerSourceDirect = "M"
44 type peerRequestState struct {
48 type PeerRemoteAddr interface {
53 // Since we have to store all the requests in memory, we can't reasonably exceed what could be
54 // indexed with the memory space available.
59 // First to ensure 64-bit alignment for atomics. See #262.
69 RemoteAddr PeerRemoteAddr
70 // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
72 localPublicAddr peerLocalPublicAddr
73 bannableAddr Option[bannableAddr]
74 // True if the connection is operating over MSE obfuscation.
76 cryptoMethod mse.CryptoMethod
79 closed chansync.SetOnce
80 // Set true after we've added our ConnStats generated during handshake to
81 // other ConnStat instances as determined when the *Torrent became known.
82 reconciledHandshakeStats bool
84 lastMessageReceived time.Time
85 completedHandshake time.Time
86 lastUsefulChunkReceived time.Time
87 lastChunkSent time.Time
89 // Stuff controlled by the local peer.
90 needRequestUpdate string
91 requestState request_strategy.PeerRequestState
92 updateRequestsTimer *time.Timer
93 lastRequestUpdate time.Time
94 peakRequests maxRequests
95 lastBecameInterested time.Time
96 priorInterest time.Duration
98 lastStartedExpectingToReceiveChunks time.Time
99 cumulativeExpectedToReceiveChunks time.Duration
100 _chunksReceivedWhileExpecting int64
103 piecesReceivedSinceLastRequestUpdate maxRequests
104 maxPiecesReceivedBetweenRequestUpdates maxRequests
105 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
106 // and implementation differences, we may receive chunks that are no longer in the set of
107 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
108 validReceiveChunks map[RequestIndex]int
109 // Indexed by metadata piece, set to true if posted and pending a
111 metadataRequests []bool
112 sentHaves bitmap.Bitmap
114 // Stuff controlled by the remote peer.
117 peerRequests map[Request]*peerRequestState
118 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
120 // The highest possible number of pieces the torrent could have based on
121 // communication with the peer. Generally only useful until we have the
123 peerMinPieces pieceIndex
124 // Pieces we've accepted chunks for from the peer.
125 peerTouchedPieces map[pieceIndex]struct{}
126 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
128 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
129 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
130 PeerClientName atomic.Value
135 type peerRequests = orderedBitmap[RequestIndex]
137 func (p *Peer) initRequestState() {
138 p.requestState.Requests = &peerRequests{}
141 // Maintains the state of a BitTorrent-protocol based connection with a peer.
142 type PeerConn struct {
145 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
146 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
151 PeerExtensionBytes pp.PeerExtensionBits
153 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
154 // while holding any mutexes.
156 // The Reader and Writer for this Conn, with hooks installed for stats,
157 // limiting, deadlines etc.
161 messageWriter peerConnMsgWriter
163 uploadTimer *time.Timer
166 // The pieces the peer has claimed to have.
167 _peerPieces roaring.Bitmap
168 // The peer has everything. This can occur due to a special message, when
169 // we may not even know the number of pieces in the torrent yet.
173 func (cn *PeerConn) connStatusString() string {
174 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
177 func (cn *Peer) updateExpectingChunks() {
178 if cn.expectingChunks() {
179 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
180 cn.lastStartedExpectingToReceiveChunks = time.Now()
183 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
184 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
185 cn.lastStartedExpectingToReceiveChunks = time.Time{}
190 func (cn *Peer) expectingChunks() bool {
191 if cn.requestState.Requests.IsEmpty() {
194 if !cn.requestState.Interested {
200 haveAllowedFastRequests := false
201 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
202 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
203 cn.requestState.Requests,
204 cn.t.pieceRequestIndexOffset(i),
205 cn.t.pieceRequestIndexOffset(i+1),
207 return !haveAllowedFastRequests
209 return haveAllowedFastRequests
212 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
213 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
216 // Returns true if the connection is over IPv6.
217 func (cn *PeerConn) ipv6() bool {
222 return len(ip) == net.IPv6len
225 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
226 // specification for this.
227 func (cn *PeerConn) isPreferredDirection() bool {
228 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
231 // Returns whether the left connection should be preferred over the right one,
232 // considering only their networking properties. If ok is false, we can't
234 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
235 var ml multiless.Computation
236 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
237 ml = ml.Bool(l.utp(), r.utp())
238 ml = ml.Bool(r.ipv6(), l.ipv6())
242 func (cn *Peer) cumInterest() time.Duration {
243 ret := cn.priorInterest
244 if cn.requestState.Interested {
245 ret += time.Since(cn.lastBecameInterested)
250 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
251 if cn.peerSentHaveAll {
254 if !cn.t.haveInfo() {
257 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
260 func (cn *Peer) locker() *lockWithDeferreds {
261 return cn.t.cl.locker()
264 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
265 _, ok := cn.PeerExtensionIDs[ext]
269 // The best guess at number of pieces in the torrent for this peer.
270 func (cn *Peer) bestPeerNumPieces() pieceIndex {
272 return cn.t.numPieces()
274 return cn.peerMinPieces
277 func (cn *Peer) completedString() string {
278 have := pieceIndex(cn.peerPieces().GetCardinality())
279 if all, _ := cn.peerHasAllPieces(); all {
280 have = cn.bestPeerNumPieces()
282 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
285 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
286 cn.setNumPieces(info.NumPieces())
289 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
290 // receiving badly sized BITFIELD, or invalid HAVE messages.
291 func (cn *PeerConn) setNumPieces(num pieceIndex) {
292 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
293 cn.peerPiecesChanged()
296 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
297 return &cn._peerPieces
300 func eventAgeString(t time.Time) string {
304 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
307 func (cn *PeerConn) connectionFlags() (ret string) {
309 ret += string([]byte{b})
311 if cn.cryptoMethod == mse.CryptoMethodRC4 {
313 } else if cn.headerEncrypted {
316 ret += string(cn.Discovery)
323 func (cn *PeerConn) utp() bool {
324 return parseNetworkString(cn.Network).Udp
327 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
328 func (cn *Peer) statusFlags() (ret string) {
330 ret += string([]byte{b})
332 if cn.requestState.Interested {
339 ret += cn.connectionFlags()
341 if cn.peerInterested {
350 func (cn *Peer) downloadRate() float64 {
351 num := cn._stats.BytesReadUsefulData.Int64()
355 return float64(num) / cn.totalExpectingTime().Seconds()
358 func (cn *Peer) DownloadRate() float64 {
360 defer cn.locker().Unlock()
362 return cn.downloadRate()
365 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
366 var last Option[pieceIndex]
368 next := func(item Option[pieceIndex]) {
379 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
380 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
383 next(None[pieceIndex]())
386 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
387 // \t isn't preserved in <pre> blocks?
388 if cn.closed.IsSet() {
389 fmt.Fprint(w, "CLOSED: ")
391 fmt.Fprintln(w, cn.connStatusString())
392 prio, err := cn.peerPriority()
393 prioStr := fmt.Sprintf("%08x", prio)
395 prioStr += ": " + err.Error()
397 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
398 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
399 eventAgeString(cn.lastMessageReceived),
400 eventAgeString(cn.completedHandshake),
401 eventAgeString(cn.lastHelpful()),
403 cn.totalExpectingTime(),
406 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
407 cn.completedString(),
408 len(cn.peerTouchedPieces),
409 &cn._stats.ChunksReadUseful,
410 &cn._stats.ChunksRead,
411 &cn._stats.ChunksWritten,
412 cn.requestState.Requests.GetCardinality(),
413 cn.requestState.Cancelled.GetCardinality(),
414 cn.nominalMaxRequests(),
416 len(cn.peerRequests),
419 cn.downloadRate()/(1<<10),
421 fmt.Fprintf(w, " requested pieces:")
422 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
423 fmt.Fprintf(w, " %v(%v)", piece, count)
428 func (p *Peer) close() {
432 if p.updateRequestsTimer != nil {
433 p.updateRequestsTimer.Stop()
437 p.t.decPeerPieceAvailability(p)
439 for _, f := range p.callbacks.PeerClosed {
444 func (cn *PeerConn) onClose() {
445 if cn.pex.IsEnabled() {
452 if cb := cn.callbacks.PeerConnClosed; cb != nil {
457 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
458 // they do (known=true).
459 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
460 if all, known := cn.peerHasAllPieces(); all && known {
463 return cn.peerPieces().ContainsInt(piece)
466 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
467 // https://github.com/pion/datachannel/issues/59 is fixed.
469 writeBufferHighWaterLen = 1 << 15
470 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
473 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
474 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
475 func (cn *PeerConn) write(msg pp.Message) bool {
476 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
477 // We don't need to track bytes here because the connection's Writer has that behaviour injected
478 // (although there's some delay between us buffering the message, and the connection writer
479 // flushing it out.).
480 notFull := cn.messageWriter.write(msg)
481 // Last I checked only Piece messages affect stats, and we don't write those.
487 func (cn *PeerConn) requestMetadataPiece(index int) {
488 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
489 if eID == pp.ExtensionDeleteNumber {
492 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
495 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
496 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
497 for index >= len(cn.metadataRequests) {
498 cn.metadataRequests = append(cn.metadataRequests, false)
500 cn.metadataRequests[index] = true
503 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
504 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
508 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
509 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
510 // This is the maximum request count that could fit in the write buffer if it's at or below the
511 // low water mark when we run maybeUpdateActualRequestState.
512 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
515 // The actual value to use as the maximum outbound requests.
516 func (cn *Peer) nominalMaxRequests() maxRequests {
517 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
520 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
521 ret = cn.cumulativeExpectedToReceiveChunks
522 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
523 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
528 func (cn *PeerConn) onPeerSentCancel(r Request) {
529 if _, ok := cn.peerRequests[r]; !ok {
530 torrent.Add("unexpected cancels received", 1)
533 if cn.fastEnabled() {
536 delete(cn.peerRequests, r)
540 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
545 more = msg(pp.Message{
548 if !cn.fastEnabled() {
549 cn.peerRequests = nil
554 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
559 return msg(pp.Message{
564 func (cn *Peer) setInterested(interested bool) bool {
565 if cn.requestState.Interested == interested {
568 cn.requestState.Interested = interested
570 cn.lastBecameInterested = time.Now()
571 } else if !cn.lastBecameInterested.IsZero() {
572 cn.priorInterest += time.Since(cn.lastBecameInterested)
574 cn.updateExpectingChunks()
575 // log.Printf("%p: setting interest: %v", cn, interested)
576 return cn.writeInterested(interested)
579 func (pc *PeerConn) writeInterested(interested bool) bool {
580 return pc.write(pp.Message{
581 Type: func() pp.MessageType {
585 return pp.NotInterested
591 // The function takes a message to be sent, and returns true if more messages
593 type messageWriter func(pp.Message) bool
595 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
596 // when we want to go fast.
597 func (cn *Peer) shouldRequest(r RequestIndex) error {
598 pi := cn.t.pieceIndexOfRequestIndex(r)
599 if cn.requestState.Cancelled.Contains(r) {
600 return errors.New("request is cancelled and waiting acknowledgement")
602 if !cn.peerHasPiece(pi) {
603 return errors.New("requesting piece peer doesn't have")
605 if !cn.t.peerIsActive(cn) {
606 panic("requesting but not in active conns")
608 if cn.closed.IsSet() {
609 panic("requesting when connection is closed")
611 if cn.t.hashingPiece(pi) {
612 panic("piece is being hashed")
614 if cn.t.pieceQueuedForHash(pi) {
615 panic("piece is queued for hash")
617 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
618 // This could occur if we made a request with the fast extension, and then got choked and
619 // haven't had the request rejected yet.
620 if !cn.requestState.Requests.Contains(r) {
621 panic("peer choking and piece not allowed fast")
627 func (cn *Peer) mustRequest(r RequestIndex) bool {
628 more, err := cn.request(r)
635 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
636 if err := cn.shouldRequest(r); err != nil {
639 if cn.requestState.Requests.Contains(r) {
642 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
643 return true, errors.New("too many outstanding requests")
645 cn.requestState.Requests.Add(r)
646 if cn.validReceiveChunks == nil {
647 cn.validReceiveChunks = make(map[RequestIndex]int)
649 cn.validReceiveChunks[r]++
650 cn.t.requestState[r] = requestState{
654 cn.updateExpectingChunks()
655 ppReq := cn.t.requestIndexToRequest(r)
656 for _, f := range cn.callbacks.SentRequest {
657 f(PeerRequestEvent{cn, ppReq})
659 return cn.peerImpl._request(ppReq), nil
662 func (me *PeerConn) _request(r Request) bool {
663 return me.write(pp.Message{
671 func (me *Peer) cancel(r RequestIndex) {
672 if !me.deleteRequest(r) {
673 panic("request not existing should have been guarded")
676 if !me.requestState.Cancelled.CheckedAdd(r) {
677 panic("request already cancelled")
681 if me.isLowOnRequests() {
682 me.updateRequests("Peer.cancel")
686 func (me *PeerConn) _cancel(r RequestIndex) bool {
687 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
688 // Transmission does not send rejects for received cancels. See
689 // https://github.com/transmission/transmission/pull/2275.
690 return me.fastEnabled() && !me.remoteIsTransmission()
693 func (cn *PeerConn) fillWriteBuffer() {
694 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
695 // Fully committing to our max requests requires sufficient space (see
696 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
697 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
698 // request reason will not be cleared, so we'll come right back here when there's space. We
699 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
700 // knowledge of write buffers.
702 cn.maybeUpdateActualRequestState()
703 if cn.pex.IsEnabled() {
704 if flow := cn.pex.Share(cn.write); !flow {
711 func (cn *PeerConn) have(piece pieceIndex) {
712 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
717 Index: pp.Integer(piece),
719 cn.sentHaves.Add(bitmap.BitIndex(piece))
722 func (cn *PeerConn) postBitfield() {
723 if cn.sentHaves.Len() != 0 {
724 panic("bitfield must be first have-related message sent")
726 if !cn.t.haveAnyPieces() {
731 Bitfield: cn.t.bitfield(),
733 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
736 // Sets a reason to update requests, and if there wasn't already one, handle it.
737 func (cn *Peer) updateRequests(reason string) {
738 if cn.needRequestUpdate != "" {
741 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
744 cn.needRequestUpdate = reason
745 cn.handleUpdateRequests()
748 func (cn *PeerConn) handleUpdateRequests() {
749 // The writer determines the request state as needed when it can write.
753 // Emits the indices in the Bitmaps bms in order, never repeating any index.
754 // skip is mutated during execution, and its initial values will never be
756 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
757 return func(cb iter.Callback) {
758 for _, bm := range bms {
760 func(_i interface{}) bool {
762 if skip.Contains(bitmap.BitIndex(i)) {
765 skip.Add(bitmap.BitIndex(i))
776 func (cn *Peer) peerPiecesChanged() {
777 cn.t.maybeDropMutuallyCompletePeer(cn)
780 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
781 if newMin > cn.peerMinPieces {
782 cn.peerMinPieces = newMin
786 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
787 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
788 return errors.New("invalid piece")
790 if cn.peerHasPiece(piece) {
793 cn.raisePeerMinPieces(piece + 1)
794 if !cn.peerHasPiece(piece) {
795 cn.t.incPieceAvailability(piece)
797 cn._peerPieces.Add(uint32(piece))
798 if cn.t.wantPieceIndex(piece) {
799 cn.updateRequests("have")
801 cn.peerPiecesChanged()
805 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
807 panic("expected bitfield length divisible by 8")
809 // We know that the last byte means that at most the last 7 bits are wasted.
810 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
811 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
812 // Ignore known excess pieces.
813 bf = bf[:cn.t.numPieces()]
815 bm := boolSliceToBitmap(bf)
816 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
817 cn.onPeerHasAllPieces()
821 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
823 shouldUpdateRequests := false
824 if cn.peerSentHaveAll {
825 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
828 cn.peerSentHaveAll = false
829 if !cn._peerPieces.IsEmpty() {
830 panic("if peer has all, we expect no individual peer pieces to be set")
833 bm.Xor(&cn._peerPieces)
835 cn.peerSentHaveAll = false
836 // bm is now 'on' for pieces that are changing
837 bm.Iterate(func(x uint32) bool {
839 if cn._peerPieces.Contains(x) {
840 // Then we must be losing this piece
841 cn.t.decPieceAvailability(pi)
843 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
844 shouldUpdateRequests = true
846 // We must be gaining this piece
847 cn.t.incPieceAvailability(pieceIndex(x))
851 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
853 cn._peerPieces.Xor(&bm)
854 if shouldUpdateRequests {
855 cn.updateRequests("bitfield")
857 // We didn't guard this before, I see no reason to do it now.
858 cn.peerPiecesChanged()
862 func (cn *PeerConn) onPeerHasAllPieces() {
865 cn._peerPieces.Iterate(func(x uint32) bool {
866 t.decPieceAvailability(pieceIndex(x))
870 t.addConnWithAllPieces(&cn.Peer)
871 cn.peerSentHaveAll = true
872 cn._peerPieces.Clear()
873 if !cn.t._pendingPieces.IsEmpty() {
874 cn.updateRequests("Peer.onPeerHasAllPieces")
876 cn.peerPiecesChanged()
879 func (cn *PeerConn) onPeerSentHaveAll() error {
880 cn.onPeerHasAllPieces()
884 func (cn *PeerConn) peerSentHaveNone() error {
885 if cn.peerSentHaveAll {
886 cn.t.decPeerPieceAvailability(&cn.Peer)
888 cn._peerPieces.Clear()
889 cn.peerSentHaveAll = false
890 cn.peerPiecesChanged()
894 func (c *PeerConn) requestPendingMetadata() {
898 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
899 // Peer doesn't support this.
902 // Request metadata pieces that we don't have in a random order.
904 for index := 0; index < c.t.metadataPieceCount(); index++ {
905 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
906 pending = append(pending, index)
909 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
910 for _, i := range pending {
911 c.requestMetadataPiece(i)
915 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
916 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
917 if msg.Type == pp.Extended {
918 for name, id := range cn.PeerExtensionIDs {
919 if id != msg.ExtendedID {
922 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
925 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
928 // After handshake, we know what Torrent and Client stats to include for a
930 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
936 // All ConnStats that include this connection. Some objects are not known
937 // until the handshake is complete, after which it's expected to reconcile the
939 func (cn *Peer) allStats(f func(*ConnStats)) {
941 if cn.reconciledHandshakeStats {
942 cn.postHandshakeStats(f)
946 func (cn *PeerConn) wroteBytes(n int64) {
947 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
950 func (cn *Peer) readBytes(n int64) {
951 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
954 // Returns whether the connection could be useful to us. We're seeding and
955 // they want data, we don't have metainfo and they can provide it, etc.
956 func (c *Peer) useful() bool {
958 if c.closed.IsSet() {
962 return c.supportsExtension("ut_metadata")
964 if t.seeding() && c.peerInterested {
967 if c.peerHasWantedPieces() {
973 func (c *Peer) lastHelpful() (ret time.Time) {
974 ret = c.lastUsefulChunkReceived
975 if c.t.seeding() && c.lastChunkSent.After(ret) {
976 ret = c.lastChunkSent
981 func (c *PeerConn) fastEnabled() bool {
982 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
985 func (c *PeerConn) reject(r Request) {
986 if !c.fastEnabled() {
987 panic("fast not enabled")
989 c.write(r.ToMsg(pp.Reject))
990 delete(c.peerRequests, r)
993 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
994 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
995 if uploadRateLimiter.Limit() == rate.Inf {
998 return Some(uploadRateLimiter.Burst())
1001 // startFetch is for testing purposes currently.
1002 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
1003 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1004 if _, ok := c.peerRequests[r]; ok {
1005 torrent.Add("duplicate requests received", 1)
1006 if c.fastEnabled() {
1007 return errors.New("received duplicate request with fast enabled")
1012 torrent.Add("requests received while choking", 1)
1013 if c.fastEnabled() {
1014 torrent.Add("requests rejected while choking", 1)
1019 // TODO: What if they've already requested this?
1020 if len(c.peerRequests) >= localClientReqq {
1021 torrent.Add("requests received while queue full", 1)
1022 if c.fastEnabled() {
1025 // BEP 6 says we may close here if we choose.
1028 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
1029 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
1030 c.logger.Levelf(log.Warning, err.Error())
1031 if c.fastEnabled() {
1038 if !c.t.havePiece(pieceIndex(r.Index)) {
1039 // TODO: Tell the peer we don't have the piece, and reject this request.
1040 requestsReceivedForMissingPieces.Add(1)
1041 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1043 // Check this after we know we have the piece, so that the piece length will be known.
1044 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1045 torrent.Add("bad requests received", 1)
1046 return errors.New("bad Request")
1048 if c.peerRequests == nil {
1049 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1051 value := &peerRequestState{}
1052 c.peerRequests[r] = value
1054 // TODO: Limit peer request data read concurrency.
1055 go c.peerRequestDataReader(r, value)
1060 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1061 b, err := readPeerRequestData(r, c)
1063 defer c.locker().Unlock()
1065 c.peerRequestDataReadFailed(err, r)
1068 panic("data must be non-nil to trigger send")
1070 torrent.Add("peer request data read successes", 1)
1072 // This might be required for the error case too (#752 and #753).
1077 // If this is maintained correctly, we might be able to support optional synchronous reading for
1078 // chunk sending, the way it used to work.
1079 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1080 torrent.Add("peer request data read failures", 1)
1081 logLevel := log.Warning
1082 if c.t.hasStorageCap() {
1083 // It's expected that pieces might drop. See
1084 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1085 logLevel = log.Debug
1087 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1088 if c.t.closed.IsSet() {
1091 i := pieceIndex(r.Index)
1092 if c.t.pieceComplete(i) {
1093 // There used to be more code here that just duplicated the following break. Piece
1094 // completions are currently cached, so I'm not sure how helpful this update is, except to
1095 // pull any completion changes pushed to the storage backend in failed reads that got us
1097 c.t.updatePieceCompletion(i)
1099 // We've probably dropped a piece from storage, but there's no way to communicate this to the
1100 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1101 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1102 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1104 if c.fastEnabled() {
1108 // If fast isn't enabled, I think we would have wiped all peer requests when we last
1109 // choked, and requests while we're choking would be ignored. It could be possible that
1110 // a peer request data read completed concurrently to it being deleted elsewhere.
1111 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1113 // Choking a non-fast peer should cause them to flush all their requests.
1118 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1119 b := make([]byte, r.Length)
1120 p := c.t.info.Piece(int(r.Index))
1121 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1128 panic("expected error")
1134 func runSafeExtraneous(f func()) {
1142 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1143 c.logger.WithContextText(fmt.Sprintf(
1144 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1145 )).SkipCallers(1).Levelf(level, format, arg...)
1148 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1149 // exit. Returning will end the connection.
1150 func (c *PeerConn) mainReadLoop() (err error) {
1153 torrent.Add("connection.mainReadLoop returned with error", 1)
1155 torrent.Add("connection.mainReadLoop returned with no error", 1)
1161 decoder := pp.Decoder{
1162 R: bufio.NewReaderSize(c.r, 1<<17),
1163 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1171 err = decoder.Decode(&msg)
1173 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1176 if t.closed.IsSet() || c.closed.IsSet() {
1182 c.lastMessageReceived = time.Now()
1184 receivedKeepalives.Add(1)
1187 messageTypesReceived.Add(msg.Type.String(), 1)
1188 if msg.Type.FastExtension() && !c.fastEnabled() {
1189 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1190 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1197 if !c.fastEnabled() {
1198 c.deleteAllRequests("choked by non-fast PeerConn")
1200 // We don't decrement pending requests here, let's wait for the peer to either
1201 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1202 // us and resume where they left off, we don't want to have piled on to those chunks
1203 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1204 // could let us request a lot of stuff, then choke us and never reject, but they're
1205 // only a single peer, our chunk balancing should smooth over this abuse.
1207 c.peerChoking = true
1208 c.updateExpectingChunks()
1211 // Some clients do this for some reason. Transmission doesn't error on this, so we
1212 // won't for consistency.
1213 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1216 c.peerChoking = false
1218 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1219 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1224 if preservedCount != 0 {
1225 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1227 c.logger.Levelf(log.Debug,
1228 "%v requests were preserved while being choked (fast=%v)",
1232 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1234 if !c.t._pendingPieces.IsEmpty() {
1235 c.updateRequests("unchoked")
1237 c.updateExpectingChunks()
1239 c.peerInterested = true
1241 case pp.NotInterested:
1242 c.peerInterested = false
1243 // We don't clear their requests since it isn't clear in the spec.
1244 // We'll probably choke them for this, which will clear them if
1245 // appropriate, and is clearly specified.
1247 err = c.peerSentHave(pieceIndex(msg.Index))
1249 err = c.peerSentBitfield(msg.Bitfield)
1251 r := newRequestFromMessage(&msg)
1252 err = c.onReadRequest(r, true)
1254 c.doChunkReadStats(int64(len(msg.Piece)))
1255 err = c.receiveChunk(&msg)
1256 if len(msg.Piece) == int(t.chunkSize) {
1257 t.chunkPool.Put(&msg.Piece)
1260 err = fmt.Errorf("receiving chunk: %w", err)
1263 req := newRequestFromMessage(&msg)
1264 c.onPeerSentCancel(req)
1266 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1270 pingAddr := net.UDPAddr{
1275 pingAddr.Port = int(msg.Port)
1277 cl.eachDhtServer(func(s DhtServer) {
1278 go s.Ping(&pingAddr)
1281 torrent.Add("suggests received", 1)
1282 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1283 c.updateRequests("suggested")
1285 err = c.onPeerSentHaveAll()
1287 err = c.peerSentHaveNone()
1289 req := newRequestFromMessage(&msg)
1290 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1291 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1292 err = fmt.Errorf("received invalid reject [request=%v]", req)
1294 case pp.AllowedFast:
1295 torrent.Add("allowed fasts received", 1)
1296 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1297 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1299 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1301 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1309 // Returns true if it was valid to reject the request.
1310 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1311 if c.deleteRequest(r) {
1313 } else if !c.requestState.Cancelled.CheckedRemove(r) {
1316 if c.isLowOnRequests() {
1317 c.updateRequests("Peer.remoteRejectedRequest")
1319 c.decExpectedChunkReceive(r)
1323 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1324 count := c.validReceiveChunks[r]
1326 delete(c.validReceiveChunks, r)
1327 } else if count > 1 {
1328 c.validReceiveChunks[r] = count - 1
1334 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1336 // TODO: Should we still do this?
1338 // These clients use their own extension IDs for outgoing message
1339 // types, which is incorrect.
1340 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1348 case pp.HandshakeExtendedID:
1349 var d pp.ExtendedHandshakeMessage
1350 if err := bencode.Unmarshal(payload, &d); err != nil {
1351 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1352 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1354 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1357 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1359 c.PeerMaxRequests = d.Reqq
1361 c.PeerClientName.Store(d.V)
1362 if c.PeerExtensionIDs == nil {
1363 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1365 c.PeerListenPort = d.Port
1366 c.PeerPrefersEncryption = d.Encryption
1367 for name, id := range d.M {
1368 if _, ok := c.PeerExtensionIDs[name]; !ok {
1369 peersSupportingExtension.Add(
1370 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1371 // entered here which caused problems later when unmarshalling.
1372 strconv.Quote(string(name)),
1375 c.PeerExtensionIDs[name] = id
1377 if d.MetadataSize != 0 {
1378 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1379 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1382 c.requestPendingMetadata()
1383 if !t.cl.config.DisablePEX {
1384 t.pex.Add(c) // we learnt enough now
1388 case metadataExtendedId:
1389 err := cl.gotMetadataExtensionMsg(payload, t, c)
1391 return fmt.Errorf("handling metadata extension message: %w", err)
1395 if !c.pex.IsEnabled() {
1396 return nil // or hang-up maybe?
1398 return c.pex.Recv(payload)
1400 return fmt.Errorf("unexpected extended message ID: %v", id)
1404 // Set both the Reader and Writer for the connection from a single ReadWriter.
1405 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1410 // Returns the Reader and Writer as a combined ReadWriter.
1411 func (cn *PeerConn) rw() io.ReadWriter {
1418 func (c *Peer) doChunkReadStats(size int64) {
1419 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1422 // Handle a received chunk from a peer.
1423 func (c *Peer) receiveChunk(msg *pp.Message) error {
1424 chunksReceived.Add("total", 1)
1426 ppReq := newRequestFromMessage(msg)
1427 req := c.t.requestIndexFromRequest(ppReq)
1430 if c.bannableAddr.Ok {
1431 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
1435 chunksReceived.Add("while choked", 1)
1438 if c.validReceiveChunks[req] <= 0 {
1439 chunksReceived.Add("unexpected", 1)
1440 return errors.New("received unexpected chunk")
1442 c.decExpectedChunkReceive(req)
1444 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1445 chunksReceived.Add("due to allowed fast", 1)
1448 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1449 // have actually already received the piece, while we have the Client unlocked to write the data
1453 if c.requestState.Requests.Contains(req) {
1454 for _, f := range c.callbacks.ReceivedRequested {
1455 f(PeerMessageEvent{c, msg})
1458 // Request has been satisfied.
1459 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1462 c._chunksReceivedWhileExpecting++
1464 if c.isLowOnRequests() {
1465 c.updateRequests("Peer.receiveChunk deleted request")
1468 chunksReceived.Add("unintended", 1)
1474 // Do we actually want this chunk?
1475 if t.haveChunk(ppReq) {
1476 // panic(fmt.Sprintf("%+v", ppReq))
1477 chunksReceived.Add("redundant", 1)
1478 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1482 piece := &t.pieces[ppReq.Index]
1484 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1485 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1487 c.piecesReceivedSinceLastRequestUpdate++
1488 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1490 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1491 f(ReceivedUsefulDataEvent{c, msg})
1493 c.lastUsefulChunkReceived = time.Now()
1495 // Need to record that it hasn't been written yet, before we attempt to do
1496 // anything with it.
1497 piece.incrementPendingWrites()
1498 // Record that we have the chunk, so we aren't trying to download it while
1499 // waiting for it to be written to storage.
1500 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1502 // Cancel pending requests for this chunk from *other* peers.
1503 if p := t.requestingPeer(req); p != nil {
1505 panic("should not be pending request from conn that just received it")
1510 err := func() error {
1513 concurrentChunkWrites.Add(1)
1514 defer concurrentChunkWrites.Add(-1)
1515 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1516 // number of connections. We write inline with receiving the chunk (with this lock dance),
1517 // because we want to handle errors synchronously and I haven't thought of a nice way to
1518 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1520 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1523 piece.decrementPendingWrites()
1526 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1528 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1529 // request update runs while we're writing the chunk that just failed. Then we never do a
1530 // fresh update after pending the failed request.
1531 c.updateRequests("Peer.receiveChunk error writing chunk")
1532 t.onWriteChunkErr(err)
1536 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1538 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1539 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1540 t.queuePieceCheck(pieceIndex(ppReq.Index))
1541 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1542 // chunk status (such as the haveChunk call above) to have to check all the various other
1543 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1544 // that chunk pieces are pended at an appropriate time later however.
1547 cl.event.Broadcast()
1548 // We do this because we've written a chunk, and may change PieceState.Partial.
1549 t.publishPieceChange(pieceIndex(ppReq.Index))
1554 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1555 if c.peerTouchedPieces == nil {
1556 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1558 c.peerTouchedPieces[piece] = struct{}{}
1559 ds := &c.t.pieces[piece].dirtiers
1561 *ds = make(map[*Peer]struct{})
1563 (*ds)[c] = struct{}{}
1566 func (c *PeerConn) uploadAllowed() bool {
1567 if c.t.cl.config.NoUpload {
1570 if c.t.dataUploadDisallowed {
1576 if !c.peerHasWantedPieces() {
1579 // Don't upload more than 100 KiB more than we download.
1580 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1586 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1587 if c.uploadTimer == nil {
1588 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1590 c.uploadTimer.Reset(delay)
1594 // Also handles choking and unchoking of the remote peer.
1595 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1596 // Breaking or completing this loop means we don't want to upload to the
1597 // peer anymore, and we choke them.
1599 for c.uploadAllowed() {
1600 // We want to upload to the peer.
1601 if !c.unchoke(msg) {
1604 for r, state := range c.peerRequests {
1605 if state.data == nil {
1608 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1610 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1612 delay := res.Delay()
1615 c.setRetryUploadTimer(delay)
1616 // Hard to say what to return here.
1619 more := c.sendChunk(r, msg, state)
1620 delete(c.peerRequests, r)
1631 func (cn *PeerConn) drop() {
1632 cn.t.dropConnection(cn)
1635 func (cn *PeerConn) ban() {
1636 cn.t.cl.banPeerIP(cn.remoteIp())
1639 func (cn *Peer) netGoodPiecesDirtied() int64 {
1640 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1643 func (c *Peer) peerHasWantedPieces() bool {
1644 if all, _ := c.peerHasAllPieces(); all {
1645 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1647 if !c.t.haveInfo() {
1648 return !c.peerPieces().IsEmpty()
1650 return c.peerPieces().Intersects(&c.t._pendingPieces)
1653 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1655 func (c *Peer) deleteRequest(r RequestIndex) bool {
1656 if !c.requestState.Requests.CheckedRemove(r) {
1659 for _, f := range c.callbacks.DeletedRequest {
1660 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1662 c.updateExpectingChunks()
1663 if c.t.requestingPeer(r) != c {
1664 panic("only one peer should have a given request at a time")
1666 delete(c.t.requestState, r)
1667 // c.t.iterPeers(func(p *Peer) {
1668 // if p.isLowOnRequests() {
1669 // p.updateRequests("Peer.deleteRequest")
1675 func (c *Peer) deleteAllRequests(reason string) {
1676 if c.requestState.Requests.IsEmpty() {
1679 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1680 if !c.deleteRequest(x) {
1681 panic("request should exist")
1685 c.assertNoRequests()
1686 c.t.iterPeers(func(p *Peer) {
1687 if p.isLowOnRequests() {
1688 p.updateRequests(reason)
1694 func (c *Peer) assertNoRequests() {
1695 if !c.requestState.Requests.IsEmpty() {
1696 panic(c.requestState.Requests.GetCardinality())
1700 func (c *Peer) cancelAllRequests() {
1701 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1705 c.assertNoRequests()
1709 // This is called when something has changed that should wake the writer, such as putting stuff into
1710 // the writeBuffer, or changing some state that the writer can act on.
1711 func (c *PeerConn) tickleWriter() {
1712 c.messageWriter.writeCond.Broadcast()
1715 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1716 c.lastChunkSent = time.Now()
1717 return msg(pp.Message{
1725 func (c *PeerConn) setTorrent(t *Torrent) {
1727 panic("connection already associated with a torrent")
1730 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1731 t.reconcileHandshakeStats(c)
1734 func (c *Peer) peerPriority() (peerPriority, error) {
1735 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
1738 func (c *Peer) remoteIp() net.IP {
1739 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1740 return net.ParseIP(host)
1743 func (c *Peer) remoteIpPort() IpPort {
1744 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1745 return IpPort{ipa.IP, uint16(ipa.Port)}
1748 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1749 f := pp.PexPeerFlags(0)
1750 if c.PeerPrefersEncryption {
1751 f |= pp.PexPrefersEncryption
1754 f |= pp.PexOutgoingConn
1757 f |= pp.PexSupportsUtp
1762 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1763 // advertised listen port.
1764 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1765 if !c.outgoing && c.PeerListenPort != 0 {
1766 switch addr := c.RemoteAddr.(type) {
1769 dialAddr.Port = c.PeerListenPort
1773 dialAddr.Port = c.PeerListenPort
1780 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1781 f := c.pexPeerFlags()
1782 addr := c.dialAddr()
1783 return pexEvent{t, addr, f, nil}
1786 func (c *PeerConn) String() string {
1787 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1790 func (c *Peer) trust() connectionTrust {
1791 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1794 type connectionTrust struct {
1796 NetGoodPiecesDirted int64
1799 func (l connectionTrust) Less(r connectionTrust) bool {
1800 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1803 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1804 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1805 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1807 defer cn.locker().RUnlock()
1808 return cn.newPeerPieces()
1811 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1812 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1813 // TODO: Can we use copy on write?
1814 ret := cn.peerPieces().Clone()
1815 if all, _ := cn.peerHasAllPieces(); all {
1816 if cn.t.haveInfo() {
1817 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1819 ret.AddRange(0, bitmap.ToEnd)
1825 func (cn *Peer) stats() *ConnStats {
1829 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1830 pc, ok := p.peerImpl.(*PeerConn)
1834 func (p *Peer) uncancelledRequests() uint64 {
1835 return p.requestState.Requests.GetCardinality()
1838 func (pc *PeerConn) remoteIsTransmission() bool {
1839 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'