15 "github.com/anacrolix/log"
16 "github.com/anacrolix/missinggo"
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/pkg/errors"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/mse"
25 pp "github.com/anacrolix/torrent/peer_protocol"
28 type PeerSource string
31 PeerSourceTracker = "Tr"
32 PeerSourceIncoming = "I"
33 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
34 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
38 // Maintains the state of a connection with a peer.
39 type PeerConn struct {
40 // First to ensure 64-bit alignment for atomics. See #262.
44 // The actual Conn, used for closing, and setting socket options.
50 // The Reader and Writer for this Conn, with hooks installed for stats,
51 // limiting, deadlines etc.
54 // True if the connection is operating over MSE obfuscation.
56 cryptoMethod mse.CryptoMethod
59 closed missinggo.Event
60 // Set true after we've added our ConnStats generated during handshake to
61 // other ConnStat instances as determined when the *Torrent became known.
62 reconciledHandshakeStats bool
64 lastMessageReceived time.Time
65 completedHandshake time.Time
66 lastUsefulChunkReceived time.Time
67 lastChunkSent time.Time
69 // Stuff controlled by the local peer.
71 lastBecameInterested time.Time
72 priorInterest time.Duration
74 lastStartedExpectingToReceiveChunks time.Time
75 cumulativeExpectedToReceiveChunks time.Duration
76 _chunksReceivedWhileExpecting int64
79 requests map[request]struct{}
81 // Chunks that we might reasonably expect to receive from the peer. Due to
82 // latency, buffering, and implementation differences, we may receive
83 // chunks that are no longer in the set of requests actually want.
84 validReceiveChunks map[request]struct{}
85 // Indexed by metadata piece, set to true if posted and pending a
87 metadataRequests []bool
88 sentHaves bitmap.Bitmap
91 // Stuff controlled by the remote peer.
95 peerRequests map[request]struct{}
96 PeerExtensionBytes pp.PeerExtensionBits
97 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
99 // The pieces the peer has claimed to have.
100 _peerPieces bitmap.Bitmap
101 // The peer has everything. This can occur due to a special message, when
102 // we may not even know the number of pieces in the torrent yet.
104 // The highest possible number of pieces the torrent could have based on
105 // communication with the peer. Generally only useful until we have the
107 peerMinPieces pieceIndex
108 // Pieces we've accepted chunks for from the peer.
109 peerTouchedPieces map[pieceIndex]struct{}
110 peerAllowedFast bitmap.Bitmap
112 PeerMaxRequests int // Maximum pending requests the peer allows.
113 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
114 PeerClientName string
116 pieceInclination []int
117 _pieceRequestOrder prioritybitmap.PriorityBitmap
119 writeBuffer *bytes.Buffer
120 uploadTimer *time.Timer
126 func (cn *PeerConn) updateExpectingChunks() {
127 if cn.expectingChunks() {
128 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
129 cn.lastStartedExpectingToReceiveChunks = time.Now()
132 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
133 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
134 cn.lastStartedExpectingToReceiveChunks = time.Time{}
139 func (cn *PeerConn) expectingChunks() bool {
140 return cn.interested && !cn.peerChoking
143 // Returns true if the connection is over IPv6.
144 func (cn *PeerConn) ipv6() bool {
145 ip := addrIpOrNil(cn.remoteAddr)
149 return len(ip) == net.IPv6len
152 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
153 // specification for this.
154 func (cn *PeerConn) isPreferredDirection() bool {
155 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
158 // Returns whether the left connection should be preferred over the right one,
159 // considering only their networking properties. If ok is false, we can't
161 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
163 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
164 ml.NextBool(!l.utp(), !r.utp())
165 ml.NextBool(l.ipv6(), r.ipv6())
169 func (cn *PeerConn) cumInterest() time.Duration {
170 ret := cn.priorInterest
172 ret += time.Since(cn.lastBecameInterested)
177 func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
178 if cn.peerSentHaveAll {
181 if !cn.t.haveInfo() {
184 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
187 func (cn *PeerConn) locker() *lockWithDeferreds {
188 return cn.t.cl.locker()
191 func (cn *PeerConn) localAddr() net.Addr {
192 return cn.conn.LocalAddr()
195 func (cn *PeerConn) supportsExtension(ext pp.ExtensionName) bool {
196 _, ok := cn.PeerExtensionIDs[ext]
200 // The best guess at number of pieces in the torrent for this peer.
201 func (cn *PeerConn) bestPeerNumPieces() pieceIndex {
203 return cn.t.numPieces()
205 return cn.peerMinPieces
208 func (cn *PeerConn) completedString() string {
209 have := pieceIndex(cn._peerPieces.Len())
210 if cn.peerSentHaveAll {
211 have = cn.bestPeerNumPieces()
213 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
216 // Correct the PeerPieces slice length. Return false if the existing slice is
217 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
219 func (cn *PeerConn) setNumPieces(num pieceIndex) error {
220 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
221 cn.peerPiecesChanged()
225 func eventAgeString(t time.Time) string {
229 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
232 func (cn *PeerConn) connectionFlags() (ret string) {
234 ret += string([]byte{b})
236 if cn.cryptoMethod == mse.CryptoMethodRC4 {
238 } else if cn.headerEncrypted {
241 ret += string(cn.Discovery)
248 func (cn *PeerConn) utp() bool {
249 return parseNetworkString(cn.network).Udp
252 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
253 func (cn *PeerConn) statusFlags() (ret string) {
255 ret += string([]byte{b})
264 ret += cn.connectionFlags()
266 if cn.peerInterested {
275 // func (cn *connection) String() string {
276 // var buf bytes.Buffer
277 // cn.writeStatus(&buf, nil)
278 // return buf.String()
281 func (cn *PeerConn) downloadRate() float64 {
282 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
285 func (cn *PeerConn) writeStatus(w io.Writer, t *Torrent) {
286 // \t isn't preserved in <pre> blocks?
287 fmt.Fprintf(w, "%+-55q %s %s\n", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
288 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
289 eventAgeString(cn.lastMessageReceived),
290 eventAgeString(cn.completedHandshake),
291 eventAgeString(cn.lastHelpful()),
293 cn.totalExpectingTime(),
296 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
297 cn.completedString(),
298 len(cn.peerTouchedPieces),
299 &cn._stats.ChunksReadUseful,
300 &cn._stats.ChunksRead,
301 &cn._stats.ChunksWritten,
303 cn.numLocalRequests(),
304 cn.nominalMaxRequests(),
305 len(cn.peerRequests),
307 cn.downloadRate()/(1<<10),
309 fmt.Fprintf(w, " next pieces: %v%s\n",
310 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
312 if cn == t.fastestConn {
321 func (cn *PeerConn) close() {
322 if !cn.closed.Set() {
325 if cn.pex.IsEnabled() {
329 cn.discardPieceInclination()
330 cn._pieceRequestOrder.Clear()
336 func (cn *PeerConn) peerHasPiece(piece pieceIndex) bool {
337 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
340 // Writes a message into the write buffer.
341 func (cn *PeerConn) post(msg pp.Message) {
342 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
343 // We don't need to track bytes here because a connection.w Writer wrapper
344 // takes care of that (although there's some delay between us recording
345 // the message, and the connection writer flushing it out.).
346 cn.writeBuffer.Write(msg.MustMarshalBinary())
347 // Last I checked only Piece messages affect stats, and we don't post
353 func (cn *PeerConn) requestMetadataPiece(index int) {
354 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
358 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
361 cn.logger.Printf("requesting metadata piece %d", index)
365 ExtendedPayload: func() []byte {
366 b, err := bencode.Marshal(map[string]int{
367 "msg_type": pp.RequestMetadataExtensionMsgType,
376 for index >= len(cn.metadataRequests) {
377 cn.metadataRequests = append(cn.metadataRequests, false)
379 cn.metadataRequests[index] = true
382 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
383 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
386 // The actual value to use as the maximum outbound requests.
387 func (cn *PeerConn) nominalMaxRequests() (ret int) {
390 int64(cn.PeerMaxRequests),
391 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
395 func (cn *PeerConn) totalExpectingTime() (ret time.Duration) {
396 ret = cn.cumulativeExpectedToReceiveChunks
397 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
398 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
404 func (cn *PeerConn) onPeerSentCancel(r request) {
405 if _, ok := cn.peerRequests[r]; !ok {
406 torrent.Add("unexpected cancels received", 1)
409 if cn.fastEnabled() {
412 delete(cn.peerRequests, r)
416 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
421 more = msg(pp.Message{
424 if cn.fastEnabled() {
425 for r := range cn.peerRequests {
426 // TODO: Don't reject pieces in allowed fast set.
430 cn.peerRequests = nil
435 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
440 return msg(pp.Message{
445 func (cn *PeerConn) setInterested(interested bool, msg func(pp.Message) bool) bool {
446 if cn.interested == interested {
449 cn.interested = interested
451 cn.lastBecameInterested = time.Now()
452 } else if !cn.lastBecameInterested.IsZero() {
453 cn.priorInterest += time.Since(cn.lastBecameInterested)
455 cn.updateExpectingChunks()
456 // log.Printf("%p: setting interest: %v", cn, interested)
457 return msg(pp.Message{
458 Type: func() pp.MessageType {
462 return pp.NotInterested
468 // The function takes a message to be sent, and returns true if more messages
470 type messageWriter func(pp.Message) bool
472 // Proxies the messageWriter's response.
473 func (cn *PeerConn) request(r request, mw messageWriter) bool {
474 if _, ok := cn.requests[r]; ok {
475 panic("chunk already requested")
477 if !cn.peerHasPiece(pieceIndex(r.Index)) {
478 panic("requesting piece peer doesn't have")
480 if _, ok := cn.t.conns[cn]; !ok {
481 panic("requesting but not in active conns")
483 if cn.closed.IsSet() {
484 panic("requesting when connection is closed")
487 if cn.peerAllowedFast.Get(int(r.Index)) {
488 torrent.Add("allowed fast requests sent", 1)
490 panic("requesting while choking and not allowed fast")
493 if cn.t.hashingPiece(pieceIndex(r.Index)) {
494 panic("piece is being hashed")
496 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
497 panic("piece is queued for hash")
499 if cn.requests == nil {
500 cn.requests = make(map[request]struct{})
502 cn.requests[r] = struct{}{}
503 if cn.validReceiveChunks == nil {
504 cn.validReceiveChunks = make(map[request]struct{})
506 cn.validReceiveChunks[r] = struct{}{}
507 cn.t.pendingRequests[r]++
508 cn.t.requestStrategy.hooks().sentRequest(r)
509 cn.updateExpectingChunks()
510 return mw(pp.Message{
518 func (cn *PeerConn) fillWriteBuffer(msg func(pp.Message) bool) {
519 if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
520 if !cn.setInterested(false, msg) {
523 if len(cn.requests) != 0 {
524 for r := range cn.requests {
526 // log.Printf("%p: cancelling request: %v", cn, r)
527 if !msg(makeCancelMessage(r)) {
532 } else if len(cn.requests) <= cn.requestsLowWater {
533 filledBuffer := false
534 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
535 cn.iterPendingRequests(pieceIndex, func(r request) bool {
536 if !cn.setInterested(true, msg) {
540 if len(cn.requests) >= cn.nominalMaxRequests() {
543 // Choking is looked at here because our interest is dependent
544 // on whether we'd make requests in its absence.
546 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
550 if _, ok := cn.requests[r]; ok {
553 filledBuffer = !cn.request(r, msg)
559 // If we didn't completely top up the requests, we shouldn't mark
560 // the low water, since we'll want to top up the requests as soon
561 // as we have more write buffer space.
564 cn.requestsLowWater = len(cn.requests) / 2
566 if cn.pex.IsEnabled() {
567 if flow := cn.pex.Share(msg); !flow {
574 // Routine that writes to the peer. Some of what to write is buffered by
575 // activity elsewhere in the Client, and some is determined locally when the
576 // connection is writable.
577 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
579 lastWrite time.Time = time.Now()
580 keepAliveTimer *time.Timer
582 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
584 defer cn.locker().Unlock()
585 if time.Since(lastWrite) >= keepAliveTimeout {
588 keepAliveTimer.Reset(keepAliveTimeout)
591 defer cn.locker().Unlock()
593 defer keepAliveTimer.Stop()
594 frontBuf := new(bytes.Buffer)
596 if cn.closed.IsSet() {
599 if cn.writeBuffer.Len() == 0 {
600 cn.fillWriteBuffer(func(msg pp.Message) bool {
602 cn.writeBuffer.Write(msg.MustMarshalBinary())
603 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
604 return cn.writeBuffer.Len() < 1<<16 // 64KiB
607 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
608 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
609 postedKeepalives.Add(1)
611 if cn.writeBuffer.Len() == 0 {
612 // TODO: Minimize wakeups....
617 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
619 n, err := cn.w.Write(frontBuf.Bytes())
622 lastWrite = time.Now()
623 keepAliveTimer.Reset(keepAliveTimeout)
628 if n != frontBuf.Len() {
635 func (cn *PeerConn) have(piece pieceIndex) {
636 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
641 Index: pp.Integer(piece),
643 cn.sentHaves.Add(bitmap.BitIndex(piece))
646 func (cn *PeerConn) postBitfield() {
647 if cn.sentHaves.Len() != 0 {
648 panic("bitfield must be first have-related message sent")
650 if !cn.t.haveAnyPieces() {
655 Bitfield: cn.t.bitfield(),
657 cn.sentHaves = cn.t._completedPieces.Copy()
660 func (cn *PeerConn) updateRequests() {
661 // log.Print("update requests")
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 {
676 bitmap.Sub(bm, *skip).Iter,
684 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
685 now, readahead := cn.torrent().readerPiecePriorities()
686 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
687 skip.Union(cn.torrent().ignorePieces())
688 // Return an iterator over the different priority classes, minus the skip pieces.
690 func(_piece interface{}) bool {
691 return f(pieceIndex(_piece.(bitmap.BitIndex)))
693 iterBitmapsDistinct(&skip, now, readahead),
694 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
695 func(cb iter.Callback) {
696 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
697 if skip.Contains(piece) {
708 // The connection should download highest priority pieces first, without any inclination toward
709 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
710 // fastest connection, and we have active readers that signal an ordering preference. It's
711 // conceivable that the best connection should do this, since it's least likely to waste our time if
712 // assigned to the highest priority pieces, and assigning more than one this role would cause
713 // significant wasted bandwidth.
714 func (cn *PeerConn) shouldRequestWithoutBias() bool {
715 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
718 func (cn *PeerConn) iterPendingPieces(f func(pieceIndex) bool) bool {
719 if !cn.t.haveInfo() {
722 return cn.t.requestStrategy.iterPendingPieces(cn, f)
724 func (cn *PeerConn) iterPendingPiecesUntyped(f iter.Callback) {
725 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
728 func (cn *PeerConn) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
729 return cn.t.requestStrategy.iterUndirtiedChunks(
730 cn.t.piece(piece).requestStrategyPiece(),
731 func(cs chunkSpec) bool {
732 return f(request{pp.Integer(piece), cs})
737 // check callers updaterequests
738 func (cn *PeerConn) stopRequestingPiece(piece pieceIndex) bool {
739 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
742 // This is distinct from Torrent piece priority, which is the user's
743 // preference. Connection piece priority is specific to a connection and is
744 // used to pseudorandomly avoid connections always requesting the same pieces
745 // and thus wasting effort.
746 func (cn *PeerConn) updatePiecePriority(piece pieceIndex) bool {
747 tpp := cn.t.piecePriority(piece)
748 if !cn.peerHasPiece(piece) {
749 tpp = PiecePriorityNone
751 if tpp == PiecePriorityNone {
752 return cn.stopRequestingPiece(piece)
754 prio := cn.getPieceInclination()[piece]
755 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
756 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
759 func (cn *PeerConn) getPieceInclination() []int {
760 if cn.pieceInclination == nil {
761 cn.pieceInclination = cn.t.getConnPieceInclination()
763 return cn.pieceInclination
766 func (cn *PeerConn) discardPieceInclination() {
767 if cn.pieceInclination == nil {
770 cn.t.putPieceInclination(cn.pieceInclination)
771 cn.pieceInclination = nil
774 func (cn *PeerConn) peerPiecesChanged() {
776 prioritiesChanged := false
777 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
778 if cn.updatePiecePriority(i) {
779 prioritiesChanged = true
782 if prioritiesChanged {
788 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
789 if newMin > cn.peerMinPieces {
790 cn.peerMinPieces = newMin
794 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
795 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
796 return errors.New("invalid piece")
798 if cn.peerHasPiece(piece) {
801 cn.raisePeerMinPieces(piece + 1)
802 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
803 if cn.updatePiecePriority(piece) {
809 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
810 cn.peerSentHaveAll = false
812 panic("expected bitfield length divisible by 8")
814 // We know that the last byte means that at most the last 7 bits are
816 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
817 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
818 // Ignore known excess pieces.
819 bf = bf[:cn.t.numPieces()]
821 for i, have := range bf {
823 cn.raisePeerMinPieces(pieceIndex(i) + 1)
825 cn._peerPieces.Set(i, have)
827 cn.peerPiecesChanged()
831 func (cn *PeerConn) onPeerSentHaveAll() error {
832 cn.peerSentHaveAll = true
833 cn._peerPieces.Clear()
834 cn.peerPiecesChanged()
838 func (cn *PeerConn) peerSentHaveNone() error {
839 cn._peerPieces.Clear()
840 cn.peerSentHaveAll = false
841 cn.peerPiecesChanged()
845 func (c *PeerConn) requestPendingMetadata() {
849 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
850 // Peer doesn't support this.
853 // Request metadata pieces that we don't have in a random order.
855 for index := 0; index < c.t.metadataPieceCount(); index++ {
856 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
857 pending = append(pending, index)
860 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
861 for _, i := range pending {
862 c.requestMetadataPiece(i)
866 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
867 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
868 if msg.Type == pp.Extended {
869 for name, id := range cn.PeerExtensionIDs {
870 if id != msg.ExtendedID {
873 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
876 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
879 func (cn *PeerConn) readMsg(msg *pp.Message) {
880 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
883 // After handshake, we know what Torrent and Client stats to include for a
885 func (cn *PeerConn) postHandshakeStats(f func(*ConnStats)) {
891 // All ConnStats that include this connection. Some objects are not known
892 // until the handshake is complete, after which it's expected to reconcile the
894 func (cn *PeerConn) allStats(f func(*ConnStats)) {
896 if cn.reconciledHandshakeStats {
897 cn.postHandshakeStats(f)
901 func (cn *PeerConn) wroteBytes(n int64) {
902 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
905 func (cn *PeerConn) readBytes(n int64) {
906 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
909 // Returns whether the connection could be useful to us. We're seeding and
910 // they want data, we don't have metainfo and they can provide it, etc.
911 func (c *PeerConn) useful() bool {
913 if c.closed.IsSet() {
917 return c.supportsExtension("ut_metadata")
919 if t.seeding() && c.peerInterested {
922 if c.peerHasWantedPieces() {
928 func (c *PeerConn) lastHelpful() (ret time.Time) {
929 ret = c.lastUsefulChunkReceived
930 if c.t.seeding() && c.lastChunkSent.After(ret) {
931 ret = c.lastChunkSent
936 func (c *PeerConn) fastEnabled() bool {
937 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
940 func (c *PeerConn) reject(r request) {
941 if !c.fastEnabled() {
942 panic("fast not enabled")
944 c.post(r.ToMsg(pp.Reject))
945 delete(c.peerRequests, r)
948 func (c *PeerConn) onReadRequest(r request) error {
949 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
950 if _, ok := c.peerRequests[r]; ok {
951 torrent.Add("duplicate requests received", 1)
955 torrent.Add("requests received while choking", 1)
957 torrent.Add("requests rejected while choking", 1)
962 if len(c.peerRequests) >= maxRequests {
963 torrent.Add("requests received while queue full", 1)
967 // BEP 6 says we may close here if we choose.
970 if !c.t.havePiece(pieceIndex(r.Index)) {
971 // This isn't necessarily them screwing up. We can drop pieces
972 // from our storage, and can't communicate this to peers
973 // except by reconnecting.
974 requestsReceivedForMissingPieces.Add(1)
975 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
977 // Check this after we know we have the piece, so that the piece length will be known.
978 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
979 torrent.Add("bad requests received", 1)
980 return errors.New("bad request")
982 if c.peerRequests == nil {
983 c.peerRequests = make(map[request]struct{}, maxRequests)
985 c.peerRequests[r] = struct{}{}
990 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
991 // exit. Returning will end the connection.
992 func (c *PeerConn) mainReadLoop() (err error) {
995 torrent.Add("connection.mainReadLoop returned with error", 1)
997 torrent.Add("connection.mainReadLoop returned with no error", 1)
1003 decoder := pp.Decoder{
1004 R: bufio.NewReaderSize(c.r, 1<<17),
1005 MaxLength: 256 * 1024,
1013 err = decoder.Decode(&msg)
1015 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1022 c.lastMessageReceived = time.Now()
1024 receivedKeepalives.Add(1)
1027 messageTypesReceived.Add(msg.Type.String(), 1)
1028 if msg.Type.FastExtension() && !c.fastEnabled() {
1029 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1033 c.peerChoking = true
1034 c.deleteAllRequests()
1035 // We can then reset our interest.
1037 c.updateExpectingChunks()
1039 c.peerChoking = false
1041 c.updateExpectingChunks()
1043 c.peerInterested = true
1045 case pp.NotInterested:
1046 c.peerInterested = false
1047 // We don't clear their requests since it isn't clear in the spec.
1048 // We'll probably choke them for this, which will clear them if
1049 // appropriate, and is clearly specified.
1051 err = c.peerSentHave(pieceIndex(msg.Index))
1053 err = c.peerSentBitfield(msg.Bitfield)
1055 r := newRequestFromMessage(&msg)
1056 err = c.onReadRequest(r)
1058 err = c.receiveChunk(&msg)
1059 if len(msg.Piece) == int(t.chunkSize) {
1060 t.chunkPool.Put(&msg.Piece)
1063 err = fmt.Errorf("receiving chunk: %s", err)
1066 req := newRequestFromMessage(&msg)
1067 c.onPeerSentCancel(req)
1069 ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1073 pingAddr := net.UDPAddr{
1078 pingAddr.Port = int(msg.Port)
1080 cl.eachDhtServer(func(s DhtServer) {
1081 go s.Ping(&pingAddr)
1084 torrent.Add("suggests received", 1)
1085 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1088 err = c.onPeerSentHaveAll()
1090 err = c.peerSentHaveNone()
1092 c.deleteRequest(newRequestFromMessage(&msg))
1093 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1094 case pp.AllowedFast:
1095 torrent.Add("allowed fasts received", 1)
1096 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1097 c.peerAllowedFast.Add(int(msg.Index))
1100 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1102 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1110 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1112 // TODO: Should we still do this?
1114 // These clients use their own extension IDs for outgoing message
1115 // types, which is incorrect.
1116 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1124 case pp.HandshakeExtendedID:
1125 var d pp.ExtendedHandshakeMessage
1126 if err := bencode.Unmarshal(payload, &d); err != nil {
1127 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1128 return errors.Wrap(err, "unmarshalling extended handshake payload")
1131 c.PeerMaxRequests = d.Reqq
1133 c.PeerClientName = d.V
1134 if c.PeerExtensionIDs == nil {
1135 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1137 c.PeerListenPort = d.Port
1138 c.PeerPrefersEncryption = d.Encryption
1139 for name, id := range d.M {
1140 if _, ok := c.PeerExtensionIDs[name]; !ok {
1141 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1143 c.PeerExtensionIDs[name] = id
1145 if d.MetadataSize != 0 {
1146 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1147 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1150 c.requestPendingMetadata()
1151 if !t.cl.config.DisablePEX {
1152 t.pex.Add(c) // we learnt enough now
1156 case metadataExtendedId:
1157 err := cl.gotMetadataExtensionMsg(payload, t, c)
1159 return fmt.Errorf("handling metadata extension message: %w", err)
1163 if !c.pex.IsEnabled() {
1164 return nil // or hang-up maybe?
1166 return c.pex.Recv(payload)
1168 return fmt.Errorf("unexpected extended message ID: %v", id)
1172 // Set both the Reader and Writer for the connection from a single ReadWriter.
1173 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1178 // Returns the Reader and Writer as a combined ReadWriter.
1179 func (cn *PeerConn) rw() io.ReadWriter {
1186 // Handle a received chunk from a peer.
1187 func (c *PeerConn) receiveChunk(msg *pp.Message) error {
1190 torrent.Add("chunks received", 1)
1192 req := newRequestFromMessage(msg)
1195 torrent.Add("chunks received while choking", 1)
1198 if _, ok := c.validReceiveChunks[req]; !ok {
1199 torrent.Add("chunks received unexpected", 1)
1200 return errors.New("received unexpected chunk")
1202 delete(c.validReceiveChunks, req)
1204 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1205 torrent.Add("chunks received due to allowed fast", 1)
1208 // Request has been satisfied.
1209 if c.deleteRequest(req) {
1210 if c.expectingChunks() {
1211 c._chunksReceivedWhileExpecting++
1214 torrent.Add("chunks received unwanted", 1)
1217 // Do we actually want this chunk?
1218 if t.haveChunk(req) {
1219 torrent.Add("chunks received wasted", 1)
1220 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1224 piece := &t.pieces[req.Index]
1226 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1227 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1228 c.lastUsefulChunkReceived = time.Now()
1229 // if t.fastestConn != c {
1230 // log.Printf("setting fastest connection %p", c)
1234 // Need to record that it hasn't been written yet, before we attempt to do
1235 // anything with it.
1236 piece.incrementPendingWrites()
1237 // Record that we have the chunk, so we aren't trying to download it while
1238 // waiting for it to be written to storage.
1239 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1241 // Cancel pending requests for this chunk.
1242 for c := range t.conns {
1246 err := func() error {
1249 concurrentChunkWrites.Add(1)
1250 defer concurrentChunkWrites.Add(-1)
1251 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1252 // number of connections. We write inline with receiving the chunk (with this lock dance),
1253 // because we want to handle errors synchronously and I haven't thought of a nice way to
1254 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1256 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1259 piece.decrementPendingWrites()
1262 c.logger.Printf("error writing received chunk %v: %v", req, err)
1264 //t.updatePieceCompletion(pieceIndex(msg.Index))
1265 t.onWriteChunkErr(err)
1269 c.onDirtiedPiece(pieceIndex(req.Index))
1271 if t.pieceAllDirty(pieceIndex(req.Index)) {
1272 t.queuePieceCheck(pieceIndex(req.Index))
1273 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1274 // chunk status (such as the haveChunk call above) to have to check all the various other
1275 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1276 // that chunk pieces are pended at an appropriate time later however.
1279 cl.event.Broadcast()
1280 // We do this because we've written a chunk, and may change PieceState.Partial.
1281 t.publishPieceChange(pieceIndex(req.Index))
1286 func (c *PeerConn) onDirtiedPiece(piece pieceIndex) {
1287 if c.peerTouchedPieces == nil {
1288 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1290 c.peerTouchedPieces[piece] = struct{}{}
1291 ds := &c.t.pieces[piece].dirtiers
1293 *ds = make(map[*PeerConn]struct{})
1295 (*ds)[c] = struct{}{}
1298 func (c *PeerConn) uploadAllowed() bool {
1299 if c.t.cl.config.NoUpload {
1305 if !c.peerHasWantedPieces() {
1308 // Don't upload more than 100 KiB more than we download.
1309 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1315 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1316 if c.uploadTimer == nil {
1317 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1319 c.uploadTimer.Reset(delay)
1323 // Also handles choking and unchoking of the remote peer.
1324 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1325 // Breaking or completing this loop means we don't want to upload to the
1326 // peer anymore, and we choke them.
1328 for c.uploadAllowed() {
1329 // We want to upload to the peer.
1330 if !c.unchoke(msg) {
1333 for r := range c.peerRequests {
1334 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1336 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1338 delay := res.Delay()
1341 c.setRetryUploadTimer(delay)
1342 // Hard to say what to return here.
1345 more, err := c.sendChunk(r, msg)
1347 i := pieceIndex(r.Index)
1348 if c.t.pieceComplete(i) {
1349 c.t.updatePieceCompletion(i)
1350 if !c.t.pieceComplete(i) {
1351 // We had the piece, but not anymore.
1355 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1356 // If we failed to send a chunk, choke the peer to ensure they
1357 // flush all their requests. We've probably dropped a piece,
1358 // but there's no way to communicate this to the peer. If they
1359 // ask for it again, we'll kick them to allow us to send them
1360 // an updated bitfield.
1363 delete(c.peerRequests, r)
1374 func (cn *PeerConn) drop() {
1375 cn.t.dropConnection(cn)
1378 func (cn *PeerConn) netGoodPiecesDirtied() int64 {
1379 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1382 func (c *PeerConn) peerHasWantedPieces() bool {
1383 return !c._pieceRequestOrder.IsEmpty()
1386 func (c *PeerConn) numLocalRequests() int {
1387 return len(c.requests)
1390 func (c *PeerConn) deleteRequest(r request) bool {
1391 if _, ok := c.requests[r]; !ok {
1394 delete(c.requests, r)
1395 c.updateExpectingChunks()
1396 c.t.requestStrategy.hooks().deletedRequest(r)
1397 pr := c.t.pendingRequests
1407 for _c := range c.t.conns {
1408 if !_c.interested && _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1415 func (c *PeerConn) deleteAllRequests() {
1416 for r := range c.requests {
1419 if len(c.requests) != 0 {
1420 panic(len(c.requests))
1422 // for c := range c.t.conns {
1427 func (c *PeerConn) tickleWriter() {
1428 c.writerCond.Broadcast()
1431 func (c *PeerConn) postCancel(r request) bool {
1432 if !c.deleteRequest(r) {
1435 c.post(makeCancelMessage(r))
1439 func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1440 // Count the chunk being sent, even if it isn't.
1441 b := make([]byte, r.Length)
1442 p := c.t.info.Piece(int(r.Index))
1443 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1446 panic("expected error")
1449 } else if err == io.EOF {
1452 more = msg(pp.Message{
1458 c.lastChunkSent = time.Now()
1462 func (c *PeerConn) setTorrent(t *Torrent) {
1464 panic("connection already associated with a torrent")
1467 c.logger.Printf("torrent=%v", t)
1468 t.reconcileHandshakeStats(c)
1471 func (c *PeerConn) peerPriority() (peerPriority, error) {
1472 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1475 func (c *PeerConn) remoteIp() net.IP {
1476 return addrIpOrNil(c.remoteAddr)
1479 func (c *PeerConn) remoteIpPort() IpPort {
1480 ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1481 return IpPort{ipa.IP, uint16(ipa.Port)}
1484 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1485 f := pp.PexPeerFlags(0)
1486 if c.PeerPrefersEncryption {
1487 f |= pp.PexPrefersEncryption
1490 f |= pp.PexOutgoingConn
1492 if c.remoteAddr != nil && strings.Contains(c.remoteAddr.Network(), "udp") {
1493 f |= pp.PexSupportsUtp
1498 func (c *PeerConn) dialAddr() net.Addr {
1499 if !c.outgoing && c.PeerListenPort != 0 {
1500 switch addr := c.remoteAddr.(type) {
1503 dialAddr.Port = c.PeerListenPort
1507 dialAddr.Port = c.PeerListenPort
1514 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1515 f := c.pexPeerFlags()
1516 addr := c.dialAddr()
1517 return pexEvent{t, addr, f}
1520 func (c *PeerConn) String() string {
1521 return fmt.Sprintf("connection %p", c)
1524 func (c *PeerConn) trust() connectionTrust {
1525 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1528 type connectionTrust struct {
1530 NetGoodPiecesDirted int64
1533 func (l connectionTrust) Less(r connectionTrust) bool {
1534 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1537 func (cn *PeerConn) requestStrategyConnection() requestStrategyConnection {
1541 func (cn *PeerConn) chunksReceivedWhileExpecting() int64 {
1542 return cn._chunksReceivedWhileExpecting
1545 func (cn *PeerConn) fastest() bool {
1546 return cn == cn.t.fastestConn
1549 func (cn *PeerConn) peerMaxRequests() int {
1550 return cn.PeerMaxRequests
1553 // Returns the pieces the peer has claimed to have.
1554 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1556 defer cn.locker().RUnlock()
1557 return cn.peerPieces()
1560 func (cn *PeerConn) peerPieces() bitmap.Bitmap {
1561 ret := cn._peerPieces.Copy()
1562 if cn.peerSentHaveAll {
1563 ret.AddRange(0, cn.t.numPieces())
1568 func (cn *PeerConn) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1569 return &cn._pieceRequestOrder
1572 func (cn *PeerConn) stats() *ConnStats {
1576 func (cn *PeerConn) torrent() requestStrategyTorrent {
1577 return cn.t.requestStrategyTorrent()