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 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[RequestIndex]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 roaring.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 roaring.Bitmap
125 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
126 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
127 PeerClientName string
132 // Maintains the state of a BitTorrent-protocol based connection with a peer.
133 type PeerConn struct {
136 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
137 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
142 PeerExtensionBytes pp.PeerExtensionBits
144 // The actual Conn, used for closing, and setting socket options.
146 // The Reader and Writer for this Conn, with hooks installed for stats,
147 // limiting, deadlines etc.
151 messageWriter peerConnMsgWriter
153 uploadTimer *time.Timer
157 func (cn *PeerConn) connStatusString() string {
158 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
161 func (cn *Peer) updateExpectingChunks() {
162 if cn.expectingChunks() {
163 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
164 cn.lastStartedExpectingToReceiveChunks = time.Now()
167 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
168 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
169 cn.lastStartedExpectingToReceiveChunks = time.Time{}
174 func (cn *Peer) expectingChunks() bool {
175 if cn.actualRequestState.Requests.IsEmpty() {
178 if !cn.actualRequestState.Interested {
184 haveAllowedFastRequests := false
185 cn.peerAllowedFast.Iterate(func(i uint32) bool {
186 haveAllowedFastRequests = roaringBitmapRangeCardinality(
187 &cn.actualRequestState.Requests,
188 cn.t.pieceRequestIndexOffset(pieceIndex(i)),
189 cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
191 return !haveAllowedFastRequests
193 return haveAllowedFastRequests
196 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
197 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
200 // Returns true if the connection is over IPv6.
201 func (cn *PeerConn) ipv6() bool {
206 return len(ip) == net.IPv6len
209 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
210 // specification for this.
211 func (cn *PeerConn) isPreferredDirection() bool {
212 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
215 // Returns whether the left connection should be preferred over the right one,
216 // considering only their networking properties. If ok is false, we can't
218 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
220 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
221 ml.NextBool(!l.utp(), !r.utp())
222 ml.NextBool(l.ipv6(), r.ipv6())
226 func (cn *Peer) cumInterest() time.Duration {
227 ret := cn.priorInterest
228 if cn.actualRequestState.Interested {
229 ret += time.Since(cn.lastBecameInterested)
234 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
235 if cn.peerSentHaveAll {
238 if !cn.t.haveInfo() {
241 return roaring.Flip(&cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
244 func (cn *PeerConn) locker() *lockWithDeferreds {
245 return cn.t.cl.locker()
248 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
249 _, ok := cn.PeerExtensionIDs[ext]
253 // The best guess at number of pieces in the torrent for this peer.
254 func (cn *Peer) bestPeerNumPieces() pieceIndex {
256 return cn.t.numPieces()
258 return cn.peerMinPieces
261 func (cn *Peer) completedString() string {
262 have := pieceIndex(cn._peerPieces.GetCardinality())
263 if cn.peerSentHaveAll {
264 have = cn.bestPeerNumPieces()
266 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
269 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
270 cn.setNumPieces(info.NumPieces())
273 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
274 // receiving badly sized BITFIELD, or invalid HAVE messages.
275 func (cn *PeerConn) setNumPieces(num pieceIndex) {
276 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
277 cn.peerPiecesChanged()
280 func eventAgeString(t time.Time) string {
284 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
287 func (cn *PeerConn) connectionFlags() (ret string) {
289 ret += string([]byte{b})
291 if cn.cryptoMethod == mse.CryptoMethodRC4 {
293 } else if cn.headerEncrypted {
296 ret += string(cn.Discovery)
303 func (cn *PeerConn) utp() bool {
304 return parseNetworkString(cn.Network).Udp
307 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
308 func (cn *Peer) statusFlags() (ret string) {
310 ret += string([]byte{b})
312 if cn.actualRequestState.Interested {
319 ret += cn.connectionFlags()
321 if cn.peerInterested {
330 func (cn *Peer) downloadRate() float64 {
331 num := cn._stats.BytesReadUsefulData.Int64()
335 return float64(num) / cn.totalExpectingTime().Seconds()
338 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
339 ret = make(map[pieceIndex]int)
340 cn.actualRequestState.Requests.Iterate(func(x uint32) bool {
341 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
347 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
348 // \t isn't preserved in <pre> blocks?
349 if cn.closed.IsSet() {
350 fmt.Fprint(w, "CLOSED: ")
352 fmt.Fprintln(w, cn.connStatusString())
353 prio, err := cn.peerPriority()
354 prioStr := fmt.Sprintf("%08x", prio)
356 prioStr += ": " + err.Error()
358 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
359 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
360 eventAgeString(cn.lastMessageReceived),
361 eventAgeString(cn.completedHandshake),
362 eventAgeString(cn.lastHelpful()),
364 cn.totalExpectingTime(),
367 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
368 cn.completedString(),
369 len(cn.peerTouchedPieces),
370 &cn._stats.ChunksReadUseful,
371 &cn._stats.ChunksRead,
372 &cn._stats.ChunksWritten,
373 cn.actualRequestState.Requests.GetCardinality(),
374 cn.nominalMaxRequests(),
376 len(cn.peerRequests),
379 cn.downloadRate()/(1<<10),
381 fmt.Fprintf(w, " requested pieces:")
382 type pieceNumRequestsType struct {
386 var pieceNumRequests []pieceNumRequestsType
387 for piece, count := range cn.numRequestsByPiece() {
388 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
390 sort.Slice(pieceNumRequests, func(i, j int) bool {
391 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
393 for _, elem := range pieceNumRequests {
394 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
399 func (p *Peer) close() {
405 p.t.decPeerPieceAvailability(p)
407 for _, f := range p.callbacks.PeerClosed {
412 func (cn *PeerConn) onClose() {
413 if cn.pex.IsEnabled() {
420 if cb := cn.callbacks.PeerConnClosed; cb != nil {
425 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
426 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
429 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
430 // https://github.com/pion/datachannel/issues/59 is fixed.
431 const writeBufferHighWaterLen = 1 << 15
433 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
434 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
435 func (cn *PeerConn) write(msg pp.Message) bool {
436 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
437 // We don't need to track bytes here because the connection's Writer has that behaviour injected
438 // (although there's some delay between us buffering the message, and the connection writer
439 // flushing it out.).
440 notFull := cn.messageWriter.write(msg)
441 // Last I checked only Piece messages affect stats, and we don't write those.
447 func (cn *PeerConn) requestMetadataPiece(index int) {
448 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
449 if eID == pp.ExtensionDeleteNumber {
452 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
455 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
456 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
457 for index >= len(cn.metadataRequests) {
458 cn.metadataRequests = append(cn.metadataRequests, false)
460 cn.metadataRequests[index] = true
463 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
464 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
467 // The actual value to use as the maximum outbound requests.
468 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
469 return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 2048))
472 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
473 ret = cn.cumulativeExpectedToReceiveChunks
474 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
475 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
481 func (cn *PeerConn) onPeerSentCancel(r Request) {
482 if _, ok := cn.peerRequests[r]; !ok {
483 torrent.Add("unexpected cancels received", 1)
486 if cn.fastEnabled() {
489 delete(cn.peerRequests, r)
493 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
498 more = msg(pp.Message{
501 if cn.fastEnabled() {
502 for r := range cn.peerRequests {
503 // TODO: Don't reject pieces in allowed fast set.
507 cn.peerRequests = nil
512 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
517 return msg(pp.Message{
522 func (cn *Peer) setInterested(interested bool) bool {
523 if cn.actualRequestState.Interested == interested {
526 cn.actualRequestState.Interested = interested
528 cn.lastBecameInterested = time.Now()
529 } else if !cn.lastBecameInterested.IsZero() {
530 cn.priorInterest += time.Since(cn.lastBecameInterested)
532 cn.updateExpectingChunks()
533 // log.Printf("%p: setting interest: %v", cn, interested)
534 return cn.writeInterested(interested)
537 func (pc *PeerConn) writeInterested(interested bool) bool {
538 return pc.write(pp.Message{
539 Type: func() pp.MessageType {
543 return pp.NotInterested
549 // The function takes a message to be sent, and returns true if more messages
551 type messageWriter func(pp.Message) bool
553 func (cn *Peer) shouldRequest(r RequestIndex) error {
554 pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
555 if !cn.peerHasPiece(pi) {
556 return errors.New("requesting piece peer doesn't have")
558 if !cn.t.peerIsActive(cn) {
559 panic("requesting but not in active conns")
561 if cn.closed.IsSet() {
562 panic("requesting when connection is closed")
564 if cn.t.hashingPiece(pi) {
565 panic("piece is being hashed")
567 if cn.t.pieceQueuedForHash(pi) {
568 panic("piece is queued for hash")
570 if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
571 panic("peer choking and piece not allowed fast")
576 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
577 if err := cn.shouldRequest(r); err != nil {
580 if cn.actualRequestState.Requests.Contains(r) {
583 if maxRequests(cn.actualRequestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
584 return true, errors.New("too many outstanding requests")
586 cn.actualRequestState.Requests.Add(r)
587 if cn.validReceiveChunks == nil {
588 cn.validReceiveChunks = make(map[RequestIndex]int)
590 cn.validReceiveChunks[r]++
591 cn.t.pendingRequests.Inc(r)
592 cn.updateExpectingChunks()
593 ppReq := cn.t.requestIndexToRequest(r)
594 for _, f := range cn.callbacks.SentRequest {
595 f(PeerRequestEvent{cn, ppReq})
597 return cn.peerImpl._request(ppReq), nil
600 func (me *PeerConn) _request(r Request) bool {
601 return me.write(pp.Message{
609 func (me *Peer) cancel(r RequestIndex) bool {
610 if me.deleteRequest(r) {
611 return me.peerImpl._cancel(me.t.requestIndexToRequest(r))
616 func (me *PeerConn) _cancel(r Request) bool {
617 return me.write(makeCancelMessage(r))
620 func (cn *PeerConn) fillWriteBuffer() {
621 if !cn.applyNextRequestState() {
624 if cn.pex.IsEnabled() {
625 if flow := cn.pex.Share(cn.write); !flow {
632 func (cn *PeerConn) have(piece pieceIndex) {
633 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
638 Index: pp.Integer(piece),
640 cn.sentHaves.Add(bitmap.BitIndex(piece))
643 func (cn *PeerConn) postBitfield() {
644 if cn.sentHaves.Len() != 0 {
645 panic("bitfield must be first have-related message sent")
647 if !cn.t.haveAnyPieces() {
652 Bitfield: cn.t.bitfield(),
654 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
657 func (cn *PeerConn) updateRequests(reason string) {
658 if cn.needRequestUpdate != "" {
661 cn.needRequestUpdate = reason
665 // Emits the indices in the Bitmaps bms in order, never repeating any index.
666 // skip is mutated during execution, and its initial values will never be
668 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
669 return func(cb iter.Callback) {
670 for _, bm := range bms {
672 func(_i interface{}) bool {
674 if skip.Contains(bitmap.BitIndex(i)) {
677 skip.Add(bitmap.BitIndex(i))
688 func (cn *Peer) peerPiecesChanged() {
689 cn.t.maybeDropMutuallyCompletePeer(cn)
692 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
693 if newMin > cn.peerMinPieces {
694 cn.peerMinPieces = newMin
698 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
699 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
700 return errors.New("invalid piece")
702 if cn.peerHasPiece(piece) {
705 cn.raisePeerMinPieces(piece + 1)
706 if !cn.peerHasPiece(piece) {
707 cn.t.incPieceAvailability(piece)
709 cn._peerPieces.Add(uint32(piece))
710 if cn.t.wantPieceIndex(piece) {
711 cn.updateRequests("have")
713 cn.peerPiecesChanged()
717 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
719 panic("expected bitfield length divisible by 8")
721 // We know that the last byte means that at most the last 7 bits are wasted.
722 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
723 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
724 // Ignore known excess pieces.
725 bf = bf[:cn.t.numPieces()]
727 pp := cn.newPeerPieces()
728 cn.peerSentHaveAll = false
729 for i, have := range bf {
731 cn.raisePeerMinPieces(pieceIndex(i) + 1)
732 if !pp.Contains(bitmap.BitIndex(i)) {
733 cn.t.incPieceAvailability(i)
736 if pp.Contains(bitmap.BitIndex(i)) {
737 cn.t.decPieceAvailability(i)
741 cn._peerPieces.Add(uint32(i))
742 if cn.t.wantPieceIndex(i) {
743 cn.updateRequests("bitfield")
746 cn._peerPieces.Remove(uint32(i))
749 cn.peerPiecesChanged()
753 func (cn *Peer) onPeerHasAllPieces() {
756 npp, pc := cn.newPeerPieces(), t.numPieces()
757 for i := 0; i < pc; i += 1 {
758 if !npp.Contains(bitmap.BitIndex(i)) {
759 t.incPieceAvailability(i)
763 cn.peerSentHaveAll = true
764 cn._peerPieces.Clear()
765 if cn.t._pendingPieces.Len() != 0 {
766 cn.updateRequests("have all")
768 cn.peerPiecesChanged()
771 func (cn *PeerConn) onPeerSentHaveAll() error {
772 cn.onPeerHasAllPieces()
776 func (cn *PeerConn) peerSentHaveNone() error {
777 cn.t.decPeerPieceAvailability(&cn.Peer)
778 cn._peerPieces.Clear()
779 cn.peerSentHaveAll = false
780 cn.peerPiecesChanged()
784 func (c *PeerConn) requestPendingMetadata() {
788 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
789 // Peer doesn't support this.
792 // Request metadata pieces that we don't have in a random order.
794 for index := 0; index < c.t.metadataPieceCount(); index++ {
795 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
796 pending = append(pending, index)
799 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
800 for _, i := range pending {
801 c.requestMetadataPiece(i)
805 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
806 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
807 if msg.Type == pp.Extended {
808 for name, id := range cn.PeerExtensionIDs {
809 if id != msg.ExtendedID {
812 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
815 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
818 // After handshake, we know what Torrent and Client stats to include for a
820 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
826 // All ConnStats that include this connection. Some objects are not known
827 // until the handshake is complete, after which it's expected to reconcile the
829 func (cn *Peer) allStats(f func(*ConnStats)) {
831 if cn.reconciledHandshakeStats {
832 cn.postHandshakeStats(f)
836 func (cn *PeerConn) wroteBytes(n int64) {
837 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
840 func (cn *PeerConn) readBytes(n int64) {
841 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
844 // Returns whether the connection could be useful to us. We're seeding and
845 // they want data, we don't have metainfo and they can provide it, etc.
846 func (c *Peer) useful() bool {
848 if c.closed.IsSet() {
852 return c.supportsExtension("ut_metadata")
854 if t.seeding() && c.peerInterested {
857 if c.peerHasWantedPieces() {
863 func (c *Peer) lastHelpful() (ret time.Time) {
864 ret = c.lastUsefulChunkReceived
865 if c.t.seeding() && c.lastChunkSent.After(ret) {
866 ret = c.lastChunkSent
871 func (c *PeerConn) fastEnabled() bool {
872 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
875 func (c *PeerConn) reject(r Request) {
876 if !c.fastEnabled() {
877 panic("fast not enabled")
879 c.write(r.ToMsg(pp.Reject))
880 delete(c.peerRequests, r)
883 func (c *PeerConn) onReadRequest(r Request) error {
884 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
885 if _, ok := c.peerRequests[r]; ok {
886 torrent.Add("duplicate requests received", 1)
890 torrent.Add("requests received while choking", 1)
892 torrent.Add("requests rejected while choking", 1)
897 // TODO: What if they've already requested this?
898 if len(c.peerRequests) >= localClientReqq {
899 torrent.Add("requests received while queue full", 1)
903 // BEP 6 says we may close here if we choose.
906 if !c.t.havePiece(pieceIndex(r.Index)) {
907 // This isn't necessarily them screwing up. We can drop pieces
908 // from our storage, and can't communicate this to peers
909 // except by reconnecting.
910 requestsReceivedForMissingPieces.Add(1)
911 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
913 // Check this after we know we have the piece, so that the piece length will be known.
914 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
915 torrent.Add("bad requests received", 1)
916 return errors.New("bad Request")
918 if c.peerRequests == nil {
919 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
921 value := &peerRequestState{}
922 c.peerRequests[r] = value
923 go c.peerRequestDataReader(r, value)
928 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
929 b, err := readPeerRequestData(r, c)
931 defer c.locker().Unlock()
933 c.peerRequestDataReadFailed(err, r)
936 panic("data must be non-nil to trigger send")
943 // If this is maintained correctly, we might be able to support optional synchronous reading for
944 // chunk sending, the way it used to work.
945 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
946 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
947 i := pieceIndex(r.Index)
948 if c.t.pieceComplete(i) {
949 // There used to be more code here that just duplicated the following break. Piece
950 // completions are currently cached, so I'm not sure how helpful this update is, except to
951 // pull any completion changes pushed to the storage backend in failed reads that got us
953 c.t.updatePieceCompletion(i)
955 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
956 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
957 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
958 // next connect. TODO: Support rejecting here too.
960 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
965 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
966 b := make([]byte, r.Length)
967 p := c.t.info.Piece(int(r.Index))
968 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
975 panic("expected error")
981 func runSafeExtraneous(f func()) {
989 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
990 // exit. Returning will end the connection.
991 func (c *PeerConn) mainReadLoop() (err error) {
994 torrent.Add("connection.mainReadLoop returned with error", 1)
996 torrent.Add("connection.mainReadLoop returned with no error", 1)
1002 decoder := pp.Decoder{
1003 R: bufio.NewReaderSize(c.r, 1<<17),
1004 MaxLength: 256 * 1024,
1012 err = decoder.Decode(&msg)
1014 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1017 if t.closed.IsSet() || c.closed.IsSet() {
1023 c.lastMessageReceived = time.Now()
1025 receivedKeepalives.Add(1)
1028 messageTypesReceived.Add(msg.Type.String(), 1)
1029 if msg.Type.FastExtension() && !c.fastEnabled() {
1030 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1031 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1035 c.peerChoking = true
1036 if !c.fastEnabled() {
1037 c.deleteAllRequests()
1039 // We can then reset our interest.
1040 c.updateRequests("choked")
1041 c.updateExpectingChunks()
1043 c.peerChoking = false
1044 c.updateRequests("unchoked")
1045 c.updateExpectingChunks()
1047 c.peerInterested = true
1049 case pp.NotInterested:
1050 c.peerInterested = false
1051 // We don't clear their requests since it isn't clear in the spec.
1052 // We'll probably choke them for this, which will clear them if
1053 // appropriate, and is clearly specified.
1055 err = c.peerSentHave(pieceIndex(msg.Index))
1057 err = c.peerSentBitfield(msg.Bitfield)
1059 r := newRequestFromMessage(&msg)
1060 err = c.onReadRequest(r)
1062 c.doChunkReadStats(int64(len(msg.Piece)))
1063 err = c.receiveChunk(&msg)
1064 if len(msg.Piece) == int(t.chunkSize) {
1065 t.chunkPool.Put(&msg.Piece)
1068 err = fmt.Errorf("receiving chunk: %w", err)
1071 req := newRequestFromMessage(&msg)
1072 c.onPeerSentCancel(req)
1074 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1078 pingAddr := net.UDPAddr{
1083 pingAddr.Port = int(msg.Port)
1085 cl.eachDhtServer(func(s DhtServer) {
1086 go s.Ping(&pingAddr)
1089 torrent.Add("suggests received", 1)
1090 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1091 c.updateRequests("suggested")
1093 err = c.onPeerSentHaveAll()
1095 err = c.peerSentHaveNone()
1097 c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1098 case pp.AllowedFast:
1099 torrent.Add("allowed fasts received", 1)
1100 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1101 c.peerAllowedFast.Add(bitmap.BitIndex(msg.Index))
1102 c.updateRequests("allowed fast")
1104 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1106 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1114 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1115 if c.deleteRequest(r) {
1116 c.decExpectedChunkReceive(r)
1120 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1121 count := c.validReceiveChunks[r]
1123 delete(c.validReceiveChunks, r)
1124 } else if count > 1 {
1125 c.validReceiveChunks[r] = count - 1
1131 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1133 // TODO: Should we still do this?
1135 // These clients use their own extension IDs for outgoing message
1136 // types, which is incorrect.
1137 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1145 case pp.HandshakeExtendedID:
1146 var d pp.ExtendedHandshakeMessage
1147 if err := bencode.Unmarshal(payload, &d); err != nil {
1148 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1149 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1151 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1154 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1156 c.PeerMaxRequests = d.Reqq
1158 c.PeerClientName = d.V
1159 if c.PeerExtensionIDs == nil {
1160 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1162 c.PeerListenPort = d.Port
1163 c.PeerPrefersEncryption = d.Encryption
1164 for name, id := range d.M {
1165 if _, ok := c.PeerExtensionIDs[name]; !ok {
1166 peersSupportingExtension.Add(string(name), 1)
1168 c.PeerExtensionIDs[name] = id
1170 if d.MetadataSize != 0 {
1171 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1172 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1175 c.requestPendingMetadata()
1176 if !t.cl.config.DisablePEX {
1177 t.pex.Add(c) // we learnt enough now
1181 case metadataExtendedId:
1182 err := cl.gotMetadataExtensionMsg(payload, t, c)
1184 return fmt.Errorf("handling metadata extension message: %w", err)
1188 if !c.pex.IsEnabled() {
1189 return nil // or hang-up maybe?
1191 return c.pex.Recv(payload)
1193 return fmt.Errorf("unexpected extended message ID: %v", id)
1197 // Set both the Reader and Writer for the connection from a single ReadWriter.
1198 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1203 // Returns the Reader and Writer as a combined ReadWriter.
1204 func (cn *PeerConn) rw() io.ReadWriter {
1211 func (c *Peer) doChunkReadStats(size int64) {
1212 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1215 // Handle a received chunk from a peer.
1216 func (c *Peer) receiveChunk(msg *pp.Message) error {
1217 chunksReceived.Add("total", 1)
1219 ppReq := newRequestFromMessage(msg)
1220 req := c.t.requestIndexFromRequest(ppReq)
1223 chunksReceived.Add("while choked", 1)
1226 if c.validReceiveChunks[req] <= 0 {
1227 chunksReceived.Add("unexpected", 1)
1228 return errors.New("received unexpected chunk")
1230 c.decExpectedChunkReceive(req)
1232 if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1233 chunksReceived.Add("due to allowed fast", 1)
1236 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1237 // have actually already received the piece, while we have the Client unlocked to write the data
1239 deletedRequest := false
1241 if c.actualRequestState.Requests.Contains(req) {
1242 for _, f := range c.callbacks.ReceivedRequested {
1243 f(PeerMessageEvent{c, msg})
1246 // Request has been satisfied.
1247 if c.deleteRequest(req) {
1248 deletedRequest = true
1250 c._chunksReceivedWhileExpecting++
1253 chunksReceived.Add("unwanted", 1)
1260 // Do we actually want this chunk?
1261 if t.haveChunk(ppReq) {
1262 chunksReceived.Add("wasted", 1)
1263 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1267 piece := &t.pieces[ppReq.Index]
1269 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1270 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1272 c.piecesReceivedSinceLastRequestUpdate++
1273 if c.actualRequestState.Requests.GetCardinality() == 0 {
1274 c.updateRequests("piece")
1276 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1278 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1279 f(ReceivedUsefulDataEvent{c, msg})
1281 c.lastUsefulChunkReceived = time.Now()
1283 // Need to record that it hasn't been written yet, before we attempt to do
1284 // anything with it.
1285 piece.incrementPendingWrites()
1286 // Record that we have the chunk, so we aren't trying to download it while
1287 // waiting for it to be written to storage.
1288 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1290 // Cancel pending requests for this chunk from *other* peers.
1291 t.iterPeers(func(p *Peer) {
1298 err := func() error {
1301 concurrentChunkWrites.Add(1)
1302 defer concurrentChunkWrites.Add(-1)
1303 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1304 // number of connections. We write inline with receiving the chunk (with this lock dance),
1305 // because we want to handle errors synchronously and I haven't thought of a nice way to
1306 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1308 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1311 piece.decrementPendingWrites()
1314 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1316 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1317 // request update runs while we're writing the chunk that just failed. Then we never do a
1318 // fresh update after pending the failed request.
1319 c.updateRequests("write chunk error")
1320 t.onWriteChunkErr(err)
1324 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1326 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1327 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1328 t.queuePieceCheck(pieceIndex(ppReq.Index))
1329 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1330 // chunk status (such as the haveChunk call above) to have to check all the various other
1331 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1332 // that chunk pieces are pended at an appropriate time later however.
1335 cl.event.Broadcast()
1336 // We do this because we've written a chunk, and may change PieceState.Partial.
1337 t.publishPieceChange(pieceIndex(ppReq.Index))
1342 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1343 if c.peerTouchedPieces == nil {
1344 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1346 c.peerTouchedPieces[piece] = struct{}{}
1347 ds := &c.t.pieces[piece].dirtiers
1349 *ds = make(map[*Peer]struct{})
1351 (*ds)[c] = struct{}{}
1354 func (c *PeerConn) uploadAllowed() bool {
1355 if c.t.cl.config.NoUpload {
1358 if c.t.dataUploadDisallowed {
1364 if !c.peerHasWantedPieces() {
1367 // Don't upload more than 100 KiB more than we download.
1368 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1374 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1375 if c.uploadTimer == nil {
1376 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1378 c.uploadTimer.Reset(delay)
1382 // Also handles choking and unchoking of the remote peer.
1383 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1384 // Breaking or completing this loop means we don't want to upload to the
1385 // peer anymore, and we choke them.
1387 for c.uploadAllowed() {
1388 // We want to upload to the peer.
1389 if !c.unchoke(msg) {
1392 for r, state := range c.peerRequests {
1393 if state.data == nil {
1396 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1398 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1400 delay := res.Delay()
1403 c.setRetryUploadTimer(delay)
1404 // Hard to say what to return here.
1407 more := c.sendChunk(r, msg, state)
1408 delete(c.peerRequests, r)
1419 func (cn *PeerConn) drop() {
1420 cn.t.dropConnection(cn)
1423 func (cn *Peer) netGoodPiecesDirtied() int64 {
1424 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1427 func (c *Peer) peerHasWantedPieces() bool {
1428 // TODO: Can this be done just with AndCardinality?
1429 missingPeerHas := c.newPeerPieces()
1430 missingPeerHas.AndNot(&c.t._completedPieces)
1431 return !missingPeerHas.IsEmpty()
1434 func (c *Peer) deleteRequest(r RequestIndex) bool {
1435 if !c.actualRequestState.Requests.CheckedRemove(r) {
1438 for _, f := range c.callbacks.DeletedRequest {
1439 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1441 c.updateExpectingChunks()
1442 c.t.pendingRequests.Dec(r)
1446 func (c *Peer) deleteAllRequests() {
1447 c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1451 if !c.actualRequestState.Requests.IsEmpty() {
1452 panic(c.actualRequestState.Requests.GetCardinality())
1454 // for c := range c.t.conns {
1459 // This is called when something has changed that should wake the writer, such as putting stuff into
1460 // the writeBuffer, or changing some state that the writer can act on.
1461 func (c *PeerConn) tickleWriter() {
1462 c.messageWriter.writeCond.Broadcast()
1465 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1466 c.lastChunkSent = time.Now()
1467 return msg(pp.Message{
1475 func (c *PeerConn) setTorrent(t *Torrent) {
1477 panic("connection already associated with a torrent")
1480 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1481 t.reconcileHandshakeStats(c)
1484 func (c *Peer) peerPriority() (peerPriority, error) {
1485 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1488 func (c *Peer) remoteIp() net.IP {
1489 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1490 return net.ParseIP(host)
1493 func (c *Peer) remoteIpPort() IpPort {
1494 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1495 return IpPort{ipa.IP, uint16(ipa.Port)}
1498 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1499 f := pp.PexPeerFlags(0)
1500 if c.PeerPrefersEncryption {
1501 f |= pp.PexPrefersEncryption
1504 f |= pp.PexOutgoingConn
1507 f |= pp.PexSupportsUtp
1512 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1513 // advertised listen port.
1514 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1515 if !c.outgoing && c.PeerListenPort != 0 {
1516 switch addr := c.RemoteAddr.(type) {
1519 dialAddr.Port = c.PeerListenPort
1523 dialAddr.Port = c.PeerListenPort
1530 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1531 f := c.pexPeerFlags()
1532 addr := c.dialAddr()
1533 return pexEvent{t, addr, f}
1536 func (c *PeerConn) String() string {
1537 return fmt.Sprintf("connection %p", c)
1540 func (c *Peer) trust() connectionTrust {
1541 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1544 type connectionTrust struct {
1546 NetGoodPiecesDirted int64
1549 func (l connectionTrust) Less(r connectionTrust) bool {
1550 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1553 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1554 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1555 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1557 defer cn.locker().RUnlock()
1558 return cn.newPeerPieces()
1561 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1562 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1563 // TODO: Can we use copy on write?
1564 ret := cn._peerPieces.Clone()
1565 if cn.peerSentHaveAll {
1566 if cn.t.haveInfo() {
1567 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1569 ret.AddRange(0, bitmap.ToEnd)
1575 func (cn *Peer) stats() *ConnStats {
1579 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1580 pc, ok := p.peerImpl.(*PeerConn)
1584 func (p *PeerConn) onNextRequestStateChanged() {