16 "github.com/RoaringBitmap/roaring"
17 "github.com/anacrolix/chansync"
18 . "github.com/anacrolix/generics"
19 "github.com/anacrolix/log"
20 "github.com/anacrolix/missinggo/iter"
21 "github.com/anacrolix/missinggo/v2/bitmap"
22 "github.com/anacrolix/multiless"
23 "golang.org/x/time/rate"
25 "github.com/anacrolix/torrent/bencode"
26 "github.com/anacrolix/torrent/metainfo"
27 "github.com/anacrolix/torrent/mse"
28 pp "github.com/anacrolix/torrent/peer_protocol"
29 request_strategy "github.com/anacrolix/torrent/request-strategy"
30 "github.com/anacrolix/torrent/typed-roaring"
33 type PeerSource string
36 PeerSourceTracker = "Tr"
37 PeerSourceIncoming = "I"
38 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
39 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
41 // The peer was given directly, such as through a magnet link.
42 PeerSourceDirect = "M"
45 type peerRequestState struct {
49 type PeerRemoteAddr interface {
54 // Since we have to store all the requests in memory, we can't reasonably exceed what could be
55 // indexed with the memory space available.
60 // First to ensure 64-bit alignment for atomics. See #262.
70 RemoteAddr PeerRemoteAddr
71 // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
73 localPublicAddr peerLocalPublicAddr
74 bannableAddr Option[bannableAddr]
75 // True if the connection is operating over MSE obfuscation.
77 cryptoMethod mse.CryptoMethod
80 closed chansync.SetOnce
81 // Set true after we've added our ConnStats generated during handshake to
82 // other ConnStat instances as determined when the *Torrent became known.
83 reconciledHandshakeStats bool
85 lastMessageReceived time.Time
86 completedHandshake time.Time
87 lastUsefulChunkReceived time.Time
88 lastChunkSent time.Time
90 // Stuff controlled by the local peer.
91 needRequestUpdate string
92 requestState request_strategy.PeerRequestState
93 updateRequestsTimer *time.Timer
94 lastRequestUpdate time.Time
95 peakRequests maxRequests
96 lastBecameInterested time.Time
97 priorInterest time.Duration
99 lastStartedExpectingToReceiveChunks time.Time
100 cumulativeExpectedToReceiveChunks time.Duration
101 _chunksReceivedWhileExpecting int64
104 piecesReceivedSinceLastRequestUpdate maxRequests
105 maxPiecesReceivedBetweenRequestUpdates maxRequests
106 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
107 // and implementation differences, we may receive chunks that are no longer in the set of
108 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
109 validReceiveChunks map[RequestIndex]int
110 // Indexed by metadata piece, set to true if posted and pending a
112 metadataRequests []bool
113 sentHaves bitmap.Bitmap
115 // Stuff controlled by the remote peer.
118 peerRequests map[Request]*peerRequestState
119 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
121 // The highest possible number of pieces the torrent could have based on
122 // communication with the peer. Generally only useful until we have the
124 peerMinPieces pieceIndex
125 // Pieces we've accepted chunks for from the peer.
126 peerTouchedPieces map[pieceIndex]struct{}
127 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
129 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
130 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
131 PeerClientName atomic.Value
136 type peerRequests = orderedBitmap[RequestIndex]
138 func (p *Peer) initRequestState() {
139 p.requestState.Requests = &peerRequests{}
142 // Maintains the state of a BitTorrent-protocol based connection with a peer.
143 type PeerConn struct {
146 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
147 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
152 PeerExtensionBytes pp.PeerExtensionBits
154 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
155 // while holding any mutexes.
157 // The Reader and Writer for this Conn, with hooks installed for stats,
158 // limiting, deadlines etc.
162 messageWriter peerConnMsgWriter
164 uploadTimer *time.Timer
167 // The pieces the peer has claimed to have.
168 _peerPieces roaring.Bitmap
169 // The peer has everything. This can occur due to a special message, when
170 // we may not even know the number of pieces in the torrent yet.
174 func (cn *PeerConn) peerImplStatusLines() []string {
175 return []string{fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)}
178 func (cn *Peer) updateExpectingChunks() {
179 if cn.expectingChunks() {
180 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
181 cn.lastStartedExpectingToReceiveChunks = time.Now()
184 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
185 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
186 cn.lastStartedExpectingToReceiveChunks = time.Time{}
191 func (cn *Peer) expectingChunks() bool {
192 if cn.requestState.Requests.IsEmpty() {
195 if !cn.requestState.Interested {
201 haveAllowedFastRequests := false
202 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
203 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
204 cn.requestState.Requests,
205 cn.t.pieceRequestIndexOffset(i),
206 cn.t.pieceRequestIndexOffset(i+1),
208 return !haveAllowedFastRequests
210 return haveAllowedFastRequests
213 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
214 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
217 // Returns true if the connection is over IPv6.
218 func (cn *PeerConn) ipv6() bool {
223 return len(ip) == net.IPv6len
226 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
227 // specification for this.
228 func (cn *PeerConn) isPreferredDirection() bool {
229 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
232 // Returns whether the left connection should be preferred over the right one,
233 // considering only their networking properties. If ok is false, we can't
235 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
236 var ml multiless.Computation
237 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
238 ml = ml.Bool(l.utp(), r.utp())
239 ml = ml.Bool(r.ipv6(), l.ipv6())
243 func (cn *Peer) cumInterest() time.Duration {
244 ret := cn.priorInterest
245 if cn.requestState.Interested {
246 ret += time.Since(cn.lastBecameInterested)
251 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
252 if cn.peerSentHaveAll {
255 if !cn.t.haveInfo() {
258 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
261 func (cn *Peer) locker() *lockWithDeferreds {
262 return cn.t.cl.locker()
265 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
266 _, ok := cn.PeerExtensionIDs[ext]
270 // The best guess at number of pieces in the torrent for this peer.
271 func (cn *Peer) bestPeerNumPieces() pieceIndex {
273 return cn.t.numPieces()
275 return cn.peerMinPieces
278 func (cn *Peer) completedString() string {
279 have := pieceIndex(cn.peerPieces().GetCardinality())
280 if all, _ := cn.peerHasAllPieces(); all {
281 have = cn.bestPeerNumPieces()
283 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
286 func (cn *Peer) CompletedString() string {
287 return cn.completedString()
290 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
291 cn.setNumPieces(info.NumPieces())
294 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
295 // receiving badly sized BITFIELD, or invalid HAVE messages.
296 func (cn *PeerConn) setNumPieces(num pieceIndex) {
297 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
298 cn.peerPiecesChanged()
301 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
302 return &cn._peerPieces
305 func eventAgeString(t time.Time) string {
309 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
312 func (cn *PeerConn) connectionFlags() (ret string) {
314 ret += string([]byte{b})
316 if cn.cryptoMethod == mse.CryptoMethodRC4 {
318 } else if cn.headerEncrypted {
321 ret += string(cn.Discovery)
328 func (cn *PeerConn) utp() bool {
329 return parseNetworkString(cn.Network).Udp
332 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
333 func (cn *Peer) statusFlags() (ret string) {
335 ret += string([]byte{b})
337 if cn.requestState.Interested {
344 ret += cn.connectionFlags()
346 if cn.peerInterested {
355 func (cn *Peer) StatusFlags() string {
356 return cn.statusFlags()
359 func (cn *Peer) downloadRate() float64 {
360 num := cn._stats.BytesReadUsefulData.Int64()
364 return float64(num) / cn.totalExpectingTime().Seconds()
367 func (cn *Peer) DownloadRate() float64 {
369 defer cn.locker().RUnlock()
371 return cn.downloadRate()
374 func (cn *Peer) UploadRate() float64 {
376 defer cn.locker().RUnlock()
377 num := cn._stats.BytesWrittenData.Int64()
381 return float64(num) / time.Now().Sub(cn.completedHandshake).Seconds()
385 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
386 var last Option[pieceIndex]
388 next := func(item Option[pieceIndex]) {
399 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
400 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
403 next(None[pieceIndex]())
406 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
407 // \t isn't preserved in <pre> blocks?
408 if cn.closed.IsSet() {
409 fmt.Fprint(w, "CLOSED: ")
411 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
412 prio, err := cn.peerPriority()
413 prioStr := fmt.Sprintf("%08x", prio)
415 prioStr += ": " + err.Error()
417 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
418 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
419 eventAgeString(cn.lastMessageReceived),
420 eventAgeString(cn.completedHandshake),
421 eventAgeString(cn.lastHelpful()),
423 cn.totalExpectingTime(),
426 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
427 cn.completedString(),
428 len(cn.peerTouchedPieces),
429 &cn._stats.ChunksReadUseful,
430 &cn._stats.ChunksRead,
431 &cn._stats.ChunksWritten,
432 cn.requestState.Requests.GetCardinality(),
433 cn.requestState.Cancelled.GetCardinality(),
434 cn.nominalMaxRequests(),
436 len(cn.peerRequests),
439 cn.downloadRate()/(1<<10),
441 fmt.Fprintf(w, "requested pieces:")
442 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
443 fmt.Fprintf(w, " %v(%v)", piece, count)
448 func (p *Peer) close() {
452 if p.updateRequestsTimer != nil {
453 p.updateRequestsTimer.Stop()
457 p.t.decPeerPieceAvailability(p)
459 for _, f := range p.callbacks.PeerClosed {
464 func (cn *PeerConn) onClose() {
465 if cn.pex.IsEnabled() {
472 if cb := cn.callbacks.PeerConnClosed; cb != nil {
477 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
478 // they do (known=true).
479 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
480 if all, known := cn.peerHasAllPieces(); all && known {
483 return cn.peerPieces().ContainsInt(piece)
486 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
487 // https://github.com/pion/datachannel/issues/59 is fixed.
489 writeBufferHighWaterLen = 1 << 15
490 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
493 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
494 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
495 func (cn *PeerConn) write(msg pp.Message) bool {
496 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
497 // We don't need to track bytes here because the connection's Writer has that behaviour injected
498 // (although there's some delay between us buffering the message, and the connection writer
499 // flushing it out.).
500 notFull := cn.messageWriter.write(msg)
501 // Last I checked only Piece messages affect stats, and we don't write those.
507 func (cn *PeerConn) requestMetadataPiece(index int) {
508 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
509 if eID == pp.ExtensionDeleteNumber {
512 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
515 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
516 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
517 for index >= len(cn.metadataRequests) {
518 cn.metadataRequests = append(cn.metadataRequests, false)
520 cn.metadataRequests[index] = true
523 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
524 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
528 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
529 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
530 // This is the maximum request count that could fit in the write buffer if it's at or below the
531 // low water mark when we run maybeUpdateActualRequestState.
532 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
535 // The actual value to use as the maximum outbound requests.
536 func (cn *Peer) nominalMaxRequests() maxRequests {
537 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
540 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
541 ret = cn.cumulativeExpectedToReceiveChunks
542 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
543 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
548 func (cn *PeerConn) onPeerSentCancel(r Request) {
549 if _, ok := cn.peerRequests[r]; !ok {
550 torrent.Add("unexpected cancels received", 1)
553 if cn.fastEnabled() {
556 delete(cn.peerRequests, r)
560 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
565 more = msg(pp.Message{
568 if !cn.fastEnabled() {
569 cn.peerRequests = nil
574 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
579 return msg(pp.Message{
584 func (cn *Peer) setInterested(interested bool) bool {
585 if cn.requestState.Interested == interested {
588 cn.requestState.Interested = interested
590 cn.lastBecameInterested = time.Now()
591 } else if !cn.lastBecameInterested.IsZero() {
592 cn.priorInterest += time.Since(cn.lastBecameInterested)
594 cn.updateExpectingChunks()
595 // log.Printf("%p: setting interest: %v", cn, interested)
596 return cn.writeInterested(interested)
599 func (pc *PeerConn) writeInterested(interested bool) bool {
600 return pc.write(pp.Message{
601 Type: func() pp.MessageType {
605 return pp.NotInterested
611 // The function takes a message to be sent, and returns true if more messages
613 type messageWriter func(pp.Message) bool
615 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
616 // when we want to go fast.
617 func (cn *Peer) shouldRequest(r RequestIndex) error {
618 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
622 pi := cn.t.pieceIndexOfRequestIndex(r)
623 if cn.requestState.Cancelled.Contains(r) {
624 return errors.New("request is cancelled and waiting acknowledgement")
626 if !cn.peerHasPiece(pi) {
627 return errors.New("requesting piece peer doesn't have")
629 if !cn.t.peerIsActive(cn) {
630 panic("requesting but not in active conns")
632 if cn.closed.IsSet() {
633 panic("requesting when connection is closed")
635 if cn.t.hashingPiece(pi) {
636 panic("piece is being hashed")
638 if cn.t.pieceQueuedForHash(pi) {
639 panic("piece is queued for hash")
641 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
642 // This could occur if we made a request with the fast extension, and then got choked and
643 // haven't had the request rejected yet.
644 if !cn.requestState.Requests.Contains(r) {
645 panic("peer choking and piece not allowed fast")
651 func (cn *Peer) mustRequest(r RequestIndex) bool {
652 more, err := cn.request(r)
659 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
660 if err := cn.shouldRequest(r); err != nil {
663 if cn.requestState.Requests.Contains(r) {
666 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
667 return true, errors.New("too many outstanding requests")
669 cn.requestState.Requests.Add(r)
670 if cn.validReceiveChunks == nil {
671 cn.validReceiveChunks = make(map[RequestIndex]int)
673 cn.validReceiveChunks[r]++
674 cn.t.requestState[r] = requestState{
678 cn.updateExpectingChunks()
679 ppReq := cn.t.requestIndexToRequest(r)
680 for _, f := range cn.callbacks.SentRequest {
681 f(PeerRequestEvent{cn, ppReq})
683 return cn.peerImpl._request(ppReq), nil
686 func (me *PeerConn) _request(r Request) bool {
687 return me.write(pp.Message{
695 func (me *Peer) cancel(r RequestIndex) {
696 if !me.deleteRequest(r) {
697 panic("request not existing should have been guarded")
700 if !me.requestState.Cancelled.CheckedAdd(r) {
701 panic("request already cancelled")
705 if me.isLowOnRequests() {
706 me.updateRequests("Peer.cancel")
710 func (me *PeerConn) _cancel(r RequestIndex) bool {
711 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
712 // Transmission does not send rejects for received cancels. See
713 // https://github.com/transmission/transmission/pull/2275.
714 return me.fastEnabled() && !me.remoteIsTransmission()
717 func (cn *PeerConn) fillWriteBuffer() {
718 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
719 // Fully committing to our max requests requires sufficient space (see
720 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
721 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
722 // request reason will not be cleared, so we'll come right back here when there's space. We
723 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
724 // knowledge of write buffers.
726 cn.maybeUpdateActualRequestState()
727 if cn.pex.IsEnabled() {
728 if flow := cn.pex.Share(cn.write); !flow {
735 func (cn *PeerConn) have(piece pieceIndex) {
736 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
741 Index: pp.Integer(piece),
743 cn.sentHaves.Add(bitmap.BitIndex(piece))
746 func (cn *PeerConn) postBitfield() {
747 if cn.sentHaves.Len() != 0 {
748 panic("bitfield must be first have-related message sent")
750 if !cn.t.haveAnyPieces() {
755 Bitfield: cn.t.bitfield(),
757 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
760 // Sets a reason to update requests, and if there wasn't already one, handle it.
761 func (cn *Peer) updateRequests(reason string) {
762 if cn.needRequestUpdate != "" {
765 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
768 cn.needRequestUpdate = reason
769 cn.handleUpdateRequests()
772 func (cn *PeerConn) handleUpdateRequests() {
773 // The writer determines the request state as needed when it can write.
777 // Emits the indices in the Bitmaps bms in order, never repeating any index.
778 // skip is mutated during execution, and its initial values will never be
780 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
781 return func(cb iter.Callback) {
782 for _, bm := range bms {
784 func(_i interface{}) bool {
786 if skip.Contains(bitmap.BitIndex(i)) {
789 skip.Add(bitmap.BitIndex(i))
800 func (cn *Peer) peerPiecesChanged() {
801 cn.t.maybeDropMutuallyCompletePeer(cn)
804 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
805 if newMin > cn.peerMinPieces {
806 cn.peerMinPieces = newMin
810 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
811 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
812 return errors.New("invalid piece")
814 if cn.peerHasPiece(piece) {
817 cn.raisePeerMinPieces(piece + 1)
818 if !cn.peerHasPiece(piece) {
819 cn.t.incPieceAvailability(piece)
821 cn._peerPieces.Add(uint32(piece))
822 if cn.t.wantPieceIndex(piece) {
823 cn.updateRequests("have")
825 cn.peerPiecesChanged()
829 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
831 panic("expected bitfield length divisible by 8")
833 // We know that the last byte means that at most the last 7 bits are wasted.
834 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
835 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
836 // Ignore known excess pieces.
837 bf = bf[:cn.t.numPieces()]
839 bm := boolSliceToBitmap(bf)
840 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
841 cn.onPeerHasAllPieces()
845 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
847 shouldUpdateRequests := false
848 if cn.peerSentHaveAll {
849 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
852 cn.peerSentHaveAll = false
853 if !cn._peerPieces.IsEmpty() {
854 panic("if peer has all, we expect no individual peer pieces to be set")
857 bm.Xor(&cn._peerPieces)
859 cn.peerSentHaveAll = false
860 // bm is now 'on' for pieces that are changing
861 bm.Iterate(func(x uint32) bool {
863 if cn._peerPieces.Contains(x) {
864 // Then we must be losing this piece
865 cn.t.decPieceAvailability(pi)
867 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
868 shouldUpdateRequests = true
870 // We must be gaining this piece
871 cn.t.incPieceAvailability(pieceIndex(x))
875 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
877 cn._peerPieces.Xor(&bm)
878 if shouldUpdateRequests {
879 cn.updateRequests("bitfield")
881 // We didn't guard this before, I see no reason to do it now.
882 cn.peerPiecesChanged()
886 func (cn *PeerConn) onPeerHasAllPieces() {
889 cn._peerPieces.Iterate(func(x uint32) bool {
890 t.decPieceAvailability(pieceIndex(x))
894 t.addConnWithAllPieces(&cn.Peer)
895 cn.peerSentHaveAll = true
896 cn._peerPieces.Clear()
897 if !cn.t._pendingPieces.IsEmpty() {
898 cn.updateRequests("Peer.onPeerHasAllPieces")
900 cn.peerPiecesChanged()
903 func (cn *PeerConn) onPeerSentHaveAll() error {
904 cn.onPeerHasAllPieces()
908 func (cn *PeerConn) peerSentHaveNone() error {
909 if cn.peerSentHaveAll {
910 cn.t.decPeerPieceAvailability(&cn.Peer)
912 cn._peerPieces.Clear()
913 cn.peerSentHaveAll = false
914 cn.peerPiecesChanged()
918 func (c *PeerConn) requestPendingMetadata() {
922 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
923 // Peer doesn't support this.
926 // Request metadata pieces that we don't have in a random order.
928 for index := 0; index < c.t.metadataPieceCount(); index++ {
929 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
930 pending = append(pending, index)
933 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
934 for _, i := range pending {
935 c.requestMetadataPiece(i)
939 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
940 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
941 if msg.Type == pp.Extended {
942 for name, id := range cn.PeerExtensionIDs {
943 if id != msg.ExtendedID {
946 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
949 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
952 // After handshake, we know what Torrent and Client stats to include for a
954 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
960 // All ConnStats that include this connection. Some objects are not known
961 // until the handshake is complete, after which it's expected to reconcile the
963 func (cn *Peer) allStats(f func(*ConnStats)) {
965 if cn.reconciledHandshakeStats {
966 cn.postHandshakeStats(f)
970 func (cn *PeerConn) wroteBytes(n int64) {
971 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
974 func (cn *Peer) readBytes(n int64) {
975 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
978 // Returns whether the connection could be useful to us. We're seeding and
979 // they want data, we don't have metainfo and they can provide it, etc.
980 func (c *Peer) useful() bool {
982 if c.closed.IsSet() {
986 return c.supportsExtension("ut_metadata")
988 if t.seeding() && c.peerInterested {
991 if c.peerHasWantedPieces() {
997 func (c *Peer) lastHelpful() (ret time.Time) {
998 ret = c.lastUsefulChunkReceived
999 if c.t.seeding() && c.lastChunkSent.After(ret) {
1000 ret = c.lastChunkSent
1005 func (c *PeerConn) fastEnabled() bool {
1006 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
1009 func (c *PeerConn) reject(r Request) {
1010 if !c.fastEnabled() {
1011 panic("fast not enabled")
1013 c.write(r.ToMsg(pp.Reject))
1014 delete(c.peerRequests, r)
1017 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
1018 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
1019 if uploadRateLimiter.Limit() == rate.Inf {
1022 return Some(uploadRateLimiter.Burst())
1025 // startFetch is for testing purposes currently.
1026 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
1027 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1028 if _, ok := c.peerRequests[r]; ok {
1029 torrent.Add("duplicate requests received", 1)
1030 if c.fastEnabled() {
1031 return errors.New("received duplicate request with fast enabled")
1036 torrent.Add("requests received while choking", 1)
1037 if c.fastEnabled() {
1038 torrent.Add("requests rejected while choking", 1)
1043 // TODO: What if they've already requested this?
1044 if len(c.peerRequests) >= localClientReqq {
1045 torrent.Add("requests received while queue full", 1)
1046 if c.fastEnabled() {
1049 // BEP 6 says we may close here if we choose.
1052 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
1053 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
1054 c.logger.Levelf(log.Warning, err.Error())
1055 if c.fastEnabled() {
1062 if !c.t.havePiece(pieceIndex(r.Index)) {
1063 // TODO: Tell the peer we don't have the piece, and reject this request.
1064 requestsReceivedForMissingPieces.Add(1)
1065 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1067 // Check this after we know we have the piece, so that the piece length will be known.
1068 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1069 torrent.Add("bad requests received", 1)
1070 return errors.New("bad Request")
1072 if c.peerRequests == nil {
1073 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1075 value := &peerRequestState{}
1076 c.peerRequests[r] = value
1078 // TODO: Limit peer request data read concurrency.
1079 go c.peerRequestDataReader(r, value)
1084 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1085 b, err := readPeerRequestData(r, c)
1087 defer c.locker().Unlock()
1089 c.peerRequestDataReadFailed(err, r)
1092 panic("data must be non-nil to trigger send")
1094 torrent.Add("peer request data read successes", 1)
1096 // This might be required for the error case too (#752 and #753).
1101 // If this is maintained correctly, we might be able to support optional synchronous reading for
1102 // chunk sending, the way it used to work.
1103 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1104 torrent.Add("peer request data read failures", 1)
1105 logLevel := log.Warning
1106 if c.t.hasStorageCap() {
1107 // It's expected that pieces might drop. See
1108 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1109 logLevel = log.Debug
1111 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1112 if c.t.closed.IsSet() {
1115 i := pieceIndex(r.Index)
1116 if c.t.pieceComplete(i) {
1117 // There used to be more code here that just duplicated the following break. Piece
1118 // completions are currently cached, so I'm not sure how helpful this update is, except to
1119 // pull any completion changes pushed to the storage backend in failed reads that got us
1121 c.t.updatePieceCompletion(i)
1123 // We've probably dropped a piece from storage, but there's no way to communicate this to the
1124 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1125 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1126 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1128 if c.fastEnabled() {
1132 // If fast isn't enabled, I think we would have wiped all peer requests when we last
1133 // choked, and requests while we're choking would be ignored. It could be possible that
1134 // a peer request data read completed concurrently to it being deleted elsewhere.
1135 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1137 // Choking a non-fast peer should cause them to flush all their requests.
1142 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1143 b := make([]byte, r.Length)
1144 p := c.t.info.Piece(int(r.Index))
1145 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1152 panic("expected error")
1158 func runSafeExtraneous(f func()) {
1166 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1167 c.logger.WithContextText(fmt.Sprintf(
1168 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1169 )).SkipCallers(1).Levelf(level, format, arg...)
1172 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1173 // exit. Returning will end the connection.
1174 func (c *PeerConn) mainReadLoop() (err error) {
1177 torrent.Add("connection.mainReadLoop returned with error", 1)
1179 torrent.Add("connection.mainReadLoop returned with no error", 1)
1185 decoder := pp.Decoder{
1186 R: bufio.NewReaderSize(c.r, 1<<17),
1187 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1195 err = decoder.Decode(&msg)
1197 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1200 if t.closed.IsSet() || c.closed.IsSet() {
1206 c.lastMessageReceived = time.Now()
1208 receivedKeepalives.Add(1)
1211 messageTypesReceived.Add(msg.Type.String(), 1)
1212 if msg.Type.FastExtension() && !c.fastEnabled() {
1213 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1214 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1221 if !c.fastEnabled() {
1222 c.deleteAllRequests("choked by non-fast PeerConn")
1224 // We don't decrement pending requests here, let's wait for the peer to either
1225 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1226 // us and resume where they left off, we don't want to have piled on to those chunks
1227 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1228 // could let us request a lot of stuff, then choke us and never reject, but they're
1229 // only a single peer, our chunk balancing should smooth over this abuse.
1231 c.peerChoking = true
1232 c.updateExpectingChunks()
1235 // Some clients do this for some reason. Transmission doesn't error on this, so we
1236 // won't for consistency.
1237 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1240 c.peerChoking = false
1242 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1243 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1248 if preservedCount != 0 {
1249 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1251 c.logger.Levelf(log.Debug,
1252 "%v requests were preserved while being choked (fast=%v)",
1256 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1258 if !c.t._pendingPieces.IsEmpty() {
1259 c.updateRequests("unchoked")
1261 c.updateExpectingChunks()
1263 c.peerInterested = true
1265 case pp.NotInterested:
1266 c.peerInterested = false
1267 // We don't clear their requests since it isn't clear in the spec.
1268 // We'll probably choke them for this, which will clear them if
1269 // appropriate, and is clearly specified.
1271 err = c.peerSentHave(pieceIndex(msg.Index))
1273 err = c.peerSentBitfield(msg.Bitfield)
1275 r := newRequestFromMessage(&msg)
1276 err = c.onReadRequest(r, true)
1278 c.doChunkReadStats(int64(len(msg.Piece)))
1279 err = c.receiveChunk(&msg)
1280 if len(msg.Piece) == int(t.chunkSize) {
1281 t.chunkPool.Put(&msg.Piece)
1284 err = fmt.Errorf("receiving chunk: %w", err)
1287 req := newRequestFromMessage(&msg)
1288 c.onPeerSentCancel(req)
1290 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1294 pingAddr := net.UDPAddr{
1299 pingAddr.Port = int(msg.Port)
1301 cl.eachDhtServer(func(s DhtServer) {
1302 go s.Ping(&pingAddr)
1305 torrent.Add("suggests received", 1)
1306 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1307 c.updateRequests("suggested")
1309 err = c.onPeerSentHaveAll()
1311 err = c.peerSentHaveNone()
1313 req := newRequestFromMessage(&msg)
1314 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1315 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1316 err = fmt.Errorf("received invalid reject [request=%v]", req)
1318 case pp.AllowedFast:
1319 torrent.Add("allowed fasts received", 1)
1320 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1321 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1323 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1325 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1333 // Returns true if it was valid to reject the request.
1334 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1335 if c.deleteRequest(r) {
1337 } else if !c.requestState.Cancelled.CheckedRemove(r) {
1340 if c.isLowOnRequests() {
1341 c.updateRequests("Peer.remoteRejectedRequest")
1343 c.decExpectedChunkReceive(r)
1347 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1348 count := c.validReceiveChunks[r]
1350 delete(c.validReceiveChunks, r)
1351 } else if count > 1 {
1352 c.validReceiveChunks[r] = count - 1
1358 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1360 // TODO: Should we still do this?
1362 // These clients use their own extension IDs for outgoing message
1363 // types, which is incorrect.
1364 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1372 case pp.HandshakeExtendedID:
1373 var d pp.ExtendedHandshakeMessage
1374 if err := bencode.Unmarshal(payload, &d); err != nil {
1375 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1376 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1378 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1381 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1383 c.PeerMaxRequests = d.Reqq
1385 c.PeerClientName.Store(d.V)
1386 if c.PeerExtensionIDs == nil {
1387 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1389 c.PeerListenPort = d.Port
1390 c.PeerPrefersEncryption = d.Encryption
1391 for name, id := range d.M {
1392 if _, ok := c.PeerExtensionIDs[name]; !ok {
1393 peersSupportingExtension.Add(
1394 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1395 // entered here which caused problems later when unmarshalling.
1396 strconv.Quote(string(name)),
1399 c.PeerExtensionIDs[name] = id
1401 if d.MetadataSize != 0 {
1402 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1403 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1406 c.requestPendingMetadata()
1407 if !t.cl.config.DisablePEX {
1408 t.pex.Add(c) // we learnt enough now
1412 case metadataExtendedId:
1413 err := cl.gotMetadataExtensionMsg(payload, t, c)
1415 return fmt.Errorf("handling metadata extension message: %w", err)
1419 if !c.pex.IsEnabled() {
1420 return nil // or hang-up maybe?
1422 return c.pex.Recv(payload)
1424 return fmt.Errorf("unexpected extended message ID: %v", id)
1428 // Set both the Reader and Writer for the connection from a single ReadWriter.
1429 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1434 // Returns the Reader and Writer as a combined ReadWriter.
1435 func (cn *PeerConn) rw() io.ReadWriter {
1442 func (c *Peer) doChunkReadStats(size int64) {
1443 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1446 // Handle a received chunk from a peer.
1447 func (c *Peer) receiveChunk(msg *pp.Message) error {
1448 chunksReceived.Add("total", 1)
1450 ppReq := newRequestFromMessage(msg)
1452 err := t.checkValidReceiveChunk(ppReq)
1454 err = log.WithLevel(log.Warning, err)
1457 req := c.t.requestIndexFromRequest(ppReq)
1459 if c.bannableAddr.Ok {
1460 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
1464 chunksReceived.Add("while choked", 1)
1467 if c.validReceiveChunks[req] <= 0 {
1468 chunksReceived.Add("unexpected", 1)
1469 return errors.New("received unexpected chunk")
1471 c.decExpectedChunkReceive(req)
1473 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1474 chunksReceived.Add("due to allowed fast", 1)
1477 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1478 // have actually already received the piece, while we have the Client unlocked to write the data
1482 if c.requestState.Requests.Contains(req) {
1483 for _, f := range c.callbacks.ReceivedRequested {
1484 f(PeerMessageEvent{c, msg})
1487 // Request has been satisfied.
1488 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1491 c._chunksReceivedWhileExpecting++
1493 if c.isLowOnRequests() {
1494 c.updateRequests("Peer.receiveChunk deleted request")
1497 chunksReceived.Add("unintended", 1)
1503 // Do we actually want this chunk?
1504 if t.haveChunk(ppReq) {
1505 // panic(fmt.Sprintf("%+v", ppReq))
1506 chunksReceived.Add("redundant", 1)
1507 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1511 piece := &t.pieces[ppReq.Index]
1513 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1514 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1516 c.piecesReceivedSinceLastRequestUpdate++
1517 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1519 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1520 f(ReceivedUsefulDataEvent{c, msg})
1522 c.lastUsefulChunkReceived = time.Now()
1524 // Need to record that it hasn't been written yet, before we attempt to do
1525 // anything with it.
1526 piece.incrementPendingWrites()
1527 // Record that we have the chunk, so we aren't trying to download it while
1528 // waiting for it to be written to storage.
1529 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1531 // Cancel pending requests for this chunk from *other* peers.
1532 if p := t.requestingPeer(req); p != nil {
1534 panic("should not be pending request from conn that just received it")
1539 err = func() error {
1542 concurrentChunkWrites.Add(1)
1543 defer concurrentChunkWrites.Add(-1)
1544 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1545 // number of connections. We write inline with receiving the chunk (with this lock dance),
1546 // because we want to handle errors synchronously and I haven't thought of a nice way to
1547 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1549 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1552 piece.decrementPendingWrites()
1555 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1557 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1558 // request update runs while we're writing the chunk that just failed. Then we never do a
1559 // fresh update after pending the failed request.
1560 c.updateRequests("Peer.receiveChunk error writing chunk")
1561 t.onWriteChunkErr(err)
1565 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1567 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1568 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1569 t.queuePieceCheck(pieceIndex(ppReq.Index))
1570 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1571 // chunk status (such as the haveChunk call above) to have to check all the various other
1572 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1573 // that chunk pieces are pended at an appropriate time later however.
1576 cl.event.Broadcast()
1577 // We do this because we've written a chunk, and may change PieceState.Partial.
1578 t.publishPieceChange(pieceIndex(ppReq.Index))
1583 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1584 if c.peerTouchedPieces == nil {
1585 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1587 c.peerTouchedPieces[piece] = struct{}{}
1588 ds := &c.t.pieces[piece].dirtiers
1590 *ds = make(map[*Peer]struct{})
1592 (*ds)[c] = struct{}{}
1595 func (c *PeerConn) uploadAllowed() bool {
1596 if c.t.cl.config.NoUpload {
1599 if c.t.dataUploadDisallowed {
1605 if !c.peerHasWantedPieces() {
1608 // Don't upload more than 100 KiB more than we download.
1609 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1615 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1616 if c.uploadTimer == nil {
1617 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1619 c.uploadTimer.Reset(delay)
1623 // Also handles choking and unchoking of the remote peer.
1624 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1625 // Breaking or completing this loop means we don't want to upload to the
1626 // peer anymore, and we choke them.
1628 for c.uploadAllowed() {
1629 // We want to upload to the peer.
1630 if !c.unchoke(msg) {
1633 for r, state := range c.peerRequests {
1634 if state.data == nil {
1637 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1639 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1641 delay := res.Delay()
1644 c.setRetryUploadTimer(delay)
1645 // Hard to say what to return here.
1648 more := c.sendChunk(r, msg, state)
1649 delete(c.peerRequests, r)
1660 func (cn *PeerConn) drop() {
1661 cn.t.dropConnection(cn)
1664 func (cn *PeerConn) ban() {
1665 cn.t.cl.banPeerIP(cn.remoteIp())
1668 func (cn *Peer) netGoodPiecesDirtied() int64 {
1669 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1672 func (c *Peer) peerHasWantedPieces() bool {
1673 if all, _ := c.peerHasAllPieces(); all {
1674 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1676 if !c.t.haveInfo() {
1677 return !c.peerPieces().IsEmpty()
1679 return c.peerPieces().Intersects(&c.t._pendingPieces)
1682 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1684 func (c *Peer) deleteRequest(r RequestIndex) bool {
1685 if !c.requestState.Requests.CheckedRemove(r) {
1688 for _, f := range c.callbacks.DeletedRequest {
1689 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1691 c.updateExpectingChunks()
1692 if c.t.requestingPeer(r) != c {
1693 panic("only one peer should have a given request at a time")
1695 delete(c.t.requestState, r)
1696 // c.t.iterPeers(func(p *Peer) {
1697 // if p.isLowOnRequests() {
1698 // p.updateRequests("Peer.deleteRequest")
1704 func (c *Peer) deleteAllRequests(reason string) {
1705 if c.requestState.Requests.IsEmpty() {
1708 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1709 if !c.deleteRequest(x) {
1710 panic("request should exist")
1714 c.assertNoRequests()
1715 c.t.iterPeers(func(p *Peer) {
1716 if p.isLowOnRequests() {
1717 p.updateRequests(reason)
1723 func (c *Peer) assertNoRequests() {
1724 if !c.requestState.Requests.IsEmpty() {
1725 panic(c.requestState.Requests.GetCardinality())
1729 func (c *Peer) cancelAllRequests() {
1730 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1734 c.assertNoRequests()
1738 // This is called when something has changed that should wake the writer, such as putting stuff into
1739 // the writeBuffer, or changing some state that the writer can act on.
1740 func (c *PeerConn) tickleWriter() {
1741 c.messageWriter.writeCond.Broadcast()
1744 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1745 c.lastChunkSent = time.Now()
1746 return msg(pp.Message{
1754 func (c *PeerConn) setTorrent(t *Torrent) {
1756 panic("connection already associated with a torrent")
1759 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1760 t.reconcileHandshakeStats(c)
1763 func (c *Peer) peerPriority() (peerPriority, error) {
1764 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
1767 func (c *Peer) remoteIp() net.IP {
1768 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1769 return net.ParseIP(host)
1772 func (c *Peer) remoteIpPort() IpPort {
1773 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1774 return IpPort{ipa.IP, uint16(ipa.Port)}
1777 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1778 f := pp.PexPeerFlags(0)
1779 if c.PeerPrefersEncryption {
1780 f |= pp.PexPrefersEncryption
1783 f |= pp.PexOutgoingConn
1786 f |= pp.PexSupportsUtp
1791 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1792 // advertised listen port.
1793 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1794 if !c.outgoing && c.PeerListenPort != 0 {
1795 switch addr := c.RemoteAddr.(type) {
1798 dialAddr.Port = c.PeerListenPort
1802 dialAddr.Port = c.PeerListenPort
1809 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1810 f := c.pexPeerFlags()
1811 addr := c.dialAddr()
1812 return pexEvent{t, addr, f, nil}
1815 func (c *PeerConn) String() string {
1816 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1819 func (c *Peer) trust() connectionTrust {
1820 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1823 type connectionTrust struct {
1825 NetGoodPiecesDirted int64
1828 func (l connectionTrust) Less(r connectionTrust) bool {
1829 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1832 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1833 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1834 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1836 defer cn.locker().RUnlock()
1837 return cn.newPeerPieces()
1840 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1841 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1842 // TODO: Can we use copy on write?
1843 ret := cn.peerPieces().Clone()
1844 if all, _ := cn.peerHasAllPieces(); all {
1845 if cn.t.haveInfo() {
1846 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1848 ret.AddRange(0, bitmap.ToEnd)
1854 func (cn *Peer) stats() *ConnStats {
1858 func (cn *Peer) Stats() *ConnStats {
1862 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1863 pc, ok := p.peerImpl.(*PeerConn)
1867 func (p *Peer) uncancelledRequests() uint64 {
1868 return p.requestState.Requests.GetCardinality()
1871 func (pc *PeerConn) remoteIsTransmission() bool {
1872 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'