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) connStatusString() string {
175 return 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 *PeerConn) onGotInfo(info *metainfo.Info) {
287 cn.setNumPieces(info.NumPieces())
290 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
291 // receiving badly sized BITFIELD, or invalid HAVE messages.
292 func (cn *PeerConn) setNumPieces(num pieceIndex) {
293 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
294 cn.peerPiecesChanged()
297 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
298 return &cn._peerPieces
301 func eventAgeString(t time.Time) string {
305 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
308 func (cn *PeerConn) connectionFlags() (ret string) {
310 ret += string([]byte{b})
312 if cn.cryptoMethod == mse.CryptoMethodRC4 {
314 } else if cn.headerEncrypted {
317 ret += string(cn.Discovery)
324 func (cn *PeerConn) utp() bool {
325 return parseNetworkString(cn.Network).Udp
328 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
329 func (cn *Peer) statusFlags() (ret string) {
331 ret += string([]byte{b})
333 if cn.requestState.Interested {
340 ret += cn.connectionFlags()
342 if cn.peerInterested {
351 func (cn *Peer) downloadRate() float64 {
352 num := cn._stats.BytesReadUsefulData.Int64()
356 return float64(num) / cn.totalExpectingTime().Seconds()
359 func (cn *Peer) DownloadRate() float64 {
361 defer cn.locker().RUnlock()
363 return cn.downloadRate()
366 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
367 var last Option[pieceIndex]
369 next := func(item Option[pieceIndex]) {
380 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
381 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
384 next(None[pieceIndex]())
387 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
388 // \t isn't preserved in <pre> blocks?
389 if cn.closed.IsSet() {
390 fmt.Fprint(w, "CLOSED: ")
392 fmt.Fprintln(w, cn.connStatusString())
393 prio, err := cn.peerPriority()
394 prioStr := fmt.Sprintf("%08x", prio)
396 prioStr += ": " + err.Error()
398 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
399 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
400 eventAgeString(cn.lastMessageReceived),
401 eventAgeString(cn.completedHandshake),
402 eventAgeString(cn.lastHelpful()),
404 cn.totalExpectingTime(),
407 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
408 cn.completedString(),
409 len(cn.peerTouchedPieces),
410 &cn._stats.ChunksReadUseful,
411 &cn._stats.ChunksRead,
412 &cn._stats.ChunksWritten,
413 cn.requestState.Requests.GetCardinality(),
414 cn.requestState.Cancelled.GetCardinality(),
415 cn.nominalMaxRequests(),
417 len(cn.peerRequests),
420 cn.downloadRate()/(1<<10),
422 fmt.Fprintf(w, " requested pieces:")
423 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
424 fmt.Fprintf(w, " %v(%v)", piece, count)
429 func (p *Peer) close() {
433 if p.updateRequestsTimer != nil {
434 p.updateRequestsTimer.Stop()
438 p.t.decPeerPieceAvailability(p)
440 for _, f := range p.callbacks.PeerClosed {
445 func (cn *PeerConn) onClose() {
446 if cn.pex.IsEnabled() {
453 if cb := cn.callbacks.PeerConnClosed; cb != nil {
458 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
459 // they do (known=true).
460 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
461 if all, known := cn.peerHasAllPieces(); all && known {
464 return cn.peerPieces().ContainsInt(piece)
467 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
468 // https://github.com/pion/datachannel/issues/59 is fixed.
470 writeBufferHighWaterLen = 1 << 15
471 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
474 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
475 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
476 func (cn *PeerConn) write(msg pp.Message) bool {
477 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
478 // We don't need to track bytes here because the connection's Writer has that behaviour injected
479 // (although there's some delay between us buffering the message, and the connection writer
480 // flushing it out.).
481 notFull := cn.messageWriter.write(msg)
482 // Last I checked only Piece messages affect stats, and we don't write those.
488 func (cn *PeerConn) requestMetadataPiece(index int) {
489 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
490 if eID == pp.ExtensionDeleteNumber {
493 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
496 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
497 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
498 for index >= len(cn.metadataRequests) {
499 cn.metadataRequests = append(cn.metadataRequests, false)
501 cn.metadataRequests[index] = true
504 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
505 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
509 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
510 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
511 // This is the maximum request count that could fit in the write buffer if it's at or below the
512 // low water mark when we run maybeUpdateActualRequestState.
513 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
516 // The actual value to use as the maximum outbound requests.
517 func (cn *Peer) nominalMaxRequests() maxRequests {
518 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
521 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
522 ret = cn.cumulativeExpectedToReceiveChunks
523 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
524 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
529 func (cn *PeerConn) onPeerSentCancel(r Request) {
530 if _, ok := cn.peerRequests[r]; !ok {
531 torrent.Add("unexpected cancels received", 1)
534 if cn.fastEnabled() {
537 delete(cn.peerRequests, r)
541 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
546 more = msg(pp.Message{
549 if !cn.fastEnabled() {
550 cn.peerRequests = nil
555 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
560 return msg(pp.Message{
565 func (cn *Peer) setInterested(interested bool) bool {
566 if cn.requestState.Interested == interested {
569 cn.requestState.Interested = interested
571 cn.lastBecameInterested = time.Now()
572 } else if !cn.lastBecameInterested.IsZero() {
573 cn.priorInterest += time.Since(cn.lastBecameInterested)
575 cn.updateExpectingChunks()
576 // log.Printf("%p: setting interest: %v", cn, interested)
577 return cn.writeInterested(interested)
580 func (pc *PeerConn) writeInterested(interested bool) bool {
581 return pc.write(pp.Message{
582 Type: func() pp.MessageType {
586 return pp.NotInterested
592 // The function takes a message to be sent, and returns true if more messages
594 type messageWriter func(pp.Message) bool
596 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
597 // when we want to go fast.
598 func (cn *Peer) shouldRequest(r RequestIndex) error {
599 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
603 pi := cn.t.pieceIndexOfRequestIndex(r)
604 if cn.requestState.Cancelled.Contains(r) {
605 return errors.New("request is cancelled and waiting acknowledgement")
607 if !cn.peerHasPiece(pi) {
608 return errors.New("requesting piece peer doesn't have")
610 if !cn.t.peerIsActive(cn) {
611 panic("requesting but not in active conns")
613 if cn.closed.IsSet() {
614 panic("requesting when connection is closed")
616 if cn.t.hashingPiece(pi) {
617 panic("piece is being hashed")
619 if cn.t.pieceQueuedForHash(pi) {
620 panic("piece is queued for hash")
622 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
623 // This could occur if we made a request with the fast extension, and then got choked and
624 // haven't had the request rejected yet.
625 if !cn.requestState.Requests.Contains(r) {
626 panic("peer choking and piece not allowed fast")
632 func (cn *Peer) mustRequest(r RequestIndex) bool {
633 more, err := cn.request(r)
640 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
641 if err := cn.shouldRequest(r); err != nil {
644 if cn.requestState.Requests.Contains(r) {
647 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
648 return true, errors.New("too many outstanding requests")
650 cn.requestState.Requests.Add(r)
651 if cn.validReceiveChunks == nil {
652 cn.validReceiveChunks = make(map[RequestIndex]int)
654 cn.validReceiveChunks[r]++
655 cn.t.requestState[r] = requestState{
659 cn.updateExpectingChunks()
660 ppReq := cn.t.requestIndexToRequest(r)
661 for _, f := range cn.callbacks.SentRequest {
662 f(PeerRequestEvent{cn, ppReq})
664 return cn.peerImpl._request(ppReq), nil
667 func (me *PeerConn) _request(r Request) bool {
668 return me.write(pp.Message{
676 func (me *Peer) cancel(r RequestIndex) {
677 if !me.deleteRequest(r) {
678 panic("request not existing should have been guarded")
681 if !me.requestState.Cancelled.CheckedAdd(r) {
682 panic("request already cancelled")
686 if me.isLowOnRequests() {
687 me.updateRequests("Peer.cancel")
691 func (me *PeerConn) _cancel(r RequestIndex) bool {
692 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
693 // Transmission does not send rejects for received cancels. See
694 // https://github.com/transmission/transmission/pull/2275.
695 return me.fastEnabled() && !me.remoteIsTransmission()
698 func (cn *PeerConn) fillWriteBuffer() {
699 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
700 // Fully committing to our max requests requires sufficient space (see
701 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
702 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
703 // request reason will not be cleared, so we'll come right back here when there's space. We
704 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
705 // knowledge of write buffers.
707 cn.maybeUpdateActualRequestState()
708 if cn.pex.IsEnabled() {
709 if flow := cn.pex.Share(cn.write); !flow {
716 func (cn *PeerConn) have(piece pieceIndex) {
717 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
722 Index: pp.Integer(piece),
724 cn.sentHaves.Add(bitmap.BitIndex(piece))
727 func (cn *PeerConn) postBitfield() {
728 if cn.sentHaves.Len() != 0 {
729 panic("bitfield must be first have-related message sent")
731 if !cn.t.haveAnyPieces() {
736 Bitfield: cn.t.bitfield(),
738 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
741 // Sets a reason to update requests, and if there wasn't already one, handle it.
742 func (cn *Peer) updateRequests(reason string) {
743 if cn.needRequestUpdate != "" {
746 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
749 cn.needRequestUpdate = reason
750 cn.handleUpdateRequests()
753 func (cn *PeerConn) handleUpdateRequests() {
754 // The writer determines the request state as needed when it can write.
758 // Emits the indices in the Bitmaps bms in order, never repeating any index.
759 // skip is mutated during execution, and its initial values will never be
761 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
762 return func(cb iter.Callback) {
763 for _, bm := range bms {
765 func(_i interface{}) bool {
767 if skip.Contains(bitmap.BitIndex(i)) {
770 skip.Add(bitmap.BitIndex(i))
781 func (cn *Peer) peerPiecesChanged() {
782 cn.t.maybeDropMutuallyCompletePeer(cn)
785 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
786 if newMin > cn.peerMinPieces {
787 cn.peerMinPieces = newMin
791 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
792 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
793 return errors.New("invalid piece")
795 if cn.peerHasPiece(piece) {
798 cn.raisePeerMinPieces(piece + 1)
799 if !cn.peerHasPiece(piece) {
800 cn.t.incPieceAvailability(piece)
802 cn._peerPieces.Add(uint32(piece))
803 if cn.t.wantPieceIndex(piece) {
804 cn.updateRequests("have")
806 cn.peerPiecesChanged()
810 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
812 panic("expected bitfield length divisible by 8")
814 // We know that the last byte means that at most the last 7 bits are wasted.
815 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
816 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
817 // Ignore known excess pieces.
818 bf = bf[:cn.t.numPieces()]
820 bm := boolSliceToBitmap(bf)
821 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
822 cn.onPeerHasAllPieces()
826 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
828 shouldUpdateRequests := false
829 if cn.peerSentHaveAll {
830 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
833 cn.peerSentHaveAll = false
834 if !cn._peerPieces.IsEmpty() {
835 panic("if peer has all, we expect no individual peer pieces to be set")
838 bm.Xor(&cn._peerPieces)
840 cn.peerSentHaveAll = false
841 // bm is now 'on' for pieces that are changing
842 bm.Iterate(func(x uint32) bool {
844 if cn._peerPieces.Contains(x) {
845 // Then we must be losing this piece
846 cn.t.decPieceAvailability(pi)
848 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
849 shouldUpdateRequests = true
851 // We must be gaining this piece
852 cn.t.incPieceAvailability(pieceIndex(x))
856 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
858 cn._peerPieces.Xor(&bm)
859 if shouldUpdateRequests {
860 cn.updateRequests("bitfield")
862 // We didn't guard this before, I see no reason to do it now.
863 cn.peerPiecesChanged()
867 func (cn *PeerConn) onPeerHasAllPieces() {
870 cn._peerPieces.Iterate(func(x uint32) bool {
871 t.decPieceAvailability(pieceIndex(x))
875 t.addConnWithAllPieces(&cn.Peer)
876 cn.peerSentHaveAll = true
877 cn._peerPieces.Clear()
878 if !cn.t._pendingPieces.IsEmpty() {
879 cn.updateRequests("Peer.onPeerHasAllPieces")
881 cn.peerPiecesChanged()
884 func (cn *PeerConn) onPeerSentHaveAll() error {
885 cn.onPeerHasAllPieces()
889 func (cn *PeerConn) peerSentHaveNone() error {
890 if cn.peerSentHaveAll {
891 cn.t.decPeerPieceAvailability(&cn.Peer)
893 cn._peerPieces.Clear()
894 cn.peerSentHaveAll = false
895 cn.peerPiecesChanged()
899 func (c *PeerConn) requestPendingMetadata() {
903 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
904 // Peer doesn't support this.
907 // Request metadata pieces that we don't have in a random order.
909 for index := 0; index < c.t.metadataPieceCount(); index++ {
910 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
911 pending = append(pending, index)
914 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
915 for _, i := range pending {
916 c.requestMetadataPiece(i)
920 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
921 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
922 if msg.Type == pp.Extended {
923 for name, id := range cn.PeerExtensionIDs {
924 if id != msg.ExtendedID {
927 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
930 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
933 // After handshake, we know what Torrent and Client stats to include for a
935 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
941 // All ConnStats that include this connection. Some objects are not known
942 // until the handshake is complete, after which it's expected to reconcile the
944 func (cn *Peer) allStats(f func(*ConnStats)) {
946 if cn.reconciledHandshakeStats {
947 cn.postHandshakeStats(f)
951 func (cn *PeerConn) wroteBytes(n int64) {
952 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
955 func (cn *Peer) readBytes(n int64) {
956 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
959 // Returns whether the connection could be useful to us. We're seeding and
960 // they want data, we don't have metainfo and they can provide it, etc.
961 func (c *Peer) useful() bool {
963 if c.closed.IsSet() {
967 return c.supportsExtension("ut_metadata")
969 if t.seeding() && c.peerInterested {
972 if c.peerHasWantedPieces() {
978 func (c *Peer) lastHelpful() (ret time.Time) {
979 ret = c.lastUsefulChunkReceived
980 if c.t.seeding() && c.lastChunkSent.After(ret) {
981 ret = c.lastChunkSent
986 func (c *PeerConn) fastEnabled() bool {
987 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
990 func (c *PeerConn) reject(r Request) {
991 if !c.fastEnabled() {
992 panic("fast not enabled")
994 c.write(r.ToMsg(pp.Reject))
995 delete(c.peerRequests, r)
998 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
999 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
1000 if uploadRateLimiter.Limit() == rate.Inf {
1003 return Some(uploadRateLimiter.Burst())
1006 // startFetch is for testing purposes currently.
1007 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
1008 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1009 if _, ok := c.peerRequests[r]; ok {
1010 torrent.Add("duplicate requests received", 1)
1011 if c.fastEnabled() {
1012 return errors.New("received duplicate request with fast enabled")
1017 torrent.Add("requests received while choking", 1)
1018 if c.fastEnabled() {
1019 torrent.Add("requests rejected while choking", 1)
1024 // TODO: What if they've already requested this?
1025 if len(c.peerRequests) >= localClientReqq {
1026 torrent.Add("requests received while queue full", 1)
1027 if c.fastEnabled() {
1030 // BEP 6 says we may close here if we choose.
1033 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
1034 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
1035 c.logger.Levelf(log.Warning, err.Error())
1036 if c.fastEnabled() {
1043 if !c.t.havePiece(pieceIndex(r.Index)) {
1044 // TODO: Tell the peer we don't have the piece, and reject this request.
1045 requestsReceivedForMissingPieces.Add(1)
1046 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1048 // Check this after we know we have the piece, so that the piece length will be known.
1049 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1050 torrent.Add("bad requests received", 1)
1051 return errors.New("bad Request")
1053 if c.peerRequests == nil {
1054 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1056 value := &peerRequestState{}
1057 c.peerRequests[r] = value
1059 // TODO: Limit peer request data read concurrency.
1060 go c.peerRequestDataReader(r, value)
1065 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1066 b, err := readPeerRequestData(r, c)
1068 defer c.locker().Unlock()
1070 c.peerRequestDataReadFailed(err, r)
1073 panic("data must be non-nil to trigger send")
1075 torrent.Add("peer request data read successes", 1)
1077 // This might be required for the error case too (#752 and #753).
1082 // If this is maintained correctly, we might be able to support optional synchronous reading for
1083 // chunk sending, the way it used to work.
1084 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1085 torrent.Add("peer request data read failures", 1)
1086 logLevel := log.Warning
1087 if c.t.hasStorageCap() {
1088 // It's expected that pieces might drop. See
1089 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1090 logLevel = log.Debug
1092 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1093 if c.t.closed.IsSet() {
1096 i := pieceIndex(r.Index)
1097 if c.t.pieceComplete(i) {
1098 // There used to be more code here that just duplicated the following break. Piece
1099 // completions are currently cached, so I'm not sure how helpful this update is, except to
1100 // pull any completion changes pushed to the storage backend in failed reads that got us
1102 c.t.updatePieceCompletion(i)
1104 // We've probably dropped a piece from storage, but there's no way to communicate this to the
1105 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1106 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1107 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1109 if c.fastEnabled() {
1113 // If fast isn't enabled, I think we would have wiped all peer requests when we last
1114 // choked, and requests while we're choking would be ignored. It could be possible that
1115 // a peer request data read completed concurrently to it being deleted elsewhere.
1116 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1118 // Choking a non-fast peer should cause them to flush all their requests.
1123 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1124 b := make([]byte, r.Length)
1125 p := c.t.info.Piece(int(r.Index))
1126 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1133 panic("expected error")
1139 func runSafeExtraneous(f func()) {
1147 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1148 c.logger.WithContextText(fmt.Sprintf(
1149 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1150 )).SkipCallers(1).Levelf(level, format, arg...)
1153 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1154 // exit. Returning will end the connection.
1155 func (c *PeerConn) mainReadLoop() (err error) {
1158 torrent.Add("connection.mainReadLoop returned with error", 1)
1160 torrent.Add("connection.mainReadLoop returned with no error", 1)
1166 decoder := pp.Decoder{
1167 R: bufio.NewReaderSize(c.r, 1<<17),
1168 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1176 err = decoder.Decode(&msg)
1178 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1181 if t.closed.IsSet() || c.closed.IsSet() {
1187 c.lastMessageReceived = time.Now()
1189 receivedKeepalives.Add(1)
1192 messageTypesReceived.Add(msg.Type.String(), 1)
1193 if msg.Type.FastExtension() && !c.fastEnabled() {
1194 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1195 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1202 if !c.fastEnabled() {
1203 c.deleteAllRequests("choked by non-fast PeerConn")
1205 // We don't decrement pending requests here, let's wait for the peer to either
1206 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1207 // us and resume where they left off, we don't want to have piled on to those chunks
1208 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1209 // could let us request a lot of stuff, then choke us and never reject, but they're
1210 // only a single peer, our chunk balancing should smooth over this abuse.
1212 c.peerChoking = true
1213 c.updateExpectingChunks()
1216 // Some clients do this for some reason. Transmission doesn't error on this, so we
1217 // won't for consistency.
1218 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1221 c.peerChoking = false
1223 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1224 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1229 if preservedCount != 0 {
1230 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1232 c.logger.Levelf(log.Debug,
1233 "%v requests were preserved while being choked (fast=%v)",
1237 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1239 if !c.t._pendingPieces.IsEmpty() {
1240 c.updateRequests("unchoked")
1242 c.updateExpectingChunks()
1244 c.peerInterested = true
1246 case pp.NotInterested:
1247 c.peerInterested = false
1248 // We don't clear their requests since it isn't clear in the spec.
1249 // We'll probably choke them for this, which will clear them if
1250 // appropriate, and is clearly specified.
1252 err = c.peerSentHave(pieceIndex(msg.Index))
1254 err = c.peerSentBitfield(msg.Bitfield)
1256 r := newRequestFromMessage(&msg)
1257 err = c.onReadRequest(r, true)
1259 c.doChunkReadStats(int64(len(msg.Piece)))
1260 err = c.receiveChunk(&msg)
1261 if len(msg.Piece) == int(t.chunkSize) {
1262 t.chunkPool.Put(&msg.Piece)
1265 err = fmt.Errorf("receiving chunk: %w", err)
1268 req := newRequestFromMessage(&msg)
1269 c.onPeerSentCancel(req)
1271 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1275 pingAddr := net.UDPAddr{
1280 pingAddr.Port = int(msg.Port)
1282 cl.eachDhtServer(func(s DhtServer) {
1283 go s.Ping(&pingAddr)
1286 torrent.Add("suggests received", 1)
1287 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1288 c.updateRequests("suggested")
1290 err = c.onPeerSentHaveAll()
1292 err = c.peerSentHaveNone()
1294 req := newRequestFromMessage(&msg)
1295 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1296 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1297 err = fmt.Errorf("received invalid reject [request=%v]", req)
1299 case pp.AllowedFast:
1300 torrent.Add("allowed fasts received", 1)
1301 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1302 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1304 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1306 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1314 // Returns true if it was valid to reject the request.
1315 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1316 if c.deleteRequest(r) {
1318 } else if !c.requestState.Cancelled.CheckedRemove(r) {
1321 if c.isLowOnRequests() {
1322 c.updateRequests("Peer.remoteRejectedRequest")
1324 c.decExpectedChunkReceive(r)
1328 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1329 count := c.validReceiveChunks[r]
1331 delete(c.validReceiveChunks, r)
1332 } else if count > 1 {
1333 c.validReceiveChunks[r] = count - 1
1339 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1341 // TODO: Should we still do this?
1343 // These clients use their own extension IDs for outgoing message
1344 // types, which is incorrect.
1345 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1353 case pp.HandshakeExtendedID:
1354 var d pp.ExtendedHandshakeMessage
1355 if err := bencode.Unmarshal(payload, &d); err != nil {
1356 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1357 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1359 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1362 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1364 c.PeerMaxRequests = d.Reqq
1366 c.PeerClientName.Store(d.V)
1367 if c.PeerExtensionIDs == nil {
1368 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1370 c.PeerListenPort = d.Port
1371 c.PeerPrefersEncryption = d.Encryption
1372 for name, id := range d.M {
1373 if _, ok := c.PeerExtensionIDs[name]; !ok {
1374 peersSupportingExtension.Add(
1375 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1376 // entered here which caused problems later when unmarshalling.
1377 strconv.Quote(string(name)),
1380 c.PeerExtensionIDs[name] = id
1382 if d.MetadataSize != 0 {
1383 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1384 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1387 c.requestPendingMetadata()
1388 if !t.cl.config.DisablePEX {
1389 t.pex.Add(c) // we learnt enough now
1393 case metadataExtendedId:
1394 err := cl.gotMetadataExtensionMsg(payload, t, c)
1396 return fmt.Errorf("handling metadata extension message: %w", err)
1400 if !c.pex.IsEnabled() {
1401 return nil // or hang-up maybe?
1403 return c.pex.Recv(payload)
1405 return fmt.Errorf("unexpected extended message ID: %v", id)
1409 // Set both the Reader and Writer for the connection from a single ReadWriter.
1410 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1415 // Returns the Reader and Writer as a combined ReadWriter.
1416 func (cn *PeerConn) rw() io.ReadWriter {
1423 func (c *Peer) doChunkReadStats(size int64) {
1424 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1427 // Handle a received chunk from a peer.
1428 func (c *Peer) receiveChunk(msg *pp.Message) error {
1429 chunksReceived.Add("total", 1)
1431 ppReq := newRequestFromMessage(msg)
1433 err := t.checkValidReceiveChunk(ppReq)
1435 err = log.WithLevel(log.Warning, err)
1438 req := c.t.requestIndexFromRequest(ppReq)
1440 if c.bannableAddr.Ok {
1441 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
1445 chunksReceived.Add("while choked", 1)
1448 if c.validReceiveChunks[req] <= 0 {
1449 chunksReceived.Add("unexpected", 1)
1450 return errors.New("received unexpected chunk")
1452 c.decExpectedChunkReceive(req)
1454 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1455 chunksReceived.Add("due to allowed fast", 1)
1458 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1459 // have actually already received the piece, while we have the Client unlocked to write the data
1463 if c.requestState.Requests.Contains(req) {
1464 for _, f := range c.callbacks.ReceivedRequested {
1465 f(PeerMessageEvent{c, msg})
1468 // Request has been satisfied.
1469 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1472 c._chunksReceivedWhileExpecting++
1474 if c.isLowOnRequests() {
1475 c.updateRequests("Peer.receiveChunk deleted request")
1478 chunksReceived.Add("unintended", 1)
1484 // Do we actually want this chunk?
1485 if t.haveChunk(ppReq) {
1486 // panic(fmt.Sprintf("%+v", ppReq))
1487 chunksReceived.Add("redundant", 1)
1488 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1492 piece := &t.pieces[ppReq.Index]
1494 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1495 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1497 c.piecesReceivedSinceLastRequestUpdate++
1498 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1500 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1501 f(ReceivedUsefulDataEvent{c, msg})
1503 c.lastUsefulChunkReceived = time.Now()
1505 // Need to record that it hasn't been written yet, before we attempt to do
1506 // anything with it.
1507 piece.incrementPendingWrites()
1508 // Record that we have the chunk, so we aren't trying to download it while
1509 // waiting for it to be written to storage.
1510 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1512 // Cancel pending requests for this chunk from *other* peers.
1513 if p := t.requestingPeer(req); p != nil {
1515 panic("should not be pending request from conn that just received it")
1520 err = func() error {
1523 concurrentChunkWrites.Add(1)
1524 defer concurrentChunkWrites.Add(-1)
1525 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1526 // number of connections. We write inline with receiving the chunk (with this lock dance),
1527 // because we want to handle errors synchronously and I haven't thought of a nice way to
1528 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1530 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1533 piece.decrementPendingWrites()
1536 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1538 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1539 // request update runs while we're writing the chunk that just failed. Then we never do a
1540 // fresh update after pending the failed request.
1541 c.updateRequests("Peer.receiveChunk error writing chunk")
1542 t.onWriteChunkErr(err)
1546 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1548 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1549 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1550 t.queuePieceCheck(pieceIndex(ppReq.Index))
1551 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1552 // chunk status (such as the haveChunk call above) to have to check all the various other
1553 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1554 // that chunk pieces are pended at an appropriate time later however.
1557 cl.event.Broadcast()
1558 // We do this because we've written a chunk, and may change PieceState.Partial.
1559 t.publishPieceChange(pieceIndex(ppReq.Index))
1564 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1565 if c.peerTouchedPieces == nil {
1566 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1568 c.peerTouchedPieces[piece] = struct{}{}
1569 ds := &c.t.pieces[piece].dirtiers
1571 *ds = make(map[*Peer]struct{})
1573 (*ds)[c] = struct{}{}
1576 func (c *PeerConn) uploadAllowed() bool {
1577 if c.t.cl.config.NoUpload {
1580 if c.t.dataUploadDisallowed {
1586 if !c.peerHasWantedPieces() {
1589 // Don't upload more than 100 KiB more than we download.
1590 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1596 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1597 if c.uploadTimer == nil {
1598 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1600 c.uploadTimer.Reset(delay)
1604 // Also handles choking and unchoking of the remote peer.
1605 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1606 // Breaking or completing this loop means we don't want to upload to the
1607 // peer anymore, and we choke them.
1609 for c.uploadAllowed() {
1610 // We want to upload to the peer.
1611 if !c.unchoke(msg) {
1614 for r, state := range c.peerRequests {
1615 if state.data == nil {
1618 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1620 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1622 delay := res.Delay()
1625 c.setRetryUploadTimer(delay)
1626 // Hard to say what to return here.
1629 more := c.sendChunk(r, msg, state)
1630 delete(c.peerRequests, r)
1641 func (cn *PeerConn) drop() {
1642 cn.t.dropConnection(cn)
1645 func (cn *PeerConn) ban() {
1646 cn.t.cl.banPeerIP(cn.remoteIp())
1649 func (cn *Peer) netGoodPiecesDirtied() int64 {
1650 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1653 func (c *Peer) peerHasWantedPieces() bool {
1654 if all, _ := c.peerHasAllPieces(); all {
1655 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1657 if !c.t.haveInfo() {
1658 return !c.peerPieces().IsEmpty()
1660 return c.peerPieces().Intersects(&c.t._pendingPieces)
1663 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1665 func (c *Peer) deleteRequest(r RequestIndex) bool {
1666 if !c.requestState.Requests.CheckedRemove(r) {
1669 for _, f := range c.callbacks.DeletedRequest {
1670 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1672 c.updateExpectingChunks()
1673 if c.t.requestingPeer(r) != c {
1674 panic("only one peer should have a given request at a time")
1676 delete(c.t.requestState, r)
1677 // c.t.iterPeers(func(p *Peer) {
1678 // if p.isLowOnRequests() {
1679 // p.updateRequests("Peer.deleteRequest")
1685 func (c *Peer) deleteAllRequests(reason string) {
1686 if c.requestState.Requests.IsEmpty() {
1689 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1690 if !c.deleteRequest(x) {
1691 panic("request should exist")
1695 c.assertNoRequests()
1696 c.t.iterPeers(func(p *Peer) {
1697 if p.isLowOnRequests() {
1698 p.updateRequests(reason)
1704 func (c *Peer) assertNoRequests() {
1705 if !c.requestState.Requests.IsEmpty() {
1706 panic(c.requestState.Requests.GetCardinality())
1710 func (c *Peer) cancelAllRequests() {
1711 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1715 c.assertNoRequests()
1719 // This is called when something has changed that should wake the writer, such as putting stuff into
1720 // the writeBuffer, or changing some state that the writer can act on.
1721 func (c *PeerConn) tickleWriter() {
1722 c.messageWriter.writeCond.Broadcast()
1725 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1726 c.lastChunkSent = time.Now()
1727 return msg(pp.Message{
1735 func (c *PeerConn) setTorrent(t *Torrent) {
1737 panic("connection already associated with a torrent")
1740 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1741 t.reconcileHandshakeStats(c)
1744 func (c *Peer) peerPriority() (peerPriority, error) {
1745 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
1748 func (c *Peer) remoteIp() net.IP {
1749 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1750 return net.ParseIP(host)
1753 func (c *Peer) remoteIpPort() IpPort {
1754 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1755 return IpPort{ipa.IP, uint16(ipa.Port)}
1758 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1759 f := pp.PexPeerFlags(0)
1760 if c.PeerPrefersEncryption {
1761 f |= pp.PexPrefersEncryption
1764 f |= pp.PexOutgoingConn
1767 f |= pp.PexSupportsUtp
1772 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1773 // advertised listen port.
1774 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1775 if !c.outgoing && c.PeerListenPort != 0 {
1776 switch addr := c.RemoteAddr.(type) {
1779 dialAddr.Port = c.PeerListenPort
1783 dialAddr.Port = c.PeerListenPort
1790 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1791 f := c.pexPeerFlags()
1792 addr := c.dialAddr()
1793 return pexEvent{t, addr, f, nil}
1796 func (c *PeerConn) String() string {
1797 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1800 func (c *Peer) trust() connectionTrust {
1801 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1804 type connectionTrust struct {
1806 NetGoodPiecesDirted int64
1809 func (l connectionTrust) Less(r connectionTrust) bool {
1810 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1813 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1814 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1815 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1817 defer cn.locker().RUnlock()
1818 return cn.newPeerPieces()
1821 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1822 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1823 // TODO: Can we use copy on write?
1824 ret := cn.peerPieces().Clone()
1825 if all, _ := cn.peerHasAllPieces(); all {
1826 if cn.t.haveInfo() {
1827 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1829 ret.AddRange(0, bitmap.ToEnd)
1835 func (cn *Peer) stats() *ConnStats {
1839 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1840 pc, ok := p.peerImpl.(*PeerConn)
1844 func (p *Peer) uncancelledRequests() uint64 {
1845 return p.requestState.Requests.GetCardinality()
1848 func (pc *PeerConn) remoteIsTransmission() bool {
1849 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'