16 "github.com/anacrolix/log"
17 "github.com/anacrolix/missinggo"
18 "github.com/anacrolix/missinggo/iter"
19 "github.com/anacrolix/missinggo/v2/bitmap"
20 "github.com/anacrolix/missinggo/v2/prioritybitmap"
21 "github.com/anacrolix/multiless"
22 "github.com/anacrolix/torrent/metainfo"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/mse"
26 pp "github.com/anacrolix/torrent/peer_protocol"
29 type PeerSource string
32 PeerSourceTracker = "Tr"
33 PeerSourceIncoming = "I"
34 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
35 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
37 // The peer was given directly, such as through a magnet link.
38 PeerSourceDirect = "M"
41 type peerRequestState struct {
45 type PeerRemoteAddr interface {
50 // First to ensure 64-bit alignment for atomics. See #262.
60 RemoteAddr PeerRemoteAddr
61 // True if the connection is operating over MSE obfuscation.
63 cryptoMethod mse.CryptoMethod
66 closed missinggo.Event
67 // Set true after we've added our ConnStats generated during handshake to
68 // other ConnStat instances as determined when the *Torrent became known.
69 reconciledHandshakeStats bool
71 lastMessageReceived time.Time
72 completedHandshake time.Time
73 lastUsefulChunkReceived time.Time
74 lastChunkSent time.Time
76 // Stuff controlled by the local peer.
78 lastBecameInterested time.Time
79 priorInterest time.Duration
81 lastStartedExpectingToReceiveChunks time.Time
82 cumulativeExpectedToReceiveChunks time.Duration
83 _chunksReceivedWhileExpecting int64
86 requests map[Request]struct{}
88 // Chunks that we might reasonably expect to receive from the peer. Due to
89 // latency, buffering, and implementation differences, we may receive
90 // chunks that are no longer in the set of requests actually want.
91 validReceiveChunks map[Request]int
92 // Indexed by metadata piece, set to true if posted and pending a
94 metadataRequests []bool
95 sentHaves bitmap.Bitmap
97 // Stuff controlled by the remote peer.
100 peerRequests map[Request]*peerRequestState
101 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
103 // The pieces the peer has claimed to have.
104 _peerPieces bitmap.Bitmap
105 // The peer has everything. This can occur due to a special message, when
106 // we may not even know the number of pieces in the torrent yet.
108 // The highest possible number of pieces the torrent could have based on
109 // communication with the peer. Generally only useful until we have the
111 peerMinPieces pieceIndex
112 // Pieces we've accepted chunks for from the peer.
113 peerTouchedPieces map[pieceIndex]struct{}
114 peerAllowedFast bitmap.Bitmap
116 PeerMaxRequests int // Maximum pending requests the peer allows.
117 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
118 PeerClientName string
120 pieceInclination []int
121 _pieceRequestOrder prioritybitmap.PriorityBitmap
126 // Maintains the state of a BitTorrent-protocol based connection with a peer.
127 type PeerConn struct {
130 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
131 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
136 PeerExtensionBytes pp.PeerExtensionBits
138 // The actual Conn, used for closing, and setting socket options.
140 // The Reader and Writer for this Conn, with hooks installed for stats,
141 // limiting, deadlines etc.
145 writeBuffer *bytes.Buffer
146 uploadTimer *time.Timer
152 func (cn *PeerConn) connStatusString() string {
153 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
156 func (cn *Peer) updateExpectingChunks() {
157 if cn.expectingChunks() {
158 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
159 cn.lastStartedExpectingToReceiveChunks = time.Now()
162 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
163 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
164 cn.lastStartedExpectingToReceiveChunks = time.Time{}
169 func (cn *Peer) expectingChunks() bool {
170 if len(cn.requests) == 0 {
179 for r := range cn.requests {
180 if cn.peerAllowedFast.Contains(bitmap.BitIndex(r.Index)) {
187 // Returns true if the connection is over IPv6.
188 func (cn *PeerConn) ipv6() bool {
193 return len(ip) == net.IPv6len
196 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
197 // specification for this.
198 func (cn *PeerConn) isPreferredDirection() bool {
199 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
202 // Returns whether the left connection should be preferred over the right one,
203 // considering only their networking properties. If ok is false, we can't
205 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
207 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
208 ml.NextBool(!l.utp(), !r.utp())
209 ml.NextBool(l.ipv6(), r.ipv6())
213 func (cn *Peer) cumInterest() time.Duration {
214 ret := cn.priorInterest
216 ret += time.Since(cn.lastBecameInterested)
221 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
222 if cn.peerSentHaveAll {
225 if !cn.t.haveInfo() {
228 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
231 func (cn *PeerConn) locker() *lockWithDeferreds {
232 return cn.t.cl.locker()
235 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
236 _, ok := cn.PeerExtensionIDs[ext]
240 // The best guess at number of pieces in the torrent for this peer.
241 func (cn *Peer) bestPeerNumPieces() pieceIndex {
243 return cn.t.numPieces()
245 return cn.peerMinPieces
248 func (cn *Peer) completedString() string {
249 have := pieceIndex(cn._peerPieces.Len())
250 if cn.peerSentHaveAll {
251 have = cn.bestPeerNumPieces()
253 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
256 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
257 cn.setNumPieces(info.NumPieces())
260 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
261 // receiving badly sized BITFIELD, or invalid HAVE messages.
262 func (cn *PeerConn) setNumPieces(num pieceIndex) {
263 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
264 cn.peerPiecesChanged()
267 func eventAgeString(t time.Time) string {
271 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
274 func (cn *PeerConn) connectionFlags() (ret string) {
276 ret += string([]byte{b})
278 if cn.cryptoMethod == mse.CryptoMethodRC4 {
280 } else if cn.headerEncrypted {
283 ret += string(cn.Discovery)
290 func (cn *PeerConn) utp() bool {
291 return parseNetworkString(cn.Network).Udp
294 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
295 func (cn *Peer) statusFlags() (ret string) {
297 ret += string([]byte{b})
306 ret += cn.connectionFlags()
308 if cn.peerInterested {
317 func (cn *Peer) downloadRate() float64 {
318 num := cn._stats.BytesReadUsefulData.Int64()
322 return float64(num) / cn.totalExpectingTime().Seconds()
325 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
326 ret = make(map[pieceIndex]int)
327 for r := range cn.requests {
328 ret[pieceIndex(r.Index)]++
333 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
334 // \t isn't preserved in <pre> blocks?
335 if cn.closed.IsSet() {
336 fmt.Fprint(w, "CLOSED: ")
338 fmt.Fprintln(w, cn.connStatusString())
339 prio, err := cn.peerPriority()
340 prioStr := fmt.Sprintf("%08x", prio)
342 prioStr += ": " + err.Error()
344 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
345 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
346 eventAgeString(cn.lastMessageReceived),
347 eventAgeString(cn.completedHandshake),
348 eventAgeString(cn.lastHelpful()),
350 cn.totalExpectingTime(),
353 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
354 cn.completedString(),
355 len(cn.peerTouchedPieces),
356 &cn._stats.ChunksReadUseful,
357 &cn._stats.ChunksRead,
358 &cn._stats.ChunksWritten,
359 cn.numLocalRequests(),
360 cn.nominalMaxRequests(),
362 len(cn.peerRequests),
365 cn.downloadRate()/(1<<10),
367 fmt.Fprintf(w, " requested pieces:")
368 for piece, count := range cn.numRequestsByPiece() {
369 fmt.Fprintf(w, " %v (%v)", piece, count)
374 func (cn *Peer) close() {
375 if !cn.closed.Set() {
378 cn.discardPieceInclination()
379 cn._pieceRequestOrder.Clear()
380 cn.peerImpl.onClose()
381 for _, f := range cn.callbacks.PeerClosed {
386 func (cn *PeerConn) onClose() {
387 if cn.pex.IsEnabled() {
394 if cb := cn.callbacks.PeerConnClosed; cb != nil {
399 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
400 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
403 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
404 // https://github.com/pion/datachannel/issues/59 is fixed.
405 const writeBufferHighWaterLen = 1 << 15
407 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Posting is
408 // done asynchronously, so it may be that we're not able to honour backpressure from this method. It
409 // might be possible to merge this with PeerConn.write down the track? They seem to be very similar.
410 func (cn *PeerConn) post(msg pp.Message) bool {
411 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
412 // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
413 // (although there's some delay between us recording the message, and the connection writer
414 // flushing it out.).
415 cn.writeBuffer.Write(msg.MustMarshalBinary())
416 // Last I checked only Piece messages affect stats, and we don't post those.
419 return cn.writeBuffer.Len() < writeBufferHighWaterLen
422 // Returns true if there's room to write more.
423 func (cn *PeerConn) write(msg pp.Message) bool {
425 cn.writeBuffer.Write(msg.MustMarshalBinary())
426 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
428 return !cn.writeBufferFull()
431 func (cn *PeerConn) writeBufferFull() bool {
432 return cn.writeBuffer.Len() >= writeBufferHighWaterLen
435 func (cn *PeerConn) requestMetadataPiece(index int) {
436 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
440 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
443 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
447 ExtendedPayload: func() []byte {
448 b, err := bencode.Marshal(map[string]int{
449 "msg_type": pp.RequestMetadataExtensionMsgType,
458 for index >= len(cn.metadataRequests) {
459 cn.metadataRequests = append(cn.metadataRequests, false)
461 cn.metadataRequests[index] = true
464 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
465 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
468 // The actual value to use as the maximum outbound requests.
469 func (cn *Peer) nominalMaxRequests() (ret int) {
470 return int(clamp(1, int64(cn.PeerMaxRequests), 64))
473 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
474 ret = cn.cumulativeExpectedToReceiveChunks
475 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
476 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
482 func (cn *PeerConn) onPeerSentCancel(r Request) {
483 if _, ok := cn.peerRequests[r]; !ok {
484 torrent.Add("unexpected cancels received", 1)
487 if cn.fastEnabled() {
490 delete(cn.peerRequests, r)
494 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
499 more = msg(pp.Message{
502 if cn.fastEnabled() {
503 for r := range cn.peerRequests {
504 // TODO: Don't reject pieces in allowed fast set.
508 cn.peerRequests = nil
513 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
518 return msg(pp.Message{
523 func (cn *Peer) setInterested(interested bool) bool {
524 if cn.interested == interested {
527 cn.interested = interested
529 cn.lastBecameInterested = time.Now()
530 } else if !cn.lastBecameInterested.IsZero() {
531 cn.priorInterest += time.Since(cn.lastBecameInterested)
533 cn.updateExpectingChunks()
534 // log.Printf("%p: setting interest: %v", cn, interested)
535 return cn.writeInterested(interested)
538 func (pc *PeerConn) writeInterested(interested bool) bool {
539 return pc.write(pp.Message{
540 Type: func() pp.MessageType {
544 return pp.NotInterested
550 // The function takes a message to be sent, and returns true if more messages
552 type messageWriter func(pp.Message) bool
554 func (cn *Peer) request(r Request) error {
555 if _, ok := cn.requests[r]; ok {
558 if cn.numLocalRequests() >= cn.nominalMaxRequests() {
559 return errors.New("too many outstanding requests")
561 if !cn.peerHasPiece(pieceIndex(r.Index)) {
562 return errors.New("requesting piece peer doesn't have")
564 if !cn.t.peerIsActive(cn) {
565 panic("requesting but not in active conns")
567 if cn.closed.IsSet() {
568 panic("requesting when connection is closed")
570 if cn.t.hashingPiece(pieceIndex(r.Index)) {
571 panic("piece is being hashed")
573 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
574 panic("piece is queued for hash")
576 if !cn.setInterested(true) {
577 return errors.New("write buffer full after expressing interest")
580 if cn.peerAllowedFast.Get(int(r.Index)) {
581 torrent.Add("allowed fast requests sent", 1)
583 errors.New("peer choking and piece not in allowed fast set")
586 if cn.requests == nil {
587 cn.requests = make(map[Request]struct{})
589 cn.requests[r] = struct{}{}
590 if cn.validReceiveChunks == nil {
591 cn.validReceiveChunks = make(map[Request]int)
593 cn.validReceiveChunks[r]++
594 cn.t.pendingRequests[r]++
595 cn.updateExpectingChunks()
596 for _, f := range cn.callbacks.SentRequest {
597 f(PeerRequestEvent{cn, r})
599 cn.peerImpl._request(r)
603 func (me *PeerConn) _request(r Request) {
612 func (me *Peer) cancel(r Request) {
613 if me.deleteRequest(r) {
614 me.peerImpl._cancel(r)
618 func (me *PeerConn) _cancel(r Request) {
619 me.write(makeCancelMessage(r))
622 func (cn *PeerConn) fillWriteBuffer() {
623 if cn.pex.IsEnabled() {
624 if flow := cn.pex.Share(cn.write); !flow {
631 // Routine that writes to the peer. Some of what to write is buffered by
632 // activity elsewhere in the Client, and some is determined locally when the
633 // connection is writable.
634 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
636 lastWrite time.Time = time.Now()
637 keepAliveTimer *time.Timer
639 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
641 defer cn.locker().Unlock()
642 if time.Since(lastWrite) >= keepAliveTimeout {
645 keepAliveTimer.Reset(keepAliveTimeout)
648 defer cn.locker().Unlock()
650 defer keepAliveTimer.Stop()
651 frontBuf := new(bytes.Buffer)
653 if cn.closed.IsSet() {
656 if cn.writeBuffer.Len() == 0 {
659 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
660 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
661 torrent.Add("written keepalives", 1)
663 if cn.writeBuffer.Len() == 0 {
664 // TODO: Minimize wakeups....
669 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
671 n, err := cn.w.Write(frontBuf.Bytes())
674 lastWrite = time.Now()
675 keepAliveTimer.Reset(keepAliveTimeout)
678 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
681 if n != frontBuf.Len() {
688 func (cn *PeerConn) have(piece pieceIndex) {
689 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
694 Index: pp.Integer(piece),
696 cn.sentHaves.Add(bitmap.BitIndex(piece))
699 func (cn *PeerConn) postBitfield() {
700 if cn.sentHaves.Len() != 0 {
701 panic("bitfield must be first have-related message sent")
703 if !cn.t.haveAnyPieces() {
708 Bitfield: cn.t.bitfield(),
710 cn.sentHaves = cn.t._completedPieces.Copy()
713 func (cn *PeerConn) updateRequests() {
714 // log.Print("update requests")
718 // Emits the indices in the Bitmaps bms in order, never repeating any index.
719 // skip is mutated during execution, and its initial values will never be
721 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
722 return func(cb iter.Callback) {
723 for _, bm := range bms {
725 func(_i interface{}) bool {
727 if skip.Contains(i) {
741 // check callers updaterequests
742 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
743 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
746 // This is distinct from Torrent piece priority, which is the user's
747 // preference. Connection piece priority is specific to a connection and is
748 // used to pseudorandomly avoid connections always requesting the same pieces
749 // and thus wasting effort.
750 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
751 tpp := cn.t.piecePriority(piece)
752 if !cn.peerHasPiece(piece) {
753 tpp = PiecePriorityNone
755 if tpp == PiecePriorityNone {
756 return cn.stopRequestingPiece(piece)
758 prio := cn.getPieceInclination()[piece]
759 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio)
762 func (cn *Peer) getPieceInclination() []int {
763 if cn.pieceInclination == nil {
764 cn.pieceInclination = cn.t.getConnPieceInclination()
766 return cn.pieceInclination
769 func (cn *Peer) discardPieceInclination() {
770 if cn.pieceInclination == nil {
773 cn.t.putPieceInclination(cn.pieceInclination)
774 cn.pieceInclination = nil
777 func (cn *PeerConn) peerPiecesChanged() {
779 prioritiesChanged := false
780 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
781 if cn.updatePiecePriority(i) {
782 prioritiesChanged = true
785 if prioritiesChanged {
789 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
792 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
793 if newMin > cn.peerMinPieces {
794 cn.peerMinPieces = newMin
798 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
799 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
800 return errors.New("invalid piece")
802 if cn.peerHasPiece(piece) {
805 cn.raisePeerMinPieces(piece + 1)
806 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
807 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
808 if cn.updatePiecePriority(piece) {
814 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
815 cn.peerSentHaveAll = false
817 panic("expected bitfield length divisible by 8")
819 // We know that the last byte means that at most the last 7 bits are
821 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
822 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
823 // Ignore known excess pieces.
824 bf = bf[:cn.t.numPieces()]
826 for i, have := range bf {
828 cn.raisePeerMinPieces(pieceIndex(i) + 1)
830 cn._peerPieces.Set(i, have)
832 cn.peerPiecesChanged()
836 func (cn *PeerConn) onPeerSentHaveAll() error {
837 cn.peerSentHaveAll = true
838 cn._peerPieces.Clear()
839 cn.peerPiecesChanged()
843 func (cn *PeerConn) peerSentHaveNone() error {
844 cn._peerPieces.Clear()
845 cn.peerSentHaveAll = false
846 cn.peerPiecesChanged()
850 func (c *PeerConn) requestPendingMetadata() {
854 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
855 // Peer doesn't support this.
858 // Request metadata pieces that we don't have in a random order.
860 for index := 0; index < c.t.metadataPieceCount(); index++ {
861 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
862 pending = append(pending, index)
865 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
866 for _, i := range pending {
867 c.requestMetadataPiece(i)
871 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
872 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
873 if msg.Type == pp.Extended {
874 for name, id := range cn.PeerExtensionIDs {
875 if id != msg.ExtendedID {
878 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
881 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
884 func (cn *PeerConn) readMsg(msg *pp.Message) {
885 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
888 // After handshake, we know what Torrent and Client stats to include for a
890 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
896 // All ConnStats that include this connection. Some objects are not known
897 // until the handshake is complete, after which it's expected to reconcile the
899 func (cn *Peer) allStats(f func(*ConnStats)) {
901 if cn.reconciledHandshakeStats {
902 cn.postHandshakeStats(f)
906 func (cn *PeerConn) wroteBytes(n int64) {
907 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
910 func (cn *PeerConn) readBytes(n int64) {
911 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
914 // Returns whether the connection could be useful to us. We're seeding and
915 // they want data, we don't have metainfo and they can provide it, etc.
916 func (c *Peer) useful() bool {
918 if c.closed.IsSet() {
922 return c.supportsExtension("ut_metadata")
924 if t.seeding() && c.peerInterested {
927 if c.peerHasWantedPieces() {
933 func (c *Peer) lastHelpful() (ret time.Time) {
934 ret = c.lastUsefulChunkReceived
935 if c.t.seeding() && c.lastChunkSent.After(ret) {
936 ret = c.lastChunkSent
941 func (c *PeerConn) fastEnabled() bool {
942 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
945 func (c *PeerConn) reject(r Request) {
946 if !c.fastEnabled() {
947 panic("fast not enabled")
949 c.post(r.ToMsg(pp.Reject))
950 delete(c.peerRequests, r)
953 func (c *PeerConn) onReadRequest(r Request) error {
954 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
955 if _, ok := c.peerRequests[r]; ok {
956 torrent.Add("duplicate requests received", 1)
960 torrent.Add("requests received while choking", 1)
962 torrent.Add("requests rejected while choking", 1)
967 if len(c.peerRequests) >= maxRequests {
968 torrent.Add("requests received while queue full", 1)
972 // BEP 6 says we may close here if we choose.
975 if !c.t.havePiece(pieceIndex(r.Index)) {
976 // This isn't necessarily them screwing up. We can drop pieces
977 // from our storage, and can't communicate this to peers
978 // except by reconnecting.
979 requestsReceivedForMissingPieces.Add(1)
980 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
982 // Check this after we know we have the piece, so that the piece length will be known.
983 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
984 torrent.Add("bad requests received", 1)
985 return errors.New("bad Request")
987 if c.peerRequests == nil {
988 c.peerRequests = make(map[Request]*peerRequestState, maxRequests)
990 value := &peerRequestState{}
991 c.peerRequests[r] = value
992 go c.peerRequestDataReader(r, value)
997 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
998 b, err := readPeerRequestData(r, c)
1000 defer c.locker().Unlock()
1002 c.peerRequestDataReadFailed(err, r)
1005 panic("data must be non-nil to trigger send")
1012 // If this is maintained correctly, we might be able to support optional synchronous reading for
1013 // chunk sending, the way it used to work.
1014 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1015 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1016 i := pieceIndex(r.Index)
1017 if c.t.pieceComplete(i) {
1018 // There used to be more code here that just duplicated the following break. Piece
1019 // completions are currently cached, so I'm not sure how helpful this update is, except to
1020 // pull any completion changes pushed to the storage backend in failed reads that got us
1022 c.t.updatePieceCompletion(i)
1024 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1025 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1026 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1027 // next connect. TODO: Support rejecting here too.
1029 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1034 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1035 b := make([]byte, r.Length)
1036 p := c.t.info.Piece(int(r.Index))
1037 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1044 panic("expected error")
1050 func runSafeExtraneous(f func()) {
1058 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1059 // exit. Returning will end the connection.
1060 func (c *PeerConn) mainReadLoop() (err error) {
1063 torrent.Add("connection.mainReadLoop returned with error", 1)
1065 torrent.Add("connection.mainReadLoop returned with no error", 1)
1071 decoder := pp.Decoder{
1072 R: bufio.NewReaderSize(c.r, 1<<17),
1073 MaxLength: 256 * 1024,
1081 err = decoder.Decode(&msg)
1083 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1086 if t.closed.IsSet() || c.closed.IsSet() {
1093 c.lastMessageReceived = time.Now()
1095 receivedKeepalives.Add(1)
1098 messageTypesReceived.Add(msg.Type.String(), 1)
1099 if msg.Type.FastExtension() && !c.fastEnabled() {
1100 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1101 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1105 c.peerChoking = true
1106 if !c.fastEnabled() {
1107 c.deleteAllRequests()
1109 // We can then reset our interest.
1111 c.updateExpectingChunks()
1113 c.peerChoking = false
1115 c.updateExpectingChunks()
1117 c.peerInterested = true
1119 case pp.NotInterested:
1120 c.peerInterested = false
1121 // We don't clear their requests since it isn't clear in the spec.
1122 // We'll probably choke them for this, which will clear them if
1123 // appropriate, and is clearly specified.
1125 err = c.peerSentHave(pieceIndex(msg.Index))
1127 err = c.peerSentBitfield(msg.Bitfield)
1129 r := newRequestFromMessage(&msg)
1130 err = c.onReadRequest(r)
1132 err = c.receiveChunk(&msg)
1133 if len(msg.Piece) == int(t.chunkSize) {
1134 t.chunkPool.Put(&msg.Piece)
1137 err = fmt.Errorf("receiving chunk: %s", err)
1140 req := newRequestFromMessage(&msg)
1141 c.onPeerSentCancel(req)
1143 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1147 pingAddr := net.UDPAddr{
1152 pingAddr.Port = int(msg.Port)
1154 cl.eachDhtServer(func(s DhtServer) {
1155 go s.Ping(&pingAddr)
1158 torrent.Add("suggests received", 1)
1159 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1162 err = c.onPeerSentHaveAll()
1164 err = c.peerSentHaveNone()
1166 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1167 case pp.AllowedFast:
1168 torrent.Add("allowed fasts received", 1)
1169 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1170 c.peerAllowedFast.Add(int(msg.Index))
1173 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1175 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1183 func (c *Peer) remoteRejectedRequest(r Request) {
1184 if c.deleteRequest(r) {
1185 c.decExpectedChunkReceive(r)
1189 func (c *Peer) decExpectedChunkReceive(r Request) {
1190 count := c.validReceiveChunks[r]
1192 delete(c.validReceiveChunks, r)
1193 } else if count > 1 {
1194 c.validReceiveChunks[r] = count - 1
1200 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1202 // TODO: Should we still do this?
1204 // These clients use their own extension IDs for outgoing message
1205 // types, which is incorrect.
1206 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1214 case pp.HandshakeExtendedID:
1215 var d pp.ExtendedHandshakeMessage
1216 if err := bencode.Unmarshal(payload, &d); err != nil {
1217 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1218 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1220 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1223 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1225 c.PeerMaxRequests = d.Reqq
1227 c.PeerClientName = d.V
1228 if c.PeerExtensionIDs == nil {
1229 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1231 c.PeerListenPort = d.Port
1232 c.PeerPrefersEncryption = d.Encryption
1233 for name, id := range d.M {
1234 if _, ok := c.PeerExtensionIDs[name]; !ok {
1235 peersSupportingExtension.Add(string(name), 1)
1237 c.PeerExtensionIDs[name] = id
1239 if d.MetadataSize != 0 {
1240 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1241 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1244 c.requestPendingMetadata()
1245 if !t.cl.config.DisablePEX {
1246 t.pex.Add(c) // we learnt enough now
1250 case metadataExtendedId:
1251 err := cl.gotMetadataExtensionMsg(payload, t, c)
1253 return fmt.Errorf("handling metadata extension message: %w", err)
1257 if !c.pex.IsEnabled() {
1258 return nil // or hang-up maybe?
1260 return c.pex.Recv(payload)
1262 return fmt.Errorf("unexpected extended message ID: %v", id)
1266 // Set both the Reader and Writer for the connection from a single ReadWriter.
1267 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1272 // Returns the Reader and Writer as a combined ReadWriter.
1273 func (cn *PeerConn) rw() io.ReadWriter {
1280 // Handle a received chunk from a peer.
1281 func (c *Peer) receiveChunk(msg *pp.Message) error {
1284 chunksReceived.Add("total", 1)
1286 req := newRequestFromMessage(msg)
1289 chunksReceived.Add("while choked", 1)
1292 if c.validReceiveChunks[req] <= 0 {
1293 chunksReceived.Add("unexpected", 1)
1294 return errors.New("received unexpected chunk")
1296 c.decExpectedChunkReceive(req)
1298 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1299 chunksReceived.Add("due to allowed fast", 1)
1302 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1303 // have actually already received the piece, while we have the Client unlocked to write the data
1305 deletedRequest := false
1307 if _, ok := c.requests[req]; ok {
1308 for _, f := range c.callbacks.ReceivedRequested {
1309 f(PeerMessageEvent{c, msg})
1312 // Request has been satisfied.
1313 if c.deleteRequest(req) {
1314 deletedRequest = true
1316 c._chunksReceivedWhileExpecting++
1319 chunksReceived.Add("unwanted", 1)
1323 // Do we actually want this chunk?
1324 if t.haveChunk(req) {
1325 chunksReceived.Add("wasted", 1)
1326 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1330 piece := &t.pieces[req.Index]
1332 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1333 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1335 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1337 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1338 f(ReceivedUsefulDataEvent{c, msg})
1340 c.lastUsefulChunkReceived = time.Now()
1342 // Need to record that it hasn't been written yet, before we attempt to do
1343 // anything with it.
1344 piece.incrementPendingWrites()
1345 // Record that we have the chunk, so we aren't trying to download it while
1346 // waiting for it to be written to storage.
1347 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1349 // Cancel pending requests for this chunk from *other* peers.
1350 t.iterPeers(func(p *Peer) {
1357 err := func() error {
1360 concurrentChunkWrites.Add(1)
1361 defer concurrentChunkWrites.Add(-1)
1362 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1363 // number of connections. We write inline with receiving the chunk (with this lock dance),
1364 // because we want to handle errors synchronously and I haven't thought of a nice way to
1365 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1367 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1370 piece.decrementPendingWrites()
1373 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1375 //t.updatePieceCompletion(pieceIndex(msg.Index))
1376 t.onWriteChunkErr(err)
1380 c.onDirtiedPiece(pieceIndex(req.Index))
1382 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1383 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1384 t.queuePieceCheck(pieceIndex(req.Index))
1385 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1386 // chunk status (such as the haveChunk call above) to have to check all the various other
1387 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1388 // that chunk pieces are pended at an appropriate time later however.
1391 cl.event.Broadcast()
1392 // We do this because we've written a chunk, and may change PieceState.Partial.
1393 t.publishPieceChange(pieceIndex(req.Index))
1398 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1399 if c.peerTouchedPieces == nil {
1400 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1402 c.peerTouchedPieces[piece] = struct{}{}
1403 ds := &c.t.pieces[piece].dirtiers
1405 *ds = make(map[*Peer]struct{})
1407 (*ds)[c] = struct{}{}
1410 func (c *PeerConn) uploadAllowed() bool {
1411 if c.t.cl.config.NoUpload {
1414 if c.t.dataUploadDisallowed {
1420 if !c.peerHasWantedPieces() {
1423 // Don't upload more than 100 KiB more than we download.
1424 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1430 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1431 if c.uploadTimer == nil {
1432 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1434 c.uploadTimer.Reset(delay)
1438 // Also handles choking and unchoking of the remote peer.
1439 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1440 // Breaking or completing this loop means we don't want to upload to the
1441 // peer anymore, and we choke them.
1443 for c.uploadAllowed() {
1444 // We want to upload to the peer.
1445 if !c.unchoke(msg) {
1448 for r, state := range c.peerRequests {
1449 if state.data == nil {
1452 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1454 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1456 delay := res.Delay()
1459 c.setRetryUploadTimer(delay)
1460 // Hard to say what to return here.
1463 more := c.sendChunk(r, msg, state)
1464 delete(c.peerRequests, r)
1475 func (cn *PeerConn) drop() {
1476 cn.t.dropConnection(cn)
1479 func (cn *Peer) netGoodPiecesDirtied() int64 {
1480 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1483 func (c *Peer) peerHasWantedPieces() bool {
1484 return !c._pieceRequestOrder.IsEmpty()
1487 func (c *Peer) numLocalRequests() int {
1488 return len(c.requests)
1491 func (c *Peer) deleteRequest(r Request) bool {
1492 if _, ok := c.requests[r]; !ok {
1495 delete(c.requests, r)
1496 for _, f := range c.callbacks.DeletedRequest {
1497 f(PeerRequestEvent{c, r})
1499 c.updateExpectingChunks()
1500 pr := c.t.pendingRequests
1512 func (c *Peer) deleteAllRequests() {
1513 for r := range c.requests {
1516 if len(c.requests) != 0 {
1517 panic(len(c.requests))
1519 // for c := range c.t.conns {
1524 // This is called when something has changed that should wake the writer, such as putting stuff into
1525 // the writeBuffer, or changing some state that the writer can act on.
1526 func (c *PeerConn) tickleWriter() {
1527 c.writerCond.Broadcast()
1530 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1531 c.lastChunkSent = time.Now()
1532 return msg(pp.Message{
1540 func (c *PeerConn) setTorrent(t *Torrent) {
1542 panic("connection already associated with a torrent")
1545 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1546 t.reconcileHandshakeStats(c)
1549 func (c *Peer) peerPriority() (peerPriority, error) {
1550 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1553 func (c *Peer) remoteIp() net.IP {
1554 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1555 return net.ParseIP(host)
1558 func (c *Peer) remoteIpPort() IpPort {
1559 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1560 return IpPort{ipa.IP, uint16(ipa.Port)}
1563 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1564 f := pp.PexPeerFlags(0)
1565 if c.PeerPrefersEncryption {
1566 f |= pp.PexPrefersEncryption
1569 f |= pp.PexOutgoingConn
1572 f |= pp.PexSupportsUtp
1577 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1578 // advertised listen port.
1579 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1580 if !c.outgoing && c.PeerListenPort != 0 {
1581 switch addr := c.RemoteAddr.(type) {
1584 dialAddr.Port = c.PeerListenPort
1588 dialAddr.Port = c.PeerListenPort
1595 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1596 f := c.pexPeerFlags()
1597 addr := c.dialAddr()
1598 return pexEvent{t, addr, f}
1601 func (c *PeerConn) String() string {
1602 return fmt.Sprintf("connection %p", c)
1605 func (c *Peer) trust() connectionTrust {
1606 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1609 type connectionTrust struct {
1611 NetGoodPiecesDirted int64
1614 func (l connectionTrust) Less(r connectionTrust) bool {
1615 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1618 func (cn *Peer) peerMaxRequests() int {
1619 return cn.PeerMaxRequests
1622 // Returns the pieces the peer has claimed to have.
1623 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1625 defer cn.locker().RUnlock()
1626 return cn.peerPieces()
1629 func (cn *Peer) peerPieces() bitmap.Bitmap {
1630 ret := cn._peerPieces.Copy()
1631 if cn.peerSentHaveAll {
1632 ret.AddRange(0, cn.t.numPieces())
1637 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1638 return &cn._pieceRequestOrder
1641 func (cn *Peer) stats() *ConnStats {
1645 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1646 pc, ok := p.peerImpl.(*PeerConn)