16 "github.com/RoaringBitmap/roaring"
17 "github.com/anacrolix/log"
18 "github.com/anacrolix/missinggo/iter"
19 "github.com/anacrolix/missinggo/v2/bitmap"
20 "github.com/anacrolix/multiless"
22 "github.com/anacrolix/chansync"
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"
30 type PeerSource string
33 PeerSourceTracker = "Tr"
34 PeerSourceIncoming = "I"
35 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
36 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
38 // The peer was given directly, such as through a magnet link.
39 PeerSourceDirect = "M"
42 type peerRequestState struct {
46 type PeerRemoteAddr interface {
50 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
51 // indexable with the memory space available.
54 requestState = request_strategy.PeerNextRequestState
58 // First to ensure 64-bit alignment for atomics. See #262.
68 RemoteAddr PeerRemoteAddr
69 // True if the connection is operating over MSE obfuscation.
71 cryptoMethod mse.CryptoMethod
74 closed chansync.SetOnce
75 // Set true after we've added our ConnStats generated during handshake to
76 // other ConnStat instances as determined when the *Torrent became known.
77 reconciledHandshakeStats bool
79 lastMessageReceived time.Time
80 completedHandshake time.Time
81 lastUsefulChunkReceived time.Time
82 lastChunkSent time.Time
84 // Stuff controlled by the local peer.
85 needRequestUpdate string
86 actualRequestState requestState
87 updateRequestsTimer *time.Timer
88 cancelledRequests roaring.Bitmap
89 lastBecameInterested time.Time
90 priorInterest time.Duration
92 lastStartedExpectingToReceiveChunks time.Time
93 cumulativeExpectedToReceiveChunks time.Duration
94 _chunksReceivedWhileExpecting int64
97 piecesReceivedSinceLastRequestUpdate maxRequests
98 maxPiecesReceivedBetweenRequestUpdates maxRequests
99 // Chunks that we might reasonably expect to receive from the peer. Due to
100 // latency, buffering, and implementation differences, we may receive
101 // chunks that are no longer in the set of requests actually want.
102 validReceiveChunks map[RequestIndex]int
103 // Indexed by metadata piece, set to true if posted and pending a
105 metadataRequests []bool
106 sentHaves bitmap.Bitmap
108 // Stuff controlled by the remote peer.
111 peerRequests map[Request]*peerRequestState
112 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
114 // The pieces the peer has claimed to have.
115 _peerPieces roaring.Bitmap
116 // The peer has everything. This can occur due to a special message, when
117 // we may not even know the number of pieces in the torrent yet.
119 // The highest possible number of pieces the torrent could have based on
120 // communication with the peer. Generally only useful until we have the
122 peerMinPieces pieceIndex
123 // Pieces we've accepted chunks for from the peer.
124 peerTouchedPieces map[pieceIndex]struct{}
125 peerAllowedFast roaring.Bitmap
127 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
128 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
129 PeerClientName string
134 // Maintains the state of a BitTorrent-protocol based connection with a peer.
135 type PeerConn struct {
138 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
139 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
144 PeerExtensionBytes pp.PeerExtensionBits
146 // The actual Conn, used for closing, and setting socket options.
148 // The Reader and Writer for this Conn, with hooks installed for stats,
149 // limiting, deadlines etc.
153 messageWriter peerConnMsgWriter
155 uploadTimer *time.Timer
159 func (cn *PeerConn) connStatusString() string {
160 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
163 func (cn *Peer) updateExpectingChunks() {
164 if cn.expectingChunks() {
165 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
166 cn.lastStartedExpectingToReceiveChunks = time.Now()
169 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
170 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
171 cn.lastStartedExpectingToReceiveChunks = time.Time{}
176 func (cn *Peer) expectingChunks() bool {
177 if cn.actualRequestState.Requests.IsEmpty() {
180 if !cn.actualRequestState.Interested {
186 haveAllowedFastRequests := false
187 cn.peerAllowedFast.Iterate(func(i uint32) bool {
188 haveAllowedFastRequests = roaringBitmapRangeCardinality(
189 &cn.actualRequestState.Requests,
190 cn.t.pieceRequestIndexOffset(pieceIndex(i)),
191 cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
193 return !haveAllowedFastRequests
195 return haveAllowedFastRequests
198 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
199 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
202 // Returns true if the connection is over IPv6.
203 func (cn *PeerConn) ipv6() bool {
208 return len(ip) == net.IPv6len
211 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
212 // specification for this.
213 func (cn *PeerConn) isPreferredDirection() bool {
214 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
217 // Returns whether the left connection should be preferred over the right one,
218 // considering only their networking properties. If ok is false, we can't
220 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
222 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
223 ml.NextBool(!l.utp(), !r.utp())
224 ml.NextBool(l.ipv6(), r.ipv6())
228 func (cn *Peer) cumInterest() time.Duration {
229 ret := cn.priorInterest
230 if cn.actualRequestState.Interested {
231 ret += time.Since(cn.lastBecameInterested)
236 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
237 if cn.peerSentHaveAll {
240 if !cn.t.haveInfo() {
243 return roaring.Flip(&cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
246 func (cn *Peer) locker() *lockWithDeferreds {
247 return cn.t.cl.locker()
250 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
251 _, ok := cn.PeerExtensionIDs[ext]
255 // The best guess at number of pieces in the torrent for this peer.
256 func (cn *Peer) bestPeerNumPieces() pieceIndex {
258 return cn.t.numPieces()
260 return cn.peerMinPieces
263 func (cn *Peer) completedString() string {
264 have := pieceIndex(cn._peerPieces.GetCardinality())
265 if cn.peerSentHaveAll {
266 have = cn.bestPeerNumPieces()
268 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
271 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
272 cn.setNumPieces(info.NumPieces())
275 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
276 // receiving badly sized BITFIELD, or invalid HAVE messages.
277 func (cn *PeerConn) setNumPieces(num pieceIndex) {
278 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
279 cn.peerPiecesChanged()
282 func eventAgeString(t time.Time) string {
286 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
289 func (cn *PeerConn) connectionFlags() (ret string) {
291 ret += string([]byte{b})
293 if cn.cryptoMethod == mse.CryptoMethodRC4 {
295 } else if cn.headerEncrypted {
298 ret += string(cn.Discovery)
305 func (cn *PeerConn) utp() bool {
306 return parseNetworkString(cn.Network).Udp
309 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
310 func (cn *Peer) statusFlags() (ret string) {
312 ret += string([]byte{b})
314 if cn.actualRequestState.Interested {
321 ret += cn.connectionFlags()
323 if cn.peerInterested {
332 func (cn *Peer) downloadRate() float64 {
333 num := cn._stats.BytesReadUsefulData.Int64()
337 return float64(num) / cn.totalExpectingTime().Seconds()
340 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
341 ret = make(map[pieceIndex]int)
342 cn.actualRequestState.Requests.Iterate(func(x uint32) bool {
343 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
349 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
350 // \t isn't preserved in <pre> blocks?
351 if cn.closed.IsSet() {
352 fmt.Fprint(w, "CLOSED: ")
354 fmt.Fprintln(w, cn.connStatusString())
355 prio, err := cn.peerPriority()
356 prioStr := fmt.Sprintf("%08x", prio)
358 prioStr += ": " + err.Error()
360 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
361 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
362 eventAgeString(cn.lastMessageReceived),
363 eventAgeString(cn.completedHandshake),
364 eventAgeString(cn.lastHelpful()),
366 cn.totalExpectingTime(),
369 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d-%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
370 cn.completedString(),
371 len(cn.peerTouchedPieces),
372 &cn._stats.ChunksReadUseful,
373 &cn._stats.ChunksRead,
374 &cn._stats.ChunksWritten,
375 cn.actualRequestState.Requests.GetCardinality(),
376 cn.cancelledRequests.GetCardinality(),
377 cn.nominalMaxRequests(),
379 len(cn.peerRequests),
382 cn.downloadRate()/(1<<10),
384 fmt.Fprintf(w, " requested pieces:")
385 type pieceNumRequestsType struct {
389 var pieceNumRequests []pieceNumRequestsType
390 for piece, count := range cn.numRequestsByPiece() {
391 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
393 sort.Slice(pieceNumRequests, func(i, j int) bool {
394 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
396 for _, elem := range pieceNumRequests {
397 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
402 func (p *Peer) close() {
406 if p.updateRequestsTimer != nil {
407 p.updateRequestsTimer.Stop()
411 p.t.decPeerPieceAvailability(p)
413 for _, f := range p.callbacks.PeerClosed {
418 func (cn *PeerConn) onClose() {
419 if cn.pex.IsEnabled() {
426 if cb := cn.callbacks.PeerConnClosed; cb != nil {
431 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
432 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
435 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
436 // https://github.com/pion/datachannel/issues/59 is fixed.
437 const writeBufferHighWaterLen = 1 << 15
439 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
440 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
441 func (cn *PeerConn) write(msg pp.Message) bool {
442 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
443 // We don't need to track bytes here because the connection's Writer has that behaviour injected
444 // (although there's some delay between us buffering the message, and the connection writer
445 // flushing it out.).
446 notFull := cn.messageWriter.write(msg)
447 // Last I checked only Piece messages affect stats, and we don't write those.
453 func (cn *PeerConn) requestMetadataPiece(index int) {
454 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
455 if eID == pp.ExtensionDeleteNumber {
458 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
461 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
462 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
463 for index >= len(cn.metadataRequests) {
464 cn.metadataRequests = append(cn.metadataRequests, false)
466 cn.metadataRequests[index] = true
469 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
470 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
473 // The actual value to use as the maximum outbound requests.
474 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
475 return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 2048))
478 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
479 ret = cn.cumulativeExpectedToReceiveChunks
480 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
481 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
487 func (cn *PeerConn) onPeerSentCancel(r Request) {
488 if _, ok := cn.peerRequests[r]; !ok {
489 torrent.Add("unexpected cancels received", 1)
492 if cn.fastEnabled() {
495 delete(cn.peerRequests, r)
499 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
504 more = msg(pp.Message{
507 if cn.fastEnabled() {
508 for r := range cn.peerRequests {
509 // TODO: Don't reject pieces in allowed fast set.
513 cn.peerRequests = nil
518 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
523 return msg(pp.Message{
528 func (cn *Peer) setInterested(interested bool) bool {
529 if cn.actualRequestState.Interested == interested {
532 cn.actualRequestState.Interested = interested
534 cn.lastBecameInterested = time.Now()
535 } else if !cn.lastBecameInterested.IsZero() {
536 cn.priorInterest += time.Since(cn.lastBecameInterested)
538 cn.updateExpectingChunks()
539 // log.Printf("%p: setting interest: %v", cn, interested)
540 return cn.writeInterested(interested)
543 func (pc *PeerConn) writeInterested(interested bool) bool {
544 return pc.write(pp.Message{
545 Type: func() pp.MessageType {
549 return pp.NotInterested
555 // The function takes a message to be sent, and returns true if more messages
557 type messageWriter func(pp.Message) bool
559 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
560 // when we want to go fast.
561 func (cn *Peer) shouldRequest(r RequestIndex) error {
562 pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
563 if !cn.peerHasPiece(pi) {
564 return errors.New("requesting piece peer doesn't have")
566 if !cn.t.peerIsActive(cn) {
567 panic("requesting but not in active conns")
569 if cn.closed.IsSet() {
570 panic("requesting when connection is closed")
572 if cn.t.hashingPiece(pi) {
573 panic("piece is being hashed")
575 if cn.t.pieceQueuedForHash(pi) {
576 panic("piece is queued for hash")
578 if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
579 // This could occur if we made a request with the fast extension, and then got choked and
580 // haven't had the request rejected yet.
581 if !cn.actualRequestState.Requests.Contains(r) {
582 panic("peer choking and piece not allowed fast")
588 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
589 if err := cn.shouldRequest(r); err != nil {
592 if cn.actualRequestState.Requests.Contains(r) {
595 if maxRequests(cn.actualRequestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
596 return true, errors.New("too many outstanding requests")
598 cn.actualRequestState.Requests.Add(r)
599 if cn.validReceiveChunks == nil {
600 cn.validReceiveChunks = make(map[RequestIndex]int)
602 cn.validReceiveChunks[r]++
603 cn.t.pendingRequests.Inc(r)
604 cn.updateExpectingChunks()
605 ppReq := cn.t.requestIndexToRequest(r)
606 for _, f := range cn.callbacks.SentRequest {
607 f(PeerRequestEvent{cn, ppReq})
609 return cn.peerImpl._request(ppReq), nil
612 func (me *PeerConn) _request(r Request) bool {
613 return me.write(pp.Message{
621 func (me *Peer) cancel(r RequestIndex) bool {
622 if !me.actualRequestState.Requests.Contains(r) {
628 func (me *PeerConn) _cancel(r RequestIndex) bool {
629 if me.cancelledRequests.Contains(r) {
630 // Already cancelled and waiting for a response.
633 if me.fastEnabled() {
634 me.cancelledRequests.Add(r)
636 if !me.deleteRequest(r) {
637 panic("request not existing should have been guarded")
639 if me.isLowOnRequests() {
640 me.updateRequests("Peer.cancel")
643 return me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
646 func (cn *PeerConn) fillWriteBuffer() {
647 if !cn.maybeUpdateActualRequestState() {
650 if cn.pex.IsEnabled() {
651 if flow := cn.pex.Share(cn.write); !flow {
658 func (cn *PeerConn) have(piece pieceIndex) {
659 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
664 Index: pp.Integer(piece),
666 cn.sentHaves.Add(bitmap.BitIndex(piece))
669 func (cn *PeerConn) postBitfield() {
670 if cn.sentHaves.Len() != 0 {
671 panic("bitfield must be first have-related message sent")
673 if !cn.t.haveAnyPieces() {
678 Bitfield: cn.t.bitfield(),
680 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
683 // Sets a reason to update requests, and if there wasn't already one, handle it.
684 func (cn *Peer) updateRequests(reason string) {
685 if cn.needRequestUpdate != "" {
688 cn.needRequestUpdate = reason
689 cn.handleUpdateRequests()
692 func (cn *PeerConn) handleUpdateRequests() {
693 // The writer determines the request state as needed when it can write.
697 // Emits the indices in the Bitmaps bms in order, never repeating any index.
698 // skip is mutated during execution, and its initial values will never be
700 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
701 return func(cb iter.Callback) {
702 for _, bm := range bms {
704 func(_i interface{}) bool {
706 if skip.Contains(bitmap.BitIndex(i)) {
709 skip.Add(bitmap.BitIndex(i))
720 func (cn *Peer) peerPiecesChanged() {
721 cn.t.maybeDropMutuallyCompletePeer(cn)
724 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
725 if newMin > cn.peerMinPieces {
726 cn.peerMinPieces = newMin
730 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
731 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
732 return errors.New("invalid piece")
734 if cn.peerHasPiece(piece) {
737 cn.raisePeerMinPieces(piece + 1)
738 if !cn.peerHasPiece(piece) {
739 cn.t.incPieceAvailability(piece)
741 cn._peerPieces.Add(uint32(piece))
742 if cn.t.wantPieceIndex(piece) {
743 cn.updateRequests("have")
745 cn.peerPiecesChanged()
749 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
751 panic("expected bitfield length divisible by 8")
753 // We know that the last byte means that at most the last 7 bits are wasted.
754 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
755 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
756 // Ignore known excess pieces.
757 bf = bf[:cn.t.numPieces()]
759 pp := cn.newPeerPieces()
760 cn.peerSentHaveAll = false
761 for i, have := range bf {
763 cn.raisePeerMinPieces(pieceIndex(i) + 1)
764 if !pp.Contains(bitmap.BitIndex(i)) {
765 cn.t.incPieceAvailability(i)
768 if pp.Contains(bitmap.BitIndex(i)) {
769 cn.t.decPieceAvailability(i)
773 cn._peerPieces.Add(uint32(i))
774 if cn.t.wantPieceIndex(i) {
775 cn.updateRequests("bitfield")
778 cn._peerPieces.Remove(uint32(i))
781 cn.peerPiecesChanged()
785 func (cn *Peer) onPeerHasAllPieces() {
788 npp, pc := cn.newPeerPieces(), t.numPieces()
789 for i := 0; i < pc; i += 1 {
790 if !npp.Contains(bitmap.BitIndex(i)) {
791 t.incPieceAvailability(i)
795 cn.peerSentHaveAll = true
796 cn._peerPieces.Clear()
797 if !cn.t._pendingPieces.IsEmpty() {
798 cn.updateRequests("Peer.onPeerHasAllPieces")
800 cn.peerPiecesChanged()
803 func (cn *PeerConn) onPeerSentHaveAll() error {
804 cn.onPeerHasAllPieces()
808 func (cn *PeerConn) peerSentHaveNone() error {
809 cn.t.decPeerPieceAvailability(&cn.Peer)
810 cn._peerPieces.Clear()
811 cn.peerSentHaveAll = false
812 cn.peerPiecesChanged()
816 func (c *PeerConn) requestPendingMetadata() {
820 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
821 // Peer doesn't support this.
824 // Request metadata pieces that we don't have in a random order.
826 for index := 0; index < c.t.metadataPieceCount(); index++ {
827 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
828 pending = append(pending, index)
831 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
832 for _, i := range pending {
833 c.requestMetadataPiece(i)
837 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
838 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
839 if msg.Type == pp.Extended {
840 for name, id := range cn.PeerExtensionIDs {
841 if id != msg.ExtendedID {
844 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
847 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
850 // After handshake, we know what Torrent and Client stats to include for a
852 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
858 // All ConnStats that include this connection. Some objects are not known
859 // until the handshake is complete, after which it's expected to reconcile the
861 func (cn *Peer) allStats(f func(*ConnStats)) {
863 if cn.reconciledHandshakeStats {
864 cn.postHandshakeStats(f)
868 func (cn *PeerConn) wroteBytes(n int64) {
869 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
872 func (cn *Peer) readBytes(n int64) {
873 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
876 // Returns whether the connection could be useful to us. We're seeding and
877 // they want data, we don't have metainfo and they can provide it, etc.
878 func (c *Peer) useful() bool {
880 if c.closed.IsSet() {
884 return c.supportsExtension("ut_metadata")
886 if t.seeding() && c.peerInterested {
889 if c.peerHasWantedPieces() {
895 func (c *Peer) lastHelpful() (ret time.Time) {
896 ret = c.lastUsefulChunkReceived
897 if c.t.seeding() && c.lastChunkSent.After(ret) {
898 ret = c.lastChunkSent
903 func (c *PeerConn) fastEnabled() bool {
904 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
907 func (c *PeerConn) reject(r Request) {
908 if !c.fastEnabled() {
909 panic("fast not enabled")
911 c.write(r.ToMsg(pp.Reject))
912 delete(c.peerRequests, r)
915 func (c *PeerConn) onReadRequest(r Request) error {
916 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
917 if _, ok := c.peerRequests[r]; ok {
918 torrent.Add("duplicate requests received", 1)
922 torrent.Add("requests received while choking", 1)
924 torrent.Add("requests rejected while choking", 1)
929 // TODO: What if they've already requested this?
930 if len(c.peerRequests) >= localClientReqq {
931 torrent.Add("requests received while queue full", 1)
935 // BEP 6 says we may close here if we choose.
938 if !c.t.havePiece(pieceIndex(r.Index)) {
939 // This isn't necessarily them screwing up. We can drop pieces
940 // from our storage, and can't communicate this to peers
941 // except by reconnecting.
942 requestsReceivedForMissingPieces.Add(1)
943 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
945 // Check this after we know we have the piece, so that the piece length will be known.
946 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
947 torrent.Add("bad requests received", 1)
948 return errors.New("bad Request")
950 if c.peerRequests == nil {
951 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
953 value := &peerRequestState{}
954 c.peerRequests[r] = value
955 go c.peerRequestDataReader(r, value)
960 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
961 b, err := readPeerRequestData(r, c)
963 defer c.locker().Unlock()
965 c.peerRequestDataReadFailed(err, r)
968 panic("data must be non-nil to trigger send")
975 // If this is maintained correctly, we might be able to support optional synchronous reading for
976 // chunk sending, the way it used to work.
977 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
978 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
979 i := pieceIndex(r.Index)
980 if c.t.pieceComplete(i) {
981 // There used to be more code here that just duplicated the following break. Piece
982 // completions are currently cached, so I'm not sure how helpful this update is, except to
983 // pull any completion changes pushed to the storage backend in failed reads that got us
985 c.t.updatePieceCompletion(i)
987 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
988 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
989 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
990 // next connect. TODO: Support rejecting here too.
992 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
997 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
998 b := make([]byte, r.Length)
999 p := c.t.info.Piece(int(r.Index))
1000 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1007 panic("expected error")
1013 func runSafeExtraneous(f func()) {
1021 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1022 c.logger.WithLevel(level).WithContextText(fmt.Sprintf(
1023 "peer id %q, ext v %q", c.PeerID, c.PeerClientName,
1024 )).SkipCallers(1).Printf(format, arg...)
1027 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1028 // exit. Returning will end the connection.
1029 func (c *PeerConn) mainReadLoop() (err error) {
1032 torrent.Add("connection.mainReadLoop returned with error", 1)
1034 torrent.Add("connection.mainReadLoop returned with no error", 1)
1040 decoder := pp.Decoder{
1041 R: bufio.NewReaderSize(c.r, 1<<17),
1042 MaxLength: 256 * 1024,
1050 err = decoder.Decode(&msg)
1052 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1055 if t.closed.IsSet() || c.closed.IsSet() {
1061 c.lastMessageReceived = time.Now()
1063 receivedKeepalives.Add(1)
1066 messageTypesReceived.Add(msg.Type.String(), 1)
1067 if msg.Type.FastExtension() && !c.fastEnabled() {
1068 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1069 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1076 if !c.fastEnabled() {
1077 c.deleteAllRequests()
1079 c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1080 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1081 c.t.pendingRequests.Dec(x)
1086 c.peerChoking = true
1087 // We can then reset our interest.
1088 c.updateRequests("choked")
1089 c.updateExpectingChunks()
1092 // Some clients do this for some reason. Transmission doesn't error on this, so we
1093 // won't for consistency.
1094 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1097 c.peerChoking = false
1099 c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1100 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1102 c.t.pendingRequests.Inc(x)
1106 if preservedCount != 0 {
1107 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1109 c.logger.WithLevel(log.Debug).Printf(
1110 "%v requests were preserved while being choked (fast=%v)",
1113 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1115 c.updateRequests("unchoked")
1116 c.updateExpectingChunks()
1118 c.peerInterested = true
1120 case pp.NotInterested:
1121 c.peerInterested = false
1122 // We don't clear their requests since it isn't clear in the spec.
1123 // We'll probably choke them for this, which will clear them if
1124 // appropriate, and is clearly specified.
1126 err = c.peerSentHave(pieceIndex(msg.Index))
1128 err = c.peerSentBitfield(msg.Bitfield)
1130 r := newRequestFromMessage(&msg)
1131 err = c.onReadRequest(r)
1133 c.doChunkReadStats(int64(len(msg.Piece)))
1134 err = c.receiveChunk(&msg)
1135 if len(msg.Piece) == int(t.chunkSize) {
1136 t.chunkPool.Put(&msg.Piece)
1139 err = fmt.Errorf("receiving chunk: %w", err)
1142 req := newRequestFromMessage(&msg)
1143 c.onPeerSentCancel(req)
1145 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1149 pingAddr := net.UDPAddr{
1154 pingAddr.Port = int(msg.Port)
1156 cl.eachDhtServer(func(s DhtServer) {
1157 go s.Ping(&pingAddr)
1160 torrent.Add("suggests received", 1)
1161 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1162 c.updateRequests("suggested")
1164 err = c.onPeerSentHaveAll()
1166 err = c.peerSentHaveNone()
1168 c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1169 case pp.AllowedFast:
1170 torrent.Add("allowed fasts received", 1)
1171 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1172 pieceIndex := msg.Index.Int()
1173 // If we have outstanding requests that aren't currently counted toward the combined
1174 // outstanding request count, increment them.
1175 if c.peerAllowedFast.CheckedAdd(msg.Index.Uint32()) && c.peerChoking &&
1176 // The check here could be against having the info, but really what we need to know
1177 // is if there are any existing requests.
1178 !c.actualRequestState.Requests.IsEmpty() {
1180 i := c.actualRequestState.Requests.Iterator()
1181 i.AdvanceIfNeeded(t.pieceRequestIndexOffset(pieceIndex))
1184 if r >= t.pieceRequestIndexOffset(pieceIndex+1) {
1187 c.t.pendingRequests.Inc(r)
1190 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1192 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1194 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1202 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1203 if c.deleteRequest(r) {
1204 if c.isLowOnRequests() {
1205 c.updateRequests("Peer.remoteRejectedRequest")
1207 c.decExpectedChunkReceive(r)
1211 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1212 count := c.validReceiveChunks[r]
1214 delete(c.validReceiveChunks, r)
1215 } else if count > 1 {
1216 c.validReceiveChunks[r] = count - 1
1222 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1224 // TODO: Should we still do this?
1226 // These clients use their own extension IDs for outgoing message
1227 // types, which is incorrect.
1228 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1236 case pp.HandshakeExtendedID:
1237 var d pp.ExtendedHandshakeMessage
1238 if err := bencode.Unmarshal(payload, &d); err != nil {
1239 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1240 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1242 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1245 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1247 c.PeerMaxRequests = d.Reqq
1249 c.PeerClientName = d.V
1250 if c.PeerExtensionIDs == nil {
1251 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1253 c.PeerListenPort = d.Port
1254 c.PeerPrefersEncryption = d.Encryption
1255 for name, id := range d.M {
1256 if _, ok := c.PeerExtensionIDs[name]; !ok {
1257 peersSupportingExtension.Add(string(name), 1)
1259 c.PeerExtensionIDs[name] = id
1261 if d.MetadataSize != 0 {
1262 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1263 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1266 c.requestPendingMetadata()
1267 if !t.cl.config.DisablePEX {
1268 t.pex.Add(c) // we learnt enough now
1272 case metadataExtendedId:
1273 err := cl.gotMetadataExtensionMsg(payload, t, c)
1275 return fmt.Errorf("handling metadata extension message: %w", err)
1279 if !c.pex.IsEnabled() {
1280 return nil // or hang-up maybe?
1282 return c.pex.Recv(payload)
1284 return fmt.Errorf("unexpected extended message ID: %v", id)
1288 // Set both the Reader and Writer for the connection from a single ReadWriter.
1289 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1294 // Returns the Reader and Writer as a combined ReadWriter.
1295 func (cn *PeerConn) rw() io.ReadWriter {
1302 func (c *Peer) doChunkReadStats(size int64) {
1303 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1306 // Handle a received chunk from a peer.
1307 func (c *Peer) receiveChunk(msg *pp.Message) error {
1308 chunksReceived.Add("total", 1)
1310 ppReq := newRequestFromMessage(msg)
1311 req := c.t.requestIndexFromRequest(ppReq)
1314 chunksReceived.Add("while choked", 1)
1317 if c.validReceiveChunks[req] <= 0 {
1318 chunksReceived.Add("unexpected", 1)
1319 return errors.New("received unexpected chunk")
1321 c.decExpectedChunkReceive(req)
1323 if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1324 chunksReceived.Add("due to allowed fast", 1)
1327 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1328 // have actually already received the piece, while we have the Client unlocked to write the data
1330 deletedRequest := false
1332 if c.actualRequestState.Requests.Contains(req) {
1333 for _, f := range c.callbacks.ReceivedRequested {
1334 f(PeerMessageEvent{c, msg})
1337 // Request has been satisfied.
1338 if c.deleteRequest(req) {
1339 deletedRequest = true
1341 c._chunksReceivedWhileExpecting++
1343 if c.isLowOnRequests() {
1344 c.updateRequests("Peer.receiveChunk deleted request")
1347 chunksReceived.Add("unwanted", 1)
1354 // Do we actually want this chunk?
1355 if t.haveChunk(ppReq) {
1356 chunksReceived.Add("wasted", 1)
1357 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1361 piece := &t.pieces[ppReq.Index]
1363 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1364 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1366 c.piecesReceivedSinceLastRequestUpdate++
1367 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1369 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1370 f(ReceivedUsefulDataEvent{c, msg})
1372 c.lastUsefulChunkReceived = time.Now()
1374 // Need to record that it hasn't been written yet, before we attempt to do
1375 // anything with it.
1376 piece.incrementPendingWrites()
1377 // Record that we have the chunk, so we aren't trying to download it while
1378 // waiting for it to be written to storage.
1379 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1381 // Cancel pending requests for this chunk from *other* peers.
1382 t.iterPeers(func(p *Peer) {
1389 err := func() error {
1392 concurrentChunkWrites.Add(1)
1393 defer concurrentChunkWrites.Add(-1)
1394 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1395 // number of connections. We write inline with receiving the chunk (with this lock dance),
1396 // because we want to handle errors synchronously and I haven't thought of a nice way to
1397 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1399 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1402 piece.decrementPendingWrites()
1405 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1407 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1408 // request update runs while we're writing the chunk that just failed. Then we never do a
1409 // fresh update after pending the failed request.
1410 c.updateRequests("Peer.receiveChunk error writing chunk")
1411 t.onWriteChunkErr(err)
1415 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1417 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1418 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1419 t.queuePieceCheck(pieceIndex(ppReq.Index))
1420 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1421 // chunk status (such as the haveChunk call above) to have to check all the various other
1422 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1423 // that chunk pieces are pended at an appropriate time later however.
1426 cl.event.Broadcast()
1427 // We do this because we've written a chunk, and may change PieceState.Partial.
1428 t.publishPieceChange(pieceIndex(ppReq.Index))
1433 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1434 if c.peerTouchedPieces == nil {
1435 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1437 c.peerTouchedPieces[piece] = struct{}{}
1438 ds := &c.t.pieces[piece].dirtiers
1440 *ds = make(map[*Peer]struct{})
1442 (*ds)[c] = struct{}{}
1445 func (c *PeerConn) uploadAllowed() bool {
1446 if c.t.cl.config.NoUpload {
1449 if c.t.dataUploadDisallowed {
1455 if !c.peerHasWantedPieces() {
1458 // Don't upload more than 100 KiB more than we download.
1459 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1465 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1466 if c.uploadTimer == nil {
1467 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1469 c.uploadTimer.Reset(delay)
1473 // Also handles choking and unchoking of the remote peer.
1474 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1475 // Breaking or completing this loop means we don't want to upload to the
1476 // peer anymore, and we choke them.
1478 for c.uploadAllowed() {
1479 // We want to upload to the peer.
1480 if !c.unchoke(msg) {
1483 for r, state := range c.peerRequests {
1484 if state.data == nil {
1487 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1489 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1491 delay := res.Delay()
1494 c.setRetryUploadTimer(delay)
1495 // Hard to say what to return here.
1498 more := c.sendChunk(r, msg, state)
1499 delete(c.peerRequests, r)
1510 func (cn *PeerConn) drop() {
1511 cn.t.dropConnection(cn)
1514 func (cn *Peer) netGoodPiecesDirtied() int64 {
1515 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1518 func (c *Peer) peerHasWantedPieces() bool {
1519 if c.peerSentHaveAll {
1520 return !c.t.haveAllPieces()
1522 if !c.t.haveInfo() {
1523 return !c._peerPieces.IsEmpty()
1525 return c._peerPieces.Intersects(&c.t._pendingPieces)
1528 func (c *Peer) deleteRequest(r RequestIndex) bool {
1529 if !c.actualRequestState.Requests.CheckedRemove(r) {
1532 c.cancelledRequests.Remove(r)
1533 for _, f := range c.callbacks.DeletedRequest {
1534 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1536 c.updateExpectingChunks()
1537 if !c.peerChoking || c.peerAllowedFast.Contains(r/c.t.chunksPerRegularPiece()) {
1538 c.t.pendingRequests.Dec(r)
1543 func (c *Peer) deleteAllRequests() {
1544 c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1548 if !c.actualRequestState.Requests.IsEmpty() {
1549 panic(c.actualRequestState.Requests.GetCardinality())
1553 // This is called when something has changed that should wake the writer, such as putting stuff into
1554 // the writeBuffer, or changing some state that the writer can act on.
1555 func (c *PeerConn) tickleWriter() {
1556 c.messageWriter.writeCond.Broadcast()
1559 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1560 c.lastChunkSent = time.Now()
1561 return msg(pp.Message{
1569 func (c *PeerConn) setTorrent(t *Torrent) {
1571 panic("connection already associated with a torrent")
1574 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1575 t.reconcileHandshakeStats(c)
1578 func (c *Peer) peerPriority() (peerPriority, error) {
1579 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1582 func (c *Peer) remoteIp() net.IP {
1583 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1584 return net.ParseIP(host)
1587 func (c *Peer) remoteIpPort() IpPort {
1588 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1589 return IpPort{ipa.IP, uint16(ipa.Port)}
1592 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1593 f := pp.PexPeerFlags(0)
1594 if c.PeerPrefersEncryption {
1595 f |= pp.PexPrefersEncryption
1598 f |= pp.PexOutgoingConn
1601 f |= pp.PexSupportsUtp
1606 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1607 // advertised listen port.
1608 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1609 if !c.outgoing && c.PeerListenPort != 0 {
1610 switch addr := c.RemoteAddr.(type) {
1613 dialAddr.Port = c.PeerListenPort
1617 dialAddr.Port = c.PeerListenPort
1624 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1625 f := c.pexPeerFlags()
1626 addr := c.dialAddr()
1627 return pexEvent{t, addr, f}
1630 func (c *PeerConn) String() string {
1631 return fmt.Sprintf("connection %p", c)
1634 func (c *Peer) trust() connectionTrust {
1635 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1638 type connectionTrust struct {
1640 NetGoodPiecesDirted int64
1643 func (l connectionTrust) Less(r connectionTrust) bool {
1644 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1647 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1648 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1649 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1651 defer cn.locker().RUnlock()
1652 return cn.newPeerPieces()
1655 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1656 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1657 // TODO: Can we use copy on write?
1658 ret := cn._peerPieces.Clone()
1659 if cn.peerSentHaveAll {
1660 if cn.t.haveInfo() {
1661 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1663 ret.AddRange(0, bitmap.ToEnd)
1669 func (cn *Peer) stats() *ConnStats {
1673 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1674 pc, ok := p.peerImpl.(*PeerConn)
1678 func (pc *PeerConn) isLowOnRequests() bool {
1679 return pc.actualRequestState.Requests.IsEmpty()