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/internal/alloclim"
25 "golang.org/x/time/rate"
27 "github.com/anacrolix/torrent/bencode"
28 "github.com/anacrolix/torrent/metainfo"
29 "github.com/anacrolix/torrent/mse"
30 pp "github.com/anacrolix/torrent/peer_protocol"
31 request_strategy "github.com/anacrolix/torrent/request-strategy"
32 "github.com/anacrolix/torrent/typed-roaring"
35 type PeerSource string
38 PeerSourceTracker = "Tr"
39 PeerSourceIncoming = "I"
40 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
41 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
43 // The peer was given directly, such as through a magnet link.
44 PeerSourceDirect = "M"
47 type peerRequestState struct {
49 allocReservation *alloclim.Reservation
52 type PeerRemoteAddr interface {
57 // Since we have to store all the requests in memory, we can't reasonably exceed what could be
58 // indexed with the memory space available.
63 // First to ensure 64-bit alignment for atomics. See #262.
73 RemoteAddr PeerRemoteAddr
74 // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
76 localPublicAddr peerLocalPublicAddr
77 bannableAddr Option[bannableAddr]
78 // True if the connection is operating over MSE obfuscation.
80 cryptoMethod mse.CryptoMethod
83 closed chansync.SetOnce
84 // Set true after we've added our ConnStats generated during handshake to
85 // other ConnStat instances as determined when the *Torrent became known.
86 reconciledHandshakeStats bool
88 lastMessageReceived time.Time
89 completedHandshake time.Time
90 lastUsefulChunkReceived time.Time
91 lastChunkSent time.Time
93 // Stuff controlled by the local peer.
94 needRequestUpdate string
95 requestState request_strategy.PeerRequestState
96 updateRequestsTimer *time.Timer
97 lastRequestUpdate time.Time
98 peakRequests maxRequests
99 lastBecameInterested time.Time
100 priorInterest time.Duration
102 lastStartedExpectingToReceiveChunks time.Time
103 cumulativeExpectedToReceiveChunks time.Duration
104 _chunksReceivedWhileExpecting int64
107 piecesReceivedSinceLastRequestUpdate maxRequests
108 maxPiecesReceivedBetweenRequestUpdates maxRequests
109 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
110 // and implementation differences, we may receive chunks that are no longer in the set of
111 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
112 validReceiveChunks map[RequestIndex]int
113 // Indexed by metadata piece, set to true if posted and pending a
115 metadataRequests []bool
116 sentHaves bitmap.Bitmap
118 // Stuff controlled by the remote peer.
121 peerRequests map[Request]*peerRequestState
122 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
124 // The highest possible number of pieces the torrent could have based on
125 // communication with the peer. Generally only useful until we have the
127 peerMinPieces pieceIndex
128 // Pieces we've accepted chunks for from the peer.
129 peerTouchedPieces map[pieceIndex]struct{}
130 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
132 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
133 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
134 PeerClientName atomic.Value
139 type peerRequests = orderedBitmap[RequestIndex]
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.
176 peerRequestDataAllocLimiter alloclim.Limiter
179 func (cn *PeerConn) peerImplStatusLines() []string {
180 return []string{fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)}
183 func (cn *Peer) updateExpectingChunks() {
184 if cn.expectingChunks() {
185 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
186 cn.lastStartedExpectingToReceiveChunks = time.Now()
189 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
190 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
191 cn.lastStartedExpectingToReceiveChunks = time.Time{}
196 func (cn *Peer) expectingChunks() bool {
197 if cn.requestState.Requests.IsEmpty() {
200 if !cn.requestState.Interested {
206 haveAllowedFastRequests := false
207 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
208 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
209 cn.requestState.Requests,
210 cn.t.pieceRequestIndexOffset(i),
211 cn.t.pieceRequestIndexOffset(i+1),
213 return !haveAllowedFastRequests
215 return haveAllowedFastRequests
218 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
219 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
222 // Returns true if the connection is over IPv6.
223 func (cn *PeerConn) ipv6() bool {
228 return len(ip) == net.IPv6len
231 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
232 // specification for this.
233 func (cn *PeerConn) isPreferredDirection() bool {
234 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
237 // Returns whether the left connection should be preferred over the right one,
238 // considering only their networking properties. If ok is false, we can't
240 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
241 var ml multiless.Computation
242 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
243 ml = ml.Bool(l.utp(), r.utp())
244 ml = ml.Bool(r.ipv6(), l.ipv6())
248 func (cn *Peer) cumInterest() time.Duration {
249 ret := cn.priorInterest
250 if cn.requestState.Interested {
251 ret += time.Since(cn.lastBecameInterested)
256 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
257 if cn.peerSentHaveAll {
260 if !cn.t.haveInfo() {
263 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
266 func (cn *Peer) locker() *lockWithDeferreds {
267 return cn.t.cl.locker()
270 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
271 _, ok := cn.PeerExtensionIDs[ext]
275 // The best guess at number of pieces in the torrent for this peer.
276 func (cn *Peer) bestPeerNumPieces() pieceIndex {
278 return cn.t.numPieces()
280 return cn.peerMinPieces
283 func (cn *Peer) completedString() string {
284 have := pieceIndex(cn.peerPieces().GetCardinality())
285 if all, _ := cn.peerHasAllPieces(); all {
286 have = cn.bestPeerNumPieces()
288 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
291 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
292 cn.setNumPieces(info.NumPieces())
295 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
296 // receiving badly sized BITFIELD, or invalid HAVE messages.
297 func (cn *PeerConn) setNumPieces(num pieceIndex) {
298 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
299 cn.peerPiecesChanged()
302 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
303 return &cn._peerPieces
306 func eventAgeString(t time.Time) string {
310 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
313 func (cn *PeerConn) connectionFlags() (ret string) {
315 ret += string([]byte{b})
317 if cn.cryptoMethod == mse.CryptoMethodRC4 {
319 } else if cn.headerEncrypted {
322 ret += string(cn.Discovery)
329 func (cn *PeerConn) utp() bool {
330 return parseNetworkString(cn.Network).Udp
333 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
334 func (cn *Peer) statusFlags() (ret string) {
336 ret += string([]byte{b})
338 if cn.requestState.Interested {
345 ret += cn.connectionFlags()
347 if cn.peerInterested {
356 func (cn *Peer) downloadRate() float64 {
357 num := cn._stats.BytesReadUsefulData.Int64()
361 return float64(num) / cn.totalExpectingTime().Seconds()
364 func (cn *Peer) DownloadRate() float64 {
366 defer cn.locker().RUnlock()
368 return cn.downloadRate()
371 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
372 var last Option[pieceIndex]
374 next := func(item Option[pieceIndex]) {
385 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
386 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
389 next(None[pieceIndex]())
392 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
393 // \t isn't preserved in <pre> blocks?
394 if cn.closed.IsSet() {
395 fmt.Fprint(w, "CLOSED: ")
397 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
398 prio, err := cn.peerPriority()
399 prioStr := fmt.Sprintf("%08x", prio)
401 prioStr += ": " + err.Error()
403 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
404 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
405 eventAgeString(cn.lastMessageReceived),
406 eventAgeString(cn.completedHandshake),
407 eventAgeString(cn.lastHelpful()),
409 cn.totalExpectingTime(),
412 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
413 cn.completedString(),
414 len(cn.peerTouchedPieces),
415 &cn._stats.ChunksReadUseful,
416 &cn._stats.ChunksRead,
417 &cn._stats.ChunksWritten,
418 cn.requestState.Requests.GetCardinality(),
419 cn.requestState.Cancelled.GetCardinality(),
420 cn.nominalMaxRequests(),
422 len(cn.peerRequests),
425 cn.downloadRate()/(1<<10),
427 fmt.Fprintf(w, "requested pieces:")
428 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
429 fmt.Fprintf(w, " %v(%v)", piece, count)
434 func (p *Peer) close() {
438 if p.updateRequestsTimer != nil {
439 p.updateRequestsTimer.Stop()
443 p.t.decPeerPieceAvailability(p)
445 for _, f := range p.callbacks.PeerClosed {
450 func (cn *PeerConn) onClose() {
451 if cn.pex.IsEnabled() {
458 if cb := cn.callbacks.PeerConnClosed; cb != nil {
463 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
464 // they do (known=true).
465 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
466 if all, known := cn.peerHasAllPieces(); all && known {
469 return cn.peerPieces().ContainsInt(piece)
472 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
473 // https://github.com/pion/datachannel/issues/59 is fixed.
475 writeBufferHighWaterLen = 1 << 15
476 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
479 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
480 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
481 func (cn *PeerConn) write(msg pp.Message) bool {
482 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
483 // We don't need to track bytes here because the connection's Writer has that behaviour injected
484 // (although there's some delay between us buffering the message, and the connection writer
485 // flushing it out.).
486 notFull := cn.messageWriter.write(msg)
487 // Last I checked only Piece messages affect stats, and we don't write those.
493 func (cn *PeerConn) requestMetadataPiece(index int) {
494 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
495 if eID == pp.ExtensionDeleteNumber {
498 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
501 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
502 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
503 for index >= len(cn.metadataRequests) {
504 cn.metadataRequests = append(cn.metadataRequests, false)
506 cn.metadataRequests[index] = true
509 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
510 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
514 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
515 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
516 // This is the maximum request count that could fit in the write buffer if it's at or below the
517 // low water mark when we run maybeUpdateActualRequestState.
518 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
521 // The actual value to use as the maximum outbound requests.
522 func (cn *Peer) nominalMaxRequests() maxRequests {
523 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
526 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
527 ret = cn.cumulativeExpectedToReceiveChunks
528 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
529 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
534 func (cn *PeerConn) onPeerSentCancel(r Request) {
535 if _, ok := cn.peerRequests[r]; !ok {
536 torrent.Add("unexpected cancels received", 1)
539 if cn.fastEnabled() {
542 delete(cn.peerRequests, r)
546 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
551 more = msg(pp.Message{
554 if !cn.fastEnabled() {
555 cn.deleteAllPeerRequests()
560 func (cn *PeerConn) deleteAllPeerRequests() {
561 for _, state := range cn.peerRequests {
562 state.allocReservation.Drop()
564 cn.peerRequests = nil
567 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
572 return msg(pp.Message{
577 func (cn *Peer) setInterested(interested bool) bool {
578 if cn.requestState.Interested == interested {
581 cn.requestState.Interested = interested
583 cn.lastBecameInterested = time.Now()
584 } else if !cn.lastBecameInterested.IsZero() {
585 cn.priorInterest += time.Since(cn.lastBecameInterested)
587 cn.updateExpectingChunks()
588 // log.Printf("%p: setting interest: %v", cn, interested)
589 return cn.writeInterested(interested)
592 func (pc *PeerConn) writeInterested(interested bool) bool {
593 return pc.write(pp.Message{
594 Type: func() pp.MessageType {
598 return pp.NotInterested
604 // The function takes a message to be sent, and returns true if more messages
606 type messageWriter func(pp.Message) bool
608 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
609 // when we want to go fast.
610 func (cn *Peer) shouldRequest(r RequestIndex) error {
611 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
615 pi := cn.t.pieceIndexOfRequestIndex(r)
616 if cn.requestState.Cancelled.Contains(r) {
617 return errors.New("request is cancelled and waiting acknowledgement")
619 if !cn.peerHasPiece(pi) {
620 return errors.New("requesting piece peer doesn't have")
622 if !cn.t.peerIsActive(cn) {
623 panic("requesting but not in active conns")
625 if cn.closed.IsSet() {
626 panic("requesting when connection is closed")
628 if cn.t.hashingPiece(pi) {
629 panic("piece is being hashed")
631 if cn.t.pieceQueuedForHash(pi) {
632 panic("piece is queued for hash")
634 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
635 // This could occur if we made a request with the fast extension, and then got choked and
636 // haven't had the request rejected yet.
637 if !cn.requestState.Requests.Contains(r) {
638 panic("peer choking and piece not allowed fast")
644 func (cn *Peer) mustRequest(r RequestIndex) bool {
645 more, err := cn.request(r)
652 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
653 if err := cn.shouldRequest(r); err != nil {
656 if cn.requestState.Requests.Contains(r) {
659 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
660 return true, errors.New("too many outstanding requests")
662 cn.requestState.Requests.Add(r)
663 if cn.validReceiveChunks == nil {
664 cn.validReceiveChunks = make(map[RequestIndex]int)
666 cn.validReceiveChunks[r]++
667 cn.t.requestState[r] = requestState{
671 cn.updateExpectingChunks()
672 ppReq := cn.t.requestIndexToRequest(r)
673 for _, f := range cn.callbacks.SentRequest {
674 f(PeerRequestEvent{cn, ppReq})
676 return cn.peerImpl._request(ppReq), nil
679 func (me *PeerConn) _request(r Request) bool {
680 return me.write(pp.Message{
688 func (me *Peer) cancel(r RequestIndex) {
689 if !me.deleteRequest(r) {
690 panic("request not existing should have been guarded")
693 if !me.requestState.Cancelled.CheckedAdd(r) {
694 panic("request already cancelled")
698 if me.isLowOnRequests() {
699 me.updateRequests("Peer.cancel")
703 func (me *PeerConn) _cancel(r RequestIndex) bool {
704 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
705 // Transmission does not send rejects for received cancels. See
706 // https://github.com/transmission/transmission/pull/2275.
707 return me.fastEnabled() && !me.remoteIsTransmission()
710 func (cn *PeerConn) fillWriteBuffer() {
711 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
712 // Fully committing to our max requests requires sufficient space (see
713 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
714 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
715 // request reason will not be cleared, so we'll come right back here when there's space. We
716 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
717 // knowledge of write buffers.
719 cn.maybeUpdateActualRequestState()
720 if cn.pex.IsEnabled() {
721 if flow := cn.pex.Share(cn.write); !flow {
728 func (cn *PeerConn) have(piece pieceIndex) {
729 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
734 Index: pp.Integer(piece),
736 cn.sentHaves.Add(bitmap.BitIndex(piece))
739 func (cn *PeerConn) postBitfield() {
740 if cn.sentHaves.Len() != 0 {
741 panic("bitfield must be first have-related message sent")
743 if !cn.t.haveAnyPieces() {
748 Bitfield: cn.t.bitfield(),
750 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
753 // Sets a reason to update requests, and if there wasn't already one, handle it.
754 func (cn *Peer) updateRequests(reason string) {
755 if cn.needRequestUpdate != "" {
758 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
761 cn.needRequestUpdate = reason
762 cn.handleUpdateRequests()
765 func (cn *PeerConn) handleUpdateRequests() {
766 // The writer determines the request state as needed when it can write.
770 // Emits the indices in the Bitmaps bms in order, never repeating any index.
771 // skip is mutated during execution, and its initial values will never be
773 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
774 return func(cb iter.Callback) {
775 for _, bm := range bms {
777 func(_i interface{}) bool {
779 if skip.Contains(bitmap.BitIndex(i)) {
782 skip.Add(bitmap.BitIndex(i))
793 func (cn *Peer) peerPiecesChanged() {
794 cn.t.maybeDropMutuallyCompletePeer(cn)
797 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
798 if newMin > cn.peerMinPieces {
799 cn.peerMinPieces = newMin
803 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
804 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
805 return errors.New("invalid piece")
807 if cn.peerHasPiece(piece) {
810 cn.raisePeerMinPieces(piece + 1)
811 if !cn.peerHasPiece(piece) {
812 cn.t.incPieceAvailability(piece)
814 cn._peerPieces.Add(uint32(piece))
815 if cn.t.wantPieceIndex(piece) {
816 cn.updateRequests("have")
818 cn.peerPiecesChanged()
822 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
824 panic("expected bitfield length divisible by 8")
826 // We know that the last byte means that at most the last 7 bits are wasted.
827 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
828 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
829 // Ignore known excess pieces.
830 bf = bf[:cn.t.numPieces()]
832 bm := boolSliceToBitmap(bf)
833 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
834 cn.onPeerHasAllPieces()
838 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
840 shouldUpdateRequests := false
841 if cn.peerSentHaveAll {
842 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
845 cn.peerSentHaveAll = false
846 if !cn._peerPieces.IsEmpty() {
847 panic("if peer has all, we expect no individual peer pieces to be set")
850 bm.Xor(&cn._peerPieces)
852 cn.peerSentHaveAll = false
853 // bm is now 'on' for pieces that are changing
854 bm.Iterate(func(x uint32) bool {
856 if cn._peerPieces.Contains(x) {
857 // Then we must be losing this piece
858 cn.t.decPieceAvailability(pi)
860 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
861 shouldUpdateRequests = true
863 // We must be gaining this piece
864 cn.t.incPieceAvailability(pieceIndex(x))
868 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
870 cn._peerPieces.Xor(&bm)
871 if shouldUpdateRequests {
872 cn.updateRequests("bitfield")
874 // We didn't guard this before, I see no reason to do it now.
875 cn.peerPiecesChanged()
879 func (cn *PeerConn) onPeerHasAllPieces() {
882 cn._peerPieces.Iterate(func(x uint32) bool {
883 t.decPieceAvailability(pieceIndex(x))
887 t.addConnWithAllPieces(&cn.Peer)
888 cn.peerSentHaveAll = true
889 cn._peerPieces.Clear()
890 if !cn.t._pendingPieces.IsEmpty() {
891 cn.updateRequests("Peer.onPeerHasAllPieces")
893 cn.peerPiecesChanged()
896 func (cn *PeerConn) onPeerSentHaveAll() error {
897 cn.onPeerHasAllPieces()
901 func (cn *PeerConn) peerSentHaveNone() error {
902 if cn.peerSentHaveAll {
903 cn.t.decPeerPieceAvailability(&cn.Peer)
905 cn._peerPieces.Clear()
906 cn.peerSentHaveAll = false
907 cn.peerPiecesChanged()
911 func (c *PeerConn) requestPendingMetadata() {
915 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
916 // Peer doesn't support this.
919 // Request metadata pieces that we don't have in a random order.
921 for index := 0; index < c.t.metadataPieceCount(); index++ {
922 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
923 pending = append(pending, index)
926 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
927 for _, i := range pending {
928 c.requestMetadataPiece(i)
932 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
933 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
934 if msg.Type == pp.Extended {
935 for name, id := range cn.PeerExtensionIDs {
936 if id != msg.ExtendedID {
939 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
942 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
945 // After handshake, we know what Torrent and Client stats to include for a
947 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
953 // All ConnStats that include this connection. Some objects are not known
954 // until the handshake is complete, after which it's expected to reconcile the
956 func (cn *Peer) allStats(f func(*ConnStats)) {
958 if cn.reconciledHandshakeStats {
959 cn.postHandshakeStats(f)
963 func (cn *PeerConn) wroteBytes(n int64) {
964 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
967 func (cn *Peer) readBytes(n int64) {
968 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
971 // Returns whether the connection could be useful to us. We're seeding and
972 // they want data, we don't have metainfo and they can provide it, etc.
973 func (c *Peer) useful() bool {
975 if c.closed.IsSet() {
979 return c.supportsExtension("ut_metadata")
981 if t.seeding() && c.peerInterested {
984 if c.peerHasWantedPieces() {
990 func (c *Peer) lastHelpful() (ret time.Time) {
991 ret = c.lastUsefulChunkReceived
992 if c.t.seeding() && c.lastChunkSent.After(ret) {
993 ret = c.lastChunkSent
998 func (c *PeerConn) fastEnabled() bool {
999 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
1002 func (c *PeerConn) reject(r Request) {
1003 if !c.fastEnabled() {
1004 panic("fast not enabled")
1006 c.write(r.ToMsg(pp.Reject))
1007 // It is possible to reject a request before it is added to peer requests due to being invalid.
1008 if state, ok := c.peerRequests[r]; ok {
1009 state.allocReservation.Drop()
1010 delete(c.peerRequests, r)
1014 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
1015 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
1016 if uploadRateLimiter.Limit() == rate.Inf {
1019 return Some(uploadRateLimiter.Burst())
1022 // Returns whether any part of the chunk would lie outside a piece of the given length.
1023 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
1027 case cs.Begin+cs.Length > pieceLength:
1028 // Check for integer overflow
1029 case cs.Begin > pp.IntegerMax-cs.Length:
1034 // startFetch is for testing purposes currently.
1035 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
1036 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1037 if _, ok := c.peerRequests[r]; ok {
1038 torrent.Add("duplicate requests received", 1)
1039 if c.fastEnabled() {
1040 return errors.New("received duplicate request with fast enabled")
1045 torrent.Add("requests received while choking", 1)
1046 if c.fastEnabled() {
1047 torrent.Add("requests rejected while choking", 1)
1052 // TODO: What if they've already requested this?
1053 if len(c.peerRequests) >= localClientReqq {
1054 torrent.Add("requests received while queue full", 1)
1055 if c.fastEnabled() {
1058 // BEP 6 says we may close here if we choose.
1061 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
1062 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
1063 c.logger.Levelf(log.Warning, err.Error())
1064 if c.fastEnabled() {
1071 if !c.t.havePiece(pieceIndex(r.Index)) {
1072 // TODO: Tell the peer we don't have the piece, and reject this request.
1073 requestsReceivedForMissingPieces.Add(1)
1074 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1076 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
1077 // Check this after we know we have the piece, so that the piece length will be known.
1078 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
1079 torrent.Add("bad requests received", 1)
1080 return errors.New("chunk overflows piece")
1082 if c.peerRequests == nil {
1083 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1085 value := &peerRequestState{
1086 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
1088 c.peerRequests[r] = value
1090 // TODO: Limit peer request data read concurrency.
1091 go c.peerRequestDataReader(r, value)
1096 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1097 b, err := c.readPeerRequestData(r, prs)
1099 defer c.locker().Unlock()
1101 c.peerRequestDataReadFailed(err, r)
1104 panic("data must be non-nil to trigger send")
1106 torrent.Add("peer request data read successes", 1)
1108 // This might be required for the error case too (#752 and #753).
1113 // If this is maintained correctly, we might be able to support optional synchronous reading for
1114 // chunk sending, the way it used to work.
1115 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1116 torrent.Add("peer request data read failures", 1)
1117 logLevel := log.Warning
1118 if c.t.hasStorageCap() {
1119 // It's expected that pieces might drop. See
1120 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1121 logLevel = log.Debug
1123 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1124 if c.t.closed.IsSet() {
1127 i := pieceIndex(r.Index)
1128 if c.t.pieceComplete(i) {
1129 // There used to be more code here that just duplicated the following break. Piece
1130 // completions are currently cached, so I'm not sure how helpful this update is, except to
1131 // pull any completion changes pushed to the storage backend in failed reads that got us
1133 c.t.updatePieceCompletion(i)
1135 // We've probably dropped a piece from storage, but there's no way to communicate this to the
1136 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1137 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1138 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1140 if c.fastEnabled() {
1144 // If fast isn't enabled, I think we would have wiped all peer requests when we last
1145 // choked, and requests while we're choking would be ignored. It could be possible that
1146 // a peer request data read completed concurrently to it being deleted elsewhere.
1147 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1149 // Choking a non-fast peer should cause them to flush all their requests.
1154 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
1155 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
1156 // or fail to read and then cleanup.
1157 ctx := context.Background()
1158 err := prs.allocReservation.Wait(ctx)
1160 if ctx.Err() == nil {
1161 // The error is from the reservation itself. Something is very broken, or we're not
1162 // guarding against excessively large requests.
1163 err = log.WithLevel(log.Critical, err)
1165 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
1168 b := make([]byte, r.Length)
1169 p := c.t.info.Piece(int(r.Index))
1170 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1177 panic("expected error")
1183 func runSafeExtraneous(f func()) {
1191 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1192 c.logger.WithContextText(fmt.Sprintf(
1193 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1194 )).SkipCallers(1).Levelf(level, format, arg...)
1197 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1198 // exit. Returning will end the connection.
1199 func (c *PeerConn) mainReadLoop() (err error) {
1202 torrent.Add("connection.mainReadLoop returned with error", 1)
1204 torrent.Add("connection.mainReadLoop returned with no error", 1)
1210 decoder := pp.Decoder{
1211 R: bufio.NewReaderSize(c.r, 1<<17),
1212 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1220 err = decoder.Decode(&msg)
1222 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1225 if t.closed.IsSet() || c.closed.IsSet() {
1231 c.lastMessageReceived = time.Now()
1233 receivedKeepalives.Add(1)
1236 messageTypesReceived.Add(msg.Type.String(), 1)
1237 if msg.Type.FastExtension() && !c.fastEnabled() {
1238 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1239 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1246 if !c.fastEnabled() {
1247 c.deleteAllRequests("choked by non-fast PeerConn")
1249 // We don't decrement pending requests here, let's wait for the peer to either
1250 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1251 // us and resume where they left off, we don't want to have piled on to those chunks
1252 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1253 // could let us request a lot of stuff, then choke us and never reject, but they're
1254 // only a single peer, our chunk balancing should smooth over this abuse.
1256 c.peerChoking = true
1257 c.updateExpectingChunks()
1260 // Some clients do this for some reason. Transmission doesn't error on this, so we
1261 // won't for consistency.
1262 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1265 c.peerChoking = false
1267 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1268 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1273 if preservedCount != 0 {
1274 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1276 c.logger.Levelf(log.Debug,
1277 "%v requests were preserved while being choked (fast=%v)",
1281 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1283 if !c.t._pendingPieces.IsEmpty() {
1284 c.updateRequests("unchoked")
1286 c.updateExpectingChunks()
1288 c.peerInterested = true
1290 case pp.NotInterested:
1291 c.peerInterested = false
1292 // We don't clear their requests since it isn't clear in the spec.
1293 // We'll probably choke them for this, which will clear them if
1294 // appropriate, and is clearly specified.
1296 err = c.peerSentHave(pieceIndex(msg.Index))
1298 err = c.peerSentBitfield(msg.Bitfield)
1300 r := newRequestFromMessage(&msg)
1301 err = c.onReadRequest(r, true)
1303 err = fmt.Errorf("on reading request %v: %w", r, err)
1306 c.doChunkReadStats(int64(len(msg.Piece)))
1307 err = c.receiveChunk(&msg)
1308 if len(msg.Piece) == int(t.chunkSize) {
1309 t.chunkPool.Put(&msg.Piece)
1312 err = fmt.Errorf("receiving chunk: %w", err)
1315 req := newRequestFromMessage(&msg)
1316 c.onPeerSentCancel(req)
1318 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1322 pingAddr := net.UDPAddr{
1327 pingAddr.Port = int(msg.Port)
1329 cl.eachDhtServer(func(s DhtServer) {
1330 go s.Ping(&pingAddr)
1333 torrent.Add("suggests received", 1)
1334 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1335 c.updateRequests("suggested")
1337 err = c.onPeerSentHaveAll()
1339 err = c.peerSentHaveNone()
1341 req := newRequestFromMessage(&msg)
1342 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1343 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1344 err = fmt.Errorf("received invalid reject [request=%v]", req)
1346 case pp.AllowedFast:
1347 torrent.Add("allowed fasts received", 1)
1348 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1349 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1351 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1353 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1361 // Returns true if it was valid to reject the request.
1362 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1363 if c.deleteRequest(r) {
1365 } else if !c.requestState.Cancelled.CheckedRemove(r) {
1368 if c.isLowOnRequests() {
1369 c.updateRequests("Peer.remoteRejectedRequest")
1371 c.decExpectedChunkReceive(r)
1375 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1376 count := c.validReceiveChunks[r]
1378 delete(c.validReceiveChunks, r)
1379 } else if count > 1 {
1380 c.validReceiveChunks[r] = count - 1
1386 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1388 // TODO: Should we still do this?
1390 // These clients use their own extension IDs for outgoing message
1391 // types, which is incorrect.
1392 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1400 case pp.HandshakeExtendedID:
1401 var d pp.ExtendedHandshakeMessage
1402 if err := bencode.Unmarshal(payload, &d); err != nil {
1403 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1404 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1406 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1409 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1411 c.PeerMaxRequests = d.Reqq
1413 c.PeerClientName.Store(d.V)
1414 if c.PeerExtensionIDs == nil {
1415 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1417 c.PeerListenPort = d.Port
1418 c.PeerPrefersEncryption = d.Encryption
1419 for name, id := range d.M {
1420 if _, ok := c.PeerExtensionIDs[name]; !ok {
1421 peersSupportingExtension.Add(
1422 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1423 // entered here which caused problems later when unmarshalling.
1424 strconv.Quote(string(name)),
1427 c.PeerExtensionIDs[name] = id
1429 if d.MetadataSize != 0 {
1430 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1431 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1434 c.requestPendingMetadata()
1435 if !t.cl.config.DisablePEX {
1436 t.pex.Add(c) // we learnt enough now
1440 case metadataExtendedId:
1441 err := cl.gotMetadataExtensionMsg(payload, t, c)
1443 return fmt.Errorf("handling metadata extension message: %w", err)
1447 if !c.pex.IsEnabled() {
1448 return nil // or hang-up maybe?
1450 return c.pex.Recv(payload)
1452 return fmt.Errorf("unexpected extended message ID: %v", id)
1456 // Set both the Reader and Writer for the connection from a single ReadWriter.
1457 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1462 // Returns the Reader and Writer as a combined ReadWriter.
1463 func (cn *PeerConn) rw() io.ReadWriter {
1470 func (c *Peer) doChunkReadStats(size int64) {
1471 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1474 // Handle a received chunk from a peer.
1475 func (c *Peer) receiveChunk(msg *pp.Message) error {
1476 chunksReceived.Add("total", 1)
1478 ppReq := newRequestFromMessage(msg)
1480 err := t.checkValidReceiveChunk(ppReq)
1482 err = log.WithLevel(log.Warning, err)
1485 req := c.t.requestIndexFromRequest(ppReq)
1487 if c.bannableAddr.Ok {
1488 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
1492 chunksReceived.Add("while choked", 1)
1495 if c.validReceiveChunks[req] <= 0 {
1496 chunksReceived.Add("unexpected", 1)
1497 return errors.New("received unexpected chunk")
1499 c.decExpectedChunkReceive(req)
1501 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1502 chunksReceived.Add("due to allowed fast", 1)
1505 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1506 // have actually already received the piece, while we have the Client unlocked to write the data
1510 if c.requestState.Requests.Contains(req) {
1511 for _, f := range c.callbacks.ReceivedRequested {
1512 f(PeerMessageEvent{c, msg})
1515 // Request has been satisfied.
1516 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1519 c._chunksReceivedWhileExpecting++
1521 if c.isLowOnRequests() {
1522 c.updateRequests("Peer.receiveChunk deleted request")
1525 chunksReceived.Add("unintended", 1)
1531 // Do we actually want this chunk?
1532 if t.haveChunk(ppReq) {
1533 // panic(fmt.Sprintf("%+v", ppReq))
1534 chunksReceived.Add("redundant", 1)
1535 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1539 piece := &t.pieces[ppReq.Index]
1541 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1542 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1544 c.piecesReceivedSinceLastRequestUpdate++
1545 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1547 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1548 f(ReceivedUsefulDataEvent{c, msg})
1550 c.lastUsefulChunkReceived = time.Now()
1552 // Need to record that it hasn't been written yet, before we attempt to do
1553 // anything with it.
1554 piece.incrementPendingWrites()
1555 // Record that we have the chunk, so we aren't trying to download it while
1556 // waiting for it to be written to storage.
1557 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1559 // Cancel pending requests for this chunk from *other* peers.
1560 if p := t.requestingPeer(req); p != nil {
1562 panic("should not be pending request from conn that just received it")
1567 err = func() error {
1570 concurrentChunkWrites.Add(1)
1571 defer concurrentChunkWrites.Add(-1)
1572 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1573 // number of connections. We write inline with receiving the chunk (with this lock dance),
1574 // because we want to handle errors synchronously and I haven't thought of a nice way to
1575 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1577 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1580 piece.decrementPendingWrites()
1583 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1585 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1586 // request update runs while we're writing the chunk that just failed. Then we never do a
1587 // fresh update after pending the failed request.
1588 c.updateRequests("Peer.receiveChunk error writing chunk")
1589 t.onWriteChunkErr(err)
1593 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1595 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1596 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1597 t.queuePieceCheck(pieceIndex(ppReq.Index))
1598 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1599 // chunk status (such as the haveChunk call above) to have to check all the various other
1600 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1601 // that chunk pieces are pended at an appropriate time later however.
1604 cl.event.Broadcast()
1605 // We do this because we've written a chunk, and may change PieceState.Partial.
1606 t.publishPieceChange(pieceIndex(ppReq.Index))
1611 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1612 if c.peerTouchedPieces == nil {
1613 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1615 c.peerTouchedPieces[piece] = struct{}{}
1616 ds := &c.t.pieces[piece].dirtiers
1618 *ds = make(map[*Peer]struct{})
1620 (*ds)[c] = struct{}{}
1623 func (c *PeerConn) uploadAllowed() bool {
1624 if c.t.cl.config.NoUpload {
1627 if c.t.dataUploadDisallowed {
1633 if !c.peerHasWantedPieces() {
1636 // Don't upload more than 100 KiB more than we download.
1637 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1643 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1644 if c.uploadTimer == nil {
1645 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1647 c.uploadTimer.Reset(delay)
1651 // Also handles choking and unchoking of the remote peer.
1652 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1653 // Breaking or completing this loop means we don't want to upload to the
1654 // peer anymore, and we choke them.
1656 for c.uploadAllowed() {
1657 // We want to upload to the peer.
1658 if !c.unchoke(msg) {
1661 for r, state := range c.peerRequests {
1662 if state.data == nil {
1665 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1667 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1669 delay := res.Delay()
1672 c.setRetryUploadTimer(delay)
1673 // Hard to say what to return here.
1676 more := c.sendChunk(r, msg, state)
1677 delete(c.peerRequests, r)
1688 func (cn *PeerConn) drop() {
1689 cn.t.dropConnection(cn)
1692 func (cn *PeerConn) ban() {
1693 cn.t.cl.banPeerIP(cn.remoteIp())
1696 func (cn *Peer) netGoodPiecesDirtied() int64 {
1697 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1700 func (c *Peer) peerHasWantedPieces() bool {
1701 if all, _ := c.peerHasAllPieces(); all {
1702 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1704 if !c.t.haveInfo() {
1705 return !c.peerPieces().IsEmpty()
1707 return c.peerPieces().Intersects(&c.t._pendingPieces)
1710 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1712 func (c *Peer) deleteRequest(r RequestIndex) bool {
1713 if !c.requestState.Requests.CheckedRemove(r) {
1716 for _, f := range c.callbacks.DeletedRequest {
1717 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1719 c.updateExpectingChunks()
1720 if c.t.requestingPeer(r) != c {
1721 panic("only one peer should have a given request at a time")
1723 delete(c.t.requestState, r)
1724 // c.t.iterPeers(func(p *Peer) {
1725 // if p.isLowOnRequests() {
1726 // p.updateRequests("Peer.deleteRequest")
1732 func (c *Peer) deleteAllRequests(reason string) {
1733 if c.requestState.Requests.IsEmpty() {
1736 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1737 if !c.deleteRequest(x) {
1738 panic("request should exist")
1742 c.assertNoRequests()
1743 c.t.iterPeers(func(p *Peer) {
1744 if p.isLowOnRequests() {
1745 p.updateRequests(reason)
1751 func (c *Peer) assertNoRequests() {
1752 if !c.requestState.Requests.IsEmpty() {
1753 panic(c.requestState.Requests.GetCardinality())
1757 func (c *Peer) cancelAllRequests() {
1758 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1762 c.assertNoRequests()
1766 // This is called when something has changed that should wake the writer, such as putting stuff into
1767 // the writeBuffer, or changing some state that the writer can act on.
1768 func (c *PeerConn) tickleWriter() {
1769 c.messageWriter.writeCond.Broadcast()
1772 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1773 c.lastChunkSent = time.Now()
1774 state.allocReservation.Release()
1775 return msg(pp.Message{
1783 func (c *PeerConn) setTorrent(t *Torrent) {
1785 panic("connection already associated with a torrent")
1788 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1789 t.reconcileHandshakeStats(c)
1792 func (c *Peer) peerPriority() (peerPriority, error) {
1793 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
1796 func (c *Peer) remoteIp() net.IP {
1797 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1798 return net.ParseIP(host)
1801 func (c *Peer) remoteIpPort() IpPort {
1802 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1803 return IpPort{ipa.IP, uint16(ipa.Port)}
1806 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1807 f := pp.PexPeerFlags(0)
1808 if c.PeerPrefersEncryption {
1809 f |= pp.PexPrefersEncryption
1812 f |= pp.PexOutgoingConn
1815 f |= pp.PexSupportsUtp
1820 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1821 // advertised listen port.
1822 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1823 if !c.outgoing && c.PeerListenPort != 0 {
1824 switch addr := c.RemoteAddr.(type) {
1827 dialAddr.Port = c.PeerListenPort
1831 dialAddr.Port = c.PeerListenPort
1838 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1839 f := c.pexPeerFlags()
1840 addr := c.dialAddr()
1841 return pexEvent{t, addr, f, nil}
1844 func (c *PeerConn) String() string {
1845 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1848 func (c *Peer) trust() connectionTrust {
1849 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1852 type connectionTrust struct {
1854 NetGoodPiecesDirted int64
1857 func (l connectionTrust) Less(r connectionTrust) bool {
1858 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1861 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1862 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1863 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1865 defer cn.locker().RUnlock()
1866 return cn.newPeerPieces()
1869 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1870 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1871 // TODO: Can we use copy on write?
1872 ret := cn.peerPieces().Clone()
1873 if all, _ := cn.peerHasAllPieces(); all {
1874 if cn.t.haveInfo() {
1875 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1877 ret.AddRange(0, bitmap.ToEnd)
1883 func (cn *Peer) stats() *ConnStats {
1887 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1888 pc, ok := p.peerImpl.(*PeerConn)
1892 func (p *Peer) uncancelledRequests() uint64 {
1893 return p.requestState.Requests.GetCardinality()
1896 func (pc *PeerConn) remoteIsTransmission() bool {
1897 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'