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.
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 *PeerConn) 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 *PeerConn) expectingChunks() bool {
136 return cn.interested && !cn.peerChoking
139 // Returns true if the connection is over IPv6.
140 func (cn *PeerConn) 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 *PeerConn) 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 *PeerConn) hasPreferredNetworkOver(r *PeerConn) (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 *PeerConn) cumInterest() time.Duration {
166 ret := cn.priorInterest
168 ret += time.Since(cn.lastBecameInterested)
173 func (cn *PeerConn) 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 *PeerConn) locker() *lockWithDeferreds {
184 return cn.t.cl.locker()
187 func (cn *PeerConn) localAddr() net.Addr {
188 return cn.conn.LocalAddr()
191 func (cn *PeerConn) 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 *PeerConn) bestPeerNumPieces() pieceIndex {
199 return cn.t.numPieces()
201 return cn.peerMinPieces
204 func (cn *PeerConn) 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 *PeerConn) 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 *PeerConn) 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 *PeerConn) utp() bool {
245 return parseNetworkString(cn.network).Udp
248 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
249 func (cn *PeerConn) 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 *PeerConn) downloadRate() float64 {
278 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
281 func (cn *PeerConn) 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 *PeerConn) close() {
318 if !cn.closed.Set() {
322 cn.discardPieceInclination()
323 cn._pieceRequestOrder.Clear()
329 func (cn *PeerConn) 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 *PeerConn) 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 *PeerConn) 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 *PeerConn) 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 *PeerConn) nominalMaxRequests() (ret int) {
383 int64(cn.PeerMaxRequests),
384 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
388 func (cn *PeerConn) totalExpectingTime() (ret time.Duration) {
389 ret = cn.cumulativeExpectedToReceiveChunks
390 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
391 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
397 func (cn *PeerConn) 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 *PeerConn) 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 *PeerConn) unchoke(msg func(pp.Message) bool) bool {
433 return msg(pp.Message{
438 func (cn *PeerConn) 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 *PeerConn) 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 choking 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 *PeerConn) fillWriteBuffer(msg func(pp.Message) bool) {
512 if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
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)) {
525 } else if len(cn.requests) <= cn.requestsLowWater {
526 filledBuffer := false
527 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
528 cn.iterPendingRequests(pieceIndex, func(r request) bool {
529 if !cn.setInterested(true, msg) {
533 if len(cn.requests) >= cn.nominalMaxRequests() {
536 // Choking is looked at here because our interest is dependent
537 // on whether we'd make requests in its absence.
539 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
543 if _, ok := cn.requests[r]; ok {
546 filledBuffer = !cn.request(r, msg)
552 // If we didn't completely top up the requests, we shouldn't mark
553 // the low water, since we'll want to top up the requests as soon
554 // as we have more write buffer space.
557 cn.requestsLowWater = len(cn.requests) / 2
563 // Routine that writes to the peer. Some of what to write is buffered by
564 // activity elsewhere in the Client, and some is determined locally when the
565 // connection is writable.
566 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
568 lastWrite time.Time = time.Now()
569 keepAliveTimer *time.Timer
571 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
573 defer cn.locker().Unlock()
574 if time.Since(lastWrite) >= keepAliveTimeout {
577 keepAliveTimer.Reset(keepAliveTimeout)
580 defer cn.locker().Unlock()
582 defer keepAliveTimer.Stop()
583 frontBuf := new(bytes.Buffer)
585 if cn.closed.IsSet() {
588 if cn.writeBuffer.Len() == 0 {
589 cn.fillWriteBuffer(func(msg pp.Message) bool {
591 cn.writeBuffer.Write(msg.MustMarshalBinary())
592 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
593 return cn.writeBuffer.Len() < 1<<16 // 64KiB
596 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
597 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
598 postedKeepalives.Add(1)
600 if cn.writeBuffer.Len() == 0 {
601 // TODO: Minimize wakeups....
606 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
608 n, err := cn.w.Write(frontBuf.Bytes())
611 lastWrite = time.Now()
612 keepAliveTimer.Reset(keepAliveTimeout)
617 if n != frontBuf.Len() {
624 func (cn *PeerConn) have(piece pieceIndex) {
625 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
630 Index: pp.Integer(piece),
632 cn.sentHaves.Add(bitmap.BitIndex(piece))
635 func (cn *PeerConn) postBitfield() {
636 if cn.sentHaves.Len() != 0 {
637 panic("bitfield must be first have-related message sent")
639 if !cn.t.haveAnyPieces() {
644 Bitfield: cn.t.bitfield(),
646 cn.sentHaves = cn.t._completedPieces.Copy()
649 func (cn *PeerConn) updateRequests() {
650 // log.Print("update requests")
654 // Emits the indices in the Bitmaps bms in order, never repeating any index.
655 // skip is mutated during execution, and its initial values will never be
657 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
658 return func(cb iter.Callback) {
659 for _, bm := range bms {
661 func(i interface{}) bool {
665 bitmap.Sub(bm, *skip).Iter,
673 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
674 now, readahead := cn.torrent().readerPiecePriorities()
675 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
676 skip.Union(cn.torrent().ignorePieces())
677 // Return an iterator over the different priority classes, minus the skip pieces.
679 func(_piece interface{}) bool {
680 return f(pieceIndex(_piece.(bitmap.BitIndex)))
682 iterBitmapsDistinct(&skip, now, readahead),
683 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
684 func(cb iter.Callback) {
685 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
686 if skip.Contains(piece) {
697 // The connection should download highest priority pieces first, without any inclination toward
698 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
699 // fastest connection, and we have active readers that signal an ordering preference. It's
700 // conceivable that the best connection should do this, since it's least likely to waste our time if
701 // assigned to the highest priority pieces, and assigning more than one this role would cause
702 // significant wasted bandwidth.
703 func (cn *PeerConn) shouldRequestWithoutBias() bool {
704 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
707 func (cn *PeerConn) iterPendingPieces(f func(pieceIndex) bool) bool {
708 if !cn.t.haveInfo() {
711 return cn.t.requestStrategy.iterPendingPieces(cn, f)
713 func (cn *PeerConn) iterPendingPiecesUntyped(f iter.Callback) {
714 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
717 func (cn *PeerConn) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
718 return cn.t.requestStrategy.iterUndirtiedChunks(
719 cn.t.piece(piece).requestStrategyPiece(),
720 func(cs chunkSpec) bool {
721 return f(request{pp.Integer(piece), cs})
726 // check callers updaterequests
727 func (cn *PeerConn) stopRequestingPiece(piece pieceIndex) bool {
728 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
731 // This is distinct from Torrent piece priority, which is the user's
732 // preference. Connection piece priority is specific to a connection and is
733 // used to pseudorandomly avoid connections always requesting the same pieces
734 // and thus wasting effort.
735 func (cn *PeerConn) updatePiecePriority(piece pieceIndex) bool {
736 tpp := cn.t.piecePriority(piece)
737 if !cn.peerHasPiece(piece) {
738 tpp = PiecePriorityNone
740 if tpp == PiecePriorityNone {
741 return cn.stopRequestingPiece(piece)
743 prio := cn.getPieceInclination()[piece]
744 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
745 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
748 func (cn *PeerConn) getPieceInclination() []int {
749 if cn.pieceInclination == nil {
750 cn.pieceInclination = cn.t.getConnPieceInclination()
752 return cn.pieceInclination
755 func (cn *PeerConn) discardPieceInclination() {
756 if cn.pieceInclination == nil {
759 cn.t.putPieceInclination(cn.pieceInclination)
760 cn.pieceInclination = nil
763 func (cn *PeerConn) peerPiecesChanged() {
765 prioritiesChanged := false
766 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
767 if cn.updatePiecePriority(i) {
768 prioritiesChanged = true
771 if prioritiesChanged {
777 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
778 if newMin > cn.peerMinPieces {
779 cn.peerMinPieces = newMin
783 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
784 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
785 return errors.New("invalid piece")
787 if cn.peerHasPiece(piece) {
790 cn.raisePeerMinPieces(piece + 1)
791 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
792 if cn.updatePiecePriority(piece) {
798 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
799 cn.peerSentHaveAll = false
801 panic("expected bitfield length divisible by 8")
803 // We know that the last byte means that at most the last 7 bits are
805 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
806 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
807 // Ignore known excess pieces.
808 bf = bf[:cn.t.numPieces()]
810 for i, have := range bf {
812 cn.raisePeerMinPieces(pieceIndex(i) + 1)
814 cn._peerPieces.Set(i, have)
816 cn.peerPiecesChanged()
820 func (cn *PeerConn) onPeerSentHaveAll() error {
821 cn.peerSentHaveAll = true
822 cn._peerPieces.Clear()
823 cn.peerPiecesChanged()
827 func (cn *PeerConn) peerSentHaveNone() error {
828 cn._peerPieces.Clear()
829 cn.peerSentHaveAll = false
830 cn.peerPiecesChanged()
834 func (c *PeerConn) requestPendingMetadata() {
838 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
839 // Peer doesn't support this.
842 // Request metadata pieces that we don't have in a random order.
844 for index := 0; index < c.t.metadataPieceCount(); index++ {
845 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
846 pending = append(pending, index)
849 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
850 for _, i := range pending {
851 c.requestMetadataPiece(i)
855 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
856 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
857 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
860 func (cn *PeerConn) readMsg(msg *pp.Message) {
861 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
864 // After handshake, we know what Torrent and Client stats to include for a
866 func (cn *PeerConn) postHandshakeStats(f func(*ConnStats)) {
872 // All ConnStats that include this connection. Some objects are not known
873 // until the handshake is complete, after which it's expected to reconcile the
875 func (cn *PeerConn) allStats(f func(*ConnStats)) {
877 if cn.reconciledHandshakeStats {
878 cn.postHandshakeStats(f)
882 func (cn *PeerConn) wroteBytes(n int64) {
883 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
886 func (cn *PeerConn) readBytes(n int64) {
887 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
890 // Returns whether the connection could be useful to us. We're seeding and
891 // they want data, we don't have metainfo and they can provide it, etc.
892 func (c *PeerConn) useful() bool {
894 if c.closed.IsSet() {
898 return c.supportsExtension("ut_metadata")
900 if t.seeding() && c.peerInterested {
903 if c.peerHasWantedPieces() {
909 func (c *PeerConn) lastHelpful() (ret time.Time) {
910 ret = c.lastUsefulChunkReceived
911 if c.t.seeding() && c.lastChunkSent.After(ret) {
912 ret = c.lastChunkSent
917 func (c *PeerConn) fastEnabled() bool {
918 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast()
921 func (c *PeerConn) reject(r request) {
922 if !c.fastEnabled() {
923 panic("fast not enabled")
925 c.post(r.ToMsg(pp.Reject))
926 delete(c.peerRequests, r)
929 func (c *PeerConn) onReadRequest(r request) error {
930 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
931 if _, ok := c.peerRequests[r]; ok {
932 torrent.Add("duplicate requests received", 1)
936 torrent.Add("requests received while choking", 1)
938 torrent.Add("requests rejected while choking", 1)
943 if len(c.peerRequests) >= maxRequests {
944 torrent.Add("requests received while queue full", 1)
948 // BEP 6 says we may close here if we choose.
951 if !c.t.havePiece(pieceIndex(r.Index)) {
952 // This isn't necessarily them screwing up. We can drop pieces
953 // from our storage, and can't communicate this to peers
954 // except by reconnecting.
955 requestsReceivedForMissingPieces.Add(1)
956 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
958 // Check this after we know we have the piece, so that the piece length will be known.
959 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
960 torrent.Add("bad requests received", 1)
961 return errors.New("bad request")
963 if c.peerRequests == nil {
964 c.peerRequests = make(map[request]struct{}, maxRequests)
966 c.peerRequests[r] = struct{}{}
971 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
972 // exit. Returning will end the connection.
973 func (c *PeerConn) mainReadLoop() (err error) {
976 torrent.Add("connection.mainReadLoop returned with error", 1)
978 torrent.Add("connection.mainReadLoop returned with no error", 1)
984 decoder := pp.Decoder{
985 R: bufio.NewReaderSize(c.r, 1<<17),
986 MaxLength: 256 * 1024,
994 err = decoder.Decode(&msg)
996 if t.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1003 c.lastMessageReceived = time.Now()
1005 receivedKeepalives.Add(1)
1008 messageTypesReceived.Add(msg.Type.String(), 1)
1009 if msg.Type.FastExtension() && !c.fastEnabled() {
1010 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1014 c.peerChoking = true
1015 c.deleteAllRequests()
1016 // We can then reset our interest.
1018 c.updateExpectingChunks()
1020 c.peerChoking = false
1022 c.updateExpectingChunks()
1024 c.peerInterested = true
1026 case pp.NotInterested:
1027 c.peerInterested = false
1028 // We don't clear their requests since it isn't clear in the spec.
1029 // We'll probably choke them for this, which will clear them if
1030 // appropriate, and is clearly specified.
1032 err = c.peerSentHave(pieceIndex(msg.Index))
1034 err = c.peerSentBitfield(msg.Bitfield)
1036 r := newRequestFromMessage(&msg)
1037 err = c.onReadRequest(r)
1039 err = c.receiveChunk(&msg)
1040 if len(msg.Piece) == int(t.chunkSize) {
1041 t.chunkPool.Put(&msg.Piece)
1044 err = fmt.Errorf("receiving chunk: %s", err)
1047 req := newRequestFromMessage(&msg)
1048 c.onPeerSentCancel(req)
1050 ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1054 pingAddr := net.UDPAddr{
1059 pingAddr.Port = int(msg.Port)
1061 cl.eachDhtServer(func(s DhtServer) {
1062 go s.Ping(&pingAddr)
1065 torrent.Add("suggests received", 1)
1066 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index, debugLogValue).Log(c.t.logger)
1069 err = c.onPeerSentHaveAll()
1071 err = c.peerSentHaveNone()
1073 c.deleteRequest(newRequestFromMessage(&msg))
1074 delete(c.validReceiveChunks, newRequestFromMessage(&msg))
1075 case pp.AllowedFast:
1076 torrent.Add("allowed fasts received", 1)
1077 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c, debugLogValue).Log(c.t.logger)
1078 c.peerAllowedFast.Add(int(msg.Index))
1081 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1083 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1091 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1093 // TODO: Should we still do this?
1095 // These clients use their own extension IDs for outgoing message
1096 // types, which is incorrect.
1097 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1105 case pp.HandshakeExtendedID:
1106 var d pp.ExtendedHandshakeMessage
1107 if err := bencode.Unmarshal(payload, &d); err != nil {
1108 c.t.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1109 return errors.Wrap(err, "unmarshalling extended handshake payload")
1112 c.PeerMaxRequests = d.Reqq
1114 c.PeerClientName = d.V
1115 if c.PeerExtensionIDs == nil {
1116 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1118 for name, id := range d.M {
1119 if _, ok := c.PeerExtensionIDs[name]; !ok {
1120 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1122 c.PeerExtensionIDs[name] = id
1124 if d.MetadataSize != 0 {
1125 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1126 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1129 c.requestPendingMetadata()
1131 case metadataExtendedId:
1132 err := cl.gotMetadataExtensionMsg(payload, t, c)
1134 return fmt.Errorf("handling metadata extension message: %w", err)
1138 if cl.config.DisablePEX {
1139 // TODO: Maybe close the connection. Check that we're not
1140 // advertising that we support PEX if it's disabled.
1143 var pexMsg pp.PexMsg
1144 err := bencode.Unmarshal(payload, &pexMsg)
1146 return fmt.Errorf("error unmarshalling PEX message: %s", err)
1148 torrent.Add("pex added6 peers received", int64(len(pexMsg.Added6)))
1150 peers.AppendFromPex(pexMsg.Added6, pexMsg.Added6Flags)
1151 peers.AppendFromPex(pexMsg.Added, pexMsg.AddedFlags)
1155 return fmt.Errorf("unexpected extended message ID: %v", id)
1159 // Set both the Reader and Writer for the connection from a single ReadWriter.
1160 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1165 // Returns the Reader and Writer as a combined ReadWriter.
1166 func (cn *PeerConn) rw() io.ReadWriter {
1173 // Handle a received chunk from a peer.
1174 func (c *PeerConn) receiveChunk(msg *pp.Message) error {
1177 torrent.Add("chunks received", 1)
1179 req := newRequestFromMessage(msg)
1182 torrent.Add("chunks received while choking", 1)
1185 if _, ok := c.validReceiveChunks[req]; !ok {
1186 torrent.Add("chunks received unexpected", 1)
1187 return errors.New("received unexpected chunk")
1189 delete(c.validReceiveChunks, req)
1191 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1192 torrent.Add("chunks received due to allowed fast", 1)
1195 // Request has been satisfied.
1196 if c.deleteRequest(req) {
1197 if c.expectingChunks() {
1198 c._chunksReceivedWhileExpecting++
1201 torrent.Add("chunks received unwanted", 1)
1204 // Do we actually want this chunk?
1205 if t.haveChunk(req) {
1206 torrent.Add("chunks received wasted", 1)
1207 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1211 piece := &t.pieces[req.Index]
1213 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1214 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1215 c.lastUsefulChunkReceived = time.Now()
1216 // if t.fastestConn != c {
1217 // log.Printf("setting fastest connection %p", c)
1221 // Need to record that it hasn't been written yet, before we attempt to do
1222 // anything with it.
1223 piece.incrementPendingWrites()
1224 // Record that we have the chunk, so we aren't trying to download it while
1225 // waiting for it to be written to storage.
1226 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1228 // Cancel pending requests for this chunk.
1229 for c := range t.conns {
1233 err := func() error {
1236 concurrentChunkWrites.Add(1)
1237 defer concurrentChunkWrites.Add(-1)
1238 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1239 // number of connections. We write inline with receiving the chunk (with this lock dance),
1240 // because we want to handle errors synchronously and I haven't thought of a nice way to
1241 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1243 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1246 piece.decrementPendingWrites()
1249 c.logger.Printf("error writing received chunk %v: %v", req, err)
1251 //t.updatePieceCompletion(pieceIndex(msg.Index))
1252 t.onWriteChunkErr(err)
1256 c.onDirtiedPiece(pieceIndex(req.Index))
1258 if t.pieceAllDirty(pieceIndex(req.Index)) {
1259 t.queuePieceCheck(pieceIndex(req.Index))
1260 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1261 // chunk status (such as the haveChunk call above) to have to check all the various other
1262 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1263 // that chunk pieces are pended at an appropriate time later however.
1266 cl.event.Broadcast()
1267 // We do this because we've written a chunk, and may change PieceState.Partial.
1268 t.publishPieceChange(pieceIndex(req.Index))
1273 func (c *PeerConn) onDirtiedPiece(piece pieceIndex) {
1274 if c.peerTouchedPieces == nil {
1275 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1277 c.peerTouchedPieces[piece] = struct{}{}
1278 ds := &c.t.pieces[piece].dirtiers
1280 *ds = make(map[*PeerConn]struct{})
1282 (*ds)[c] = struct{}{}
1285 func (c *PeerConn) uploadAllowed() bool {
1286 if c.t.cl.config.NoUpload {
1292 if !c.peerHasWantedPieces() {
1295 // Don't upload more than 100 KiB more than we download.
1296 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1302 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1303 if c.uploadTimer == nil {
1304 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1306 c.uploadTimer.Reset(delay)
1310 // Also handles choking and unchoking of the remote peer.
1311 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1312 // Breaking or completing this loop means we don't want to upload to the
1313 // peer anymore, and we choke them.
1315 for c.uploadAllowed() {
1316 // We want to upload to the peer.
1317 if !c.unchoke(msg) {
1320 for r := range c.peerRequests {
1321 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1323 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1325 delay := res.Delay()
1328 c.setRetryUploadTimer(delay)
1329 // Hard to say what to return here.
1332 more, err := c.sendChunk(r, msg)
1334 i := pieceIndex(r.Index)
1335 if c.t.pieceComplete(i) {
1336 c.t.updatePieceCompletion(i)
1337 if !c.t.pieceComplete(i) {
1338 // We had the piece, but not anymore.
1342 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1343 // If we failed to send a chunk, choke the peer to ensure they
1344 // flush all their requests. We've probably dropped a piece,
1345 // but there's no way to communicate this to the peer. If they
1346 // ask for it again, we'll kick them to allow us to send them
1347 // an updated bitfield.
1350 delete(c.peerRequests, r)
1361 func (cn *PeerConn) drop() {
1362 cn.t.dropConnection(cn)
1365 func (cn *PeerConn) netGoodPiecesDirtied() int64 {
1366 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1369 func (c *PeerConn) peerHasWantedPieces() bool {
1370 return !c._pieceRequestOrder.IsEmpty()
1373 func (c *PeerConn) numLocalRequests() int {
1374 return len(c.requests)
1377 func (c *PeerConn) deleteRequest(r request) bool {
1378 if _, ok := c.requests[r]; !ok {
1381 delete(c.requests, r)
1382 c.updateExpectingChunks()
1383 c.t.requestStrategy.hooks().deletedRequest(r)
1384 pr := c.t.pendingRequests
1394 for _c := range c.t.conns {
1395 if !_c.interested && _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1402 func (c *PeerConn) deleteAllRequests() {
1403 for r := range c.requests {
1406 if len(c.requests) != 0 {
1407 panic(len(c.requests))
1409 // for c := range c.t.conns {
1414 func (c *PeerConn) tickleWriter() {
1415 c.writerCond.Broadcast()
1418 func (c *PeerConn) postCancel(r request) bool {
1419 if !c.deleteRequest(r) {
1422 c.post(makeCancelMessage(r))
1426 func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1427 // Count the chunk being sent, even if it isn't.
1428 b := make([]byte, r.Length)
1429 p := c.t.info.Piece(int(r.Index))
1430 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1433 panic("expected error")
1436 } else if err == io.EOF {
1439 more = msg(pp.Message{
1445 c.lastChunkSent = time.Now()
1449 func (c *PeerConn) setTorrent(t *Torrent) {
1451 panic("connection already associated with a torrent")
1454 c.logger.Printf("torrent=%v", t)
1455 t.reconcileHandshakeStats(c)
1458 func (c *PeerConn) peerPriority() peerPriority {
1459 return bep40PriorityIgnoreError(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1462 func (c *PeerConn) remoteIp() net.IP {
1463 return addrIpOrNil(c.remoteAddr)
1466 func (c *PeerConn) remoteIpPort() IpPort {
1467 ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1468 return IpPort{ipa.IP, uint16(ipa.Port)}
1471 func (c *PeerConn) String() string {
1472 return fmt.Sprintf("connection %p", c)
1475 func (c *PeerConn) trust() connectionTrust {
1476 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1479 type connectionTrust struct {
1481 NetGoodPiecesDirted int64
1484 func (l connectionTrust) Less(r connectionTrust) bool {
1485 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1488 func (cn *PeerConn) requestStrategyConnection() requestStrategyConnection {
1492 func (cn *PeerConn) chunksReceivedWhileExpecting() int64 {
1493 return cn._chunksReceivedWhileExpecting
1496 func (cn *PeerConn) fastest() bool {
1497 return cn == cn.t.fastestConn
1500 func (cn *PeerConn) peerMaxRequests() int {
1501 return cn.PeerMaxRequests
1504 // Returns the pieces the peer has claimed to have.
1505 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1507 defer cn.locker().RUnlock()
1508 return cn.peerPieces()
1511 func (cn *PeerConn) peerPieces() bitmap.Bitmap {
1512 ret := cn._peerPieces.Copy()
1513 if cn.peerSentHaveAll {
1514 ret.AddRange(0, cn.t.numPieces())
1519 func (cn *PeerConn) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1520 return &cn._pieceRequestOrder
1523 func (cn *PeerConn) stats() *ConnStats {
1527 func (cn *PeerConn) torrent() requestStrategyTorrent {
1528 return cn.t.requestStrategyTorrent()