15 "github.com/anacrolix/dht/v2"
16 "github.com/anacrolix/log"
17 "github.com/anacrolix/missinggo"
18 "github.com/anacrolix/missinggo/iter"
19 "github.com/anacrolix/missinggo/v2/bitmap"
20 "github.com/anacrolix/missinggo/v2/prioritybitmap"
21 "github.com/anacrolix/multiless"
22 "github.com/pkg/errors"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/mse"
26 pp "github.com/anacrolix/torrent/peer_protocol"
29 type peerSource string
32 peerSourceTracker = "Tr"
33 peerSourceIncoming = "I"
34 peerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
35 peerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
39 // Maintains the state of a connection with a peer.
40 type connection struct {
41 // First to ensure 64-bit alignment for atomics. See #262.
45 // 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
90 // Stuff controlled by the remote peer.
94 PeerRequests map[request]struct{}
95 PeerExtensionBytes pp.PeerExtensionBits
96 // The pieces the peer has claimed to have.
97 _peerPieces bitmap.Bitmap
98 // The peer has everything. This can occur due to a special message, when
99 // we may not even know the number of pieces in the torrent yet.
101 // The highest possible number of pieces the torrent could have based on
102 // communication with the peer. Generally only useful until we have the
104 peerMinPieces pieceIndex
105 // Pieces we've accepted chunks for from the peer.
106 peerTouchedPieces map[pieceIndex]struct{}
107 peerAllowedFast bitmap.Bitmap
109 PeerMaxRequests int // Maximum pending requests the peer allows.
110 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
111 PeerClientName string
113 pieceInclination []int
114 _pieceRequestOrder prioritybitmap.PriorityBitmap
116 writeBuffer *bytes.Buffer
117 uploadTimer *time.Timer
123 func (cn *connection) updateExpectingChunks() {
124 if cn.expectingChunks() {
125 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
126 cn.lastStartedExpectingToReceiveChunks = time.Now()
129 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
130 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
131 cn.lastStartedExpectingToReceiveChunks = time.Time{}
136 func (cn *connection) expectingChunks() bool {
137 return cn.Interested && !cn.PeerChoked
140 // Returns true if the connection is over IPv6.
141 func (cn *connection) ipv6() bool {
142 ip := addrIpOrNil(cn.remoteAddr)
146 return len(ip) == net.IPv6len
149 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
150 // specification for this.
151 func (cn *connection) isPreferredDirection() bool {
152 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
155 // Returns whether the left connection should be preferred over the right one,
156 // considering only their networking properties. If ok is false, we can't
158 func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) {
160 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
161 ml.NextBool(!l.utp(), !r.utp())
162 ml.NextBool(l.ipv6(), r.ipv6())
166 func (cn *connection) cumInterest() time.Duration {
167 ret := cn.priorInterest
169 ret += time.Since(cn.lastBecameInterested)
174 func (cn *connection) peerHasAllPieces() (all bool, known bool) {
175 if cn.peerSentHaveAll {
178 if !cn.t.haveInfo() {
181 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
184 func (cn *connection) mu() sync.Locker {
185 return cn.t.cl.locker()
188 func (cn *connection) localAddr() net.Addr {
189 return cn.conn.LocalAddr()
192 func (cn *connection) supportsExtension(ext pp.ExtensionName) bool {
193 _, ok := cn.PeerExtensionIDs[ext]
197 // The best guess at number of pieces in the torrent for this peer.
198 func (cn *connection) bestPeerNumPieces() pieceIndex {
200 return cn.t.numPieces()
202 return cn.peerMinPieces
205 func (cn *connection) completedString() string {
206 have := pieceIndex(cn._peerPieces.Len())
207 if cn.peerSentHaveAll {
208 have = cn.bestPeerNumPieces()
210 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
213 // Correct the PeerPieces slice length. Return false if the existing slice is
214 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
216 func (cn *connection) setNumPieces(num pieceIndex) error {
217 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
218 cn.peerPiecesChanged()
222 func eventAgeString(t time.Time) string {
226 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
229 func (cn *connection) connectionFlags() (ret string) {
231 ret += string([]byte{b})
233 if cn.cryptoMethod == mse.CryptoMethodRC4 {
235 } else if cn.headerEncrypted {
238 ret += string(cn.Discovery)
245 func (cn *connection) utp() bool {
246 return parseNetworkString(cn.network).Udp
249 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
250 func (cn *connection) statusFlags() (ret string) {
252 ret += string([]byte{b})
261 ret += cn.connectionFlags()
263 if cn.PeerInterested {
272 // func (cn *connection) String() string {
273 // var buf bytes.Buffer
274 // cn.WriteStatus(&buf, nil)
275 // return buf.String()
278 func (cn *connection) downloadRate() float64 {
279 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
282 func (cn *connection) WriteStatus(w io.Writer, t *Torrent) {
283 // \t isn't preserved in <pre> blocks?
284 fmt.Fprintf(w, "%+-55q %s %s-%s\n", cn.PeerID, cn.PeerExtensionBytes, cn.localAddr(), cn.remoteAddr)
285 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
286 eventAgeString(cn.lastMessageReceived),
287 eventAgeString(cn.completedHandshake),
288 eventAgeString(cn.lastHelpful()),
290 cn.totalExpectingTime(),
293 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
294 cn.completedString(),
295 len(cn.peerTouchedPieces),
296 &cn._stats.ChunksReadUseful,
297 &cn._stats.ChunksRead,
298 &cn._stats.ChunksWritten,
300 cn.numLocalRequests(),
301 cn.nominalMaxRequests(),
302 len(cn.PeerRequests),
304 cn.downloadRate()/(1<<10),
306 fmt.Fprintf(w, " next pieces: %v%s\n",
307 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
309 if cn == t.fastestConn {
318 func (cn *connection) Close() {
319 if !cn.closed.Set() {
323 cn.discardPieceInclination()
324 cn._pieceRequestOrder.Clear()
330 func (cn *connection) PeerHasPiece(piece pieceIndex) bool {
331 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
334 // Writes a message into the write buffer.
335 func (cn *connection) Post(msg pp.Message) {
336 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
337 // We don't need to track bytes here because a connection.w Writer wrapper
338 // takes care of that (although there's some delay between us recording
339 // the message, and the connection writer flushing it out.).
340 cn.writeBuffer.Write(msg.MustMarshalBinary())
341 // Last I checked only Piece messages affect stats, and we don't post
347 func (cn *connection) requestMetadataPiece(index int) {
348 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
352 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
355 cn.logger.Printf("requesting metadata piece %d", index)
359 ExtendedPayload: func() []byte {
360 b, err := bencode.Marshal(map[string]int{
361 "msg_type": pp.RequestMetadataExtensionMsgType,
370 for index >= len(cn.metadataRequests) {
371 cn.metadataRequests = append(cn.metadataRequests, false)
373 cn.metadataRequests[index] = true
376 func (cn *connection) requestedMetadataPiece(index int) bool {
377 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
380 // The actual value to use as the maximum outbound requests.
381 func (cn *connection) nominalMaxRequests() (ret int) {
384 int64(cn.PeerMaxRequests),
385 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
389 func (cn *connection) totalExpectingTime() (ret time.Duration) {
390 ret = cn.cumulativeExpectedToReceiveChunks
391 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
392 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
398 func (cn *connection) onPeerSentCancel(r request) {
399 if _, ok := cn.PeerRequests[r]; !ok {
400 torrent.Add("unexpected cancels received", 1)
403 if cn.fastEnabled() {
406 delete(cn.PeerRequests, r)
410 func (cn *connection) Choke(msg messageWriter) (more bool) {
415 more = msg(pp.Message{
418 if cn.fastEnabled() {
419 for r := range cn.PeerRequests {
420 // TODO: Don't reject pieces in allowed fast set.
424 cn.PeerRequests = nil
429 func (cn *connection) Unchoke(msg func(pp.Message) bool) bool {
434 return msg(pp.Message{
439 func (cn *connection) SetInterested(interested bool, msg func(pp.Message) bool) bool {
440 if cn.Interested == interested {
443 cn.Interested = interested
445 cn.lastBecameInterested = time.Now()
446 } else if !cn.lastBecameInterested.IsZero() {
447 cn.priorInterest += time.Since(cn.lastBecameInterested)
449 cn.updateExpectingChunks()
450 // log.Printf("%p: setting interest: %v", cn, interested)
451 return msg(pp.Message{
452 Type: func() pp.MessageType {
456 return pp.NotInterested
462 // The function takes a message to be sent, and returns true if more messages
464 type messageWriter func(pp.Message) bool
466 // Proxies the messageWriter's response.
467 func (cn *connection) request(r request, mw messageWriter) bool {
468 if _, ok := cn.requests[r]; ok {
469 panic("chunk already requested")
471 if !cn.PeerHasPiece(pieceIndex(r.Index)) {
472 panic("requesting piece peer doesn't have")
474 if _, ok := cn.t.conns[cn]; !ok {
475 panic("requesting but not in active conns")
477 if cn.closed.IsSet() {
478 panic("requesting when connection is closed")
481 if cn.peerAllowedFast.Get(int(r.Index)) {
482 torrent.Add("allowed fast requests sent", 1)
484 panic("requesting while choked and not allowed fast")
487 if cn.t.hashingPiece(pieceIndex(r.Index)) {
488 panic("piece is being hashed")
490 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
491 panic("piece is queued for hash")
493 if cn.requests == nil {
494 cn.requests = make(map[request]struct{})
496 cn.requests[r] = struct{}{}
497 if cn.validReceiveChunks == nil {
498 cn.validReceiveChunks = make(map[request]struct{})
500 cn.validReceiveChunks[r] = struct{}{}
501 cn.t.pendingRequests[r]++
502 cn.t.requestStrategy.hooks().sentRequest(r)
503 cn.updateExpectingChunks()
504 return mw(pp.Message{
512 func (cn *connection) fillWriteBuffer(msg func(pp.Message) bool) {
513 if !cn.t.networkingEnabled {
514 if !cn.SetInterested(false, msg) {
517 if len(cn.requests) != 0 {
518 for r := range cn.requests {
520 // log.Printf("%p: cancelling request: %v", cn, r)
521 if !msg(makeCancelMessage(r)) {
527 if len(cn.requests) <= cn.requestsLowWater {
528 filledBuffer := false
529 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
530 cn.iterPendingRequests(pieceIndex, func(r request) bool {
531 if !cn.SetInterested(true, msg) {
535 if len(cn.requests) >= cn.nominalMaxRequests() {
538 // Choking is looked at here because our interest is dependent
539 // on whether we'd make requests in its absence.
541 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
545 if _, ok := cn.requests[r]; ok {
548 filledBuffer = !cn.request(r, msg)
554 // If we didn't completely top up the requests, we shouldn't mark
555 // the low water, since we'll want to top up the requests as soon
556 // as we have more write buffer space.
559 cn.requestsLowWater = len(cn.requests) / 2
565 // Routine that writes to the peer. Some of what to write is buffered by
566 // activity elsewhere in the Client, and some is determined locally when the
567 // connection is writable.
568 func (cn *connection) writer(keepAliveTimeout time.Duration) {
570 lastWrite time.Time = time.Now()
571 keepAliveTimer *time.Timer
573 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
575 defer cn.mu().Unlock()
576 if time.Since(lastWrite) >= keepAliveTimeout {
579 keepAliveTimer.Reset(keepAliveTimeout)
582 defer cn.mu().Unlock()
584 defer keepAliveTimer.Stop()
585 frontBuf := new(bytes.Buffer)
587 if cn.closed.IsSet() {
590 if cn.writeBuffer.Len() == 0 {
591 cn.fillWriteBuffer(func(msg pp.Message) bool {
593 cn.writeBuffer.Write(msg.MustMarshalBinary())
594 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
595 return cn.writeBuffer.Len() < 1<<16 // 64KiB
598 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
599 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
600 postedKeepalives.Add(1)
602 if cn.writeBuffer.Len() == 0 {
603 // TODO: Minimize wakeups....
608 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
610 n, err := cn.w.Write(frontBuf.Bytes())
613 lastWrite = time.Now()
614 keepAliveTimer.Reset(keepAliveTimeout)
619 if n != frontBuf.Len() {
626 func (cn *connection) Have(piece pieceIndex) {
627 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
632 Index: pp.Integer(piece),
634 cn.sentHaves.Add(bitmap.BitIndex(piece))
637 func (cn *connection) PostBitfield() {
638 if cn.sentHaves.Len() != 0 {
639 panic("bitfield must be first have-related message sent")
641 if !cn.t.haveAnyPieces() {
646 Bitfield: cn.t.bitfield(),
648 cn.sentHaves = cn.t._completedPieces.Copy()
651 func (cn *connection) updateRequests() {
652 // log.Print("update requests")
656 // Emits the indices in the Bitmaps bms in order, never repeating any index.
657 // skip is mutated during execution, and its initial values will never be
659 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
660 return func(cb iter.Callback) {
661 for _, bm := range bms {
663 func(i interface{}) bool {
667 bitmap.Sub(bm, *skip).Iter,
675 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
676 now, readahead := cn.torrent().readerPiecePriorities()
677 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
678 skip.Union(cn.torrent().ignorePieces())
679 // Return an iterator over the different priority classes, minus the skip pieces.
681 func(_piece interface{}) bool {
682 return f(pieceIndex(_piece.(bitmap.BitIndex)))
684 iterBitmapsDistinct(&skip, now, readahead),
685 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
686 func(cb iter.Callback) {
687 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
688 if skip.Contains(piece) {
699 // The connection should download highest priority pieces first, without any inclination toward
700 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
701 // fastest connection, and we have active readers that signal an ordering preference. It's
702 // conceivable that the best connection should do this, since it's least likely to waste our time if
703 // assigned to the highest priority pieces, and assigning more than one this role would cause
704 // significant wasted bandwidth.
705 func (cn *connection) shouldRequestWithoutBias() bool {
706 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
709 func (cn *connection) iterPendingPieces(f func(pieceIndex) bool) bool {
710 if !cn.t.haveInfo() {
713 return cn.t.requestStrategy.iterPendingPieces(cn, f)
715 func (cn *connection) iterPendingPiecesUntyped(f iter.Callback) {
716 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
719 func (cn *connection) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
720 return cn.t.requestStrategy.iterUndirtiedChunks(
721 cn.t.piece(piece).requestStrategyPiece(),
722 func(cs chunkSpec) bool {
723 return f(request{pp.Integer(piece), cs})
728 // check callers updaterequests
729 func (cn *connection) stopRequestingPiece(piece pieceIndex) bool {
730 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
733 // This is distinct from Torrent piece priority, which is the user's
734 // preference. Connection piece priority is specific to a connection and is
735 // used to pseudorandomly avoid connections always requesting the same pieces
736 // and thus wasting effort.
737 func (cn *connection) updatePiecePriority(piece pieceIndex) bool {
738 tpp := cn.t.piecePriority(piece)
739 if !cn.PeerHasPiece(piece) {
740 tpp = PiecePriorityNone
742 if tpp == PiecePriorityNone {
743 return cn.stopRequestingPiece(piece)
745 prio := cn.getPieceInclination()[piece]
746 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
747 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
750 func (cn *connection) getPieceInclination() []int {
751 if cn.pieceInclination == nil {
752 cn.pieceInclination = cn.t.getConnPieceInclination()
754 return cn.pieceInclination
757 func (cn *connection) discardPieceInclination() {
758 if cn.pieceInclination == nil {
761 cn.t.putPieceInclination(cn.pieceInclination)
762 cn.pieceInclination = nil
765 func (cn *connection) peerPiecesChanged() {
767 prioritiesChanged := false
768 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
769 if cn.updatePiecePriority(i) {
770 prioritiesChanged = true
773 if prioritiesChanged {
779 func (cn *connection) raisePeerMinPieces(newMin pieceIndex) {
780 if newMin > cn.peerMinPieces {
781 cn.peerMinPieces = newMin
785 func (cn *connection) peerSentHave(piece pieceIndex) error {
786 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
787 return errors.New("invalid piece")
789 if cn.PeerHasPiece(piece) {
792 cn.raisePeerMinPieces(piece + 1)
793 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
794 if cn.updatePiecePriority(piece) {
800 func (cn *connection) peerSentBitfield(bf []bool) error {
801 cn.peerSentHaveAll = false
803 panic("expected bitfield length divisible by 8")
805 // We know that the last byte means that at most the last 7 bits are
807 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
808 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
809 // Ignore known excess pieces.
810 bf = bf[:cn.t.numPieces()]
812 for i, have := range bf {
814 cn.raisePeerMinPieces(pieceIndex(i) + 1)
816 cn._peerPieces.Set(i, have)
818 cn.peerPiecesChanged()
822 func (cn *connection) onPeerSentHaveAll() error {
823 cn.peerSentHaveAll = true
824 cn._peerPieces.Clear()
825 cn.peerPiecesChanged()
829 func (cn *connection) peerSentHaveNone() error {
830 cn._peerPieces.Clear()
831 cn.peerSentHaveAll = false
832 cn.peerPiecesChanged()
836 func (c *connection) requestPendingMetadata() {
840 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
841 // Peer doesn't support this.
844 // Request metadata pieces that we don't have in a random order.
846 for index := 0; index < c.t.metadataPieceCount(); index++ {
847 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
848 pending = append(pending, index)
851 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
852 for _, i := range pending {
853 c.requestMetadataPiece(i)
857 func (cn *connection) wroteMsg(msg *pp.Message) {
858 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
859 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
862 func (cn *connection) readMsg(msg *pp.Message) {
863 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
866 // After handshake, we know what Torrent and Client stats to include for a
868 func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
874 // All ConnStats that include this connection. Some objects are not known
875 // until the handshake is complete, after which it's expected to reconcile the
877 func (cn *connection) allStats(f func(*ConnStats)) {
879 if cn.reconciledHandshakeStats {
880 cn.postHandshakeStats(f)
884 func (cn *connection) wroteBytes(n int64) {
885 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
888 func (cn *connection) readBytes(n int64) {
889 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
892 // Returns whether the connection could be useful to us. We're seeding and
893 // they want data, we don't have metainfo and they can provide it, etc.
894 func (c *connection) useful() bool {
896 if c.closed.IsSet() {
900 return c.supportsExtension("ut_metadata")
902 if t.seeding() && c.PeerInterested {
905 if c.peerHasWantedPieces() {
911 func (c *connection) lastHelpful() (ret time.Time) {
912 ret = c.lastUsefulChunkReceived
913 if c.t.seeding() && c.lastChunkSent.After(ret) {
914 ret = c.lastChunkSent
919 func (c *connection) fastEnabled() bool {
920 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
923 func (c *connection) reject(r request) {
924 if !c.fastEnabled() {
925 panic("fast not enabled")
927 c.Post(r.ToMsg(pp.Reject))
928 delete(c.PeerRequests, r)
931 func (c *connection) onReadRequest(r request) error {
932 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
933 if _, ok := c.PeerRequests[r]; ok {
934 torrent.Add("duplicate requests received", 1)
938 torrent.Add("requests received while choking", 1)
940 torrent.Add("requests rejected while choking", 1)
945 if len(c.PeerRequests) >= maxRequests {
946 torrent.Add("requests received while queue full", 1)
950 // BEP 6 says we may close here if we choose.
953 if !c.t.havePiece(pieceIndex(r.Index)) {
954 // This isn't necessarily them screwing up. We can drop pieces
955 // from our storage, and can't communicate this to peers
956 // except by reconnecting.
957 requestsReceivedForMissingPieces.Add(1)
958 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
960 // Check this after we know we have the piece, so that the piece length will be known.
961 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
962 torrent.Add("bad requests received", 1)
963 return errors.New("bad request")
965 if c.PeerRequests == nil {
966 c.PeerRequests = make(map[request]struct{}, maxRequests)
968 c.PeerRequests[r] = struct{}{}
973 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
974 // exit. Returning will end the connection.
975 func (c *connection) mainReadLoop() (err error) {
978 torrent.Add("connection.mainReadLoop returned with error", 1)
980 torrent.Add("connection.mainReadLoop returned with no error", 1)
986 decoder := pp.Decoder{
987 R: bufio.NewReaderSize(c.r, 1<<17),
988 MaxLength: 256 * 1024,
996 err = decoder.Decode(&msg)
998 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1005 c.lastMessageReceived = time.Now()
1007 receivedKeepalives.Add(1)
1010 messageTypesReceived.Add(msg.Type.String(), 1)
1011 if msg.Type.FastExtension() && !c.fastEnabled() {
1012 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1017 c.deleteAllRequests()
1018 // We can then reset our interest.
1020 c.updateExpectingChunks()
1022 c.PeerChoked = false
1024 c.updateExpectingChunks()
1026 c.PeerInterested = true
1028 case pp.NotInterested:
1029 c.PeerInterested = false
1030 // We don't clear their requests since it isn't clear in the spec.
1031 // We'll probably choke them for this, which will clear them if
1032 // appropriate, and is clearly specified.
1034 err = c.peerSentHave(pieceIndex(msg.Index))
1036 err = c.peerSentBitfield(msg.Bitfield)
1038 r := newRequestFromMessage(&msg)
1039 err = c.onReadRequest(r)
1041 err = c.receiveChunk(&msg)
1042 if len(msg.Piece) == int(t.chunkSize) {
1043 t.chunkPool.Put(&msg.Piece)
1046 err = fmt.Errorf("receiving chunk: %s", err)
1049 req := newRequestFromMessage(&msg)
1050 c.onPeerSentCancel(req)
1052 ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1056 pingAddr := net.UDPAddr{
1061 pingAddr.Port = int(msg.Port)
1063 cl.eachDhtServer(func(s *dht.Server) {
1064 go s.Ping(&pingAddr, nil)
1067 torrent.Add("suggests received", 1)
1068 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1071 err = c.onPeerSentHaveAll()
1073 err = c.peerSentHaveNone()
1075 c.deleteRequest(newRequestFromMessage(&msg))
1076 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1077 case pp.AllowedFast:
1078 torrent.Add("allowed fasts received", 1)
1079 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1080 c.peerAllowedFast.Add(int(msg.Index))
1083 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1085 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1093 func (c *connection) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1095 // TODO: Should we still do this?
1097 // These clients use their own extension IDs for outgoing message
1098 // types, which is incorrect.
1099 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1107 case pp.HandshakeExtendedID:
1108 var d pp.ExtendedHandshakeMessage
1109 if err := bencode.Unmarshal(payload, &d); err != nil {
1110 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1111 return errors.Wrap(err, "unmarshalling extended handshake payload")
1114 c.PeerMaxRequests = d.Reqq
1116 c.PeerClientName = d.V
1117 if c.PeerExtensionIDs == nil {
1118 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1120 for name, id := range d.M {
1121 if _, ok := c.PeerExtensionIDs[name]; !ok {
1122 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1124 c.PeerExtensionIDs[name] = id
1126 if d.MetadataSize != 0 {
1127 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1128 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1131 c.requestPendingMetadata()
1133 case metadataExtendedId:
1134 err := cl.gotMetadataExtensionMsg(payload, t, c)
1136 return fmt.Errorf("handling metadata extension message: %w", err)
1140 if cl.config.DisablePEX {
1141 // TODO: Maybe close the connection. Check that we're not
1142 // advertising that we support PEX if it's disabled.
1145 var pexMsg pp.PexMsg
1146 err := bencode.Unmarshal(payload, &pexMsg)
1148 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1150 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1152 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1153 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1157 return fmt.Errorf("unexpected extended message ID: %v", id)
1161 // Set both the Reader and Writer for the connection from a single ReadWriter.
1162 func (cn *connection) setRW(rw io.ReadWriter) {
1167 // Returns the Reader and Writer as a combined ReadWriter.
1168 func (cn *connection) rw() io.ReadWriter {
1175 // Handle a received chunk from a peer.
1176 func (c *connection) receiveChunk(msg *pp.Message) error {
1179 torrent.Add("chunks received", 1)
1181 req := newRequestFromMessage(msg)
1184 torrent.Add("chunks received while choked", 1)
1187 if _, ok := c.validReceiveChunks[req]; !ok {
1188 torrent.Add("chunks received unexpected", 1)
1189 return errors.New("received unexpected chunk")
1191 delete(c.validReceiveChunks, req)
1193 if c.PeerChoked && c.peerAllowedFast.Get(int(req.Index)) {
1194 torrent.Add("chunks received due to allowed fast", 1)
1197 // Request has been satisfied.
1198 if c.deleteRequest(req) {
1199 if c.expectingChunks() {
1200 c._chunksReceivedWhileExpecting++
1203 torrent.Add("chunks received unwanted", 1)
1206 // Do we actually want this chunk?
1207 if t.haveChunk(req) {
1208 torrent.Add("chunks received wasted", 1)
1209 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1213 piece := &t.pieces[req.Index]
1215 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1216 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1217 c.lastUsefulChunkReceived = time.Now()
1218 // if t.fastestConn != c {
1219 // log.Printf("setting fastest connection %p", c)
1223 // Need to record that it hasn't been written yet, before we attempt to do
1224 // anything with it.
1225 piece.incrementPendingWrites()
1226 // Record that we have the chunk, so we aren't trying to download it while
1227 // waiting for it to be written to storage.
1228 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1230 // Cancel pending requests for this chunk.
1231 for c := range t.conns {
1235 err := func() error {
1238 concurrentChunkWrites.Add(1)
1239 defer concurrentChunkWrites.Add(-1)
1240 // Write the chunk out. Note that the upper bound on chunk writing
1241 // concurrency will be the number of connections. We write inline with
1242 // receiving the chunk (with this lock dance), because we want to
1243 // handle errors synchronously and I haven't thought of a nice way to
1244 // defer any concurrency to the storage and have that notify the
1245 // client of errors. TODO: Do that instead.
1246 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1249 piece.decrementPendingWrites()
1252 panic(fmt.Sprintf("error writing chunk: %v", err))
1254 t.updatePieceCompletion(pieceIndex(msg.Index))
1258 c.onDirtiedPiece(pieceIndex(req.Index))
1260 if t.pieceAllDirty(pieceIndex(req.Index)) {
1261 t.queuePieceCheck(pieceIndex(req.Index))
1262 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1263 // chunk status (such as the haveChunk call above) to have to check all the various other
1264 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1265 // that chunk pieces are pended at an appropriate time later however.
1268 cl.event.Broadcast()
1269 // We do this because we've written a chunk, and may change PieceState.Partial.
1270 t.publishPieceChange(pieceIndex(req.Index))
1275 func (c *connection) onDirtiedPiece(piece pieceIndex) {
1276 if c.peerTouchedPieces == nil {
1277 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1279 c.peerTouchedPieces[piece] = struct{}{}
1280 ds := &c.t.pieces[piece].dirtiers
1282 *ds = make(map[*connection]struct{})
1284 (*ds)[c] = struct{}{}
1287 func (c *connection) uploadAllowed() bool {
1288 if c.t.cl.config.NoUpload {
1294 if !c.peerHasWantedPieces() {
1297 // Don't upload more than 100 KiB more than we download.
1298 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1304 func (c *connection) setRetryUploadTimer(delay time.Duration) {
1305 if c.uploadTimer == nil {
1306 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1308 c.uploadTimer.Reset(delay)
1312 // Also handles choking and unchoking of the remote peer.
1313 func (c *connection) upload(msg func(pp.Message) bool) bool {
1314 // Breaking or completing this loop means we don't want to upload to the
1315 // peer anymore, and we choke them.
1317 for c.uploadAllowed() {
1318 // We want to upload to the peer.
1319 if !c.Unchoke(msg) {
1322 for r := range c.PeerRequests {
1323 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1325 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1327 delay := res.Delay()
1330 c.setRetryUploadTimer(delay)
1331 // Hard to say what to return here.
1334 more, err := c.sendChunk(r, msg)
1336 i := pieceIndex(r.Index)
1337 if c.t.pieceComplete(i) {
1338 c.t.updatePieceCompletion(i)
1339 if !c.t.pieceComplete(i) {
1340 // We had the piece, but not anymore.
1344 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1345 // If we failed to send a chunk, choke the peer to ensure they
1346 // flush all their requests. We've probably dropped a piece,
1347 // but there's no way to communicate this to the peer. If they
1348 // ask for it again, we'll kick them to allow us to send them
1349 // an updated bitfield.
1352 delete(c.PeerRequests, r)
1363 func (cn *connection) Drop() {
1364 cn.t.dropConnection(cn)
1367 func (cn *connection) netGoodPiecesDirtied() int64 {
1368 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1371 func (c *connection) peerHasWantedPieces() bool {
1372 return !c._pieceRequestOrder.IsEmpty()
1375 func (c *connection) numLocalRequests() int {
1376 return len(c.requests)
1379 func (c *connection) deleteRequest(r request) bool {
1380 if _, ok := c.requests[r]; !ok {
1383 delete(c.requests, r)
1384 c.updateExpectingChunks()
1385 c.t.requestStrategy.hooks().deletedRequest(r)
1386 pr := c.t.pendingRequests
1396 for _c := range c.t.conns {
1397 if !_c.Interested && _c != c && c.PeerHasPiece(pieceIndex(r.Index)) {
1404 func (c *connection) deleteAllRequests() {
1405 for r := range c.requests {
1408 if len(c.requests) != 0 {
1409 panic(len(c.requests))
1411 // for c := range c.t.conns {
1416 func (c *connection) tickleWriter() {
1417 c.writerCond.Broadcast()
1420 func (c *connection) postCancel(r request) bool {
1421 if !c.deleteRequest(r) {
1424 c.Post(makeCancelMessage(r))
1428 func (c *connection) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1429 // Count the chunk being sent, even if it isn't.
1430 b := make([]byte, r.Length)
1431 p := c.t.info.Piece(int(r.Index))
1432 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1435 panic("expected error")
1438 } else if err == io.EOF {
1441 more = msg(pp.Message{
1447 c.lastChunkSent = time.Now()
1451 func (c *connection) setTorrent(t *Torrent) {
1453 panic("connection already associated with a torrent")
1456 c.logger.Printf("torrent=%v", t)
1457 t.reconcileHandshakeStats(c)
1460 func (c *connection) peerPriority() peerPriority {
1461 return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1464 func (c *connection) remoteIp() net.IP {
1465 return addrIpOrNil(c.remoteAddr)
1468 func (c *connection) remoteIpPort() IpPort {
1469 ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1470 return IpPort{ipa.IP, uint16(ipa.Port)}
1473 func (c *connection) String() string {
1474 return fmt.Sprintf("connection %p", c)
1477 func (c *connection) trust() connectionTrust {
1478 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1481 type connectionTrust struct {
1483 NetGoodPiecesDirted int64
1486 func (l connectionTrust) Less(r connectionTrust) bool {
1487 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1490 func (cn *connection) requestStrategyConnection() requestStrategyConnection {
1494 func (cn *connection) chunksReceivedWhileExpecting() int64 {
1495 return cn._chunksReceivedWhileExpecting
1498 func (cn *connection) fastest() bool {
1499 return cn == cn.t.fastestConn
1502 func (cn *connection) peerMaxRequests() int {
1503 return cn.PeerMaxRequests
1506 func (cn *connection) peerPieces() bitmap.Bitmap {
1507 ret := cn._peerPieces.Copy()
1508 if cn.peerSentHaveAll {
1509 ret.AddRange(0, cn.t.numPieces())
1514 func (cn *connection) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1515 return &cn._pieceRequestOrder
1518 func (cn *connection) stats() *ConnStats {
1522 func (cn *connection) torrent() requestStrategyTorrent {
1523 return cn.t.requestStrategyTorrent()