17 "github.com/RoaringBitmap/roaring"
18 "github.com/anacrolix/chansync"
19 . "github.com/anacrolix/generics"
20 "github.com/anacrolix/log"
21 "github.com/anacrolix/missinggo/iter"
22 "github.com/anacrolix/missinggo/v2/bitmap"
23 "github.com/anacrolix/multiless"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/metainfo"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
28 request_strategy "github.com/anacrolix/torrent/request-strategy"
29 "github.com/anacrolix/torrent/typed-roaring"
32 type PeerSource string
35 PeerSourceTracker = "Tr"
36 PeerSourceIncoming = "I"
37 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
38 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
40 // The peer was given directly, such as through a magnet link.
41 PeerSourceDirect = "M"
44 type peerRequestState struct {
48 type PeerRemoteAddr interface {
52 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
53 // indexable with the memory space available.
56 requestState = request_strategy.PeerRequestState
60 // First to ensure 64-bit alignment for atomics. See #262.
70 RemoteAddr PeerRemoteAddr
71 bannableAddr Option[bannableAddr]
72 // True if the connection is operating over MSE obfuscation.
74 cryptoMethod mse.CryptoMethod
77 closed chansync.SetOnce
78 // Set true after we've added our ConnStats generated during handshake to
79 // other ConnStat instances as determined when the *Torrent became known.
80 reconciledHandshakeStats bool
82 lastMessageReceived time.Time
83 completedHandshake time.Time
84 lastUsefulChunkReceived time.Time
85 lastChunkSent time.Time
87 // Stuff controlled by the local peer.
88 needRequestUpdate string
89 requestState requestState
90 updateRequestsTimer *time.Timer
91 lastRequestUpdate time.Time
92 peakRequests maxRequests
93 lastBecameInterested time.Time
94 priorInterest time.Duration
96 lastStartedExpectingToReceiveChunks time.Time
97 cumulativeExpectedToReceiveChunks time.Duration
98 _chunksReceivedWhileExpecting int64
101 piecesReceivedSinceLastRequestUpdate maxRequests
102 maxPiecesReceivedBetweenRequestUpdates maxRequests
103 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
104 // and implementation differences, we may receive chunks that are no longer in the set of
105 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
106 validReceiveChunks map[RequestIndex]int
107 // Indexed by metadata piece, set to true if posted and pending a
109 metadataRequests []bool
110 sentHaves bitmap.Bitmap
112 // Stuff controlled by the remote peer.
115 peerRequests map[Request]*peerRequestState
116 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
118 // The highest possible number of pieces the torrent could have based on
119 // communication with the peer. Generally only useful until we have the
121 peerMinPieces pieceIndex
122 // Pieces we've accepted chunks for from the peer.
123 peerTouchedPieces map[pieceIndex]struct{}
124 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
126 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
127 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
128 PeerClientName atomic.Value
133 type peerRequests struct {
134 typedRoaring.Bitmap[RequestIndex]
137 func (p *peerRequests) IterateSnapshot(f func(request_strategy.RequestIndex) bool) {
141 func (p *Peer) initRequestState() {
142 p.requestState.Requests = &peerRequests{}
145 // Maintains the state of a BitTorrent-protocol based connection with a peer.
146 type PeerConn struct {
149 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
150 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
155 PeerExtensionBytes pp.PeerExtensionBits
157 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
158 // while holding any mutexes.
160 // The Reader and Writer for this Conn, with hooks installed for stats,
161 // limiting, deadlines etc.
165 messageWriter peerConnMsgWriter
167 uploadTimer *time.Timer
170 // The pieces the peer has claimed to have.
171 _peerPieces roaring.Bitmap
172 // The peer has everything. This can occur due to a special message, when
173 // we may not even know the number of pieces in the torrent yet.
177 func (cn *PeerConn) connStatusString() string {
178 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
181 func (cn *Peer) updateExpectingChunks() {
182 if cn.expectingChunks() {
183 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
184 cn.lastStartedExpectingToReceiveChunks = time.Now()
187 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
188 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
189 cn.lastStartedExpectingToReceiveChunks = time.Time{}
194 func (cn *Peer) expectingChunks() bool {
195 if cn.requestState.Requests.IsEmpty() {
198 if !cn.requestState.Interested {
204 haveAllowedFastRequests := false
205 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
206 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
207 cn.requestState.Requests,
208 cn.t.pieceRequestIndexOffset(i),
209 cn.t.pieceRequestIndexOffset(i+1),
211 return !haveAllowedFastRequests
213 return haveAllowedFastRequests
216 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
217 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
220 // Returns true if the connection is over IPv6.
221 func (cn *PeerConn) ipv6() bool {
226 return len(ip) == net.IPv6len
229 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
230 // specification for this.
231 func (cn *PeerConn) isPreferredDirection() bool {
232 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
235 // Returns whether the left connection should be preferred over the right one,
236 // considering only their networking properties. If ok is false, we can't
238 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
239 var ml multiless.Computation
240 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
241 ml = ml.Bool(l.utp(), r.utp())
242 ml = ml.Bool(r.ipv6(), l.ipv6())
246 func (cn *Peer) cumInterest() time.Duration {
247 ret := cn.priorInterest
248 if cn.requestState.Interested {
249 ret += time.Since(cn.lastBecameInterested)
254 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
255 if cn.peerSentHaveAll {
258 if !cn.t.haveInfo() {
261 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
264 func (cn *Peer) locker() *lockWithDeferreds {
265 return cn.t.cl.locker()
268 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
269 _, ok := cn.PeerExtensionIDs[ext]
273 // The best guess at number of pieces in the torrent for this peer.
274 func (cn *Peer) bestPeerNumPieces() pieceIndex {
276 return cn.t.numPieces()
278 return cn.peerMinPieces
281 func (cn *Peer) completedString() string {
282 have := pieceIndex(cn.peerPieces().GetCardinality())
283 if all, _ := cn.peerHasAllPieces(); all {
284 have = cn.bestPeerNumPieces()
286 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
289 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
290 cn.setNumPieces(info.NumPieces())
293 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
294 // receiving badly sized BITFIELD, or invalid HAVE messages.
295 func (cn *PeerConn) setNumPieces(num pieceIndex) {
296 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
297 cn.peerPiecesChanged()
300 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
301 return &cn._peerPieces
304 func eventAgeString(t time.Time) string {
308 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
311 func (cn *PeerConn) connectionFlags() (ret string) {
313 ret += string([]byte{b})
315 if cn.cryptoMethod == mse.CryptoMethodRC4 {
317 } else if cn.headerEncrypted {
320 ret += string(cn.Discovery)
327 func (cn *PeerConn) utp() bool {
328 return parseNetworkString(cn.Network).Udp
331 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
332 func (cn *Peer) statusFlags() (ret string) {
334 ret += string([]byte{b})
336 if cn.requestState.Interested {
343 ret += cn.connectionFlags()
345 if cn.peerInterested {
354 func (cn *Peer) downloadRate() float64 {
355 num := cn._stats.BytesReadUsefulData.Int64()
359 return float64(num) / cn.totalExpectingTime().Seconds()
362 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
363 ret = make(map[pieceIndex]int)
364 cn.requestState.Requests.Iterate(func(x RequestIndex) bool {
365 ret[cn.t.pieceIndexOfRequestIndex(x)]++
371 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
372 // \t isn't preserved in <pre> blocks?
373 if cn.closed.IsSet() {
374 fmt.Fprint(w, "CLOSED: ")
376 fmt.Fprintln(w, cn.connStatusString())
377 prio, err := cn.peerPriority()
378 prioStr := fmt.Sprintf("%08x", prio)
380 prioStr += ": " + err.Error()
382 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
383 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
384 eventAgeString(cn.lastMessageReceived),
385 eventAgeString(cn.completedHandshake),
386 eventAgeString(cn.lastHelpful()),
388 cn.totalExpectingTime(),
391 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
392 cn.completedString(),
393 len(cn.peerTouchedPieces),
394 &cn._stats.ChunksReadUseful,
395 &cn._stats.ChunksRead,
396 &cn._stats.ChunksWritten,
397 cn.requestState.Requests.GetCardinality(),
398 cn.requestState.Cancelled.GetCardinality(),
399 cn.nominalMaxRequests(),
401 len(cn.peerRequests),
404 cn.downloadRate()/(1<<10),
406 fmt.Fprintf(w, " requested pieces:")
407 type pieceNumRequestsType struct {
411 var pieceNumRequests []pieceNumRequestsType
412 for piece, count := range cn.numRequestsByPiece() {
413 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
415 sort.Slice(pieceNumRequests, func(i, j int) bool {
416 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
418 for _, elem := range pieceNumRequests {
419 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
424 func (p *Peer) close() {
428 if p.updateRequestsTimer != nil {
429 p.updateRequestsTimer.Stop()
433 p.t.decPeerPieceAvailability(p)
435 for _, f := range p.callbacks.PeerClosed {
440 func (cn *PeerConn) onClose() {
441 if cn.pex.IsEnabled() {
448 if cb := cn.callbacks.PeerConnClosed; cb != nil {
453 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
454 // they do (known=true).
455 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
456 if all, known := cn.peerHasAllPieces(); all && known {
459 return cn.peerPieces().ContainsInt(piece)
462 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
463 // https://github.com/pion/datachannel/issues/59 is fixed.
465 writeBufferHighWaterLen = 1 << 15
466 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
469 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
470 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
471 func (cn *PeerConn) write(msg pp.Message) bool {
472 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
473 // We don't need to track bytes here because the connection's Writer has that behaviour injected
474 // (although there's some delay between us buffering the message, and the connection writer
475 // flushing it out.).
476 notFull := cn.messageWriter.write(msg)
477 // Last I checked only Piece messages affect stats, and we don't write those.
483 func (cn *PeerConn) requestMetadataPiece(index int) {
484 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
485 if eID == pp.ExtensionDeleteNumber {
488 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
491 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
492 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
493 for index >= len(cn.metadataRequests) {
494 cn.metadataRequests = append(cn.metadataRequests, false)
496 cn.metadataRequests[index] = true
499 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
500 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
504 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
505 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
506 // This is the maximum request count that could fit in the write buffer if it's at or below the
507 // low water mark when we run maybeUpdateActualRequestState.
508 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
511 // The actual value to use as the maximum outbound requests.
512 func (cn *Peer) nominalMaxRequests() maxRequests {
513 return maxRequests(maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests)))
516 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
517 ret = cn.cumulativeExpectedToReceiveChunks
518 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
519 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
524 func (cn *PeerConn) onPeerSentCancel(r Request) {
525 if _, ok := cn.peerRequests[r]; !ok {
526 torrent.Add("unexpected cancels received", 1)
529 if cn.fastEnabled() {
532 delete(cn.peerRequests, r)
536 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
541 more = msg(pp.Message{
544 if !cn.fastEnabled() {
545 cn.peerRequests = nil
550 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
555 return msg(pp.Message{
560 func (cn *Peer) setInterested(interested bool) bool {
561 if cn.requestState.Interested == interested {
564 cn.requestState.Interested = interested
566 cn.lastBecameInterested = time.Now()
567 } else if !cn.lastBecameInterested.IsZero() {
568 cn.priorInterest += time.Since(cn.lastBecameInterested)
570 cn.updateExpectingChunks()
571 // log.Printf("%p: setting interest: %v", cn, interested)
572 return cn.writeInterested(interested)
575 func (pc *PeerConn) writeInterested(interested bool) bool {
576 return pc.write(pp.Message{
577 Type: func() pp.MessageType {
581 return pp.NotInterested
587 // The function takes a message to be sent, and returns true if more messages
589 type messageWriter func(pp.Message) bool
591 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
592 // when we want to go fast.
593 func (cn *Peer) shouldRequest(r RequestIndex) error {
594 pi := cn.t.pieceIndexOfRequestIndex(r)
595 if cn.requestState.Cancelled.Contains(r) {
596 return errors.New("request is cancelled and waiting acknowledgement")
598 if !cn.peerHasPiece(pi) {
599 return errors.New("requesting piece peer doesn't have")
601 if !cn.t.peerIsActive(cn) {
602 panic("requesting but not in active conns")
604 if cn.closed.IsSet() {
605 panic("requesting when connection is closed")
607 if cn.t.hashingPiece(pi) {
608 panic("piece is being hashed")
610 if cn.t.pieceQueuedForHash(pi) {
611 panic("piece is queued for hash")
613 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
614 // This could occur if we made a request with the fast extension, and then got choked and
615 // haven't had the request rejected yet.
616 if !cn.requestState.Requests.Contains(r) {
617 panic("peer choking and piece not allowed fast")
623 func (cn *Peer) mustRequest(r RequestIndex) bool {
624 more, err := cn.request(r)
631 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
632 if err := cn.shouldRequest(r); err != nil {
635 if cn.requestState.Requests.Contains(r) {
638 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
639 return true, errors.New("too many outstanding requests")
641 cn.requestState.Requests.Add(r)
642 if cn.validReceiveChunks == nil {
643 cn.validReceiveChunks = make(map[RequestIndex]int)
645 cn.validReceiveChunks[r]++
646 cn.t.pendingRequests[r] = cn
647 cn.t.lastRequested[r] = time.Now()
648 cn.updateExpectingChunks()
649 ppReq := cn.t.requestIndexToRequest(r)
650 for _, f := range cn.callbacks.SentRequest {
651 f(PeerRequestEvent{cn, ppReq})
653 return cn.peerImpl._request(ppReq), nil
656 func (me *PeerConn) _request(r Request) bool {
657 return me.write(pp.Message{
665 func (me *Peer) cancel(r RequestIndex) {
666 if !me.deleteRequest(r) {
667 panic("request not existing should have been guarded")
670 if !me.requestState.Cancelled.CheckedAdd(r) {
671 panic("request already cancelled")
675 if me.isLowOnRequests() {
676 me.updateRequests("Peer.cancel")
680 func (me *PeerConn) _cancel(r RequestIndex) bool {
681 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
682 // Transmission does not send rejects for received cancels. See
683 // https://github.com/transmission/transmission/pull/2275.
684 return me.fastEnabled() && !me.remoteIsTransmission()
687 func (cn *PeerConn) fillWriteBuffer() {
688 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
689 // Fully committing to our max requests requires sufficient space (see
690 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
691 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
692 // request reason will not be cleared, so we'll come right back here when there's space. We
693 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
694 // knowledge of write buffers.
696 cn.maybeUpdateActualRequestState()
697 if cn.pex.IsEnabled() {
698 if flow := cn.pex.Share(cn.write); !flow {
705 func (cn *PeerConn) have(piece pieceIndex) {
706 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
711 Index: pp.Integer(piece),
713 cn.sentHaves.Add(bitmap.BitIndex(piece))
716 func (cn *PeerConn) postBitfield() {
717 if cn.sentHaves.Len() != 0 {
718 panic("bitfield must be first have-related message sent")
720 if !cn.t.haveAnyPieces() {
725 Bitfield: cn.t.bitfield(),
727 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
730 // Sets a reason to update requests, and if there wasn't already one, handle it.
731 func (cn *Peer) updateRequests(reason string) {
732 if cn.needRequestUpdate != "" {
735 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
738 cn.needRequestUpdate = reason
739 cn.handleUpdateRequests()
742 func (cn *PeerConn) handleUpdateRequests() {
743 // The writer determines the request state as needed when it can write.
747 // Emits the indices in the Bitmaps bms in order, never repeating any index.
748 // skip is mutated during execution, and its initial values will never be
750 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
751 return func(cb iter.Callback) {
752 for _, bm := range bms {
754 func(_i interface{}) bool {
756 if skip.Contains(bitmap.BitIndex(i)) {
759 skip.Add(bitmap.BitIndex(i))
770 func (cn *Peer) peerPiecesChanged() {
771 cn.t.maybeDropMutuallyCompletePeer(cn)
774 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
775 if newMin > cn.peerMinPieces {
776 cn.peerMinPieces = newMin
780 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
781 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
782 return errors.New("invalid piece")
784 if cn.peerHasPiece(piece) {
787 cn.raisePeerMinPieces(piece + 1)
788 if !cn.peerHasPiece(piece) {
789 cn.t.incPieceAvailability(piece)
791 cn._peerPieces.Add(uint32(piece))
792 if cn.t.wantPieceIndex(piece) {
793 cn.updateRequests("have")
795 cn.peerPiecesChanged()
799 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
801 panic("expected bitfield length divisible by 8")
803 // We know that the last byte means that at most the last 7 bits are wasted.
804 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
805 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
806 // Ignore known excess pieces.
807 bf = bf[:cn.t.numPieces()]
809 bm := boolSliceToBitmap(bf)
810 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
811 cn.onPeerHasAllPieces()
815 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
817 shouldUpdateRequests := false
818 if cn.peerSentHaveAll {
819 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
822 cn.peerSentHaveAll = false
823 if !cn._peerPieces.IsEmpty() {
824 panic("if peer has all, we expect no individual peer pieces to be set")
827 bm.Xor(&cn._peerPieces)
829 cn.peerSentHaveAll = false
830 // bm is now 'on' for pieces that are changing
831 bm.Iterate(func(x uint32) bool {
833 if cn._peerPieces.Contains(x) {
834 // Then we must be losing this piece
835 cn.t.decPieceAvailability(pi)
837 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
838 shouldUpdateRequests = true
840 // We must be gaining this piece
841 cn.t.incPieceAvailability(pieceIndex(x))
845 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
847 cn._peerPieces.Xor(&bm)
848 if shouldUpdateRequests {
849 cn.updateRequests("bitfield")
851 // We didn't guard this before, I see no reason to do it now.
852 cn.peerPiecesChanged()
856 func (cn *PeerConn) onPeerHasAllPieces() {
859 cn._peerPieces.Iterate(func(x uint32) bool {
860 t.decPieceAvailability(pieceIndex(x))
864 t.addConnWithAllPieces(&cn.Peer)
865 cn.peerSentHaveAll = true
866 cn._peerPieces.Clear()
867 if !cn.t._pendingPieces.IsEmpty() {
868 cn.updateRequests("Peer.onPeerHasAllPieces")
870 cn.peerPiecesChanged()
873 func (cn *PeerConn) onPeerSentHaveAll() error {
874 cn.onPeerHasAllPieces()
878 func (cn *PeerConn) peerSentHaveNone() error {
879 if cn.peerSentHaveAll {
880 cn.t.decPeerPieceAvailability(&cn.Peer)
882 cn._peerPieces.Clear()
883 cn.peerSentHaveAll = false
884 cn.peerPiecesChanged()
888 func (c *PeerConn) requestPendingMetadata() {
892 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
893 // Peer doesn't support this.
896 // Request metadata pieces that we don't have in a random order.
898 for index := 0; index < c.t.metadataPieceCount(); index++ {
899 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
900 pending = append(pending, index)
903 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
904 for _, i := range pending {
905 c.requestMetadataPiece(i)
909 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
910 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
911 if msg.Type == pp.Extended {
912 for name, id := range cn.PeerExtensionIDs {
913 if id != msg.ExtendedID {
916 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
919 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
922 // After handshake, we know what Torrent and Client stats to include for a
924 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
930 // All ConnStats that include this connection. Some objects are not known
931 // until the handshake is complete, after which it's expected to reconcile the
933 func (cn *Peer) allStats(f func(*ConnStats)) {
935 if cn.reconciledHandshakeStats {
936 cn.postHandshakeStats(f)
940 func (cn *PeerConn) wroteBytes(n int64) {
941 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
944 func (cn *Peer) readBytes(n int64) {
945 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
948 // Returns whether the connection could be useful to us. We're seeding and
949 // they want data, we don't have metainfo and they can provide it, etc.
950 func (c *Peer) useful() bool {
952 if c.closed.IsSet() {
956 return c.supportsExtension("ut_metadata")
958 if t.seeding() && c.peerInterested {
961 if c.peerHasWantedPieces() {
967 func (c *Peer) lastHelpful() (ret time.Time) {
968 ret = c.lastUsefulChunkReceived
969 if c.t.seeding() && c.lastChunkSent.After(ret) {
970 ret = c.lastChunkSent
975 func (c *PeerConn) fastEnabled() bool {
976 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
979 func (c *PeerConn) reject(r Request) {
980 if !c.fastEnabled() {
981 panic("fast not enabled")
983 c.write(r.ToMsg(pp.Reject))
984 delete(c.peerRequests, r)
987 func (c *PeerConn) onReadRequest(r Request) error {
988 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
989 if _, ok := c.peerRequests[r]; ok {
990 torrent.Add("duplicate requests received", 1)
994 torrent.Add("requests received while choking", 1)
996 torrent.Add("requests rejected while choking", 1)
1001 // TODO: What if they've already requested this?
1002 if len(c.peerRequests) >= localClientReqq {
1003 torrent.Add("requests received while queue full", 1)
1004 if c.fastEnabled() {
1007 // BEP 6 says we may close here if we choose.
1010 if !c.t.havePiece(pieceIndex(r.Index)) {
1011 // This isn't necessarily them screwing up. We can drop pieces
1012 // from our storage, and can't communicate this to peers
1013 // except by reconnecting.
1014 requestsReceivedForMissingPieces.Add(1)
1015 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1017 // Check this after we know we have the piece, so that the piece length will be known.
1018 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1019 torrent.Add("bad requests received", 1)
1020 return errors.New("bad Request")
1022 if c.peerRequests == nil {
1023 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1025 value := &peerRequestState{}
1026 c.peerRequests[r] = value
1027 go c.peerRequestDataReader(r, value)
1031 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1032 b, err := readPeerRequestData(r, c)
1034 defer c.locker().Unlock()
1036 c.peerRequestDataReadFailed(err, r)
1039 panic("data must be non-nil to trigger send")
1041 torrent.Add("peer request data read successes", 1)
1047 // If this is maintained correctly, we might be able to support optional synchronous reading for
1048 // chunk sending, the way it used to work.
1049 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1050 torrent.Add("peer request data read failures", 1)
1051 logLevel := log.Warning
1052 if c.t.hasStorageCap() {
1053 // It's expected that pieces might drop. See
1054 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1055 logLevel = log.Debug
1057 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1058 if c.t.closed.IsSet() {
1061 i := pieceIndex(r.Index)
1062 if c.t.pieceComplete(i) {
1063 // There used to be more code here that just duplicated the following break. Piece
1064 // completions are currently cached, so I'm not sure how helpful this update is, except to
1065 // pull any completion changes pushed to the storage backend in failed reads that got us
1067 c.t.updatePieceCompletion(i)
1069 // We've probably dropped a piece from storage, but there's no way to communicate this to the
1070 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1071 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1072 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1074 if c.fastEnabled() {
1078 // If fast isn't enabled, I think we would have wiped all peer requests when we last
1079 // choked, and requests while we're choking would be ignored. It could be possible that
1080 // a peer request data read completed concurrently to it being deleted elsewhere.
1081 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1083 // Choking a non-fast peer should cause them to flush all their requests.
1088 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1089 b := make([]byte, r.Length)
1090 p := c.t.info.Piece(int(r.Index))
1091 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1098 panic("expected error")
1104 func runSafeExtraneous(f func()) {
1112 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1113 c.logger.WithContextText(fmt.Sprintf(
1114 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1115 )).SkipCallers(1).Levelf(level, format, arg...)
1118 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1119 // exit. Returning will end the connection.
1120 func (c *PeerConn) mainReadLoop() (err error) {
1123 torrent.Add("connection.mainReadLoop returned with error", 1)
1125 torrent.Add("connection.mainReadLoop returned with no error", 1)
1131 decoder := pp.Decoder{
1132 R: bufio.NewReaderSize(c.r, 1<<17),
1133 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1141 err = decoder.Decode(&msg)
1143 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1146 if t.closed.IsSet() || c.closed.IsSet() {
1152 c.lastMessageReceived = time.Now()
1154 receivedKeepalives.Add(1)
1157 messageTypesReceived.Add(msg.Type.String(), 1)
1158 if msg.Type.FastExtension() && !c.fastEnabled() {
1159 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1160 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1167 if !c.fastEnabled() {
1168 c.deleteAllRequests("choked by non-fast PeerConn")
1170 // We don't decrement pending requests here, let's wait for the peer to either
1171 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1172 // us and resume where they left off, we don't want to have piled on to those chunks
1173 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1174 // could let us request a lot of stuff, then choke us and never reject, but they're
1175 // only a single peer, our chunk balancing should smooth over this abuse.
1177 c.peerChoking = true
1178 c.updateExpectingChunks()
1181 // Some clients do this for some reason. Transmission doesn't error on this, so we
1182 // won't for consistency.
1183 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1186 c.peerChoking = false
1188 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1189 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1194 if preservedCount != 0 {
1195 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1197 c.logger.Levelf(log.Debug,
1198 "%v requests were preserved while being choked (fast=%v)",
1202 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1204 if !c.t._pendingPieces.IsEmpty() {
1205 c.updateRequests("unchoked")
1207 c.updateExpectingChunks()
1209 c.peerInterested = true
1211 case pp.NotInterested:
1212 c.peerInterested = false
1213 // We don't clear their requests since it isn't clear in the spec.
1214 // We'll probably choke them for this, which will clear them if
1215 // appropriate, and is clearly specified.
1217 err = c.peerSentHave(pieceIndex(msg.Index))
1219 err = c.peerSentBitfield(msg.Bitfield)
1221 r := newRequestFromMessage(&msg)
1222 err = c.onReadRequest(r)
1224 c.doChunkReadStats(int64(len(msg.Piece)))
1225 err = c.receiveChunk(&msg)
1226 if len(msg.Piece) == int(t.chunkSize) {
1227 t.chunkPool.Put(&msg.Piece)
1230 err = fmt.Errorf("receiving chunk: %w", err)
1233 req := newRequestFromMessage(&msg)
1234 c.onPeerSentCancel(req)
1236 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1240 pingAddr := net.UDPAddr{
1245 pingAddr.Port = int(msg.Port)
1247 cl.eachDhtServer(func(s DhtServer) {
1248 go s.Ping(&pingAddr)
1251 torrent.Add("suggests received", 1)
1252 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1253 c.updateRequests("suggested")
1255 err = c.onPeerSentHaveAll()
1257 err = c.peerSentHaveNone()
1259 req := newRequestFromMessage(&msg)
1260 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1261 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1262 err = fmt.Errorf("received invalid reject [request=%v]", req)
1264 case pp.AllowedFast:
1265 torrent.Add("allowed fasts received", 1)
1266 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1267 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1269 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1271 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1279 // Returns true if it was valid to reject the request.
1280 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1281 if c.deleteRequest(r) {
1283 } else if !c.requestState.Cancelled.CheckedRemove(r) {
1286 if c.isLowOnRequests() {
1287 c.updateRequests("Peer.remoteRejectedRequest")
1289 c.decExpectedChunkReceive(r)
1293 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1294 count := c.validReceiveChunks[r]
1296 delete(c.validReceiveChunks, r)
1297 } else if count > 1 {
1298 c.validReceiveChunks[r] = count - 1
1304 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1306 // TODO: Should we still do this?
1308 // These clients use their own extension IDs for outgoing message
1309 // types, which is incorrect.
1310 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1318 case pp.HandshakeExtendedID:
1319 var d pp.ExtendedHandshakeMessage
1320 if err := bencode.Unmarshal(payload, &d); err != nil {
1321 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1322 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1324 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1327 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1329 c.PeerMaxRequests = d.Reqq
1331 c.PeerClientName.Store(d.V)
1332 if c.PeerExtensionIDs == nil {
1333 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1335 c.PeerListenPort = d.Port
1336 c.PeerPrefersEncryption = d.Encryption
1337 for name, id := range d.M {
1338 if _, ok := c.PeerExtensionIDs[name]; !ok {
1339 peersSupportingExtension.Add(
1340 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1341 // entered here which caused problems later when unmarshalling.
1342 strconv.Quote(string(name)),
1345 c.PeerExtensionIDs[name] = id
1347 if d.MetadataSize != 0 {
1348 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1349 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1352 c.requestPendingMetadata()
1353 if !t.cl.config.DisablePEX {
1354 t.pex.Add(c) // we learnt enough now
1358 case metadataExtendedId:
1359 err := cl.gotMetadataExtensionMsg(payload, t, c)
1361 return fmt.Errorf("handling metadata extension message: %w", err)
1365 if !c.pex.IsEnabled() {
1366 return nil // or hang-up maybe?
1368 return c.pex.Recv(payload)
1370 return fmt.Errorf("unexpected extended message ID: %v", id)
1374 // Set both the Reader and Writer for the connection from a single ReadWriter.
1375 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1380 // Returns the Reader and Writer as a combined ReadWriter.
1381 func (cn *PeerConn) rw() io.ReadWriter {
1388 func (c *Peer) doChunkReadStats(size int64) {
1389 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1392 // Handle a received chunk from a peer.
1393 func (c *Peer) receiveChunk(msg *pp.Message) error {
1394 chunksReceived.Add("total", 1)
1396 ppReq := newRequestFromMessage(msg)
1397 req := c.t.requestIndexFromRequest(ppReq)
1400 if c.bannableAddr.Ok() {
1401 t.smartBanCache.RecordBlock(c.bannableAddr.Value(), req, msg.Piece)
1405 chunksReceived.Add("while choked", 1)
1408 if c.validReceiveChunks[req] <= 0 {
1409 chunksReceived.Add("unexpected", 1)
1410 return errors.New("received unexpected chunk")
1412 c.decExpectedChunkReceive(req)
1414 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1415 chunksReceived.Add("due to allowed fast", 1)
1418 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1419 // have actually already received the piece, while we have the Client unlocked to write the data
1423 if c.requestState.Requests.Contains(req) {
1424 for _, f := range c.callbacks.ReceivedRequested {
1425 f(PeerMessageEvent{c, msg})
1428 // Request has been satisfied.
1429 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1432 c._chunksReceivedWhileExpecting++
1434 if c.isLowOnRequests() {
1435 c.updateRequests("Peer.receiveChunk deleted request")
1438 chunksReceived.Add("unintended", 1)
1444 // Do we actually want this chunk?
1445 if t.haveChunk(ppReq) {
1446 // panic(fmt.Sprintf("%+v", ppReq))
1447 chunksReceived.Add("redundant", 1)
1448 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1452 piece := &t.pieces[ppReq.Index]
1454 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1455 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1457 c.piecesReceivedSinceLastRequestUpdate++
1458 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1460 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1461 f(ReceivedUsefulDataEvent{c, msg})
1463 c.lastUsefulChunkReceived = time.Now()
1465 // Need to record that it hasn't been written yet, before we attempt to do
1466 // anything with it.
1467 piece.incrementPendingWrites()
1468 // Record that we have the chunk, so we aren't trying to download it while
1469 // waiting for it to be written to storage.
1470 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1472 // Cancel pending requests for this chunk from *other* peers.
1473 if p := t.pendingRequests[req]; p != nil {
1475 panic("should not be pending request from conn that just received it")
1480 err := func() error {
1483 concurrentChunkWrites.Add(1)
1484 defer concurrentChunkWrites.Add(-1)
1485 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1486 // number of connections. We write inline with receiving the chunk (with this lock dance),
1487 // because we want to handle errors synchronously and I haven't thought of a nice way to
1488 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1490 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1493 piece.decrementPendingWrites()
1496 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1498 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1499 // request update runs while we're writing the chunk that just failed. Then we never do a
1500 // fresh update after pending the failed request.
1501 c.updateRequests("Peer.receiveChunk error writing chunk")
1502 t.onWriteChunkErr(err)
1506 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1508 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1509 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1510 t.queuePieceCheck(pieceIndex(ppReq.Index))
1511 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1512 // chunk status (such as the haveChunk call above) to have to check all the various other
1513 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1514 // that chunk pieces are pended at an appropriate time later however.
1517 cl.event.Broadcast()
1518 // We do this because we've written a chunk, and may change PieceState.Partial.
1519 t.publishPieceChange(pieceIndex(ppReq.Index))
1524 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1525 if c.peerTouchedPieces == nil {
1526 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1528 c.peerTouchedPieces[piece] = struct{}{}
1529 ds := &c.t.pieces[piece].dirtiers
1531 *ds = make(map[*Peer]struct{})
1533 (*ds)[c] = struct{}{}
1536 func (c *PeerConn) uploadAllowed() bool {
1537 if c.t.cl.config.NoUpload {
1540 if c.t.dataUploadDisallowed {
1546 if !c.peerHasWantedPieces() {
1549 // Don't upload more than 100 KiB more than we download.
1550 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1556 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1557 if c.uploadTimer == nil {
1558 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1560 c.uploadTimer.Reset(delay)
1564 // Also handles choking and unchoking of the remote peer.
1565 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1566 // Breaking or completing this loop means we don't want to upload to the
1567 // peer anymore, and we choke them.
1569 for c.uploadAllowed() {
1570 // We want to upload to the peer.
1571 if !c.unchoke(msg) {
1574 for r, state := range c.peerRequests {
1575 if state.data == nil {
1578 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1580 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1582 delay := res.Delay()
1585 c.setRetryUploadTimer(delay)
1586 // Hard to say what to return here.
1589 more := c.sendChunk(r, msg, state)
1590 delete(c.peerRequests, r)
1601 func (cn *PeerConn) drop() {
1602 cn.t.dropConnection(cn)
1605 func (cn *PeerConn) ban() {
1606 cn.t.cl.banPeerIP(cn.remoteIp())
1609 func (cn *Peer) netGoodPiecesDirtied() int64 {
1610 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1613 func (c *Peer) peerHasWantedPieces() bool {
1614 if all, _ := c.peerHasAllPieces(); all {
1615 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1617 if !c.t.haveInfo() {
1618 return !c.peerPieces().IsEmpty()
1620 return c.peerPieces().Intersects(&c.t._pendingPieces)
1623 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1625 func (c *Peer) deleteRequest(r RequestIndex) bool {
1626 if !c.requestState.Requests.CheckedRemove(r) {
1629 for _, f := range c.callbacks.DeletedRequest {
1630 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1632 c.updateExpectingChunks()
1633 if c.t.requestingPeer(r) != c {
1634 panic("only one peer should have a given request at a time")
1636 delete(c.t.pendingRequests, r)
1637 delete(c.t.lastRequested, r)
1638 // c.t.iterPeers(func(p *Peer) {
1639 // if p.isLowOnRequests() {
1640 // p.updateRequests("Peer.deleteRequest")
1646 func (c *Peer) deleteAllRequests(reason string) {
1647 if c.requestState.Requests.IsEmpty() {
1650 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1651 if !c.deleteRequest(x) {
1652 panic("request should exist")
1656 c.assertNoRequests()
1657 c.t.iterPeers(func(p *Peer) {
1658 if p.isLowOnRequests() {
1659 p.updateRequests(reason)
1665 func (c *Peer) assertNoRequests() {
1666 if !c.requestState.Requests.IsEmpty() {
1667 panic(c.requestState.Requests.GetCardinality())
1671 func (c *Peer) cancelAllRequests() {
1672 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1676 c.assertNoRequests()
1680 // This is called when something has changed that should wake the writer, such as putting stuff into
1681 // the writeBuffer, or changing some state that the writer can act on.
1682 func (c *PeerConn) tickleWriter() {
1683 c.messageWriter.writeCond.Broadcast()
1686 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1687 c.lastChunkSent = time.Now()
1688 return msg(pp.Message{
1696 func (c *PeerConn) setTorrent(t *Torrent) {
1698 panic("connection already associated with a torrent")
1701 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1702 t.reconcileHandshakeStats(c)
1705 func (c *Peer) peerPriority() (peerPriority, error) {
1706 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1709 func (c *Peer) remoteIp() net.IP {
1710 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1711 return net.ParseIP(host)
1714 func (c *Peer) remoteIpPort() IpPort {
1715 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1716 return IpPort{ipa.IP, uint16(ipa.Port)}
1719 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1720 f := pp.PexPeerFlags(0)
1721 if c.PeerPrefersEncryption {
1722 f |= pp.PexPrefersEncryption
1725 f |= pp.PexOutgoingConn
1728 f |= pp.PexSupportsUtp
1733 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1734 // advertised listen port.
1735 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1736 if !c.outgoing && c.PeerListenPort != 0 {
1737 switch addr := c.RemoteAddr.(type) {
1740 dialAddr.Port = c.PeerListenPort
1744 dialAddr.Port = c.PeerListenPort
1751 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1752 f := c.pexPeerFlags()
1753 addr := c.dialAddr()
1754 return pexEvent{t, addr, f, nil}
1757 func (c *PeerConn) String() string {
1758 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1761 func (c *Peer) trust() connectionTrust {
1762 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1765 type connectionTrust struct {
1767 NetGoodPiecesDirted int64
1770 func (l connectionTrust) Less(r connectionTrust) bool {
1771 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1774 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1775 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1776 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1778 defer cn.locker().RUnlock()
1779 return cn.newPeerPieces()
1782 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1783 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1784 // TODO: Can we use copy on write?
1785 ret := cn.peerPieces().Clone()
1786 if all, _ := cn.peerHasAllPieces(); all {
1787 if cn.t.haveInfo() {
1788 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1790 ret.AddRange(0, bitmap.ToEnd)
1796 func (cn *Peer) stats() *ConnStats {
1800 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1801 pc, ok := p.peerImpl.(*PeerConn)
1805 func (p *Peer) uncancelledRequests() uint64 {
1806 return p.requestState.Requests.GetCardinality()
1809 func (pc *PeerConn) remoteIsTransmission() bool {
1810 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'