16 "github.com/anacrolix/log"
17 "github.com/anacrolix/missinggo/iter"
18 "github.com/anacrolix/missinggo/v2/bitmap"
19 "github.com/anacrolix/missinggo/v2/prioritybitmap"
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 nextRequestState requestState
86 actualRequestState requestState
87 lastBecameInterested time.Time
88 priorInterest time.Duration
90 lastStartedExpectingToReceiveChunks time.Time
91 cumulativeExpectedToReceiveChunks time.Duration
92 _chunksReceivedWhileExpecting int64
95 piecesReceivedSinceLastRequestUpdate maxRequests
96 maxPiecesReceivedBetweenRequestUpdates maxRequests
97 // Chunks that we might reasonably expect to receive from the peer. Due to
98 // latency, buffering, and implementation differences, we may receive
99 // chunks that are no longer in the set of requests actually want.
100 validReceiveChunks map[Request]int
101 // Indexed by metadata piece, set to true if posted and pending a
103 metadataRequests []bool
104 sentHaves bitmap.Bitmap
106 // Stuff controlled by the remote peer.
109 peerRequests map[Request]*peerRequestState
110 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
112 // The pieces the peer has claimed to have.
113 _peerPieces bitmap.Bitmap
114 // The peer has everything. This can occur due to a special message, when
115 // we may not even know the number of pieces in the torrent yet.
117 // The highest possible number of pieces the torrent could have based on
118 // communication with the peer. Generally only useful until we have the
120 peerMinPieces pieceIndex
121 // Pieces we've accepted chunks for from the peer.
122 peerTouchedPieces map[pieceIndex]struct{}
123 peerAllowedFast bitmap.Bitmap
125 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
126 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
127 PeerClientName string
129 pieceInclination []int
130 _pieceRequestOrder prioritybitmap.PriorityBitmap
135 // Maintains the state of a BitTorrent-protocol based connection with a peer.
136 type PeerConn struct {
139 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
140 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
145 PeerExtensionBytes pp.PeerExtensionBits
147 // The actual Conn, used for closing, and setting socket options.
149 // The Reader and Writer for this Conn, with hooks installed for stats,
150 // limiting, deadlines etc.
154 messageWriter peerConnMsgWriter
156 uploadTimer *time.Timer
160 func (cn *PeerConn) connStatusString() string {
161 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
164 func (cn *Peer) updateExpectingChunks() {
165 if cn.expectingChunks() {
166 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
167 cn.lastStartedExpectingToReceiveChunks = time.Now()
170 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
171 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
172 cn.lastStartedExpectingToReceiveChunks = time.Time{}
177 func (cn *Peer) expectingChunks() bool {
178 if len(cn.actualRequestState.Requests) == 0 {
181 if !cn.actualRequestState.Interested {
184 for r := range cn.actualRequestState.Requests {
185 if !cn.remoteChokingPiece(r.Index.Int()) {
192 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
193 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
196 // Returns true if the connection is over IPv6.
197 func (cn *PeerConn) ipv6() bool {
202 return len(ip) == net.IPv6len
205 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
206 // specification for this.
207 func (cn *PeerConn) isPreferredDirection() bool {
208 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
211 // Returns whether the left connection should be preferred over the right one,
212 // considering only their networking properties. If ok is false, we can't
214 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
216 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
217 ml.NextBool(!l.utp(), !r.utp())
218 ml.NextBool(l.ipv6(), r.ipv6())
222 func (cn *Peer) cumInterest() time.Duration {
223 ret := cn.priorInterest
224 if cn.actualRequestState.Interested {
225 ret += time.Since(cn.lastBecameInterested)
230 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
231 if cn.peerSentHaveAll {
234 if !cn.t.haveInfo() {
237 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
240 func (cn *PeerConn) locker() *lockWithDeferreds {
241 return cn.t.cl.locker()
244 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
245 _, ok := cn.PeerExtensionIDs[ext]
249 // The best guess at number of pieces in the torrent for this peer.
250 func (cn *Peer) bestPeerNumPieces() pieceIndex {
252 return cn.t.numPieces()
254 return cn.peerMinPieces
257 func (cn *Peer) completedString() string {
258 have := pieceIndex(cn._peerPieces.Len())
259 if cn.peerSentHaveAll {
260 have = cn.bestPeerNumPieces()
262 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
265 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
266 cn.setNumPieces(info.NumPieces())
269 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
270 // receiving badly sized BITFIELD, or invalid HAVE messages.
271 func (cn *PeerConn) setNumPieces(num pieceIndex) {
272 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
273 cn.peerPiecesChanged()
276 func eventAgeString(t time.Time) string {
280 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
283 func (cn *PeerConn) connectionFlags() (ret string) {
285 ret += string([]byte{b})
287 if cn.cryptoMethod == mse.CryptoMethodRC4 {
289 } else if cn.headerEncrypted {
292 ret += string(cn.Discovery)
299 func (cn *PeerConn) utp() bool {
300 return parseNetworkString(cn.Network).Udp
303 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
304 func (cn *Peer) statusFlags() (ret string) {
306 ret += string([]byte{b})
308 if cn.actualRequestState.Interested {
315 ret += cn.connectionFlags()
317 if cn.peerInterested {
326 func (cn *Peer) downloadRate() float64 {
327 num := cn._stats.BytesReadUsefulData.Int64()
331 return float64(num) / cn.totalExpectingTime().Seconds()
334 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
335 ret = make(map[pieceIndex]int)
336 for r := range cn.actualRequestState.Requests {
337 ret[pieceIndex(r.Index)]++
342 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
343 // \t isn't preserved in <pre> blocks?
344 if cn.closed.IsSet() {
345 fmt.Fprint(w, "CLOSED: ")
347 fmt.Fprintln(w, cn.connStatusString())
348 prio, err := cn.peerPriority()
349 prioStr := fmt.Sprintf("%08x", prio)
351 prioStr += ": " + err.Error()
353 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
354 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
355 eventAgeString(cn.lastMessageReceived),
356 eventAgeString(cn.completedHandshake),
357 eventAgeString(cn.lastHelpful()),
359 cn.totalExpectingTime(),
362 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
363 cn.completedString(),
364 len(cn.peerTouchedPieces),
365 &cn._stats.ChunksReadUseful,
366 &cn._stats.ChunksRead,
367 &cn._stats.ChunksWritten,
368 len(cn.actualRequestState.Requests),
369 cn.nominalMaxRequests(),
371 len(cn.peerRequests),
374 cn.downloadRate()/(1<<10),
376 fmt.Fprintf(w, " requested pieces:")
377 type pieceNumRequestsType struct {
381 var pieceNumRequests []pieceNumRequestsType
382 for piece, count := range cn.numRequestsByPiece() {
383 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
385 sort.Slice(pieceNumRequests, func(i, j int) bool {
386 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
388 for _, elem := range pieceNumRequests {
389 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
394 func (p *Peer) close() {
398 p.discardPieceInclination()
399 p._pieceRequestOrder.Clear()
402 p.t.decPeerPieceAvailability(p)
404 for _, f := range p.callbacks.PeerClosed {
409 func (cn *PeerConn) onClose() {
410 if cn.pex.IsEnabled() {
417 if cb := cn.callbacks.PeerConnClosed; cb != nil {
422 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
423 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
426 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
427 // https://github.com/pion/datachannel/issues/59 is fixed.
428 const writeBufferHighWaterLen = 1 << 15
430 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
431 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
432 func (cn *PeerConn) write(msg pp.Message) bool {
433 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
434 // We don't need to track bytes here because the connection's Writer has that behaviour injected
435 // (although there's some delay between us buffering the message, and the connection writer
436 // flushing it out.).
437 notFull := cn.messageWriter.write(msg)
438 // Last I checked only Piece messages affect stats, and we don't write those.
444 func (cn *PeerConn) requestMetadataPiece(index int) {
445 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
446 if eID == pp.ExtensionDeleteNumber {
449 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
452 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
453 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
454 for index >= len(cn.metadataRequests) {
455 cn.metadataRequests = append(cn.metadataRequests, false)
457 cn.metadataRequests[index] = true
460 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
461 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
464 // The actual value to use as the maximum outbound requests.
465 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
466 return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 128))
469 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
470 ret = cn.cumulativeExpectedToReceiveChunks
471 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
472 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
478 func (cn *PeerConn) onPeerSentCancel(r Request) {
479 if _, ok := cn.peerRequests[r]; !ok {
480 torrent.Add("unexpected cancels received", 1)
483 if cn.fastEnabled() {
486 delete(cn.peerRequests, r)
490 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
495 more = msg(pp.Message{
498 if cn.fastEnabled() {
499 for r := range cn.peerRequests {
500 // TODO: Don't reject pieces in allowed fast set.
504 cn.peerRequests = nil
509 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
514 return msg(pp.Message{
519 func (cn *Peer) setInterested(interested bool) bool {
520 if cn.actualRequestState.Interested == interested {
523 cn.actualRequestState.Interested = interested
525 cn.lastBecameInterested = time.Now()
526 } else if !cn.lastBecameInterested.IsZero() {
527 cn.priorInterest += time.Since(cn.lastBecameInterested)
529 cn.updateExpectingChunks()
530 // log.Printf("%p: setting interest: %v", cn, interested)
531 return cn.writeInterested(interested)
534 func (pc *PeerConn) writeInterested(interested bool) bool {
535 return pc.write(pp.Message{
536 Type: func() pp.MessageType {
540 return pp.NotInterested
546 // The function takes a message to be sent, and returns true if more messages
548 type messageWriter func(pp.Message) bool
550 func (cn *Peer) shouldRequest(r Request) error {
551 if !cn.peerHasPiece(pieceIndex(r.Index)) {
552 return errors.New("requesting piece peer doesn't have")
554 if !cn.t.peerIsActive(cn) {
555 panic("requesting but not in active conns")
557 if cn.closed.IsSet() {
558 panic("requesting when connection is closed")
560 if cn.t.hashingPiece(pieceIndex(r.Index)) {
561 panic("piece is being hashed")
563 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
564 panic("piece is queued for hash")
566 if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(r.Index)) {
567 panic("peer choking and piece not allowed fast")
572 func (cn *Peer) request(r Request) (more bool, err error) {
573 if err := cn.shouldRequest(r); err != nil {
576 if _, ok := cn.actualRequestState.Requests[r]; ok {
579 if len(cn.actualRequestState.Requests) >= cn.nominalMaxRequests() {
580 return true, errors.New("too many outstanding requests")
582 if cn.actualRequestState.Requests == nil {
583 cn.actualRequestState.Requests = make(map[Request]struct{})
585 cn.actualRequestState.Requests[r] = struct{}{}
586 if cn.validReceiveChunks == nil {
587 cn.validReceiveChunks = make(map[Request]int)
589 cn.validReceiveChunks[r]++
590 cn.t.pendingRequests[r]++
591 cn.updateExpectingChunks()
592 for _, f := range cn.callbacks.SentRequest {
593 f(PeerRequestEvent{cn, r})
595 return cn.peerImpl._request(r), nil
598 func (me *PeerConn) _request(r Request) bool {
599 return me.write(pp.Message{
607 func (me *Peer) cancel(r Request) bool {
608 if me.deleteRequest(r) {
609 return me.peerImpl._cancel(r)
614 func (me *PeerConn) _cancel(r Request) bool {
615 return me.write(makeCancelMessage(r))
618 func (cn *PeerConn) fillWriteBuffer() {
619 if !cn.applyNextRequestState() {
622 if cn.pex.IsEnabled() {
623 if flow := cn.pex.Share(cn.write); !flow {
630 func (cn *PeerConn) have(piece pieceIndex) {
631 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
636 Index: pp.Integer(piece),
638 cn.sentHaves.Add(bitmap.BitIndex(piece))
641 func (cn *PeerConn) postBitfield() {
642 if cn.sentHaves.Len() != 0 {
643 panic("bitfield must be first have-related message sent")
645 if !cn.t.haveAnyPieces() {
650 Bitfield: cn.t.bitfield(),
652 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
655 func (cn *PeerConn) updateRequests() {
659 // Emits the indices in the Bitmaps bms in order, never repeating any index.
660 // skip is mutated during execution, and its initial values will never be
662 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
663 return func(cb iter.Callback) {
664 for _, bm := range bms {
666 func(_i interface{}) bool {
668 if skip.Contains(bitmap.BitIndex(i)) {
671 skip.Add(bitmap.BitIndex(i))
682 // check callers updaterequests
683 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
684 return cn._pieceRequestOrder.Remove(piece)
687 // This is distinct from Torrent piece priority, which is the user's
688 // preference. Connection piece priority is specific to a connection and is
689 // used to pseudorandomly avoid connections always requesting the same pieces
690 // and thus wasting effort.
691 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
692 tpp := cn.t.piecePriority(piece)
693 if !cn.peerHasPiece(piece) {
694 tpp = PiecePriorityNone
696 if tpp == PiecePriorityNone {
697 return cn.stopRequestingPiece(piece)
699 prio := cn.getPieceInclination()[piece]
700 return cn._pieceRequestOrder.Set(piece, prio)
703 func (cn *Peer) getPieceInclination() []int {
704 if cn.pieceInclination == nil {
705 cn.pieceInclination = cn.t.getConnPieceInclination()
707 return cn.pieceInclination
710 func (cn *Peer) discardPieceInclination() {
711 if cn.pieceInclination == nil {
714 cn.t.putPieceInclination(cn.pieceInclination)
715 cn.pieceInclination = nil
718 func (cn *Peer) peerPiecesChanged() {
720 prioritiesChanged := false
721 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
722 if cn.updatePiecePriority(i) {
723 prioritiesChanged = true
726 if prioritiesChanged {
730 cn.t.maybeDropMutuallyCompletePeer(cn)
733 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
734 if newMin > cn.peerMinPieces {
735 cn.peerMinPieces = newMin
739 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
740 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
741 return errors.New("invalid piece")
743 if cn.peerHasPiece(piece) {
746 cn.raisePeerMinPieces(piece + 1)
747 if !cn.peerHasPiece(piece) {
748 cn.t.incPieceAvailability(piece)
750 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
751 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
752 if cn.updatePiecePriority(piece) {
758 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
760 panic("expected bitfield length divisible by 8")
762 // We know that the last byte means that at most the last 7 bits are wasted.
763 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
764 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
765 // Ignore known excess pieces.
766 bf = bf[:cn.t.numPieces()]
768 pp := cn.newPeerPieces()
769 cn.peerSentHaveAll = false
770 for i, have := range bf {
772 cn.raisePeerMinPieces(pieceIndex(i) + 1)
773 if !pp.Contains(bitmap.BitIndex(i)) {
774 cn.t.incPieceAvailability(i)
777 if pp.Contains(bitmap.BitIndex(i)) {
778 cn.t.decPieceAvailability(i)
781 cn._peerPieces.Set(bitmap.BitIndex(i), have)
783 cn.peerPiecesChanged()
787 func (cn *Peer) onPeerHasAllPieces() {
790 npp, pc := cn.newPeerPieces(), t.numPieces()
791 for i := 0; i < pc; i += 1 {
792 if !npp.Contains(bitmap.BitIndex(i)) {
793 t.incPieceAvailability(i)
797 cn.peerSentHaveAll = true
798 cn._peerPieces.Clear()
799 cn.peerPiecesChanged()
802 func (cn *PeerConn) onPeerSentHaveAll() error {
803 cn.onPeerHasAllPieces()
807 func (cn *PeerConn) peerSentHaveNone() error {
808 cn.t.decPeerPieceAvailability(&cn.Peer)
809 cn._peerPieces.Clear()
810 cn.peerSentHaveAll = false
811 cn.peerPiecesChanged()
815 func (c *PeerConn) requestPendingMetadata() {
819 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
820 // Peer doesn't support this.
823 // Request metadata pieces that we don't have in a random order.
825 for index := 0; index < c.t.metadataPieceCount(); index++ {
826 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
827 pending = append(pending, index)
830 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
831 for _, i := range pending {
832 c.requestMetadataPiece(i)
836 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
837 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
838 if msg.Type == pp.Extended {
839 for name, id := range cn.PeerExtensionIDs {
840 if id != msg.ExtendedID {
843 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
846 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
849 // After handshake, we know what Torrent and Client stats to include for a
851 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
857 // All ConnStats that include this connection. Some objects are not known
858 // until the handshake is complete, after which it's expected to reconcile the
860 func (cn *Peer) allStats(f func(*ConnStats)) {
862 if cn.reconciledHandshakeStats {
863 cn.postHandshakeStats(f)
867 func (cn *PeerConn) wroteBytes(n int64) {
868 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
871 func (cn *PeerConn) readBytes(n int64) {
872 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
875 // Returns whether the connection could be useful to us. We're seeding and
876 // they want data, we don't have metainfo and they can provide it, etc.
877 func (c *Peer) useful() bool {
879 if c.closed.IsSet() {
883 return c.supportsExtension("ut_metadata")
885 if t.seeding() && c.peerInterested {
888 if c.peerHasWantedPieces() {
894 func (c *Peer) lastHelpful() (ret time.Time) {
895 ret = c.lastUsefulChunkReceived
896 if c.t.seeding() && c.lastChunkSent.After(ret) {
897 ret = c.lastChunkSent
902 func (c *PeerConn) fastEnabled() bool {
903 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
906 func (c *PeerConn) reject(r Request) {
907 if !c.fastEnabled() {
908 panic("fast not enabled")
910 c.write(r.ToMsg(pp.Reject))
911 delete(c.peerRequests, r)
914 func (c *PeerConn) onReadRequest(r Request) error {
915 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
916 if _, ok := c.peerRequests[r]; ok {
917 torrent.Add("duplicate requests received", 1)
921 torrent.Add("requests received while choking", 1)
923 torrent.Add("requests rejected while choking", 1)
928 // TODO: What if they've already requested this?
929 if len(c.peerRequests) >= localClientReqq {
930 torrent.Add("requests received while queue full", 1)
934 // BEP 6 says we may close here if we choose.
937 if !c.t.havePiece(pieceIndex(r.Index)) {
938 // This isn't necessarily them screwing up. We can drop pieces
939 // from our storage, and can't communicate this to peers
940 // except by reconnecting.
941 requestsReceivedForMissingPieces.Add(1)
942 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
944 // Check this after we know we have the piece, so that the piece length will be known.
945 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
946 torrent.Add("bad requests received", 1)
947 return errors.New("bad Request")
949 if c.peerRequests == nil {
950 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
952 value := &peerRequestState{}
953 c.peerRequests[r] = value
954 go c.peerRequestDataReader(r, value)
959 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
960 b, err := readPeerRequestData(r, c)
962 defer c.locker().Unlock()
964 c.peerRequestDataReadFailed(err, r)
967 panic("data must be non-nil to trigger send")
974 // If this is maintained correctly, we might be able to support optional synchronous reading for
975 // chunk sending, the way it used to work.
976 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
977 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
978 i := pieceIndex(r.Index)
979 if c.t.pieceComplete(i) {
980 // There used to be more code here that just duplicated the following break. Piece
981 // completions are currently cached, so I'm not sure how helpful this update is, except to
982 // pull any completion changes pushed to the storage backend in failed reads that got us
984 c.t.updatePieceCompletion(i)
986 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
987 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
988 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
989 // next connect. TODO: Support rejecting here too.
991 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
996 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
997 b := make([]byte, r.Length)
998 p := c.t.info.Piece(int(r.Index))
999 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1006 panic("expected error")
1012 func runSafeExtraneous(f func()) {
1020 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1021 // exit. Returning will end the connection.
1022 func (c *PeerConn) mainReadLoop() (err error) {
1025 torrent.Add("connection.mainReadLoop returned with error", 1)
1027 torrent.Add("connection.mainReadLoop returned with no error", 1)
1033 decoder := pp.Decoder{
1034 R: bufio.NewReaderSize(c.r, 1<<17),
1035 MaxLength: 256 * 1024,
1043 err = decoder.Decode(&msg)
1045 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1048 if t.closed.IsSet() || c.closed.IsSet() {
1054 c.lastMessageReceived = time.Now()
1056 receivedKeepalives.Add(1)
1059 messageTypesReceived.Add(msg.Type.String(), 1)
1060 if msg.Type.FastExtension() && !c.fastEnabled() {
1061 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1062 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1066 c.peerChoking = true
1067 if !c.fastEnabled() {
1068 c.deleteAllRequests()
1070 // We can then reset our interest.
1072 c.updateExpectingChunks()
1074 c.peerChoking = false
1076 c.updateExpectingChunks()
1078 c.peerInterested = true
1080 case pp.NotInterested:
1081 c.peerInterested = false
1082 // We don't clear their requests since it isn't clear in the spec.
1083 // We'll probably choke them for this, which will clear them if
1084 // appropriate, and is clearly specified.
1086 err = c.peerSentHave(pieceIndex(msg.Index))
1088 err = c.peerSentBitfield(msg.Bitfield)
1090 r := newRequestFromMessage(&msg)
1091 err = c.onReadRequest(r)
1093 c.doChunkReadStats(int64(len(msg.Piece)))
1094 err = c.receiveChunk(&msg)
1095 if len(msg.Piece) == int(t.chunkSize) {
1096 t.chunkPool.Put(&msg.Piece)
1099 err = fmt.Errorf("receiving chunk: %s", err)
1102 req := newRequestFromMessage(&msg)
1103 c.onPeerSentCancel(req)
1105 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1109 pingAddr := net.UDPAddr{
1114 pingAddr.Port = int(msg.Port)
1116 cl.eachDhtServer(func(s DhtServer) {
1117 go s.Ping(&pingAddr)
1120 torrent.Add("suggests received", 1)
1121 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1124 err = c.onPeerSentHaveAll()
1126 err = c.peerSentHaveNone()
1128 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1129 case pp.AllowedFast:
1130 torrent.Add("allowed fasts received", 1)
1131 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1132 c.peerAllowedFast.Add(bitmap.BitIndex(msg.Index))
1135 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1137 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1145 func (c *Peer) remoteRejectedRequest(r Request) {
1146 if c.deleteRequest(r) {
1147 c.decExpectedChunkReceive(r)
1151 func (c *Peer) decExpectedChunkReceive(r Request) {
1152 count := c.validReceiveChunks[r]
1154 delete(c.validReceiveChunks, r)
1155 } else if count > 1 {
1156 c.validReceiveChunks[r] = count - 1
1162 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1164 // TODO: Should we still do this?
1166 // These clients use their own extension IDs for outgoing message
1167 // types, which is incorrect.
1168 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1176 case pp.HandshakeExtendedID:
1177 var d pp.ExtendedHandshakeMessage
1178 if err := bencode.Unmarshal(payload, &d); err != nil {
1179 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1180 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1182 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1185 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1187 c.PeerMaxRequests = d.Reqq
1189 c.PeerClientName = d.V
1190 if c.PeerExtensionIDs == nil {
1191 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1193 c.PeerListenPort = d.Port
1194 c.PeerPrefersEncryption = d.Encryption
1195 for name, id := range d.M {
1196 if _, ok := c.PeerExtensionIDs[name]; !ok {
1197 peersSupportingExtension.Add(string(name), 1)
1199 c.PeerExtensionIDs[name] = id
1201 if d.MetadataSize != 0 {
1202 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1203 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1206 c.requestPendingMetadata()
1207 if !t.cl.config.DisablePEX {
1208 t.pex.Add(c) // we learnt enough now
1212 case metadataExtendedId:
1213 err := cl.gotMetadataExtensionMsg(payload, t, c)
1215 return fmt.Errorf("handling metadata extension message: %w", err)
1219 if !c.pex.IsEnabled() {
1220 return nil // or hang-up maybe?
1222 return c.pex.Recv(payload)
1224 return fmt.Errorf("unexpected extended message ID: %v", id)
1228 // Set both the Reader and Writer for the connection from a single ReadWriter.
1229 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1234 // Returns the Reader and Writer as a combined ReadWriter.
1235 func (cn *PeerConn) rw() io.ReadWriter {
1242 func (c *Peer) doChunkReadStats(size int64) {
1243 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1246 // Handle a received chunk from a peer.
1247 func (c *Peer) receiveChunk(msg *pp.Message) error {
1248 chunksReceived.Add("total", 1)
1250 req := newRequestFromMessage(msg)
1253 chunksReceived.Add("while choked", 1)
1256 if c.validReceiveChunks[req] <= 0 {
1257 chunksReceived.Add("unexpected", 1)
1258 return errors.New("received unexpected chunk")
1260 c.decExpectedChunkReceive(req)
1262 if c.peerChoking && c.peerAllowedFast.Get(bitmap.BitIndex(req.Index)) {
1263 chunksReceived.Add("due to allowed fast", 1)
1266 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1267 // have actually already received the piece, while we have the Client unlocked to write the data
1269 deletedRequest := false
1271 if _, ok := c.actualRequestState.Requests[req]; ok {
1272 for _, f := range c.callbacks.ReceivedRequested {
1273 f(PeerMessageEvent{c, msg})
1276 // Request has been satisfied.
1277 if c.deleteRequest(req) {
1278 deletedRequest = true
1280 c._chunksReceivedWhileExpecting++
1283 chunksReceived.Add("unwanted", 1)
1290 // Do we actually want this chunk?
1291 if t.haveChunk(req) {
1292 chunksReceived.Add("wasted", 1)
1293 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1297 piece := &t.pieces[req.Index]
1299 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1300 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1302 c.piecesReceivedSinceLastRequestUpdate++
1304 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1306 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1307 f(ReceivedUsefulDataEvent{c, msg})
1309 c.lastUsefulChunkReceived = time.Now()
1311 // Need to record that it hasn't been written yet, before we attempt to do
1312 // anything with it.
1313 piece.incrementPendingWrites()
1314 // Record that we have the chunk, so we aren't trying to download it while
1315 // waiting for it to be written to storage.
1316 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1318 // Cancel pending requests for this chunk from *other* peers.
1319 t.iterPeers(func(p *Peer) {
1326 err := func() error {
1329 concurrentChunkWrites.Add(1)
1330 defer concurrentChunkWrites.Add(-1)
1331 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1332 // number of connections. We write inline with receiving the chunk (with this lock dance),
1333 // because we want to handle errors synchronously and I haven't thought of a nice way to
1334 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1336 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1339 piece.decrementPendingWrites()
1342 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1344 //t.updatePieceCompletion(pieceIndex(msg.Index))
1345 t.onWriteChunkErr(err)
1349 c.onDirtiedPiece(pieceIndex(req.Index))
1351 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1352 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1353 t.queuePieceCheck(pieceIndex(req.Index))
1354 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1355 // chunk status (such as the haveChunk call above) to have to check all the various other
1356 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1357 // that chunk pieces are pended at an appropriate time later however.
1360 cl.event.Broadcast()
1361 // We do this because we've written a chunk, and may change PieceState.Partial.
1362 t.publishPieceChange(pieceIndex(req.Index))
1367 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1368 if c.peerTouchedPieces == nil {
1369 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1371 c.peerTouchedPieces[piece] = struct{}{}
1372 ds := &c.t.pieces[piece].dirtiers
1374 *ds = make(map[*Peer]struct{})
1376 (*ds)[c] = struct{}{}
1379 func (c *PeerConn) uploadAllowed() bool {
1380 if c.t.cl.config.NoUpload {
1383 if c.t.dataUploadDisallowed {
1389 if !c.peerHasWantedPieces() {
1392 // Don't upload more than 100 KiB more than we download.
1393 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1399 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1400 if c.uploadTimer == nil {
1401 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1403 c.uploadTimer.Reset(delay)
1407 // Also handles choking and unchoking of the remote peer.
1408 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1409 // Breaking or completing this loop means we don't want to upload to the
1410 // peer anymore, and we choke them.
1412 for c.uploadAllowed() {
1413 // We want to upload to the peer.
1414 if !c.unchoke(msg) {
1417 for r, state := range c.peerRequests {
1418 if state.data == nil {
1421 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1423 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1425 delay := res.Delay()
1428 c.setRetryUploadTimer(delay)
1429 // Hard to say what to return here.
1432 more := c.sendChunk(r, msg, state)
1433 delete(c.peerRequests, r)
1444 func (cn *PeerConn) drop() {
1445 cn.t.dropConnection(cn)
1448 func (cn *Peer) netGoodPiecesDirtied() int64 {
1449 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1452 func (c *Peer) peerHasWantedPieces() bool {
1453 return !c._pieceRequestOrder.IsEmpty()
1456 func (c *Peer) deleteRequest(r Request) bool {
1457 delete(c.nextRequestState.Requests, r)
1458 if _, ok := c.actualRequestState.Requests[r]; !ok {
1461 delete(c.actualRequestState.Requests, r)
1462 for _, f := range c.callbacks.DeletedRequest {
1463 f(PeerRequestEvent{c, r})
1465 c.updateExpectingChunks()
1466 pr := c.t.pendingRequests
1478 func (c *Peer) deleteAllRequests() {
1479 for r := range c.actualRequestState.Requests {
1482 if l := len(c.actualRequestState.Requests); l != 0 {
1485 c.nextRequestState.Requests = nil
1486 // for c := range c.t.conns {
1491 // This is called when something has changed that should wake the writer, such as putting stuff into
1492 // the writeBuffer, or changing some state that the writer can act on.
1493 func (c *PeerConn) tickleWriter() {
1494 c.messageWriter.writeCond.Broadcast()
1497 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1498 c.lastChunkSent = time.Now()
1499 return msg(pp.Message{
1507 func (c *PeerConn) setTorrent(t *Torrent) {
1509 panic("connection already associated with a torrent")
1512 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1513 t.reconcileHandshakeStats(c)
1516 func (c *Peer) peerPriority() (peerPriority, error) {
1517 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1520 func (c *Peer) remoteIp() net.IP {
1521 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1522 return net.ParseIP(host)
1525 func (c *Peer) remoteIpPort() IpPort {
1526 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1527 return IpPort{ipa.IP, uint16(ipa.Port)}
1530 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1531 f := pp.PexPeerFlags(0)
1532 if c.PeerPrefersEncryption {
1533 f |= pp.PexPrefersEncryption
1536 f |= pp.PexOutgoingConn
1539 f |= pp.PexSupportsUtp
1544 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1545 // advertised listen port.
1546 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1547 if !c.outgoing && c.PeerListenPort != 0 {
1548 switch addr := c.RemoteAddr.(type) {
1551 dialAddr.Port = c.PeerListenPort
1555 dialAddr.Port = c.PeerListenPort
1562 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1563 f := c.pexPeerFlags()
1564 addr := c.dialAddr()
1565 return pexEvent{t, addr, f}
1568 func (c *PeerConn) String() string {
1569 return fmt.Sprintf("connection %p", c)
1572 func (c *Peer) trust() connectionTrust {
1573 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1576 type connectionTrust struct {
1578 NetGoodPiecesDirted int64
1581 func (l connectionTrust) Less(r connectionTrust) bool {
1582 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1585 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1586 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1587 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1589 defer cn.locker().RUnlock()
1590 return cn.newPeerPieces()
1593 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1594 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1595 ret := cn._peerPieces.Copy()
1596 if cn.peerSentHaveAll {
1597 if cn.t.haveInfo() {
1598 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1600 ret.AddRange(0, bitmap.ToEnd)
1606 func (cn *Peer) stats() *ConnStats {
1610 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1611 pc, ok := p.peerImpl.(*PeerConn)
1615 func (p *PeerConn) onNextRequestStateChanged() {