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 type PeerImpl interface {
40 WriteInterested(interested bool) bool
42 // Return true if there's room for more activity.
44 ConnectionFlags() string
51 // First to ensure 64-bit alignment for atomics. See #262.
62 // True if the connection is operating over MSE obfuscation.
64 cryptoMethod mse.CryptoMethod
67 closed missinggo.Event
68 // Set true after we've added our ConnStats generated during handshake to
69 // other ConnStat instances as determined when the *Torrent became known.
70 reconciledHandshakeStats bool
72 lastMessageReceived time.Time
73 completedHandshake time.Time
74 lastUsefulChunkReceived time.Time
75 lastChunkSent time.Time
77 // Stuff controlled by the local peer.
79 lastBecameInterested time.Time
80 priorInterest time.Duration
82 lastStartedExpectingToReceiveChunks time.Time
83 cumulativeExpectedToReceiveChunks time.Duration
84 _chunksReceivedWhileExpecting int64
87 requests map[request]struct{}
89 // Chunks that we might reasonably expect to receive from the peer. Due to
90 // latency, buffering, and implementation differences, we may receive
91 // chunks that are no longer in the set of requests actually want.
92 validReceiveChunks map[request]int
93 // Indexed by metadata piece, set to true if posted and pending a
95 metadataRequests []bool
96 sentHaves bitmap.Bitmap
99 // Stuff controlled by the remote peer.
103 peerRequests map[request]struct{}
104 PeerExtensionBytes pp.PeerExtensionBits
105 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
107 // The pieces the peer has claimed to have.
108 _peerPieces bitmap.Bitmap
109 // The peer has everything. This can occur due to a special message, when
110 // we may not even know the number of pieces in the torrent yet.
112 // The highest possible number of pieces the torrent could have based on
113 // communication with the peer. Generally only useful until we have the
115 peerMinPieces pieceIndex
116 // Pieces we've accepted chunks for from the peer.
117 peerTouchedPieces map[pieceIndex]struct{}
118 peerAllowedFast bitmap.Bitmap
120 PeerMaxRequests int // Maximum pending requests the peer allows.
121 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
122 PeerClientName string
124 pieceInclination []int
125 _pieceRequestOrder prioritybitmap.PriorityBitmap
130 // Maintains the state of a connection with a peer.
131 type PeerConn struct {
134 // The actual Conn, used for closing, and setting socket options.
136 // The Reader and Writer for this Conn, with hooks installed for stats,
137 // limiting, deadlines etc.
141 writeBuffer *bytes.Buffer
142 uploadTimer *time.Timer
146 func (cn *peer) updateExpectingChunks() {
147 if cn.expectingChunks() {
148 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
149 cn.lastStartedExpectingToReceiveChunks = time.Now()
152 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
153 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
154 cn.lastStartedExpectingToReceiveChunks = time.Time{}
159 func (cn *peer) expectingChunks() bool {
160 return cn.interested && !cn.peerChoking
163 // Returns true if the connection is over IPv6.
164 func (cn *PeerConn) ipv6() bool {
165 ip := addrIpOrNil(cn.remoteAddr)
169 return len(ip) == net.IPv6len
172 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
173 // specification for this.
174 func (cn *PeerConn) isPreferredDirection() bool {
175 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
178 // Returns whether the left connection should be preferred over the right one,
179 // considering only their networking properties. If ok is false, we can't
181 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
183 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
184 ml.NextBool(!l.utp(), !r.utp())
185 ml.NextBool(l.ipv6(), r.ipv6())
189 func (cn *peer) cumInterest() time.Duration {
190 ret := cn.priorInterest
192 ret += time.Since(cn.lastBecameInterested)
197 func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
198 if cn.peerSentHaveAll {
201 if !cn.t.haveInfo() {
204 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
207 func (cn *PeerConn) locker() *lockWithDeferreds {
208 return cn.t.cl.locker()
211 func (cn *PeerConn) localAddr() net.Addr {
212 return cn.conn.LocalAddr()
215 func (cn *peer) supportsExtension(ext pp.ExtensionName) bool {
216 _, ok := cn.PeerExtensionIDs[ext]
220 // The best guess at number of pieces in the torrent for this peer.
221 func (cn *peer) bestPeerNumPieces() pieceIndex {
223 return cn.t.numPieces()
225 return cn.peerMinPieces
228 func (cn *peer) completedString() string {
229 have := pieceIndex(cn._peerPieces.Len())
230 if cn.peerSentHaveAll {
231 have = cn.bestPeerNumPieces()
233 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
236 // Correct the PeerPieces slice length. Return false if the existing slice is
237 // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE
239 func (cn *PeerConn) setNumPieces(num pieceIndex) error {
240 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
241 cn.peerPiecesChanged()
245 func eventAgeString(t time.Time) string {
249 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
252 func (cn *PeerConn) ConnectionFlags() (ret string) {
254 ret += string([]byte{b})
256 if cn.cryptoMethod == mse.CryptoMethodRC4 {
258 } else if cn.headerEncrypted {
261 ret += string(cn.Discovery)
268 func (cn *PeerConn) utp() bool {
269 return parseNetworkString(cn.network).Udp
272 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
273 func (cn *peer) statusFlags() (ret string) {
275 ret += string([]byte{b})
284 ret += cn.ConnectionFlags()
286 if cn.peerInterested {
295 // func (cn *connection) String() string {
296 // var buf bytes.Buffer
297 // cn.writeStatus(&buf, nil)
298 // return buf.String()
301 func (cn *peer) downloadRate() float64 {
302 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
305 func (cn *peer) writeStatus(w io.Writer, t *Torrent) {
306 // \t isn't preserved in <pre> blocks?
307 fmt.Fprintf(w, "%+-55q %s %s\n", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
308 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
309 eventAgeString(cn.lastMessageReceived),
310 eventAgeString(cn.completedHandshake),
311 eventAgeString(cn.lastHelpful()),
313 cn.totalExpectingTime(),
316 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
317 cn.completedString(),
318 len(cn.peerTouchedPieces),
319 &cn._stats.ChunksReadUseful,
320 &cn._stats.ChunksRead,
321 &cn._stats.ChunksWritten,
323 cn.numLocalRequests(),
324 cn.nominalMaxRequests(),
325 len(cn.peerRequests),
327 cn.downloadRate()/(1<<10),
329 fmt.Fprintf(w, " next pieces: %v%s\n",
330 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
332 if cn == t.fastestConn {
341 func (cn *peer) close() {
342 if !cn.closed.Set() {
345 cn.discardPieceInclination()
346 cn._pieceRequestOrder.Clear()
350 func (cn *PeerConn) Close() {
351 if cn.pex.IsEnabled() {
360 func (cn *peer) peerHasPiece(piece pieceIndex) bool {
361 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
364 // Writes a message into the write buffer.
365 func (cn *PeerConn) post(msg pp.Message) {
366 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
367 // We don't need to track bytes here because a connection.w Writer wrapper
368 // takes care of that (although there's some delay between us recording
369 // the message, and the connection writer flushing it out.).
370 cn.writeBuffer.Write(msg.MustMarshalBinary())
371 // Last I checked only Piece messages affect stats, and we don't post
377 // Returns true if there's room to write more.
378 func (cn *PeerConn) write(msg pp.Message) bool {
380 cn.writeBuffer.Write(msg.MustMarshalBinary())
381 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
382 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update
383 // when https://github.com/pion/datachannel/issues/59 is fixed.
384 return cn.writeBuffer.Len() < 1<<15
387 func (cn *PeerConn) requestMetadataPiece(index int) {
388 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
392 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
395 cn.logger.Printf("requesting metadata piece %d", index)
399 ExtendedPayload: func() []byte {
400 b, err := bencode.Marshal(map[string]int{
401 "msg_type": pp.RequestMetadataExtensionMsgType,
410 for index >= len(cn.metadataRequests) {
411 cn.metadataRequests = append(cn.metadataRequests, false)
413 cn.metadataRequests[index] = true
416 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
417 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
420 // The actual value to use as the maximum outbound requests.
421 func (cn *peer) nominalMaxRequests() (ret int) {
424 int64(cn.PeerMaxRequests),
425 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
429 func (cn *peer) totalExpectingTime() (ret time.Duration) {
430 ret = cn.cumulativeExpectedToReceiveChunks
431 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
432 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
438 func (cn *PeerConn) onPeerSentCancel(r request) {
439 if _, ok := cn.peerRequests[r]; !ok {
440 torrent.Add("unexpected cancels received", 1)
443 if cn.fastEnabled() {
446 delete(cn.peerRequests, r)
450 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
455 more = msg(pp.Message{
458 if cn.fastEnabled() {
459 for r := range cn.peerRequests {
460 // TODO: Don't reject pieces in allowed fast set.
464 cn.peerRequests = nil
469 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
474 return msg(pp.Message{
479 func (cn *peer) setInterested(interested bool) bool {
480 if cn.interested == interested {
483 cn.interested = interested
485 cn.lastBecameInterested = time.Now()
486 } else if !cn.lastBecameInterested.IsZero() {
487 cn.priorInterest += time.Since(cn.lastBecameInterested)
489 cn.updateExpectingChunks()
490 // log.Printf("%p: setting interest: %v", cn, interested)
491 return cn.WriteInterested(interested)
494 func (pc *PeerConn) WriteInterested(interested bool) bool {
495 return pc.write(pp.Message{
496 Type: func() pp.MessageType {
500 return pp.NotInterested
506 // The function takes a message to be sent, and returns true if more messages
508 type messageWriter func(pp.Message) bool
510 func (cn *peer) request(r request) bool {
511 if _, ok := cn.requests[r]; ok {
512 panic("chunk already requested")
514 if !cn.peerHasPiece(pieceIndex(r.Index)) {
515 panic("requesting piece peer doesn't have")
517 if !cn.t.peerIsActive(cn) {
518 panic("requesting but not in active conns")
520 if cn.closed.IsSet() {
521 panic("requesting when connection is closed")
524 if cn.peerAllowedFast.Get(int(r.Index)) {
525 torrent.Add("allowed fast requests sent", 1)
527 panic("requesting while choking and not allowed fast")
530 if cn.t.hashingPiece(pieceIndex(r.Index)) {
531 panic("piece is being hashed")
533 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
534 panic("piece is queued for hash")
536 if cn.requests == nil {
537 cn.requests = make(map[request]struct{})
539 cn.requests[r] = struct{}{}
540 if cn.validReceiveChunks == nil {
541 cn.validReceiveChunks = make(map[request]int)
543 cn.validReceiveChunks[r]++
544 cn.t.pendingRequests[r]++
545 cn.t.requestStrategy.hooks().sentRequest(r)
546 cn.updateExpectingChunks()
547 return cn.PeerImpl.Request(r)
550 func (me *PeerConn) Request(r request) bool {
551 return me.write(pp.Message{
559 func (me *PeerConn) Cancel(r request) bool {
560 return me.write(makeCancelMessage(r))
563 func (cn *peer) doRequestState() bool {
564 if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
565 if !cn.setInterested(false) {
568 if len(cn.requests) != 0 {
569 for r := range cn.requests {
571 // log.Printf("%p: cancelling request: %v", cn, r)
572 if !cn.PeerImpl.Cancel(r) {
577 } else if len(cn.requests) <= cn.requestsLowWater {
578 filledBuffer := false
579 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
580 cn.iterPendingRequests(pieceIndex, func(r request) bool {
581 if !cn.setInterested(true) {
585 if len(cn.requests) >= cn.nominalMaxRequests() {
588 // Choking is looked at here because our interest is dependent
589 // on whether we'd make requests in its absence.
591 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
595 if _, ok := cn.requests[r]; ok {
598 filledBuffer = !cn.request(r)
604 // If we didn't completely top up the requests, we shouldn't mark
605 // the low water, since we'll want to top up the requests as soon
606 // as we have more write buffer space.
609 cn.requestsLowWater = len(cn.requests) / 2
614 func (cn *PeerConn) fillWriteBuffer() {
615 if !cn.doRequestState() {
618 if cn.pex.IsEnabled() {
619 if flow := cn.pex.Share(cn.write); !flow {
626 // Routine that writes to the peer. Some of what to write is buffered by
627 // activity elsewhere in the Client, and some is determined locally when the
628 // connection is writable.
629 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
631 lastWrite time.Time = time.Now()
632 keepAliveTimer *time.Timer
634 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
636 defer cn.locker().Unlock()
637 if time.Since(lastWrite) >= keepAliveTimeout {
640 keepAliveTimer.Reset(keepAliveTimeout)
643 defer cn.locker().Unlock()
645 defer keepAliveTimer.Stop()
646 frontBuf := new(bytes.Buffer)
648 if cn.closed.IsSet() {
651 if cn.writeBuffer.Len() == 0 {
654 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
655 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
656 postedKeepalives.Add(1)
658 if cn.writeBuffer.Len() == 0 {
659 // TODO: Minimize wakeups....
664 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
666 n, err := cn.w.Write(frontBuf.Bytes())
669 lastWrite = time.Now()
670 keepAliveTimer.Reset(keepAliveTimeout)
673 cn.logger.Printf("error writing: %v", err)
676 if n != frontBuf.Len() {
683 func (cn *PeerConn) have(piece pieceIndex) {
684 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
689 Index: pp.Integer(piece),
691 cn.sentHaves.Add(bitmap.BitIndex(piece))
694 func (cn *PeerConn) postBitfield() {
695 if cn.sentHaves.Len() != 0 {
696 panic("bitfield must be first have-related message sent")
698 if !cn.t.haveAnyPieces() {
703 Bitfield: cn.t.bitfield(),
705 cn.sentHaves = cn.t._completedPieces.Copy()
708 func (cn *PeerConn) UpdateRequests() {
709 // log.Print("update requests")
713 // Emits the indices in the Bitmaps bms in order, never repeating any index.
714 // skip is mutated during execution, and its initial values will never be
716 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
717 return func(cb iter.Callback) {
718 for _, bm := range bms {
720 func(i interface{}) bool {
724 bitmap.Sub(bm, *skip).Iter,
732 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
733 now, readahead := cn.torrent().readerPiecePriorities()
734 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
735 skip.Union(cn.torrent().ignorePieces())
736 // Return an iterator over the different priority classes, minus the skip pieces.
738 func(_piece interface{}) bool {
739 return f(pieceIndex(_piece.(bitmap.BitIndex)))
741 iterBitmapsDistinct(&skip, now, readahead),
742 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
743 func(cb iter.Callback) {
744 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
745 if skip.Contains(piece) {
756 // The connection should download highest priority pieces first, without any inclination toward
757 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
758 // fastest connection, and we have active readers that signal an ordering preference. It's
759 // conceivable that the best connection should do this, since it's least likely to waste our time if
760 // assigned to the highest priority pieces, and assigning more than one this role would cause
761 // significant wasted bandwidth.
762 func (cn *peer) shouldRequestWithoutBias() bool {
763 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
766 func (cn *peer) iterPendingPieces(f func(pieceIndex) bool) bool {
767 if !cn.t.haveInfo() {
770 return cn.t.requestStrategy.iterPendingPieces(cn, f)
772 func (cn *peer) iterPendingPiecesUntyped(f iter.Callback) {
773 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
776 func (cn *peer) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
777 return cn.t.requestStrategy.iterUndirtiedChunks(
778 cn.t.piece(piece).requestStrategyPiece(),
779 func(cs chunkSpec) bool {
780 return f(request{pp.Integer(piece), cs})
785 // check callers updaterequests
786 func (cn *peer) stopRequestingPiece(piece pieceIndex) bool {
787 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
790 // This is distinct from Torrent piece priority, which is the user's
791 // preference. Connection piece priority is specific to a connection and is
792 // used to pseudorandomly avoid connections always requesting the same pieces
793 // and thus wasting effort.
794 func (cn *peer) updatePiecePriority(piece pieceIndex) bool {
795 tpp := cn.t.piecePriority(piece)
796 if !cn.peerHasPiece(piece) {
797 tpp = PiecePriorityNone
799 if tpp == PiecePriorityNone {
800 return cn.stopRequestingPiece(piece)
802 prio := cn.getPieceInclination()[piece]
803 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
804 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
807 func (cn *peer) getPieceInclination() []int {
808 if cn.pieceInclination == nil {
809 cn.pieceInclination = cn.t.getConnPieceInclination()
811 return cn.pieceInclination
814 func (cn *peer) discardPieceInclination() {
815 if cn.pieceInclination == nil {
818 cn.t.putPieceInclination(cn.pieceInclination)
819 cn.pieceInclination = nil
822 func (cn *PeerConn) peerPiecesChanged() {
824 prioritiesChanged := false
825 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
826 if cn.updatePiecePriority(i) {
827 prioritiesChanged = true
830 if prioritiesChanged {
836 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
837 if newMin > cn.peerMinPieces {
838 cn.peerMinPieces = newMin
842 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
843 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
844 return errors.New("invalid piece")
846 if cn.peerHasPiece(piece) {
849 cn.raisePeerMinPieces(piece + 1)
850 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
851 if cn.updatePiecePriority(piece) {
857 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
858 cn.peerSentHaveAll = false
860 panic("expected bitfield length divisible by 8")
862 // We know that the last byte means that at most the last 7 bits are
864 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
865 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
866 // Ignore known excess pieces.
867 bf = bf[:cn.t.numPieces()]
869 for i, have := range bf {
871 cn.raisePeerMinPieces(pieceIndex(i) + 1)
873 cn._peerPieces.Set(i, have)
875 cn.peerPiecesChanged()
879 func (cn *PeerConn) onPeerSentHaveAll() error {
880 cn.peerSentHaveAll = true
881 cn._peerPieces.Clear()
882 cn.peerPiecesChanged()
886 func (cn *PeerConn) peerSentHaveNone() error {
887 cn._peerPieces.Clear()
888 cn.peerSentHaveAll = false
889 cn.peerPiecesChanged()
893 func (c *PeerConn) requestPendingMetadata() {
897 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
898 // Peer doesn't support this.
901 // Request metadata pieces that we don't have in a random order.
903 for index := 0; index < c.t.metadataPieceCount(); index++ {
904 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
905 pending = append(pending, index)
908 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
909 for _, i := range pending {
910 c.requestMetadataPiece(i)
914 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
915 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
916 if msg.Type == pp.Extended {
917 for name, id := range cn.PeerExtensionIDs {
918 if id != msg.ExtendedID {
921 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
924 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
927 func (cn *PeerConn) readMsg(msg *pp.Message) {
928 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
931 // After handshake, we know what Torrent and Client stats to include for a
933 func (cn *peer) postHandshakeStats(f func(*ConnStats)) {
939 // All ConnStats that include this connection. Some objects are not known
940 // until the handshake is complete, after which it's expected to reconcile the
942 func (cn *peer) allStats(f func(*ConnStats)) {
944 if cn.reconciledHandshakeStats {
945 cn.postHandshakeStats(f)
949 func (cn *PeerConn) wroteBytes(n int64) {
950 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
953 func (cn *PeerConn) readBytes(n int64) {
954 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
957 // Returns whether the connection could be useful to us. We're seeding and
958 // they want data, we don't have metainfo and they can provide it, etc.
959 func (c *peer) useful() bool {
961 if c.closed.IsSet() {
965 return c.supportsExtension("ut_metadata")
967 if t.seeding() && c.peerInterested {
970 if c.peerHasWantedPieces() {
976 func (c *peer) lastHelpful() (ret time.Time) {
977 ret = c.lastUsefulChunkReceived
978 if c.t.seeding() && c.lastChunkSent.After(ret) {
979 ret = c.lastChunkSent
984 func (c *PeerConn) fastEnabled() bool {
985 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
988 func (c *PeerConn) reject(r request) {
989 if !c.fastEnabled() {
990 panic("fast not enabled")
992 c.post(r.ToMsg(pp.Reject))
993 delete(c.peerRequests, r)
996 func (c *PeerConn) onReadRequest(r request) error {
997 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
998 if _, ok := c.peerRequests[r]; ok {
999 torrent.Add("duplicate requests received", 1)
1003 torrent.Add("requests received while choking", 1)
1004 if c.fastEnabled() {
1005 torrent.Add("requests rejected while choking", 1)
1010 if len(c.peerRequests) >= maxRequests {
1011 torrent.Add("requests received while queue full", 1)
1012 if c.fastEnabled() {
1015 // BEP 6 says we may close here if we choose.
1018 if !c.t.havePiece(pieceIndex(r.Index)) {
1019 // This isn't necessarily them screwing up. We can drop pieces
1020 // from our storage, and can't communicate this to peers
1021 // except by reconnecting.
1022 requestsReceivedForMissingPieces.Add(1)
1023 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1025 // Check this after we know we have the piece, so that the piece length will be known.
1026 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1027 torrent.Add("bad requests received", 1)
1028 return errors.New("bad request")
1030 if c.peerRequests == nil {
1031 c.peerRequests = make(map[request]struct{}, maxRequests)
1033 c.peerRequests[r] = struct{}{}
1038 func runSafeExtraneous(f func()) {
1046 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1047 // exit. Returning will end the connection.
1048 func (c *PeerConn) mainReadLoop() (err error) {
1051 torrent.Add("connection.mainReadLoop returned with error", 1)
1053 torrent.Add("connection.mainReadLoop returned with no error", 1)
1059 decoder := pp.Decoder{
1060 R: bufio.NewReaderSize(c.r, 1<<17),
1061 MaxLength: 256 * 1024,
1069 err = decoder.Decode(&msg)
1071 if t.closed.IsSet() || c.closed.IsSet() {
1078 c.lastMessageReceived = time.Now()
1080 receivedKeepalives.Add(1)
1083 messageTypesReceived.Add(msg.Type.String(), 1)
1084 if msg.Type.FastExtension() && !c.fastEnabled() {
1085 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1086 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1090 c.peerChoking = true
1091 if !c.fastEnabled() {
1092 c.deleteAllRequests()
1094 // We can then reset our interest.
1096 c.updateExpectingChunks()
1098 c.peerChoking = false
1100 c.updateExpectingChunks()
1102 c.peerInterested = true
1104 case pp.NotInterested:
1105 c.peerInterested = false
1106 // We don't clear their requests since it isn't clear in the spec.
1107 // We'll probably choke them for this, which will clear them if
1108 // appropriate, and is clearly specified.
1110 err = c.peerSentHave(pieceIndex(msg.Index))
1112 err = c.peerSentBitfield(msg.Bitfield)
1114 r := newRequestFromMessage(&msg)
1115 err = c.onReadRequest(r)
1117 err = c.receiveChunk(&msg)
1118 if len(msg.Piece) == int(t.chunkSize) {
1119 t.chunkPool.Put(&msg.Piece)
1122 err = fmt.Errorf("receiving chunk: %s", err)
1125 req := newRequestFromMessage(&msg)
1126 c.onPeerSentCancel(req)
1128 ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1132 pingAddr := net.UDPAddr{
1137 pingAddr.Port = int(msg.Port)
1139 cl.eachDhtServer(func(s DhtServer) {
1140 go s.Ping(&pingAddr)
1143 torrent.Add("suggests received", 1)
1144 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1147 err = c.onPeerSentHaveAll()
1149 err = c.peerSentHaveNone()
1151 c.deleteRequest(newRequestFromMessage(&msg))
1152 c.decExpectedChunkReceive(newRequestFromMessage(&msg))
1153 case pp.AllowedFast:
1154 torrent.Add("allowed fasts received", 1)
1155 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1156 c.peerAllowedFast.Add(int(msg.Index))
1159 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1161 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1169 func (c *peer) decExpectedChunkReceive(r request) {
1170 count := c.validReceiveChunks[r]
1172 delete(c.validReceiveChunks, r)
1173 } else if count > 1 {
1174 c.validReceiveChunks[r] = count - 1
1180 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1182 // TODO: Should we still do this?
1184 // These clients use their own extension IDs for outgoing message
1185 // types, which is incorrect.
1186 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1194 case pp.HandshakeExtendedID:
1195 var d pp.ExtendedHandshakeMessage
1196 if err := bencode.Unmarshal(payload, &d); err != nil {
1197 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1198 return errors.Wrap(err, "unmarshalling extended handshake payload")
1200 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1202 c.PeerMaxRequests = d.Reqq
1204 c.PeerClientName = d.V
1205 if c.PeerExtensionIDs == nil {
1206 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1208 c.PeerListenPort = d.Port
1209 c.PeerPrefersEncryption = d.Encryption
1210 for name, id := range d.M {
1211 if _, ok := c.PeerExtensionIDs[name]; !ok {
1212 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1214 c.PeerExtensionIDs[name] = id
1216 if d.MetadataSize != 0 {
1217 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1218 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1221 c.requestPendingMetadata()
1222 if !t.cl.config.DisablePEX {
1223 t.pex.Add(c) // we learnt enough now
1227 case metadataExtendedId:
1228 err := cl.gotMetadataExtensionMsg(payload, t, c)
1230 return fmt.Errorf("handling metadata extension message: %w", err)
1234 if !c.pex.IsEnabled() {
1235 return nil // or hang-up maybe?
1237 return c.pex.Recv(payload)
1239 return fmt.Errorf("unexpected extended message ID: %v", id)
1243 // Set both the Reader and Writer for the connection from a single ReadWriter.
1244 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1249 // Returns the Reader and Writer as a combined ReadWriter.
1250 func (cn *PeerConn) rw() io.ReadWriter {
1257 // Handle a received chunk from a peer.
1258 func (c *peer) receiveChunk(msg *pp.Message) error {
1261 torrent.Add("chunks received", 1)
1263 req := newRequestFromMessage(msg)
1266 torrent.Add("chunks received while choking", 1)
1269 if c.validReceiveChunks[req] <= 0 {
1270 torrent.Add("chunks received unexpected", 1)
1271 return errors.New("received unexpected chunk")
1273 c.decExpectedChunkReceive(req)
1275 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1276 torrent.Add("chunks received due to allowed fast", 1)
1279 // Request has been satisfied.
1280 if c.deleteRequest(req) {
1281 if c.expectingChunks() {
1282 c._chunksReceivedWhileExpecting++
1285 torrent.Add("chunks received unwanted", 1)
1288 // Do we actually want this chunk?
1289 if t.haveChunk(req) {
1290 torrent.Add("chunks received wasted", 1)
1291 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1295 piece := &t.pieces[req.Index]
1297 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1298 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1299 c.lastUsefulChunkReceived = time.Now()
1300 // if t.fastestConn != c {
1301 // log.Printf("setting fastest connection %p", c)
1305 // Need to record that it hasn't been written yet, before we attempt to do
1306 // anything with it.
1307 piece.incrementPendingWrites()
1308 // Record that we have the chunk, so we aren't trying to download it while
1309 // waiting for it to be written to storage.
1310 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1312 // Cancel pending requests for this chunk.
1313 for c := range t.conns {
1317 err := func() error {
1320 concurrentChunkWrites.Add(1)
1321 defer concurrentChunkWrites.Add(-1)
1322 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1323 // number of connections. We write inline with receiving the chunk (with this lock dance),
1324 // because we want to handle errors synchronously and I haven't thought of a nice way to
1325 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1327 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1330 piece.decrementPendingWrites()
1333 c.logger.Printf("error writing received chunk %v: %v", req, err)
1335 //t.updatePieceCompletion(pieceIndex(msg.Index))
1336 t.onWriteChunkErr(err)
1340 c.onDirtiedPiece(pieceIndex(req.Index))
1342 if t.pieceAllDirty(pieceIndex(req.Index)) {
1343 t.queuePieceCheck(pieceIndex(req.Index))
1344 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1345 // chunk status (such as the haveChunk call above) to have to check all the various other
1346 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1347 // that chunk pieces are pended at an appropriate time later however.
1350 cl.event.Broadcast()
1351 // We do this because we've written a chunk, and may change PieceState.Partial.
1352 t.publishPieceChange(pieceIndex(req.Index))
1357 func (c *peer) onDirtiedPiece(piece pieceIndex) {
1358 if c.peerTouchedPieces == nil {
1359 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1361 c.peerTouchedPieces[piece] = struct{}{}
1362 ds := &c.t.pieces[piece].dirtiers
1364 *ds = make(map[*peer]struct{})
1366 (*ds)[c] = struct{}{}
1369 func (c *PeerConn) uploadAllowed() bool {
1370 if c.t.cl.config.NoUpload {
1376 if !c.peerHasWantedPieces() {
1379 // Don't upload more than 100 KiB more than we download.
1380 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1386 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1387 if c.uploadTimer == nil {
1388 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1390 c.uploadTimer.Reset(delay)
1394 // Also handles choking and unchoking of the remote peer.
1395 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1396 // Breaking or completing this loop means we don't want to upload to the
1397 // peer anymore, and we choke them.
1399 for c.uploadAllowed() {
1400 // We want to upload to the peer.
1401 if !c.unchoke(msg) {
1404 for r := range c.peerRequests {
1405 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1407 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1409 delay := res.Delay()
1412 c.setRetryUploadTimer(delay)
1413 // Hard to say what to return here.
1416 more, err := c.sendChunk(r, msg)
1418 i := pieceIndex(r.Index)
1419 if c.t.pieceComplete(i) {
1420 c.t.updatePieceCompletion(i)
1421 if !c.t.pieceComplete(i) {
1422 // We had the piece, but not anymore.
1426 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1427 // If we failed to send a chunk, choke the peer to ensure they
1428 // flush all their requests. We've probably dropped a piece,
1429 // but there's no way to communicate this to the peer. If they
1430 // ask for it again, we'll kick them to allow us to send them
1431 // an updated bitfield.
1434 delete(c.peerRequests, r)
1445 func (cn *PeerConn) Drop() {
1446 cn.t.dropConnection(cn)
1449 func (cn *peer) netGoodPiecesDirtied() int64 {
1450 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1453 func (c *peer) peerHasWantedPieces() bool {
1454 return !c._pieceRequestOrder.IsEmpty()
1457 func (c *peer) numLocalRequests() int {
1458 return len(c.requests)
1461 func (c *peer) deleteRequest(r request) bool {
1462 if _, ok := c.requests[r]; !ok {
1465 delete(c.requests, r)
1466 c.updateExpectingChunks()
1467 c.t.requestStrategy.hooks().deletedRequest(r)
1468 pr := c.t.pendingRequests
1478 c.t.iterPeers(func(_c *peer) {
1479 if !_c.interested && _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1486 func (c *peer) deleteAllRequests() {
1487 for r := range c.requests {
1490 if len(c.requests) != 0 {
1491 panic(len(c.requests))
1493 // for c := range c.t.conns {
1498 func (c *PeerConn) tickleWriter() {
1499 c.writerCond.Broadcast()
1502 func (c *peer) postCancel(r request) bool {
1503 if !c.deleteRequest(r) {
1506 c.PeerImpl.PostCancel(r)
1510 func (c *PeerConn) PostCancel(r request) {
1511 c.post(makeCancelMessage(r))
1514 func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1515 // Count the chunk being sent, even if it isn't.
1516 b := make([]byte, r.Length)
1517 p := c.t.info.Piece(int(r.Index))
1518 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1521 panic("expected error")
1524 } else if err == io.EOF {
1527 more = msg(pp.Message{
1533 c.lastChunkSent = time.Now()
1537 func (c *PeerConn) setTorrent(t *Torrent) {
1539 panic("connection already associated with a torrent")
1542 c.logger.Printf("torrent=%v", t)
1543 t.reconcileHandshakeStats(c)
1546 func (c *peer) peerPriority() (peerPriority, error) {
1547 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1550 func (c *peer) remoteIp() net.IP {
1551 return addrIpOrNil(c.remoteAddr)
1554 func (c *peer) remoteIpPort() IpPort {
1555 ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1556 return IpPort{ipa.IP, uint16(ipa.Port)}
1559 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1560 f := pp.PexPeerFlags(0)
1561 if c.PeerPrefersEncryption {
1562 f |= pp.PexPrefersEncryption
1565 f |= pp.PexOutgoingConn
1567 if c.remoteAddr != nil && strings.Contains(c.remoteAddr.Network(), "udp") {
1568 f |= pp.PexSupportsUtp
1573 func (c *PeerConn) dialAddr() net.Addr {
1574 if !c.outgoing && c.PeerListenPort != 0 {
1575 switch addr := c.remoteAddr.(type) {
1578 dialAddr.Port = c.PeerListenPort
1582 dialAddr.Port = c.PeerListenPort
1589 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1590 f := c.pexPeerFlags()
1591 addr := c.dialAddr()
1592 return pexEvent{t, addr, f}
1595 func (c *PeerConn) String() string {
1596 return fmt.Sprintf("connection %p", c)
1599 func (c *peer) trust() connectionTrust {
1600 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1603 type connectionTrust struct {
1605 NetGoodPiecesDirted int64
1608 func (l connectionTrust) Less(r connectionTrust) bool {
1609 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1612 func (cn *peer) requestStrategyConnection() requestStrategyConnection {
1616 func (cn *peer) chunksReceivedWhileExpecting() int64 {
1617 return cn._chunksReceivedWhileExpecting
1620 func (cn *peer) fastest() bool {
1621 return cn == cn.t.fastestConn
1624 func (cn *peer) peerMaxRequests() int {
1625 return cn.PeerMaxRequests
1628 // Returns the pieces the peer has claimed to have.
1629 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1631 defer cn.locker().RUnlock()
1632 return cn.peerPieces()
1635 func (cn *peer) peerPieces() bitmap.Bitmap {
1636 ret := cn._peerPieces.Copy()
1637 if cn.peerSentHaveAll {
1638 ret.AddRange(0, cn.t.numPieces())
1643 func (cn *peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1644 return &cn._pieceRequestOrder
1647 func (cn *peer) stats() *ConnStats {
1651 func (cn *peer) torrent() requestStrategyTorrent {
1652 return cn.t.requestStrategyTorrent()