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 connection struct {
40 // First to ensure 64-bit alignment for atomics. See #262.
44 // The actual Conn, used for closing, and setting socket options.
49 // The Reader and Writer for this Conn, with hooks installed for stats,
50 // limiting, deadlines etc.
53 // True if the connection is operating over MSE obfuscation.
55 cryptoMethod mse.CryptoMethod
58 closed missinggo.Event
59 // Set true after we've added our ConnStats generated during handshake to
60 // other ConnStat instances as determined when the *Torrent became known.
61 reconciledHandshakeStats bool
63 lastMessageReceived time.Time
64 completedHandshake time.Time
65 lastUsefulChunkReceived time.Time
66 lastChunkSent time.Time
68 // Stuff controlled by the local peer.
70 lastBecameInterested time.Time
71 priorInterest time.Duration
73 lastStartedExpectingToReceiveChunks time.Time
74 cumulativeExpectedToReceiveChunks time.Duration
75 _chunksReceivedWhileExpecting int64
78 requests map[request]struct{}
80 // Chunks that we might reasonably expect to receive from the peer. Due to
81 // latency, buffering, and implementation differences, we may receive
82 // chunks that are no longer in the set of requests actually want.
83 validReceiveChunks map[request]struct{}
84 // Indexed by metadata piece, set to true if posted and pending a
86 metadataRequests []bool
87 sentHaves bitmap.Bitmap
89 // Stuff controlled by the remote peer.
93 PeerRequests map[request]struct{}
94 PeerExtensionBytes pp.PeerExtensionBits
95 // The pieces the peer has claimed to have.
96 _peerPieces bitmap.Bitmap
97 // The peer has everything. This can occur due to a special message, when
98 // we may not even know the number of pieces in the torrent yet.
100 // The highest possible number of pieces the torrent could have based on
101 // communication with the peer. Generally only useful until we have the
103 peerMinPieces pieceIndex
104 // Pieces we've accepted chunks for from the peer.
105 peerTouchedPieces map[pieceIndex]struct{}
106 peerAllowedFast bitmap.Bitmap
108 PeerMaxRequests int // Maximum pending requests the peer allows.
109 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
110 PeerClientName string
112 pieceInclination []int
113 _pieceRequestOrder prioritybitmap.PriorityBitmap
115 writeBuffer *bytes.Buffer
116 uploadTimer *time.Timer
122 func (cn *connection) updateExpectingChunks() {
123 if cn.expectingChunks() {
124 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
125 cn.lastStartedExpectingToReceiveChunks = time.Now()
128 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
129 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
130 cn.lastStartedExpectingToReceiveChunks = time.Time{}
135 func (cn *connection) expectingChunks() bool {
136 return cn.Interested && !cn.PeerChoked
139 // Returns true if the connection is over IPv6.
140 func (cn *connection) ipv6() bool {
141 ip := addrIpOrNil(cn.remoteAddr)
145 return len(ip) == net.IPv6len
148 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
149 // specification for this.
150 func (cn *connection) isPreferredDirection() bool {
151 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
154 // Returns whether the left connection should be preferred over the right one,
155 // considering only their networking properties. If ok is false, we can't
157 func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
159 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
160 ml.NextBool(!l.utp(), !r.utp())
161 ml.NextBool(l.ipv6(), r.ipv6())
165 func (cn *connection) cumInterest() time.Duration {
166 ret := cn.priorInterest
168 ret += time.Since(cn.lastBecameInterested)
173 func (cn *connection) peerHasAllPieces() (all bool, known bool) {
174 if cn.peerSentHaveAll {
177 if !cn.t.haveInfo() {
180 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
183 func (cn *connection) mu() sync.Locker {
184 return cn.t.cl.locker()
187 func (cn *connection) localAddr() net.Addr {
188 return cn.conn.LocalAddr()
191 func (cn *connection) supportsExtension(ext pp.ExtensionName) bool {
192 _, ok := cn.PeerExtensionIDs[ext]
196 // The best guess at number of pieces in the torrent for this peer.
197 func (cn *connection) bestPeerNumPieces() pieceIndex {
199 return cn.t.numPieces()
201 return cn.peerMinPieces
204 func (cn *connection) completedString() string {
205 have := pieceIndex(cn._peerPieces.Len())
206 if cn.peerSentHaveAll {
207 have = cn.bestPeerNumPieces()
209 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
212 // Correct the PeerPieces slice length. Return false if the existing slice is
213 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
215 func (cn *connection) setNumPieces(num pieceIndex) error {
216 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
217 cn.peerPiecesChanged()
221 func eventAgeString(t time.Time) string {
225 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
228 func (cn *connection) connectionFlags() (ret string) {
230 ret += string([]byte{b})
232 if cn.cryptoMethod == mse.CryptoMethodRC4 {
234 } else if cn.headerEncrypted {
237 ret += string(cn.Discovery)
244 func (cn *connection) utp() bool {
245 return parseNetworkString(cn.network).Udp
248 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
249 func (cn *connection) statusFlags() (ret string) {
251 ret += string([]byte{b})
260 ret += cn.connectionFlags()
262 if cn.PeerInterested {
271 // func (cn *connection) String() string {
272 // var buf bytes.Buffer
273 // cn.WriteStatus(&buf, nil)
274 // return buf.String()
277 func (cn *connection) downloadRate() float64 {
278 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
281 func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
282 // \t isn't preserved in <pre> blocks?
283 fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr)
284 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
285 eventAgeString(cn.lastMessageReceived),
286 eventAgeString(cn.completedHandshake),
287 eventAgeString(cn.lastHelpful()),
289 cn.totalExpectingTime(),
292 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
293 cn.completedString(),
294 len(cn.peerTouchedPieces),
295 &cn._stats.ChunksReadUseful,
296 &cn._stats.ChunksRead,
297 &cn._stats.ChunksWritten,
299 cn.numLocalRequests(),
300 cn.nominalMaxRequests(),
301 len(cn.PeerRequests),
303 cn.downloadRate()/(1<<10),
305 fmt.Fprintf(w, " next pieces: %v%s\n",
306 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
308 if cn == t.fastestConn {
317 func (cn *connection) Close() {
318 if !cn.closed.Set() {
322 cn.discardPieceInclination()
323 cn._pieceRequestOrder.Clear()
329 func (cn *connection) PeerHasPiece(piece pieceIndex) bool {
330 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
333 // Writes a message into the write buffer.
334 func (cn *connection) Post(msg pp.Message) {
335 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
336 // We don't need to track bytes here because a connection.w Writer wrapper
337 // takes care of that (although there's some delay between us recording
338 // the message, and the connection writer flushing it out.).
339 cn.writeBuffer.Write(msg.MustMarshalBinary())
340 // Last I checked only Piece messages affect stats, and we don't post
346 func (cn *connection) requestMetadataPiece(index int) {
347 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
351 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
354 cn.logger.Printf("requesting metadata piece %d", index)
358 ExtendedPayload: func() []byte {
359 b, err := bencode.Marshal(map[string]int{
360 "msg_type": pp.RequestMetadataExtensionMsgType,
369 for index >= len(cn.metadataRequests) {
370 cn.metadataRequests = append(cn.metadataRequests, false)
372 cn.metadataRequests[index] = true
375 func (cn *connection) requestedMetadataPiece(index int) bool {
376 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
379 // The actual value to use as the maximum outbound requests.
380 func (cn *connection) nominalMaxRequests() (ret int) {
383 int64(cn.PeerMaxRequests),
384 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
388 func (cn *connection) totalExpectingTime() (ret time.Duration) {
389 ret = cn.cumulativeExpectedToReceiveChunks
390 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
391 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
397 func (cn *connection) onPeerSentCancel(r request) {
398 if _, ok := cn.PeerRequests[r]; !ok {
399 torrent.Add("unexpected cancels received", 1)
402 if cn.fastEnabled() {
405 delete(cn.PeerRequests, r)
409 func (cn *connection) Choke(msg messageWriter) (more bool) {
414 more = msg(pp.Message{
417 if cn.fastEnabled() {
418 for r := range cn.PeerRequests {
419 // TODO: Don't reject pieces in allowed fast set.
423 cn.PeerRequests = nil
428 func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
433 return msg(pp.Message{
438 func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
439 if cn.Interested == interested {
442 cn.Interested = interested
444 cn.lastBecameInterested = time.Now()
445 } else if !cn.lastBecameInterested.IsZero() {
446 cn.priorInterest += time.Since(cn.lastBecameInterested)
448 cn.updateExpectingChunks()
449 // log.Printf("%p: setting interest: %v", cn, interested)
450 return msg(pp.Message{
451 Type: func() pp.MessageType {
455 return pp.NotInterested
461 // The function takes a message to be sent, and returns true if more messages
463 type messageWriter func(pp.Message) bool
465 // Proxies the messageWriter's response.
466 func (cn *connection) request(r request, mw messageWriter) bool {
467 if _, ok := cn.requests[r]; ok {
468 panic("chunk already requested")
470 if !cn.PeerHasPiece(pieceIndex(r.Index)) {
471 panic("requesting piece peer doesn't have")
473 if _, ok := cn.t.conns[cn]; !ok {
474 panic("requesting but not in active conns")
476 if cn.closed.IsSet() {
477 panic("requesting when connection is closed")
480 if cn.peerAllowedFast.Get(int(r.Index)) {
481 torrent.Add("allowed fast requests sent", 1)
483 panic("requesting while choked and not allowed fast")
486 if cn.t.hashingPiece(pieceIndex(r.Index)) {
487 panic("piece is being hashed")
489 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
490 panic("piece is queued for hash")
492 if cn.requests == nil {
493 cn.requests = make(map[request]struct{})
495 cn.requests[r] = struct{}{}
496 if cn.validReceiveChunks == nil {
497 cn.validReceiveChunks = make(map[request]struct{})
499 cn.validReceiveChunks[r] = struct{}{}
500 cn.t.pendingRequests[r]++
501 cn.t.requestStrategy.hooks().sentRequest(r)
502 cn.updateExpectingChunks()
503 return mw(pp.Message{
511 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
512 if !cn.t.networkingEnabled {
513 if !cn.SetInterested(false, msg) {
516 if len(cn.requests) != 0 {
517 for r := range cn.requests {
519 // log.Printf("%p: cancelling request: %v", cn, r)
520 if !msg(makeCancelMessage(r)) {
526 if len(cn.requests) <= cn.requestsLowWater {
527 filledBuffer := false
528 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
529 cn.iterPendingRequests(pieceIndex, func(r request) bool {
530 if !cn.SetInterested(true, msg) {
534 if len(cn.requests) >= cn.nominalMaxRequests() {
537 // Choking is looked at here because our interest is dependent
538 // on whether we'd make requests in its absence.
540 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
544 if _, ok := cn.requests[r]; ok {
547 filledBuffer = !cn.request(r, msg)
553 // If we didn't completely top up the requests, we shouldn't mark
554 // the low water, since we'll want to top up the requests as soon
555 // as we have more write buffer space.
558 cn.requestsLowWater = len(cn.requests) / 2
564 // Routine that writes to the peer. Some of what to write is buffered by
565 // activity elsewhere in the Client, and some is determined locally when the
566 // connection is writable.
567 func (cn *connection) writer(keepAliveTimeout time.Duration) {
569 lastWrite time.Time = time.Now()
570 keepAliveTimer *time.Timer
572 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
574 defer cn.mu().Unlock()
575 if time.Since(lastWrite) >= keepAliveTimeout {
578 keepAliveTimer.Reset(keepAliveTimeout)
581 defer cn.mu().Unlock()
583 defer keepAliveTimer.Stop()
584 frontBuf := new(bytes.Buffer)
586 if cn.closed.IsSet() {
589 if cn.writeBuffer.Len() == 0 {
590 cn.fillWriteBuffer(func(msg pp.Message) bool {
592 cn.writeBuffer.Write(msg.MustMarshalBinary())
593 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
594 return cn.writeBuffer.Len() < 1<<16 // 64KiB
597 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
598 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
599 postedKeepalives.Add(1)
601 if cn.writeBuffer.Len() == 0 {
602 // TODO: Minimize wakeups....
607 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
609 n, err := cn.w.Write(frontBuf.Bytes())
612 lastWrite = time.Now()
613 keepAliveTimer.Reset(keepAliveTimeout)
618 if n != frontBuf.Len() {
625 func (cn *connection) Have(piece pieceIndex) {
626 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
631 Index: pp.Integer(piece),
633 cn.sentHaves.Add(bitmap.BitIndex(piece))
636 func (cn *connection) PostBitfield() {
637 if cn.sentHaves.Len() != 0 {
638 panic("bitfield must be first have-related message sent")
640 if !cn.t.haveAnyPieces() {
645 Bitfield: cn.t.bitfield(),
647 cn.sentHaves = cn.t._completedPieces.Copy()
650 func (cn *connection) updateRequests() {
651 // log.Print("update requests")
655 // Emits the indices in the Bitmaps bms in order, never repeating any index.
656 // skip is mutated during execution, and its initial values will never be
658 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
659 return func(cb iter.Callback) {
660 for _, bm := range bms {
662 func(i interface{}) bool {
666 bitmap.Sub(bm, *skip).Iter,
674 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
675 now, readahead := cn.torrent().readerPiecePriorities()
676 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
677 skip.Union(cn.torrent().ignorePieces())
678 // Return an iterator over the different priority classes, minus the skip pieces.
680 func(_piece interface{}) bool {
681 return f(pieceIndex(_piece.(bitmap.BitIndex)))
683 iterBitmapsDistinct(&skip, now, readahead),
684 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
685 func(cb iter.Callback) {
686 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
687 if skip.Contains(piece) {
698 // The connection should download highest priority pieces first, without any inclination toward
699 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
700 // fastest connection, and we have active readers that signal an ordering preference. It's
701 // conceivable that the best connection should do this, since it's least likely to waste our time if
702 // assigned to the highest priority pieces, and assigning more than one this role would cause
703 // significant wasted bandwidth.
704 func (cn *connection) shouldRequestWithoutBias() bool {
705 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
708 func (cn *connection) iterPendingPieces(f func(pieceIndex) bool) bool {
709 if !cn.t.haveInfo() {
712 return cn.t.requestStrategy.iterPendingPieces(cn, f)
714 func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
715 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
718 func (cn *connection) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
719 return cn.t.requestStrategy.iterUndirtiedChunks(
720 cn.t.piece(piece).requestStrategyPiece(),
721 func(cs chunkSpec) bool {
722 return f(request{pp.Integer(piece), cs})
727 // check callers updaterequests
728 func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
729 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
732 // This is distinct from Torrent piece priority, which is the user's
733 // preference. Connection piece priority is specific to a connection and is
734 // used to pseudorandomly avoid connections always requesting the same pieces
735 // and thus wasting effort.
736 func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
737 tpp := cn.t.piecePriority(piece)
738 if !cn.PeerHasPiece(piece) {
739 tpp = PiecePriorityNone
741 if tpp == PiecePriorityNone {
742 return cn.stopRequestingPiece(piece)
744 prio := cn.getPieceInclination()[piece]
745 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
746 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
749 func (cn *connection) getPieceInclination() []int {
750 if cn.pieceInclination == nil {
751 cn.pieceInclination = cn.t.getConnPieceInclination()
753 return cn.pieceInclination
756 func (cn *connection) discardPieceInclination() {
757 if cn.pieceInclination == nil {
760 cn.t.putPieceInclination(cn.pieceInclination)
761 cn.pieceInclination = nil
764 func (cn *connection) peerPiecesChanged() {
766 prioritiesChanged := false
767 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
768 if cn.updatePiecePriority(i) {
769 prioritiesChanged = true
772 if prioritiesChanged {
778 func (cn *connection) raisePeerMinPieces(newMin pieceIndex) {
779 if newMin > cn.peerMinPieces {
780 cn.peerMinPieces = newMin
784 func (cn *connection) peerSentHave(piece pieceIndex) error {
785 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
786 return errors.New("invalid piece")
788 if cn.PeerHasPiece(piece) {
791 cn.raisePeerMinPieces(piece + 1)
792 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
793 if cn.updatePiecePriority(piece) {
799 func (cn *connection) peerSentBitfield(bf []bool) error {
800 cn.peerSentHaveAll = false
802 panic("expected bitfield length divisible by 8")
804 // We know that the last byte means that at most the last 7 bits are
806 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
807 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
808 // Ignore known excess pieces.
809 bf = bf[:cn.t.numPieces()]
811 for i, have := range bf {
813 cn.raisePeerMinPieces(pieceIndex(i) + 1)
815 cn._peerPieces.Set(i, have)
817 cn.peerPiecesChanged()
821 func (cn *connection) onPeerSentHaveAll() error {
822 cn.peerSentHaveAll = true
823 cn._peerPieces.Clear()
824 cn.peerPiecesChanged()
828 func (cn *connection) peerSentHaveNone() error {
829 cn._peerPieces.Clear()
830 cn.peerSentHaveAll = false
831 cn.peerPiecesChanged()
835 func (c *connection) requestPendingMetadata() {
839 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
840 // Peer doesn't support this.
843 // Request metadata pieces that we don't have in a random order.
845 for index := 0; index < c.t.metadataPieceCount(); index++ {
846 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
847 pending = append(pending, index)
850 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
851 for _, i := range pending {
852 c.requestMetadataPiece(i)
856 func (cn *connection) wroteMsg(msg *pp.Message) {
857 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
858 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
861 func (cn *connection) readMsg(msg *pp.Message) {
862 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
865 // After handshake, we know what Torrent and Client stats to include for a
867 func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
873 // All ConnStats that include this connection. Some objects are not known
874 // until the handshake is complete, after which it's expected to reconcile the
876 func (cn *connection) allStats(f func(*ConnStats)) {
878 if cn.reconciledHandshakeStats {
879 cn.postHandshakeStats(f)
883 func (cn *connection) wroteBytes(n int64) {
884 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
887 func (cn *connection) readBytes(n int64) {
888 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
891 // Returns whether the connection could be useful to us. We're seeding and
892 // they want data, we don't have metainfo and they can provide it, etc.
893 func (c *connection) useful() bool {
895 if c.closed.IsSet() {
899 return c.supportsExtension("ut_metadata")
901 if t.seeding() && c.PeerInterested {
904 if c.peerHasWantedPieces() {
910 func (c *connection) lastHelpful() (ret time.Time) {
911 ret = c.lastUsefulChunkReceived
912 if c.t.seeding() && c.lastChunkSent.After(ret) {
913 ret = c.lastChunkSent
918 func (c *connection) fastEnabled() bool {
919 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
922 func (c *connection) reject(r request) {
923 if !c.fastEnabled() {
924 panic("fast not enabled")
926 c.Post(r.ToMsg(pp.Reject))
927 delete(c.PeerRequests, r)
930 func (c *connection) onReadRequest(r request) error {
931 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
932 if _, ok := c.PeerRequests[r]; ok {
933 torrent.Add("duplicate requests received", 1)
937 torrent.Add("requests received while choking", 1)
939 torrent.Add("requests rejected while choking", 1)
944 if len(c.PeerRequests) >= maxRequests {
945 torrent.Add("requests received while queue full", 1)
949 // BEP 6 says we may close here if we choose.
952 if !c.t.havePiece(pieceIndex(r.Index)) {
953 // This isn't necessarily them screwing up. We can drop pieces
954 // from our storage, and can't communicate this to peers
955 // except by reconnecting.
956 requestsReceivedForMissingPieces.Add(1)
957 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
959 // Check this after we know we have the piece, so that the piece length will be known.
960 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
961 torrent.Add("bad requests received", 1)
962 return errors.New("bad request")
964 if c.PeerRequests == nil {
965 c.PeerRequests = make(map[request]struct{}, maxRequests)
967 c.PeerRequests[r] = struct{}{}
972 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
973 // exit. Returning will end the connection.
974 func (c *connection) mainReadLoop() (err error) {
977 torrent.Add("connection.mainReadLoop returned with error", 1)
979 torrent.Add("connection.mainReadLoop returned with no error", 1)
985 decoder := pp.Decoder{
986 R: bufio.NewReaderSize(c.r, 1<<17),
987 MaxLength: 256 * 1024,
995 err = decoder.Decode(&msg)
997 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1004 c.lastMessageReceived = time.Now()
1006 receivedKeepalives.Add(1)
1009 messageTypesReceived.Add(msg.Type.String(), 1)
1010 if msg.Type.FastExtension() && !c.fastEnabled() {
1011 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1016 c.deleteAllRequests()
1017 // We can then reset our interest.
1019 c.updateExpectingChunks()
1021 c.PeerChoked = false
1023 c.updateExpectingChunks()
1025 c.PeerInterested = true
1027 case pp.NotInterested:
1028 c.PeerInterested = false
1029 // We don't clear their requests since it isn't clear in the spec.
1030 // We'll probably choke them for this, which will clear them if
1031 // appropriate, and is clearly specified.
1033 err = c.peerSentHave(pieceIndex(msg.Index))
1035 err = c.peerSentBitfield(msg.Bitfield)
1037 r := newRequestFromMessage(&msg)
1038 err = c.onReadRequest(r)
1040 err = c.receiveChunk(&msg)
1041 if len(msg.Piece) == int(t.chunkSize) {
1042 t.chunkPool.Put(&msg.Piece)
1045 err = fmt.Errorf("receiving chunk: %s", err)
1048 req := newRequestFromMessage(&msg)
1049 c.onPeerSentCancel(req)
1051 ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1055 pingAddr := net.UDPAddr{
1060 pingAddr.Port = int(msg.Port)
1062 cl.eachDhtServer(func(s DhtServer) {
1063 go s.Ping(&pingAddr)
1066 torrent.Add("suggests received", 1)
1067 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1070 err = c.onPeerSentHaveAll()
1072 err = c.peerSentHaveNone()
1074 c.deleteRequest(newRequestFromMessage(&msg))
1075 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1076 case pp.AllowedFast:
1077 torrent.Add("allowed fasts received", 1)
1078 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1079 c.peerAllowedFast.Add(int(msg.Index))
1082 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1084 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1092 func (c *connection) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1094 // TODO: Should we still do this?
1096 // These clients use their own extension IDs for outgoing message
1097 // types, which is incorrect.
1098 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1106 case pp.HandshakeExtendedID:
1107 var d pp.ExtendedHandshakeMessage
1108 if err := bencode.Unmarshal(payload, &d); err != nil {
1109 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1110 return errors.Wrap(err, "unmarshalling extended handshake payload")
1113 c.PeerMaxRequests = d.Reqq
1115 c.PeerClientName = d.V
1116 if c.PeerExtensionIDs == nil {
1117 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1119 for name, id := range d.M {
1120 if _, ok := c.PeerExtensionIDs[name]; !ok {
1121 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1123 c.PeerExtensionIDs[name] = id
1125 if d.MetadataSize != 0 {
1126 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1127 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1130 c.requestPendingMetadata()
1132 case metadataExtendedId:
1133 err := cl.gotMetadataExtensionMsg(payload, t, c)
1135 return fmt.Errorf("handling metadata extension message: %w", err)
1139 if cl.config.DisablePEX {
1140 // TODO: Maybe close the connection. Check that we're not
1141 // advertising that we support PEX if it's disabled.
1144 var pexMsg pp.PexMsg
1145 err := bencode.Unmarshal(payload, &pexMsg)
1147 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1149 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1151 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1152 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1156 return fmt.Errorf("unexpected extended message ID: %v", id)
1160 // Set both the Reader and Writer for the connection from a single ReadWriter.
1161 func (cn *connection) setRW(rw io.ReadWriter) {
1166 // Returns the Reader and Writer as a combined ReadWriter.
1167 func (cn *connection) rw() io.ReadWriter {
1174 // Handle a received chunk from a peer.
1175 func (c *connection) receiveChunk(msg *pp.Message) error {
1178 torrent.Add("chunks received", 1)
1180 req := newRequestFromMessage(msg)
1183 torrent.Add("chunks received while choked", 1)
1186 if _, ok := c.validReceiveChunks[req]; !ok {
1187 torrent.Add("chunks received unexpected", 1)
1188 return errors.New("received unexpected chunk")
1190 delete(c.validReceiveChunks, req)
1192 if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) {
1193 torrent.Add("chunks received due to allowed fast", 1)
1196 // Request has been satisfied.
1197 if c.deleteRequest(req) {
1198 if c.expectingChunks() {
1199 c._chunksReceivedWhileExpecting++
1202 torrent.Add("chunks received unwanted", 1)
1205 // Do we actually want this chunk?
1206 if t.haveChunk(req) {
1207 torrent.Add("chunks received wasted", 1)
1208 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1212 piece := &t.pieces[req.Index]
1214 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1215 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1216 c.lastUsefulChunkReceived = time.Now()
1217 // if t.fastestConn != c {
1218 // log.Printf("setting fastest connection %p", c)
1222 // Need to record that it hasn't been written yet, before we attempt to do
1223 // anything with it.
1224 piece.incrementPendingWrites()
1225 // Record that we have the chunk, so we aren't trying to download it while
1226 // waiting for it to be written to storage.
1227 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1229 // Cancel pending requests for this chunk.
1230 for c := range t.conns {
1234 err := func() error {
1237 concurrentChunkWrites.Add(1)
1238 defer concurrentChunkWrites.Add(-1)
1239 // Write the chunk out. Note that the upper bound on chunk writing
1240 // concurrency will be the number of connections. We write inline with
1241 // receiving the chunk (with this lock dance), because we want to
1242 // handle errors synchronously and I haven't thought of a nice way to
1243 // defer any concurrency to the storage and have that notify the
1244 // client of errors. TODO: Do that instead.
1245 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1248 piece.decrementPendingWrites()
1251 panic(fmt.Sprintf("error writing chunk: %v", err))
1253 t.updatePieceCompletion(pieceIndex(msg.Index))
1257 c.onDirtiedPiece(pieceIndex(req.Index))
1259 if t.pieceAllDirty(pieceIndex(req.Index)) {
1260 t.queuePieceCheck(pieceIndex(req.Index))
1261 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1262 // chunk status (such as the haveChunk call above) to have to check all the various other
1263 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1264 // that chunk pieces are pended at an appropriate time later however.
1267 cl.event.Broadcast()
1268 // We do this because we've written a chunk, and may change PieceState.Partial.
1269 t.publishPieceChange(pieceIndex(req.Index))
1274 func (c *connection) onDirtiedPiece(piece pieceIndex) {
1275 if c.peerTouchedPieces == nil {
1276 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1278 c.peerTouchedPieces[piece] = struct{}{}
1279 ds := &c.t.pieces[piece].dirtiers
1281 *ds = make(map[*connection]struct{})
1283 (*ds)[c] = struct{}{}
1286 func (c *connection) uploadAllowed() bool {
1287 if c.t.cl.config.NoUpload {
1293 if !c.peerHasWantedPieces() {
1296 // Don't upload more than 100 KiB more than we download.
1297 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1303 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1304 if c.uploadTimer == nil {
1305 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1307 c.uploadTimer.Reset(delay)
1311 // Also handles choking and unchoking of the remote peer.
1312 func (c *connection) upload(msg func(pp.Message) bool) bool {
1313 // Breaking or completing this loop means we don't want to upload to the
1314 // peer anymore, and we choke them.
1316 for c.uploadAllowed() {
1317 // We want to upload to the peer.
1318 if !c.Unchoke(msg) {
1321 for r := range c.PeerRequests {
1322 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1324 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1326 delay := res.Delay()
1329 c.setRetryUploadTimer(delay)
1330 // Hard to say what to return here.
1333 more, err := c.sendChunk(r, msg)
1335 i := pieceIndex(r.Index)
1336 if c.t.pieceComplete(i) {
1337 c.t.updatePieceCompletion(i)
1338 if !c.t.pieceComplete(i) {
1339 // We had the piece, but not anymore.
1343 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1344 // If we failed to send a chunk, choke the peer to ensure they
1345 // flush all their requests. We've probably dropped a piece,
1346 // but there's no way to communicate this to the peer. If they
1347 // ask for it again, we'll kick them to allow us to send them
1348 // an updated bitfield.
1351 delete(c.PeerRequests, r)
1362 func (cn *connection) Drop() {
1363 cn.t.dropConnection(cn)
1366 func (cn *connection) netGoodPiecesDirtied() int64 {
1367 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1370 func (c *connection) peerHasWantedPieces() bool {
1371 return !c._pieceRequestOrder.IsEmpty()
1374 func (c *connection) numLocalRequests() int {
1375 return len(c.requests)
1378 func (c *connection) deleteRequest(r request) bool {
1379 if _, ok := c.requests[r]; !ok {
1382 delete(c.requests, r)
1383 c.updateExpectingChunks()
1384 c.t.requestStrategy.hooks().deletedRequest(r)
1385 pr := c.t.pendingRequests
1395 for _c := range c.t.conns {
1396 if !_c.Interested && _c != c && c.PeerHasPiece(pieceIndex(r.Index)) {
1403 func (c *connection) deleteAllRequests() {
1404 for r := range c.requests {
1407 if len(c.requests) != 0 {
1408 panic(len(c.requests))
1410 // for c := range c.t.conns {
1415 func (c *connection) tickleWriter() {
1416 c.writerCond.Broadcast()
1419 func (c *connection) postCancel(r request) bool {
1420 if !c.deleteRequest(r) {
1423 c.Post(makeCancelMessage(r))
1427 func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1428 // Count the chunk being sent, even if it isn't.
1429 b := make([]byte, r.Length)
1430 p := c.t.info.Piece(int(r.Index))
1431 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1434 panic("expected error")
1437 } else if err == io.EOF {
1440 more = msg(pp.Message{
1446 c.lastChunkSent = time.Now()
1450 func (c *connection) setTorrent(t *Torrent) {
1452 panic("connection already associated with a torrent")
1455 c.logger.Printf("torrent=%v", t)
1456 t.reconcileHandshakeStats(c)
1459 func (c *connection) peerPriority() peerPriority {
1460 return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1463 func (c *connection) remoteIp() net.IP {
1464 return addrIpOrNil(c.remoteAddr)
1467 func (c *connection) remoteIpPort() IpPort {
1468 ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1469 return IpPort{ipa.IP, uint16(ipa.Port)}
1472 func (c *connection) String() string {
1473 return fmt.Sprintf("connection %p", c)
1476 func (c *connection) trust() connectionTrust {
1477 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1480 type connectionTrust struct {
1482 NetGoodPiecesDirted int64
1485 func (l connectionTrust) Less(r connectionTrust) bool {
1486 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1489 func (cn *connection) requestStrategyConnection() requestStrategyConnection {
1493 func (cn *connection) chunksReceivedWhileExpecting() int64 {
1494 return cn._chunksReceivedWhileExpecting
1497 func (cn *connection) fastest() bool {
1498 return cn == cn.t.fastestConn
1501 func (cn *connection) peerMaxRequests() int {
1502 return cn.PeerMaxRequests
1505 func (cn *connection) peerPieces() bitmap.Bitmap {
1506 ret := cn._peerPieces.Copy()
1507 if cn.peerSentHaveAll {
1508 ret.AddRange(0, cn.t.numPieces())
1513 func (cn *connection) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1514 return &cn._pieceRequestOrder
1517 func (cn *connection) stats() *ConnStats {
1521 func (cn *connection) torrent() requestStrategyTorrent {
1522 return cn.t.requestStrategyTorrent()