16 "github.com/RoaringBitmap/roaring"
17 "github.com/anacrolix/chansync"
18 . "github.com/anacrolix/generics"
19 "github.com/anacrolix/log"
20 "github.com/anacrolix/missinggo/iter"
21 "github.com/anacrolix/missinggo/v2/bitmap"
22 "github.com/anacrolix/multiless"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/metainfo"
25 "github.com/anacrolix/torrent/mse"
26 pp "github.com/anacrolix/torrent/peer_protocol"
27 request_strategy "github.com/anacrolix/torrent/request-strategy"
28 "github.com/anacrolix/torrent/typed-roaring"
31 type PeerSource string
34 PeerSourceTracker = "Tr"
35 PeerSourceIncoming = "I"
36 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
37 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
39 // The peer was given directly, such as through a magnet link.
40 PeerSourceDirect = "M"
43 type peerRequestState struct {
47 type PeerRemoteAddr interface {
52 // Since we have to store all the requests in memory, we can't reasonably exceed what could be
53 // indexed with the memory space available.
58 // First to ensure 64-bit alignment for atomics. See #262.
68 RemoteAddr PeerRemoteAddr
69 bannableAddr Option[bannableAddr]
70 // True if the connection is operating over MSE obfuscation.
72 cryptoMethod mse.CryptoMethod
75 closed chansync.SetOnce
76 // Set true after we've added our ConnStats generated during handshake to
77 // other ConnStat instances as determined when the *Torrent became known.
78 reconciledHandshakeStats bool
80 lastMessageReceived time.Time
81 completedHandshake time.Time
82 lastUsefulChunkReceived time.Time
83 lastChunkSent time.Time
85 // Stuff controlled by the local peer.
86 needRequestUpdate string
87 requestState request_strategy.PeerRequestState
88 updateRequestsTimer *time.Timer
89 lastRequestUpdate time.Time
90 peakRequests maxRequests
91 lastBecameInterested time.Time
92 priorInterest time.Duration
94 lastStartedExpectingToReceiveChunks time.Time
95 cumulativeExpectedToReceiveChunks time.Duration
96 _chunksReceivedWhileExpecting int64
99 piecesReceivedSinceLastRequestUpdate maxRequests
100 maxPiecesReceivedBetweenRequestUpdates maxRequests
101 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
102 // and implementation differences, we may receive chunks that are no longer in the set of
103 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
104 validReceiveChunks map[RequestIndex]int
105 // Indexed by metadata piece, set to true if posted and pending a
107 metadataRequests []bool
108 sentHaves bitmap.Bitmap
110 // Stuff controlled by the remote peer.
113 peerRequests map[Request]*peerRequestState
114 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
116 // The highest possible number of pieces the torrent could have based on
117 // communication with the peer. Generally only useful until we have the
119 peerMinPieces pieceIndex
120 // Pieces we've accepted chunks for from the peer.
121 peerTouchedPieces map[pieceIndex]struct{}
122 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
124 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
125 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
126 PeerClientName atomic.Value
131 type peerRequests = orderedBitmap[RequestIndex]
133 func (p *Peer) initRequestState() {
134 p.requestState.Requests = &peerRequests{}
137 // Maintains the state of a BitTorrent-protocol based connection with a peer.
138 type PeerConn struct {
141 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
142 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
147 PeerExtensionBytes pp.PeerExtensionBits
149 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
150 // while holding any mutexes.
152 // The Reader and Writer for this Conn, with hooks installed for stats,
153 // limiting, deadlines etc.
157 messageWriter peerConnMsgWriter
159 uploadTimer *time.Timer
162 // The pieces the peer has claimed to have.
163 _peerPieces roaring.Bitmap
164 // The peer has everything. This can occur due to a special message, when
165 // we may not even know the number of pieces in the torrent yet.
169 func (cn *PeerConn) connStatusString() string {
170 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
173 func (cn *Peer) updateExpectingChunks() {
174 if cn.expectingChunks() {
175 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
176 cn.lastStartedExpectingToReceiveChunks = time.Now()
179 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
180 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
181 cn.lastStartedExpectingToReceiveChunks = time.Time{}
186 func (cn *Peer) expectingChunks() bool {
187 if cn.requestState.Requests.IsEmpty() {
190 if !cn.requestState.Interested {
196 haveAllowedFastRequests := false
197 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
198 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
199 cn.requestState.Requests,
200 cn.t.pieceRequestIndexOffset(i),
201 cn.t.pieceRequestIndexOffset(i+1),
203 return !haveAllowedFastRequests
205 return haveAllowedFastRequests
208 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
209 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
212 // Returns true if the connection is over IPv6.
213 func (cn *PeerConn) ipv6() bool {
218 return len(ip) == net.IPv6len
221 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
222 // specification for this.
223 func (cn *PeerConn) isPreferredDirection() bool {
224 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
227 // Returns whether the left connection should be preferred over the right one,
228 // considering only their networking properties. If ok is false, we can't
230 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
231 var ml multiless.Computation
232 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
233 ml = ml.Bool(l.utp(), r.utp())
234 ml = ml.Bool(r.ipv6(), l.ipv6())
238 func (cn *Peer) cumInterest() time.Duration {
239 ret := cn.priorInterest
240 if cn.requestState.Interested {
241 ret += time.Since(cn.lastBecameInterested)
246 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
247 if cn.peerSentHaveAll {
250 if !cn.t.haveInfo() {
253 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
256 func (cn *Peer) locker() *lockWithDeferreds {
257 return cn.t.cl.locker()
260 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
261 _, ok := cn.PeerExtensionIDs[ext]
265 // The best guess at number of pieces in the torrent for this peer.
266 func (cn *Peer) bestPeerNumPieces() pieceIndex {
268 return cn.t.numPieces()
270 return cn.peerMinPieces
273 func (cn *Peer) completedString() string {
274 have := pieceIndex(cn.peerPieces().GetCardinality())
275 if all, _ := cn.peerHasAllPieces(); all {
276 have = cn.bestPeerNumPieces()
278 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
281 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
282 cn.setNumPieces(info.NumPieces())
285 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
286 // receiving badly sized BITFIELD, or invalid HAVE messages.
287 func (cn *PeerConn) setNumPieces(num pieceIndex) {
288 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
289 cn.peerPiecesChanged()
292 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
293 return &cn._peerPieces
296 func eventAgeString(t time.Time) string {
300 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
303 func (cn *PeerConn) connectionFlags() (ret string) {
305 ret += string([]byte{b})
307 if cn.cryptoMethod == mse.CryptoMethodRC4 {
309 } else if cn.headerEncrypted {
312 ret += string(cn.Discovery)
319 func (cn *PeerConn) utp() bool {
320 return parseNetworkString(cn.Network).Udp
323 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
324 func (cn *Peer) statusFlags() (ret string) {
326 ret += string([]byte{b})
328 if cn.requestState.Interested {
335 ret += cn.connectionFlags()
337 if cn.peerInterested {
346 func (cn *Peer) downloadRate() float64 {
347 num := cn._stats.BytesReadUsefulData.Int64()
351 return float64(num) / cn.totalExpectingTime().Seconds()
354 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
355 var last Option[pieceIndex]
357 next := func(item Option[pieceIndex]) {
362 f(last.Value(), count)
368 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
369 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
372 next(None[pieceIndex]())
375 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
376 // \t isn't preserved in <pre> blocks?
377 if cn.closed.IsSet() {
378 fmt.Fprint(w, "CLOSED: ")
380 fmt.Fprintln(w, cn.connStatusString())
381 prio, err := cn.peerPriority()
382 prioStr := fmt.Sprintf("%08x", prio)
384 prioStr += ": " + err.Error()
386 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
387 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
388 eventAgeString(cn.lastMessageReceived),
389 eventAgeString(cn.completedHandshake),
390 eventAgeString(cn.lastHelpful()),
392 cn.totalExpectingTime(),
395 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
396 cn.completedString(),
397 len(cn.peerTouchedPieces),
398 &cn._stats.ChunksReadUseful,
399 &cn._stats.ChunksRead,
400 &cn._stats.ChunksWritten,
401 cn.requestState.Requests.GetCardinality(),
402 cn.requestState.Cancelled.GetCardinality(),
403 cn.nominalMaxRequests(),
405 len(cn.peerRequests),
408 cn.downloadRate()/(1<<10),
410 fmt.Fprintf(w, " requested pieces:")
411 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
412 fmt.Fprintf(w, " %v(%v)", piece, count)
417 func (p *Peer) close() {
421 if p.updateRequestsTimer != nil {
422 p.updateRequestsTimer.Stop()
426 p.t.decPeerPieceAvailability(p)
428 for _, f := range p.callbacks.PeerClosed {
433 func (cn *PeerConn) onClose() {
434 if cn.pex.IsEnabled() {
441 if cb := cn.callbacks.PeerConnClosed; cb != nil {
446 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
447 // they do (known=true).
448 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
449 if all, known := cn.peerHasAllPieces(); all && known {
452 return cn.peerPieces().ContainsInt(piece)
455 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
456 // https://github.com/pion/datachannel/issues/59 is fixed.
458 writeBufferHighWaterLen = 1 << 15
459 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
462 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
463 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
464 func (cn *PeerConn) write(msg pp.Message) bool {
465 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
466 // We don't need to track bytes here because the connection's Writer has that behaviour injected
467 // (although there's some delay between us buffering the message, and the connection writer
468 // flushing it out.).
469 notFull := cn.messageWriter.write(msg)
470 // Last I checked only Piece messages affect stats, and we don't write those.
476 func (cn *PeerConn) requestMetadataPiece(index int) {
477 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
478 if eID == pp.ExtensionDeleteNumber {
481 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
484 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
485 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
486 for index >= len(cn.metadataRequests) {
487 cn.metadataRequests = append(cn.metadataRequests, false)
489 cn.metadataRequests[index] = true
492 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
493 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
497 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
498 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
499 // This is the maximum request count that could fit in the write buffer if it's at or below the
500 // low water mark when we run maybeUpdateActualRequestState.
501 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
504 // The actual value to use as the maximum outbound requests.
505 func (cn *Peer) nominalMaxRequests() maxRequests {
506 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
509 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
510 ret = cn.cumulativeExpectedToReceiveChunks
511 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
512 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
517 func (cn *PeerConn) onPeerSentCancel(r Request) {
518 if _, ok := cn.peerRequests[r]; !ok {
519 torrent.Add("unexpected cancels received", 1)
522 if cn.fastEnabled() {
525 delete(cn.peerRequests, r)
529 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
534 more = msg(pp.Message{
537 if !cn.fastEnabled() {
538 cn.peerRequests = nil
543 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
548 return msg(pp.Message{
553 func (cn *Peer) setInterested(interested bool) bool {
554 if cn.requestState.Interested == interested {
557 cn.requestState.Interested = interested
559 cn.lastBecameInterested = time.Now()
560 } else if !cn.lastBecameInterested.IsZero() {
561 cn.priorInterest += time.Since(cn.lastBecameInterested)
563 cn.updateExpectingChunks()
564 // log.Printf("%p: setting interest: %v", cn, interested)
565 return cn.writeInterested(interested)
568 func (pc *PeerConn) writeInterested(interested bool) bool {
569 return pc.write(pp.Message{
570 Type: func() pp.MessageType {
574 return pp.NotInterested
580 // The function takes a message to be sent, and returns true if more messages
582 type messageWriter func(pp.Message) bool
584 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
585 // when we want to go fast.
586 func (cn *Peer) shouldRequest(r RequestIndex) error {
587 pi := cn.t.pieceIndexOfRequestIndex(r)
588 if cn.requestState.Cancelled.Contains(r) {
589 return errors.New("request is cancelled and waiting acknowledgement")
591 if !cn.peerHasPiece(pi) {
592 return errors.New("requesting piece peer doesn't have")
594 if !cn.t.peerIsActive(cn) {
595 panic("requesting but not in active conns")
597 if cn.closed.IsSet() {
598 panic("requesting when connection is closed")
600 if cn.t.hashingPiece(pi) {
601 panic("piece is being hashed")
603 if cn.t.pieceQueuedForHash(pi) {
604 panic("piece is queued for hash")
606 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
607 // This could occur if we made a request with the fast extension, and then got choked and
608 // haven't had the request rejected yet.
609 if !cn.requestState.Requests.Contains(r) {
610 panic("peer choking and piece not allowed fast")
616 func (cn *Peer) mustRequest(r RequestIndex) bool {
617 more, err := cn.request(r)
624 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
625 if err := cn.shouldRequest(r); err != nil {
628 if cn.requestState.Requests.Contains(r) {
631 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
632 return true, errors.New("too many outstanding requests")
634 cn.requestState.Requests.Add(r)
635 if cn.validReceiveChunks == nil {
636 cn.validReceiveChunks = make(map[RequestIndex]int)
638 cn.validReceiveChunks[r]++
639 cn.t.requestState[r] = requestState{
643 cn.updateExpectingChunks()
644 ppReq := cn.t.requestIndexToRequest(r)
645 for _, f := range cn.callbacks.SentRequest {
646 f(PeerRequestEvent{cn, ppReq})
648 return cn.peerImpl._request(ppReq), nil
651 func (me *PeerConn) _request(r Request) bool {
652 return me.write(pp.Message{
660 func (me *Peer) cancel(r RequestIndex) {
661 if !me.deleteRequest(r) {
662 panic("request not existing should have been guarded")
665 if !me.requestState.Cancelled.CheckedAdd(r) {
666 panic("request already cancelled")
670 if me.isLowOnRequests() {
671 me.updateRequests("Peer.cancel")
675 func (me *PeerConn) _cancel(r RequestIndex) bool {
676 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
677 // Transmission does not send rejects for received cancels. See
678 // https://github.com/transmission/transmission/pull/2275.
679 return me.fastEnabled() && !me.remoteIsTransmission()
682 func (cn *PeerConn) fillWriteBuffer() {
683 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
684 // Fully committing to our max requests requires sufficient space (see
685 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
686 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
687 // request reason will not be cleared, so we'll come right back here when there's space. We
688 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
689 // knowledge of write buffers.
691 cn.maybeUpdateActualRequestState()
692 if cn.pex.IsEnabled() {
693 if flow := cn.pex.Share(cn.write); !flow {
700 func (cn *PeerConn) have(piece pieceIndex) {
701 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
706 Index: pp.Integer(piece),
708 cn.sentHaves.Add(bitmap.BitIndex(piece))
711 func (cn *PeerConn) postBitfield() {
712 if cn.sentHaves.Len() != 0 {
713 panic("bitfield must be first have-related message sent")
715 if !cn.t.haveAnyPieces() {
720 Bitfield: cn.t.bitfield(),
722 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
725 // Sets a reason to update requests, and if there wasn't already one, handle it.
726 func (cn *Peer) updateRequests(reason string) {
727 if cn.needRequestUpdate != "" {
730 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
733 cn.needRequestUpdate = reason
734 cn.handleUpdateRequests()
737 func (cn *PeerConn) handleUpdateRequests() {
738 // The writer determines the request state as needed when it can write.
742 // Emits the indices in the Bitmaps bms in order, never repeating any index.
743 // skip is mutated during execution, and its initial values will never be
745 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
746 return func(cb iter.Callback) {
747 for _, bm := range bms {
749 func(_i interface{}) bool {
751 if skip.Contains(bitmap.BitIndex(i)) {
754 skip.Add(bitmap.BitIndex(i))
765 func (cn *Peer) peerPiecesChanged() {
766 cn.t.maybeDropMutuallyCompletePeer(cn)
769 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
770 if newMin > cn.peerMinPieces {
771 cn.peerMinPieces = newMin
775 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
776 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
777 return errors.New("invalid piece")
779 if cn.peerHasPiece(piece) {
782 cn.raisePeerMinPieces(piece + 1)
783 if !cn.peerHasPiece(piece) {
784 cn.t.incPieceAvailability(piece)
786 cn._peerPieces.Add(uint32(piece))
787 if cn.t.wantPieceIndex(piece) {
788 cn.updateRequests("have")
790 cn.peerPiecesChanged()
794 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
796 panic("expected bitfield length divisible by 8")
798 // We know that the last byte means that at most the last 7 bits are wasted.
799 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
800 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
801 // Ignore known excess pieces.
802 bf = bf[:cn.t.numPieces()]
804 bm := boolSliceToBitmap(bf)
805 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
806 cn.onPeerHasAllPieces()
810 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
812 shouldUpdateRequests := false
813 if cn.peerSentHaveAll {
814 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
817 cn.peerSentHaveAll = false
818 if !cn._peerPieces.IsEmpty() {
819 panic("if peer has all, we expect no individual peer pieces to be set")
822 bm.Xor(&cn._peerPieces)
824 cn.peerSentHaveAll = false
825 // bm is now 'on' for pieces that are changing
826 bm.Iterate(func(x uint32) bool {
828 if cn._peerPieces.Contains(x) {
829 // Then we must be losing this piece
830 cn.t.decPieceAvailability(pi)
832 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
833 shouldUpdateRequests = true
835 // We must be gaining this piece
836 cn.t.incPieceAvailability(pieceIndex(x))
840 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
842 cn._peerPieces.Xor(&bm)
843 if shouldUpdateRequests {
844 cn.updateRequests("bitfield")
846 // We didn't guard this before, I see no reason to do it now.
847 cn.peerPiecesChanged()
851 func (cn *PeerConn) onPeerHasAllPieces() {
854 cn._peerPieces.Iterate(func(x uint32) bool {
855 t.decPieceAvailability(pieceIndex(x))
859 t.addConnWithAllPieces(&cn.Peer)
860 cn.peerSentHaveAll = true
861 cn._peerPieces.Clear()
862 if !cn.t._pendingPieces.IsEmpty() {
863 cn.updateRequests("Peer.onPeerHasAllPieces")
865 cn.peerPiecesChanged()
868 func (cn *PeerConn) onPeerSentHaveAll() error {
869 cn.onPeerHasAllPieces()
873 func (cn *PeerConn) peerSentHaveNone() error {
874 if cn.peerSentHaveAll {
875 cn.t.decPeerPieceAvailability(&cn.Peer)
877 cn._peerPieces.Clear()
878 cn.peerSentHaveAll = false
879 cn.peerPiecesChanged()
883 func (c *PeerConn) requestPendingMetadata() {
887 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
888 // Peer doesn't support this.
891 // Request metadata pieces that we don't have in a random order.
893 for index := 0; index < c.t.metadataPieceCount(); index++ {
894 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
895 pending = append(pending, index)
898 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
899 for _, i := range pending {
900 c.requestMetadataPiece(i)
904 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
905 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
906 if msg.Type == pp.Extended {
907 for name, id := range cn.PeerExtensionIDs {
908 if id != msg.ExtendedID {
911 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
914 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
917 // After handshake, we know what Torrent and Client stats to include for a
919 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
925 // All ConnStats that include this connection. Some objects are not known
926 // until the handshake is complete, after which it's expected to reconcile the
928 func (cn *Peer) allStats(f func(*ConnStats)) {
930 if cn.reconciledHandshakeStats {
931 cn.postHandshakeStats(f)
935 func (cn *PeerConn) wroteBytes(n int64) {
936 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
939 func (cn *Peer) readBytes(n int64) {
940 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
943 // Returns whether the connection could be useful to us. We're seeding and
944 // they want data, we don't have metainfo and they can provide it, etc.
945 func (c *Peer) useful() bool {
947 if c.closed.IsSet() {
951 return c.supportsExtension("ut_metadata")
953 if t.seeding() && c.peerInterested {
956 if c.peerHasWantedPieces() {
962 func (c *Peer) lastHelpful() (ret time.Time) {
963 ret = c.lastUsefulChunkReceived
964 if c.t.seeding() && c.lastChunkSent.After(ret) {
965 ret = c.lastChunkSent
970 func (c *PeerConn) fastEnabled() bool {
971 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
974 func (c *PeerConn) reject(r Request) {
975 if !c.fastEnabled() {
976 panic("fast not enabled")
978 c.write(r.ToMsg(pp.Reject))
979 delete(c.peerRequests, r)
982 func (c *PeerConn) onReadRequest(r Request) error {
983 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
984 if _, ok := c.peerRequests[r]; ok {
985 torrent.Add("duplicate requests received", 1)
989 torrent.Add("requests received while choking", 1)
991 torrent.Add("requests rejected while choking", 1)
996 // TODO: What if they've already requested this?
997 if len(c.peerRequests) >= localClientReqq {
998 torrent.Add("requests received while queue full", 1)
1002 // BEP 6 says we may close here if we choose.
1005 if !c.t.havePiece(pieceIndex(r.Index)) {
1006 // This isn't necessarily them screwing up. We can drop pieces
1007 // from our storage, and can't communicate this to peers
1008 // except by reconnecting.
1009 requestsReceivedForMissingPieces.Add(1)
1010 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1012 // Check this after we know we have the piece, so that the piece length will be known.
1013 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1014 torrent.Add("bad requests received", 1)
1015 return errors.New("bad Request")
1017 if c.peerRequests == nil {
1018 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1020 value := &peerRequestState{}
1021 c.peerRequests[r] = value
1022 go c.peerRequestDataReader(r, value)
1026 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1027 b, err := readPeerRequestData(r, c)
1029 defer c.locker().Unlock()
1031 c.peerRequestDataReadFailed(err, r)
1034 panic("data must be non-nil to trigger send")
1036 torrent.Add("peer request data read successes", 1)
1042 // If this is maintained correctly, we might be able to support optional synchronous reading for
1043 // chunk sending, the way it used to work.
1044 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1045 torrent.Add("peer request data read failures", 1)
1046 logLevel := log.Warning
1047 if c.t.hasStorageCap() {
1048 // It's expected that pieces might drop. See
1049 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1050 logLevel = log.Debug
1052 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1053 if c.t.closed.IsSet() {
1056 i := pieceIndex(r.Index)
1057 if c.t.pieceComplete(i) {
1058 // There used to be more code here that just duplicated the following break. Piece
1059 // completions are currently cached, so I'm not sure how helpful this update is, except to
1060 // pull any completion changes pushed to the storage backend in failed reads that got us
1062 c.t.updatePieceCompletion(i)
1064 // We've probably dropped a piece from storage, but there's no way to communicate this to the
1065 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1066 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1067 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1069 if c.fastEnabled() {
1073 // If fast isn't enabled, I think we would have wiped all peer requests when we last
1074 // choked, and requests while we're choking would be ignored. It could be possible that
1075 // a peer request data read completed concurrently to it being deleted elsewhere.
1076 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1078 // Choking a non-fast peer should cause them to flush all their requests.
1083 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1084 b := make([]byte, r.Length)
1085 p := c.t.info.Piece(int(r.Index))
1086 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1093 panic("expected error")
1099 func runSafeExtraneous(f func()) {
1107 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1108 c.logger.WithContextText(fmt.Sprintf(
1109 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1110 )).SkipCallers(1).Levelf(level, format, arg...)
1113 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1114 // exit. Returning will end the connection.
1115 func (c *PeerConn) mainReadLoop() (err error) {
1118 torrent.Add("connection.mainReadLoop returned with error", 1)
1120 torrent.Add("connection.mainReadLoop returned with no error", 1)
1126 decoder := pp.Decoder{
1127 R: bufio.NewReaderSize(c.r, 1<<17),
1128 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1136 err = decoder.Decode(&msg)
1138 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1141 if t.closed.IsSet() || c.closed.IsSet() {
1147 c.lastMessageReceived = time.Now()
1149 receivedKeepalives.Add(1)
1152 messageTypesReceived.Add(msg.Type.String(), 1)
1153 if msg.Type.FastExtension() && !c.fastEnabled() {
1154 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1155 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1162 if !c.fastEnabled() {
1163 c.deleteAllRequests("choked by non-fast PeerConn")
1165 // We don't decrement pending requests here, let's wait for the peer to either
1166 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1167 // us and resume where they left off, we don't want to have piled on to those chunks
1168 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1169 // could let us request a lot of stuff, then choke us and never reject, but they're
1170 // only a single peer, our chunk balancing should smooth over this abuse.
1172 c.peerChoking = true
1173 c.updateExpectingChunks()
1176 // Some clients do this for some reason. Transmission doesn't error on this, so we
1177 // won't for consistency.
1178 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1181 c.peerChoking = false
1183 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1184 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1189 if preservedCount != 0 {
1190 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1192 c.logger.Levelf(log.Debug,
1193 "%v requests were preserved while being choked (fast=%v)",
1197 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1199 if !c.t._pendingPieces.IsEmpty() {
1200 c.updateRequests("unchoked")
1202 c.updateExpectingChunks()
1204 c.peerInterested = true
1206 case pp.NotInterested:
1207 c.peerInterested = false
1208 // We don't clear their requests since it isn't clear in the spec.
1209 // We'll probably choke them for this, which will clear them if
1210 // appropriate, and is clearly specified.
1212 err = c.peerSentHave(pieceIndex(msg.Index))
1214 err = c.peerSentBitfield(msg.Bitfield)
1216 r := newRequestFromMessage(&msg)
1217 err = c.onReadRequest(r)
1219 c.doChunkReadStats(int64(len(msg.Piece)))
1220 err = c.receiveChunk(&msg)
1221 if len(msg.Piece) == int(t.chunkSize) {
1222 t.chunkPool.Put(&msg.Piece)
1225 err = fmt.Errorf("receiving chunk: %w", err)
1228 req := newRequestFromMessage(&msg)
1229 c.onPeerSentCancel(req)
1231 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1235 pingAddr := net.UDPAddr{
1240 pingAddr.Port = int(msg.Port)
1242 cl.eachDhtServer(func(s DhtServer) {
1243 go s.Ping(&pingAddr)
1246 torrent.Add("suggests received", 1)
1247 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1248 c.updateRequests("suggested")
1250 err = c.onPeerSentHaveAll()
1252 err = c.peerSentHaveNone()
1254 req := newRequestFromMessage(&msg)
1255 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1256 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1257 err = fmt.Errorf("received invalid reject [request=%v]", req)
1259 case pp.AllowedFast:
1260 torrent.Add("allowed fasts received", 1)
1261 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1262 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1264 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1266 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1274 // Returns true if it was valid to reject the request.
1275 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1276 if c.deleteRequest(r) {
1278 } else if !c.requestState.Cancelled.CheckedRemove(r) {
1281 if c.isLowOnRequests() {
1282 c.updateRequests("Peer.remoteRejectedRequest")
1284 c.decExpectedChunkReceive(r)
1288 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1289 count := c.validReceiveChunks[r]
1291 delete(c.validReceiveChunks, r)
1292 } else if count > 1 {
1293 c.validReceiveChunks[r] = count - 1
1299 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1301 // TODO: Should we still do this?
1303 // These clients use their own extension IDs for outgoing message
1304 // types, which is incorrect.
1305 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1313 case pp.HandshakeExtendedID:
1314 var d pp.ExtendedHandshakeMessage
1315 if err := bencode.Unmarshal(payload, &d); err != nil {
1316 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1317 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1319 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1322 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1324 c.PeerMaxRequests = d.Reqq
1326 c.PeerClientName.Store(d.V)
1327 if c.PeerExtensionIDs == nil {
1328 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1330 c.PeerListenPort = d.Port
1331 c.PeerPrefersEncryption = d.Encryption
1332 for name, id := range d.M {
1333 if _, ok := c.PeerExtensionIDs[name]; !ok {
1334 peersSupportingExtension.Add(
1335 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1336 // entered here which caused problems later when unmarshalling.
1337 strconv.Quote(string(name)),
1340 c.PeerExtensionIDs[name] = id
1342 if d.MetadataSize != 0 {
1343 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1344 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1347 c.requestPendingMetadata()
1348 if !t.cl.config.DisablePEX {
1349 t.pex.Add(c) // we learnt enough now
1353 case metadataExtendedId:
1354 err := cl.gotMetadataExtensionMsg(payload, t, c)
1356 return fmt.Errorf("handling metadata extension message: %w", err)
1360 if !c.pex.IsEnabled() {
1361 return nil // or hang-up maybe?
1363 return c.pex.Recv(payload)
1365 return fmt.Errorf("unexpected extended message ID: %v", id)
1369 // Set both the Reader and Writer for the connection from a single ReadWriter.
1370 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1375 // Returns the Reader and Writer as a combined ReadWriter.
1376 func (cn *PeerConn) rw() io.ReadWriter {
1383 func (c *Peer) doChunkReadStats(size int64) {
1384 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1387 // Handle a received chunk from a peer.
1388 func (c *Peer) receiveChunk(msg *pp.Message) error {
1389 chunksReceived.Add("total", 1)
1391 ppReq := newRequestFromMessage(msg)
1392 req := c.t.requestIndexFromRequest(ppReq)
1395 if c.bannableAddr.Ok() {
1396 t.smartBanCache.RecordBlock(c.bannableAddr.Value(), req, msg.Piece)
1400 chunksReceived.Add("while choked", 1)
1403 if c.validReceiveChunks[req] <= 0 {
1404 chunksReceived.Add("unexpected", 1)
1405 return errors.New("received unexpected chunk")
1407 c.decExpectedChunkReceive(req)
1409 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1410 chunksReceived.Add("due to allowed fast", 1)
1413 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1414 // have actually already received the piece, while we have the Client unlocked to write the data
1418 if c.requestState.Requests.Contains(req) {
1419 for _, f := range c.callbacks.ReceivedRequested {
1420 f(PeerMessageEvent{c, msg})
1423 // Request has been satisfied.
1424 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1427 c._chunksReceivedWhileExpecting++
1429 if c.isLowOnRequests() {
1430 c.updateRequests("Peer.receiveChunk deleted request")
1433 chunksReceived.Add("unintended", 1)
1439 // Do we actually want this chunk?
1440 if t.haveChunk(ppReq) {
1441 // panic(fmt.Sprintf("%+v", ppReq))
1442 chunksReceived.Add("redundant", 1)
1443 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1447 piece := &t.pieces[ppReq.Index]
1449 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1450 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1452 c.piecesReceivedSinceLastRequestUpdate++
1453 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1455 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1456 f(ReceivedUsefulDataEvent{c, msg})
1458 c.lastUsefulChunkReceived = time.Now()
1460 // Need to record that it hasn't been written yet, before we attempt to do
1461 // anything with it.
1462 piece.incrementPendingWrites()
1463 // Record that we have the chunk, so we aren't trying to download it while
1464 // waiting for it to be written to storage.
1465 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1467 // Cancel pending requests for this chunk from *other* peers.
1468 if p := t.requestingPeer(req); p != nil {
1470 panic("should not be pending request from conn that just received it")
1475 err := func() error {
1478 concurrentChunkWrites.Add(1)
1479 defer concurrentChunkWrites.Add(-1)
1480 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1481 // number of connections. We write inline with receiving the chunk (with this lock dance),
1482 // because we want to handle errors synchronously and I haven't thought of a nice way to
1483 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1485 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1488 piece.decrementPendingWrites()
1491 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1493 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1494 // request update runs while we're writing the chunk that just failed. Then we never do a
1495 // fresh update after pending the failed request.
1496 c.updateRequests("Peer.receiveChunk error writing chunk")
1497 t.onWriteChunkErr(err)
1501 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1503 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1504 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1505 t.queuePieceCheck(pieceIndex(ppReq.Index))
1506 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1507 // chunk status (such as the haveChunk call above) to have to check all the various other
1508 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1509 // that chunk pieces are pended at an appropriate time later however.
1512 cl.event.Broadcast()
1513 // We do this because we've written a chunk, and may change PieceState.Partial.
1514 t.publishPieceChange(pieceIndex(ppReq.Index))
1519 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1520 if c.peerTouchedPieces == nil {
1521 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1523 c.peerTouchedPieces[piece] = struct{}{}
1524 ds := &c.t.pieces[piece].dirtiers
1526 *ds = make(map[*Peer]struct{})
1528 (*ds)[c] = struct{}{}
1531 func (c *PeerConn) uploadAllowed() bool {
1532 if c.t.cl.config.NoUpload {
1535 if c.t.dataUploadDisallowed {
1541 if !c.peerHasWantedPieces() {
1544 // Don't upload more than 100 KiB more than we download.
1545 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1551 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1552 if c.uploadTimer == nil {
1553 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1555 c.uploadTimer.Reset(delay)
1559 // Also handles choking and unchoking of the remote peer.
1560 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1561 // Breaking or completing this loop means we don't want to upload to the
1562 // peer anymore, and we choke them.
1564 for c.uploadAllowed() {
1565 // We want to upload to the peer.
1566 if !c.unchoke(msg) {
1569 for r, state := range c.peerRequests {
1570 if state.data == nil {
1573 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1575 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1577 delay := res.Delay()
1580 c.setRetryUploadTimer(delay)
1581 // Hard to say what to return here.
1584 more := c.sendChunk(r, msg, state)
1585 delete(c.peerRequests, r)
1596 func (cn *PeerConn) drop() {
1597 cn.t.dropConnection(cn)
1600 func (cn *PeerConn) ban() {
1601 cn.t.cl.banPeerIP(cn.remoteIp())
1604 func (cn *Peer) netGoodPiecesDirtied() int64 {
1605 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1608 func (c *Peer) peerHasWantedPieces() bool {
1609 if all, _ := c.peerHasAllPieces(); all {
1610 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1612 if !c.t.haveInfo() {
1613 return !c.peerPieces().IsEmpty()
1615 return c.peerPieces().Intersects(&c.t._pendingPieces)
1618 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1620 func (c *Peer) deleteRequest(r RequestIndex) bool {
1621 if !c.requestState.Requests.CheckedRemove(r) {
1624 for _, f := range c.callbacks.DeletedRequest {
1625 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1627 c.updateExpectingChunks()
1628 if c.t.requestingPeer(r) != c {
1629 panic("only one peer should have a given request at a time")
1631 c.t.requestState[r] = requestState{}
1632 // c.t.iterPeers(func(p *Peer) {
1633 // if p.isLowOnRequests() {
1634 // p.updateRequests("Peer.deleteRequest")
1640 func (c *Peer) deleteAllRequests(reason string) {
1641 if c.requestState.Requests.IsEmpty() {
1644 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1645 if !c.deleteRequest(x) {
1646 panic("request should exist")
1650 c.assertNoRequests()
1651 c.t.iterPeers(func(p *Peer) {
1652 if p.isLowOnRequests() {
1653 p.updateRequests(reason)
1659 func (c *Peer) assertNoRequests() {
1660 if !c.requestState.Requests.IsEmpty() {
1661 panic(c.requestState.Requests.GetCardinality())
1665 func (c *Peer) cancelAllRequests() {
1666 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1670 c.assertNoRequests()
1674 // This is called when something has changed that should wake the writer, such as putting stuff into
1675 // the writeBuffer, or changing some state that the writer can act on.
1676 func (c *PeerConn) tickleWriter() {
1677 c.messageWriter.writeCond.Broadcast()
1680 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1681 c.lastChunkSent = time.Now()
1682 return msg(pp.Message{
1690 func (c *PeerConn) setTorrent(t *Torrent) {
1692 panic("connection already associated with a torrent")
1695 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1696 t.reconcileHandshakeStats(c)
1699 func (c *Peer) peerPriority() (peerPriority, error) {
1700 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1703 func (c *Peer) remoteIp() net.IP {
1704 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1705 return net.ParseIP(host)
1708 func (c *Peer) remoteIpPort() IpPort {
1709 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1710 return IpPort{ipa.IP, uint16(ipa.Port)}
1713 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1714 f := pp.PexPeerFlags(0)
1715 if c.PeerPrefersEncryption {
1716 f |= pp.PexPrefersEncryption
1719 f |= pp.PexOutgoingConn
1722 f |= pp.PexSupportsUtp
1727 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1728 // advertised listen port.
1729 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1730 if !c.outgoing && c.PeerListenPort != 0 {
1731 switch addr := c.RemoteAddr.(type) {
1734 dialAddr.Port = c.PeerListenPort
1738 dialAddr.Port = c.PeerListenPort
1745 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1746 f := c.pexPeerFlags()
1747 addr := c.dialAddr()
1748 return pexEvent{t, addr, f, nil}
1751 func (c *PeerConn) String() string {
1752 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1755 func (c *Peer) trust() connectionTrust {
1756 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1759 type connectionTrust struct {
1761 NetGoodPiecesDirted int64
1764 func (l connectionTrust) Less(r connectionTrust) bool {
1765 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1768 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1769 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1770 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1772 defer cn.locker().RUnlock()
1773 return cn.newPeerPieces()
1776 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1777 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1778 // TODO: Can we use copy on write?
1779 ret := cn.peerPieces().Clone()
1780 if all, _ := cn.peerHasAllPieces(); all {
1781 if cn.t.haveInfo() {
1782 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1784 ret.AddRange(0, bitmap.ToEnd)
1790 func (cn *Peer) stats() *ConnStats {
1794 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1795 pc, ok := p.peerImpl.(*PeerConn)
1799 func (p *Peer) uncancelledRequests() uint64 {
1800 return p.requestState.Requests.GetCardinality()
1803 func (pc *PeerConn) remoteIsTransmission() bool {
1804 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'