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"
21 "github.com/anacrolix/sync"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/internal/chansync"
25 "github.com/anacrolix/torrent/metainfo"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
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.
52 type maxRequests = int
55 // First to ensure 64-bit alignment for atomics. See #262.
65 RemoteAddr PeerRemoteAddr
66 // True if the connection is operating over MSE obfuscation.
68 cryptoMethod mse.CryptoMethod
71 closed chansync.SetOnce
72 // Set true after we've added our ConnStats generated during handshake to
73 // other ConnStat instances as determined when the *Torrent became known.
74 reconciledHandshakeStats bool
76 lastMessageReceived time.Time
77 completedHandshake time.Time
78 lastUsefulChunkReceived time.Time
79 lastChunkSent time.Time
81 // Stuff controlled by the local peer.
83 lastBecameInterested time.Time
84 priorInterest time.Duration
86 lastStartedExpectingToReceiveChunks time.Time
87 cumulativeExpectedToReceiveChunks time.Duration
88 _chunksReceivedWhileExpecting int64
91 requests map[Request]struct{}
92 piecesReceivedSinceLastRequestUpdate maxRequests
93 maxPiecesReceivedBetweenRequestUpdates maxRequests
94 // Chunks that we might reasonably expect to receive from the peer. Due to
95 // latency, buffering, and implementation differences, we may receive
96 // chunks that are no longer in the set of requests actually want.
97 validReceiveChunks map[Request]int
98 // Indexed by metadata piece, set to true if posted and pending a
100 metadataRequests []bool
101 sentHaves bitmap.Bitmap
103 // Stuff controlled by the remote peer.
106 peerRequests map[Request]*peerRequestState
107 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
109 // The pieces the peer has claimed to have.
110 _peerPieces bitmap.Bitmap
111 // The peer has everything. This can occur due to a special message, when
112 // we may not even know the number of pieces in the torrent yet.
114 // The highest possible number of pieces the torrent could have based on
115 // communication with the peer. Generally only useful until we have the
117 peerMinPieces pieceIndex
118 // Pieces we've accepted chunks for from the peer.
119 peerTouchedPieces map[pieceIndex]struct{}
120 peerAllowedFast bitmap.Bitmap
122 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
123 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
124 PeerClientName string
126 pieceInclination []int
127 _pieceRequestOrder prioritybitmap.PriorityBitmap
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 peerConnWriter
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 len(cn.requests) == 0 {
181 for r := range cn.requests {
182 if !cn.remoteChokingPiece(r.Index.Int()) {
189 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
190 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
193 // Returns true if the connection is over IPv6.
194 func (cn *PeerConn) ipv6() bool {
199 return len(ip) == net.IPv6len
202 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
203 // specification for this.
204 func (cn *PeerConn) isPreferredDirection() bool {
205 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
208 // Returns whether the left connection should be preferred over the right one,
209 // considering only their networking properties. If ok is false, we can't
211 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
213 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
214 ml.NextBool(!l.utp(), !r.utp())
215 ml.NextBool(l.ipv6(), r.ipv6())
219 func (cn *Peer) cumInterest() time.Duration {
220 ret := cn.priorInterest
222 ret += time.Since(cn.lastBecameInterested)
227 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
228 if cn.peerSentHaveAll {
231 if !cn.t.haveInfo() {
234 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
237 func (cn *PeerConn) locker() *lockWithDeferreds {
238 return cn.t.cl.locker()
241 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
242 _, ok := cn.PeerExtensionIDs[ext]
246 // The best guess at number of pieces in the torrent for this peer.
247 func (cn *Peer) bestPeerNumPieces() pieceIndex {
249 return cn.t.numPieces()
251 return cn.peerMinPieces
254 func (cn *Peer) completedString() string {
255 have := pieceIndex(cn._peerPieces.Len())
256 if cn.peerSentHaveAll {
257 have = cn.bestPeerNumPieces()
259 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
262 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
263 cn.setNumPieces(info.NumPieces())
266 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
267 // receiving badly sized BITFIELD, or invalid HAVE messages.
268 func (cn *PeerConn) setNumPieces(num pieceIndex) {
269 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
270 cn.peerPiecesChanged()
273 func eventAgeString(t time.Time) string {
277 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
280 func (cn *PeerConn) connectionFlags() (ret string) {
282 ret += string([]byte{b})
284 if cn.cryptoMethod == mse.CryptoMethodRC4 {
286 } else if cn.headerEncrypted {
289 ret += string(cn.Discovery)
296 func (cn *PeerConn) utp() bool {
297 return parseNetworkString(cn.Network).Udp
300 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
301 func (cn *Peer) statusFlags() (ret string) {
303 ret += string([]byte{b})
312 ret += cn.connectionFlags()
314 if cn.peerInterested {
323 func (cn *Peer) downloadRate() float64 {
324 num := cn._stats.BytesReadUsefulData.Int64()
328 return float64(num) / cn.totalExpectingTime().Seconds()
331 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
332 ret = make(map[pieceIndex]int)
333 for r := range cn.requests {
334 ret[pieceIndex(r.Index)]++
339 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
340 // \t isn't preserved in <pre> blocks?
341 if cn.closed.IsSet() {
342 fmt.Fprint(w, "CLOSED: ")
344 fmt.Fprintln(w, cn.connStatusString())
345 prio, err := cn.peerPriority()
346 prioStr := fmt.Sprintf("%08x", prio)
348 prioStr += ": " + err.Error()
350 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
351 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
352 eventAgeString(cn.lastMessageReceived),
353 eventAgeString(cn.completedHandshake),
354 eventAgeString(cn.lastHelpful()),
356 cn.totalExpectingTime(),
359 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
360 cn.completedString(),
361 len(cn.peerTouchedPieces),
362 &cn._stats.ChunksReadUseful,
363 &cn._stats.ChunksRead,
364 &cn._stats.ChunksWritten,
365 cn.numLocalRequests(),
366 cn.nominalMaxRequests(),
368 len(cn.peerRequests),
371 cn.downloadRate()/(1<<10),
373 fmt.Fprintf(w, " requested pieces:")
374 type pieceNumRequestsType struct {
378 var pieceNumRequests []pieceNumRequestsType
379 for piece, count := range cn.numRequestsByPiece() {
380 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
382 sort.Slice(pieceNumRequests, func(i, j int) bool {
383 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
385 for _, elem := range pieceNumRequests {
386 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
391 func (p *Peer) close() {
395 p.discardPieceInclination()
396 p._pieceRequestOrder.Clear()
399 p.t.decPeerPieceAvailability(p)
401 for _, f := range p.callbacks.PeerClosed {
406 func (cn *PeerConn) onClose() {
407 if cn.pex.IsEnabled() {
414 if cb := cn.callbacks.PeerConnClosed; cb != nil {
419 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
420 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
423 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
424 // https://github.com/pion/datachannel/issues/59 is fixed.
425 const writeBufferHighWaterLen = 1 << 15
427 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
428 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
429 func (cn *PeerConn) write(msg pp.Message) bool {
430 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
431 // We don't need to track bytes here because the connection's Writer has that behaviour injected
432 // (although there's some delay between us buffering the message, and the connection writer
433 // flushing it out.).
434 notFull := cn.messageWriter.write(msg)
435 // Last I checked only Piece messages affect stats, and we don't write those.
441 func (cn *peerConnWriter) write(msg pp.Message) bool {
444 cn.writeBuffer.Write(msg.MustMarshalBinary())
445 cn.writeCond.Broadcast()
446 return !cn.writeBufferFull()
449 func (cn *peerConnWriter) writeBufferFull() bool {
450 return cn.writeBuffer.Len() >= writeBufferHighWaterLen
453 func (cn *PeerConn) requestMetadataPiece(index int) {
454 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
458 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
461 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
465 ExtendedPayload: func() []byte {
466 b, err := bencode.Marshal(map[string]int{
467 "msg_type": pp.RequestMetadataExtensionMsgType,
476 for index >= len(cn.metadataRequests) {
477 cn.metadataRequests = append(cn.metadataRequests, false)
479 cn.metadataRequests[index] = true
482 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
483 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
486 // The actual value to use as the maximum outbound requests.
487 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
488 return int(clamp(1, 2*int64(cn.maxPiecesReceivedBetweenRequestUpdates), int64(cn.PeerMaxRequests)))
491 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
492 ret = cn.cumulativeExpectedToReceiveChunks
493 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
494 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
500 func (cn *PeerConn) onPeerSentCancel(r Request) {
501 if _, ok := cn.peerRequests[r]; !ok {
502 torrent.Add("unexpected cancels received", 1)
505 if cn.fastEnabled() {
508 delete(cn.peerRequests, r)
512 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
517 more = msg(pp.Message{
520 if cn.fastEnabled() {
521 for r := range cn.peerRequests {
522 // TODO: Don't reject pieces in allowed fast set.
526 cn.peerRequests = nil
531 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
536 return msg(pp.Message{
541 func (cn *Peer) setInterested(interested bool) bool {
542 if cn.interested == interested {
545 cn.interested = interested
547 cn.lastBecameInterested = time.Now()
548 } else if !cn.lastBecameInterested.IsZero() {
549 cn.priorInterest += time.Since(cn.lastBecameInterested)
551 cn.updateExpectingChunks()
552 // log.Printf("%p: setting interest: %v", cn, interested)
553 return cn.writeInterested(interested)
556 func (pc *PeerConn) writeInterested(interested bool) bool {
557 return pc.write(pp.Message{
558 Type: func() pp.MessageType {
562 return pp.NotInterested
568 // The function takes a message to be sent, and returns true if more messages
570 type messageWriter func(pp.Message) bool
572 func (cn *Peer) shouldRequest(r Request) error {
573 if !cn.peerHasPiece(pieceIndex(r.Index)) {
574 return errors.New("requesting piece peer doesn't have")
576 if !cn.t.peerIsActive(cn) {
577 panic("requesting but not in active conns")
579 if cn.closed.IsSet() {
580 panic("requesting when connection is closed")
582 if cn.t.hashingPiece(pieceIndex(r.Index)) {
583 panic("piece is being hashed")
585 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
586 panic("piece is queued for hash")
591 func (cn *Peer) request(r Request) error {
592 if err := cn.shouldRequest(r); err != nil {
595 if _, ok := cn.requests[r]; ok {
598 if cn.numLocalRequests() >= cn.nominalMaxRequests() {
599 return errors.New("too many outstanding requests")
601 if cn.requests == nil {
602 cn.requests = make(map[Request]struct{})
604 cn.requests[r] = struct{}{}
605 if cn.validReceiveChunks == nil {
606 cn.validReceiveChunks = make(map[Request]int)
608 cn.validReceiveChunks[r]++
609 cn.t.pendingRequests[r]++
610 cn.updateExpectingChunks()
611 for _, f := range cn.callbacks.SentRequest {
612 f(PeerRequestEvent{cn, r})
614 cn.peerImpl._request(r)
618 func (me *PeerConn) _request(r Request) {
627 func (me *Peer) cancel(r Request) {
628 if me.deleteRequest(r) {
629 me.peerImpl._cancel(r)
633 func (me *PeerConn) _cancel(r Request) {
634 me.write(makeCancelMessage(r))
637 func (cn *PeerConn) fillWriteBuffer() {
638 if cn.pex.IsEnabled() {
639 if flow := cn.pex.Share(cn.write); !flow {
646 type peerConnWriter struct {
647 // Must not be called with the local mutex held, as it will call back into the write method.
648 fillWriteBuffer func()
649 closed *chansync.SetOnce
652 keepAlive func() bool
655 writeCond chansync.BroadcastCond
656 // Pointer so we can swap with the "front buffer".
657 writeBuffer *bytes.Buffer
660 // Routine that writes to the peer. Some of what to write is buffered by
661 // activity elsewhere in the Client, and some is determined locally when the
662 // connection is writable.
663 func (cn *peerConnWriter) run(keepAliveTimeout time.Duration) {
665 lastWrite time.Time = time.Now()
666 keepAliveTimer *time.Timer
668 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
671 if time.Since(lastWrite) >= keepAliveTimeout {
672 cn.writeCond.Broadcast()
674 keepAliveTimer.Reset(keepAliveTimeout)
678 defer keepAliveTimer.Stop()
679 frontBuf := new(bytes.Buffer)
681 if cn.closed.IsSet() {
684 if cn.writeBuffer.Len() == 0 {
691 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.keepAlive() {
692 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
693 torrent.Add("written keepalives", 1)
695 if cn.writeBuffer.Len() == 0 {
696 writeCond := cn.writeCond.WaitChan()
699 case <-cn.closed.Chan():
706 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
708 n, err := cn.w.Write(frontBuf.Bytes())
711 lastWrite = time.Now()
712 keepAliveTimer.Reset(keepAliveTimeout)
715 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
718 if n != frontBuf.Len() {
725 func (cn *PeerConn) have(piece pieceIndex) {
726 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
731 Index: pp.Integer(piece),
733 cn.sentHaves.Add(bitmap.BitIndex(piece))
736 func (cn *PeerConn) postBitfield() {
737 if cn.sentHaves.Len() != 0 {
738 panic("bitfield must be first have-related message sent")
740 if !cn.t.haveAnyPieces() {
745 Bitfield: cn.t.bitfield(),
747 cn.sentHaves = cn.t._completedPieces.Copy()
750 func (cn *PeerConn) updateRequests() {
751 // log.Print("update requests")
755 // Emits the indices in the Bitmaps bms in order, never repeating any index.
756 // skip is mutated during execution, and its initial values will never be
758 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
759 return func(cb iter.Callback) {
760 for _, bm := range bms {
762 func(_i interface{}) bool {
764 if skip.Contains(bitmap.BitIndex(i)) {
767 skip.Add(bitmap.BitIndex(i))
778 // check callers updaterequests
779 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
780 return cn._pieceRequestOrder.Remove(piece)
783 // This is distinct from Torrent piece priority, which is the user's
784 // preference. Connection piece priority is specific to a connection and is
785 // used to pseudorandomly avoid connections always requesting the same pieces
786 // and thus wasting effort.
787 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
788 tpp := cn.t.piecePriority(piece)
789 if !cn.peerHasPiece(piece) {
790 tpp = PiecePriorityNone
792 if tpp == PiecePriorityNone {
793 return cn.stopRequestingPiece(piece)
795 prio := cn.getPieceInclination()[piece]
796 return cn._pieceRequestOrder.Set(piece, prio)
799 func (cn *Peer) getPieceInclination() []int {
800 if cn.pieceInclination == nil {
801 cn.pieceInclination = cn.t.getConnPieceInclination()
803 return cn.pieceInclination
806 func (cn *Peer) discardPieceInclination() {
807 if cn.pieceInclination == nil {
810 cn.t.putPieceInclination(cn.pieceInclination)
811 cn.pieceInclination = nil
814 func (cn *Peer) peerPiecesChanged() {
816 prioritiesChanged := false
817 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
818 if cn.updatePiecePriority(i) {
819 prioritiesChanged = true
822 if prioritiesChanged {
826 cn.t.maybeDropMutuallyCompletePeer(cn)
829 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
830 if newMin > cn.peerMinPieces {
831 cn.peerMinPieces = newMin
835 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
836 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
837 return errors.New("invalid piece")
839 if cn.peerHasPiece(piece) {
842 cn.raisePeerMinPieces(piece + 1)
843 if !cn.peerHasPiece(piece) {
844 cn.t.incPieceAvailability(piece)
846 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
847 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
848 if cn.updatePiecePriority(piece) {
854 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
856 panic("expected bitfield length divisible by 8")
858 // We know that the last byte means that at most the last 7 bits are wasted.
859 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
860 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
861 // Ignore known excess pieces.
862 bf = bf[:cn.t.numPieces()]
864 pp := cn.newPeerPieces()
865 cn.peerSentHaveAll = false
866 for i, have := range bf {
868 cn.raisePeerMinPieces(pieceIndex(i) + 1)
869 if !pp.Contains(bitmap.BitIndex(i)) {
870 cn.t.incPieceAvailability(i)
873 if pp.Contains(bitmap.BitIndex(i)) {
874 cn.t.decPieceAvailability(i)
877 cn._peerPieces.Set(bitmap.BitIndex(i), have)
879 cn.peerPiecesChanged()
883 func (cn *Peer) onPeerHasAllPieces() {
886 pp := cn.newPeerPieces()
887 for i := range iter.N(t.numPieces()) {
888 if !pp.Contains(bitmap.BitIndex(i)) {
889 t.incPieceAvailability(i)
893 cn.peerSentHaveAll = true
894 cn._peerPieces.Clear()
895 cn.peerPiecesChanged()
898 func (cn *PeerConn) onPeerSentHaveAll() error {
899 cn.onPeerHasAllPieces()
903 func (cn *PeerConn) peerSentHaveNone() error {
904 cn.t.decPeerPieceAvailability(&cn.Peer)
905 cn._peerPieces.Clear()
906 cn.peerSentHaveAll = false
907 cn.peerPiecesChanged()
911 func (c *PeerConn) requestPendingMetadata() {
915 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
916 // Peer doesn't support this.
919 // Request metadata pieces that we don't have in a random order.
921 for index := 0; index < c.t.metadataPieceCount(); index++ {
922 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
923 pending = append(pending, index)
926 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
927 for _, i := range pending {
928 c.requestMetadataPiece(i)
932 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
933 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
934 if msg.Type == pp.Extended {
935 for name, id := range cn.PeerExtensionIDs {
936 if id != msg.ExtendedID {
939 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
942 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
945 func (cn *PeerConn) readMsg(msg *pp.Message) {
946 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
949 // After handshake, we know what Torrent and Client stats to include for a
951 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
957 // All ConnStats that include this connection. Some objects are not known
958 // until the handshake is complete, after which it's expected to reconcile the
960 func (cn *Peer) allStats(f func(*ConnStats)) {
962 if cn.reconciledHandshakeStats {
963 cn.postHandshakeStats(f)
967 func (cn *PeerConn) wroteBytes(n int64) {
968 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
971 func (cn *PeerConn) readBytes(n int64) {
972 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
975 // Returns whether the connection could be useful to us. We're seeding and
976 // they want data, we don't have metainfo and they can provide it, etc.
977 func (c *Peer) useful() bool {
979 if c.closed.IsSet() {
983 return c.supportsExtension("ut_metadata")
985 if t.seeding() && c.peerInterested {
988 if c.peerHasWantedPieces() {
994 func (c *Peer) lastHelpful() (ret time.Time) {
995 ret = c.lastUsefulChunkReceived
996 if c.t.seeding() && c.lastChunkSent.After(ret) {
997 ret = c.lastChunkSent
1002 func (c *PeerConn) fastEnabled() bool {
1003 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
1006 func (c *PeerConn) reject(r Request) {
1007 if !c.fastEnabled() {
1008 panic("fast not enabled")
1010 c.write(r.ToMsg(pp.Reject))
1011 delete(c.peerRequests, r)
1014 func (c *PeerConn) onReadRequest(r Request) error {
1015 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1016 if _, ok := c.peerRequests[r]; ok {
1017 torrent.Add("duplicate requests received", 1)
1021 torrent.Add("requests received while choking", 1)
1022 if c.fastEnabled() {
1023 torrent.Add("requests rejected while choking", 1)
1028 // TODO: What if they've already requested this?
1029 if len(c.peerRequests) >= localClientReqq {
1030 torrent.Add("requests received while queue full", 1)
1031 if c.fastEnabled() {
1034 // BEP 6 says we may close here if we choose.
1037 if !c.t.havePiece(pieceIndex(r.Index)) {
1038 // This isn't necessarily them screwing up. We can drop pieces
1039 // from our storage, and can't communicate this to peers
1040 // except by reconnecting.
1041 requestsReceivedForMissingPieces.Add(1)
1042 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1044 // Check this after we know we have the piece, so that the piece length will be known.
1045 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1046 torrent.Add("bad requests received", 1)
1047 return errors.New("bad Request")
1049 if c.peerRequests == nil {
1050 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1052 value := &peerRequestState{}
1053 c.peerRequests[r] = value
1054 go c.peerRequestDataReader(r, value)
1059 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1060 b, err := readPeerRequestData(r, c)
1062 defer c.locker().Unlock()
1064 c.peerRequestDataReadFailed(err, r)
1067 panic("data must be non-nil to trigger send")
1074 // If this is maintained correctly, we might be able to support optional synchronous reading for
1075 // chunk sending, the way it used to work.
1076 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1077 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1078 i := pieceIndex(r.Index)
1079 if c.t.pieceComplete(i) {
1080 // There used to be more code here that just duplicated the following break. Piece
1081 // completions are currently cached, so I'm not sure how helpful this update is, except to
1082 // pull any completion changes pushed to the storage backend in failed reads that got us
1084 c.t.updatePieceCompletion(i)
1086 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1087 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1088 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1089 // next connect. TODO: Support rejecting here too.
1091 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1096 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1097 b := make([]byte, r.Length)
1098 p := c.t.info.Piece(int(r.Index))
1099 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1106 panic("expected error")
1112 func runSafeExtraneous(f func()) {
1120 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1121 // exit. Returning will end the connection.
1122 func (c *PeerConn) mainReadLoop() (err error) {
1125 torrent.Add("connection.mainReadLoop returned with error", 1)
1127 torrent.Add("connection.mainReadLoop returned with no error", 1)
1133 decoder := pp.Decoder{
1134 R: bufio.NewReaderSize(c.r, 1<<17),
1135 MaxLength: 256 * 1024,
1143 err = decoder.Decode(&msg)
1145 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1148 if t.closed.IsSet() || c.closed.IsSet() {
1155 c.lastMessageReceived = time.Now()
1157 receivedKeepalives.Add(1)
1160 messageTypesReceived.Add(msg.Type.String(), 1)
1161 if msg.Type.FastExtension() && !c.fastEnabled() {
1162 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1163 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1167 c.peerChoking = true
1168 if !c.fastEnabled() {
1169 c.deleteAllRequests()
1171 // We can then reset our interest.
1173 c.updateExpectingChunks()
1175 c.peerChoking = false
1177 c.updateExpectingChunks()
1179 c.peerInterested = true
1181 case pp.NotInterested:
1182 c.peerInterested = false
1183 // We don't clear their requests since it isn't clear in the spec.
1184 // We'll probably choke them for this, which will clear them if
1185 // appropriate, and is clearly specified.
1187 err = c.peerSentHave(pieceIndex(msg.Index))
1189 err = c.peerSentBitfield(msg.Bitfield)
1191 r := newRequestFromMessage(&msg)
1192 err = c.onReadRequest(r)
1194 err = c.receiveChunk(&msg)
1195 if len(msg.Piece) == int(t.chunkSize) {
1196 t.chunkPool.Put(&msg.Piece)
1199 err = fmt.Errorf("receiving chunk: %s", err)
1202 req := newRequestFromMessage(&msg)
1203 c.onPeerSentCancel(req)
1205 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1209 pingAddr := net.UDPAddr{
1214 pingAddr.Port = int(msg.Port)
1216 cl.eachDhtServer(func(s DhtServer) {
1217 go s.Ping(&pingAddr)
1220 torrent.Add("suggests received", 1)
1221 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1224 err = c.onPeerSentHaveAll()
1226 err = c.peerSentHaveNone()
1228 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1229 case pp.AllowedFast:
1230 torrent.Add("allowed fasts received", 1)
1231 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1232 c.peerAllowedFast.Add(bitmap.BitIndex(msg.Index))
1235 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1237 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1245 func (c *Peer) remoteRejectedRequest(r Request) {
1246 if c.deleteRequest(r) {
1247 c.decExpectedChunkReceive(r)
1251 func (c *Peer) decExpectedChunkReceive(r Request) {
1252 count := c.validReceiveChunks[r]
1254 delete(c.validReceiveChunks, r)
1255 } else if count > 1 {
1256 c.validReceiveChunks[r] = count - 1
1262 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1264 // TODO: Should we still do this?
1266 // These clients use their own extension IDs for outgoing message
1267 // types, which is incorrect.
1268 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1276 case pp.HandshakeExtendedID:
1277 var d pp.ExtendedHandshakeMessage
1278 if err := bencode.Unmarshal(payload, &d); err != nil {
1279 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1280 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1282 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1285 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1287 c.PeerMaxRequests = d.Reqq
1289 c.PeerClientName = d.V
1290 if c.PeerExtensionIDs == nil {
1291 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1293 c.PeerListenPort = d.Port
1294 c.PeerPrefersEncryption = d.Encryption
1295 for name, id := range d.M {
1296 if _, ok := c.PeerExtensionIDs[name]; !ok {
1297 peersSupportingExtension.Add(string(name), 1)
1299 c.PeerExtensionIDs[name] = id
1301 if d.MetadataSize != 0 {
1302 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1303 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1306 c.requestPendingMetadata()
1307 if !t.cl.config.DisablePEX {
1308 t.pex.Add(c) // we learnt enough now
1312 case metadataExtendedId:
1313 err := cl.gotMetadataExtensionMsg(payload, t, c)
1315 return fmt.Errorf("handling metadata extension message: %w", err)
1319 if !c.pex.IsEnabled() {
1320 return nil // or hang-up maybe?
1322 return c.pex.Recv(payload)
1324 return fmt.Errorf("unexpected extended message ID: %v", id)
1328 // Set both the Reader and Writer for the connection from a single ReadWriter.
1329 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1334 // Returns the Reader and Writer as a combined ReadWriter.
1335 func (cn *PeerConn) rw() io.ReadWriter {
1342 // Handle a received chunk from a peer.
1343 func (c *Peer) receiveChunk(msg *pp.Message) error {
1346 chunksReceived.Add("total", 1)
1348 req := newRequestFromMessage(msg)
1351 chunksReceived.Add("while choked", 1)
1354 if c.validReceiveChunks[req] <= 0 {
1355 chunksReceived.Add("unexpected", 1)
1356 return errors.New("received unexpected chunk")
1358 c.decExpectedChunkReceive(req)
1360 if c.peerChoking && c.peerAllowedFast.Get(bitmap.BitIndex(req.Index)) {
1361 chunksReceived.Add("due to allowed fast", 1)
1364 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1365 // have actually already received the piece, while we have the Client unlocked to write the data
1367 deletedRequest := false
1369 if _, ok := c.requests[req]; ok {
1370 for _, f := range c.callbacks.ReceivedRequested {
1371 f(PeerMessageEvent{c, msg})
1374 // Request has been satisfied.
1375 if c.deleteRequest(req) {
1376 deletedRequest = true
1378 c._chunksReceivedWhileExpecting++
1381 chunksReceived.Add("unwanted", 1)
1385 // Do we actually want this chunk?
1386 if t.haveChunk(req) {
1387 chunksReceived.Add("wasted", 1)
1388 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1392 piece := &t.pieces[req.Index]
1394 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1395 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1397 c.piecesReceivedSinceLastRequestUpdate++
1398 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1400 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1401 f(ReceivedUsefulDataEvent{c, msg})
1403 c.lastUsefulChunkReceived = time.Now()
1405 // Need to record that it hasn't been written yet, before we attempt to do
1406 // anything with it.
1407 piece.incrementPendingWrites()
1408 // Record that we have the chunk, so we aren't trying to download it while
1409 // waiting for it to be written to storage.
1410 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1412 // Cancel pending requests for this chunk from *other* peers.
1413 t.iterPeers(func(p *Peer) {
1420 err := func() error {
1423 concurrentChunkWrites.Add(1)
1424 defer concurrentChunkWrites.Add(-1)
1425 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1426 // number of connections. We write inline with receiving the chunk (with this lock dance),
1427 // because we want to handle errors synchronously and I haven't thought of a nice way to
1428 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1430 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1433 piece.decrementPendingWrites()
1436 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1438 //t.updatePieceCompletion(pieceIndex(msg.Index))
1439 t.onWriteChunkErr(err)
1443 c.onDirtiedPiece(pieceIndex(req.Index))
1445 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1446 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1447 t.queuePieceCheck(pieceIndex(req.Index))
1448 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1449 // chunk status (such as the haveChunk call above) to have to check all the various other
1450 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1451 // that chunk pieces are pended at an appropriate time later however.
1454 cl.event.Broadcast()
1455 // We do this because we've written a chunk, and may change PieceState.Partial.
1456 t.publishPieceChange(pieceIndex(req.Index))
1461 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1462 if c.peerTouchedPieces == nil {
1463 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1465 c.peerTouchedPieces[piece] = struct{}{}
1466 ds := &c.t.pieces[piece].dirtiers
1468 *ds = make(map[*Peer]struct{})
1470 (*ds)[c] = struct{}{}
1473 func (c *PeerConn) uploadAllowed() bool {
1474 if c.t.cl.config.NoUpload {
1477 if c.t.dataUploadDisallowed {
1483 if !c.peerHasWantedPieces() {
1486 // Don't upload more than 100 KiB more than we download.
1487 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1493 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1494 if c.uploadTimer == nil {
1495 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1497 c.uploadTimer.Reset(delay)
1501 // Also handles choking and unchoking of the remote peer.
1502 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1503 // Breaking or completing this loop means we don't want to upload to the
1504 // peer anymore, and we choke them.
1506 for c.uploadAllowed() {
1507 // We want to upload to the peer.
1508 if !c.unchoke(msg) {
1511 for r, state := range c.peerRequests {
1512 if state.data == nil {
1515 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1517 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1519 delay := res.Delay()
1522 c.setRetryUploadTimer(delay)
1523 // Hard to say what to return here.
1526 more := c.sendChunk(r, msg, state)
1527 delete(c.peerRequests, r)
1538 func (cn *PeerConn) drop() {
1539 cn.t.dropConnection(cn)
1542 func (cn *Peer) netGoodPiecesDirtied() int64 {
1543 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1546 func (c *Peer) peerHasWantedPieces() bool {
1547 return !c._pieceRequestOrder.IsEmpty()
1550 func (c *Peer) numLocalRequests() int {
1551 return len(c.requests)
1554 func (c *Peer) deleteRequest(r Request) bool {
1555 if _, ok := c.requests[r]; !ok {
1558 delete(c.requests, r)
1559 for _, f := range c.callbacks.DeletedRequest {
1560 f(PeerRequestEvent{c, r})
1562 c.updateExpectingChunks()
1563 pr := c.t.pendingRequests
1575 func (c *Peer) deleteAllRequests() {
1576 for r := range c.requests {
1579 if len(c.requests) != 0 {
1580 panic(len(c.requests))
1582 // for c := range c.t.conns {
1587 // This is called when something has changed that should wake the writer, such as putting stuff into
1588 // the writeBuffer, or changing some state that the writer can act on.
1589 func (c *PeerConn) tickleWriter() {
1590 c.messageWriter.writeCond.Broadcast()
1593 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1594 c.lastChunkSent = time.Now()
1595 return msg(pp.Message{
1603 func (c *PeerConn) setTorrent(t *Torrent) {
1605 panic("connection already associated with a torrent")
1608 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1609 t.reconcileHandshakeStats(c)
1612 func (c *Peer) peerPriority() (peerPriority, error) {
1613 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1616 func (c *Peer) remoteIp() net.IP {
1617 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1618 return net.ParseIP(host)
1621 func (c *Peer) remoteIpPort() IpPort {
1622 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1623 return IpPort{ipa.IP, uint16(ipa.Port)}
1626 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1627 f := pp.PexPeerFlags(0)
1628 if c.PeerPrefersEncryption {
1629 f |= pp.PexPrefersEncryption
1632 f |= pp.PexOutgoingConn
1635 f |= pp.PexSupportsUtp
1640 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1641 // advertised listen port.
1642 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1643 if !c.outgoing && c.PeerListenPort != 0 {
1644 switch addr := c.RemoteAddr.(type) {
1647 dialAddr.Port = c.PeerListenPort
1651 dialAddr.Port = c.PeerListenPort
1658 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1659 f := c.pexPeerFlags()
1660 addr := c.dialAddr()
1661 return pexEvent{t, addr, f}
1664 func (c *PeerConn) String() string {
1665 return fmt.Sprintf("connection %p", c)
1668 func (c *Peer) trust() connectionTrust {
1669 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1672 type connectionTrust struct {
1674 NetGoodPiecesDirted int64
1677 func (l connectionTrust) Less(r connectionTrust) bool {
1678 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1681 func (cn *Peer) peerMaxRequests() int {
1682 return cn.PeerMaxRequests
1685 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1686 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1687 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1689 defer cn.locker().RUnlock()
1690 return cn.newPeerPieces()
1693 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1694 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1695 ret := cn._peerPieces.Copy()
1696 if cn.peerSentHaveAll {
1697 if cn.t.haveInfo() {
1698 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1700 ret.AddRange(0, bitmap.ToEnd)
1706 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1707 return &cn._pieceRequestOrder
1710 func (cn *Peer) stats() *ConnStats {
1714 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1715 pc, ok := p.peerImpl.(*PeerConn)