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/anacrolix/torrent/metainfo"
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.
37 // The peer was given directly, such as through a magnet link.
38 PeerSourceDirect = "M"
41 type peerRequestState struct {
46 // First to ensure 64-bit alignment for atomics. See #262.
56 // True if the connection is operating over MSE obfuscation.
58 cryptoMethod mse.CryptoMethod
61 closed missinggo.Event
62 // Set true after we've added our ConnStats generated during handshake to
63 // other ConnStat instances as determined when the *Torrent became known.
64 reconciledHandshakeStats bool
66 lastMessageReceived time.Time
67 completedHandshake time.Time
68 lastUsefulChunkReceived time.Time
69 lastChunkSent time.Time
71 // Stuff controlled by the local peer.
73 lastBecameInterested time.Time
74 priorInterest time.Duration
76 lastStartedExpectingToReceiveChunks time.Time
77 cumulativeExpectedToReceiveChunks time.Duration
78 _chunksReceivedWhileExpecting int64
81 requests map[request]struct{}
83 // Chunks that we might reasonably expect to receive from the peer. Due to
84 // latency, buffering, and implementation differences, we may receive
85 // chunks that are no longer in the set of requests actually want.
86 validReceiveChunks map[request]int
87 // Indexed by metadata piece, set to true if posted and pending a
89 metadataRequests []bool
90 sentHaves bitmap.Bitmap
92 // Stuff controlled by the remote peer.
95 peerRequests map[request]*peerRequestState
96 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
98 // The pieces the peer has claimed to have.
99 _peerPieces bitmap.Bitmap
100 // The peer has everything. This can occur due to a special message, when
101 // we may not even know the number of pieces in the torrent yet.
103 // The highest possible number of pieces the torrent could have based on
104 // communication with the peer. Generally only useful until we have the
106 peerMinPieces pieceIndex
107 // Pieces we've accepted chunks for from the peer.
108 peerTouchedPieces map[pieceIndex]struct{}
109 peerAllowedFast bitmap.Bitmap
111 PeerMaxRequests int // Maximum pending requests the peer allows.
112 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
113 PeerClientName string
115 pieceInclination []int
116 _pieceRequestOrder prioritybitmap.PriorityBitmap
121 // Maintains the state of a BitTorrent-protocol based connection with a peer.
122 type PeerConn struct {
125 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
126 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
131 PeerExtensionBytes pp.PeerExtensionBits
133 // The actual Conn, used for closing, and setting socket options.
135 // The Reader and Writer for this Conn, with hooks installed for stats,
136 // limiting, deadlines etc.
140 writeBuffer *bytes.Buffer
141 uploadTimer *time.Timer
149 func (cn *PeerConn) connStatusString() string {
150 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
153 func (cn *peer) updateExpectingChunks() {
154 if cn.expectingChunks() {
155 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
156 cn.lastStartedExpectingToReceiveChunks = time.Now()
159 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
160 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
161 cn.lastStartedExpectingToReceiveChunks = time.Time{}
166 func (cn *peer) expectingChunks() bool {
167 return cn.interested && !cn.peerChoking
170 // Returns true if the connection is over IPv6.
171 func (cn *PeerConn) ipv6() bool {
172 ip := addrIpOrNil(cn.RemoteAddr)
176 return len(ip) == net.IPv6len
179 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
180 // specification for this.
181 func (cn *PeerConn) isPreferredDirection() bool {
182 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
185 // Returns whether the left connection should be preferred over the right one,
186 // considering only their networking properties. If ok is false, we can't
188 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
190 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
191 ml.NextBool(!l.utp(), !r.utp())
192 ml.NextBool(l.ipv6(), r.ipv6())
196 func (cn *peer) cumInterest() time.Duration {
197 ret := cn.priorInterest
199 ret += time.Since(cn.lastBecameInterested)
204 func (cn *peer) peerHasAllPieces() (all bool, known bool) {
205 if cn.peerSentHaveAll {
208 if !cn.t.haveInfo() {
211 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
214 func (cn *PeerConn) locker() *lockWithDeferreds {
215 return cn.t.cl.locker()
218 func (cn *peer) supportsExtension(ext pp.ExtensionName) bool {
219 _, ok := cn.PeerExtensionIDs[ext]
223 // The best guess at number of pieces in the torrent for this peer.
224 func (cn *peer) bestPeerNumPieces() pieceIndex {
226 return cn.t.numPieces()
228 return cn.peerMinPieces
231 func (cn *peer) completedString() string {
232 have := pieceIndex(cn._peerPieces.Len())
233 if cn.peerSentHaveAll {
234 have = cn.bestPeerNumPieces()
236 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
239 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
240 cn.setNumPieces(info.NumPieces())
243 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
244 // receiving badly sized BITFIELD, or invalid HAVE messages.
245 func (cn *PeerConn) setNumPieces(num pieceIndex) {
246 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
247 cn.peerPiecesChanged()
250 func eventAgeString(t time.Time) string {
254 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
257 func (cn *PeerConn) connectionFlags() (ret string) {
259 ret += string([]byte{b})
261 if cn.cryptoMethod == mse.CryptoMethodRC4 {
263 } else if cn.headerEncrypted {
266 ret += string(cn.Discovery)
273 func (cn *PeerConn) utp() bool {
274 return parseNetworkString(cn.network).Udp
277 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
278 func (cn *peer) statusFlags() (ret string) {
280 ret += string([]byte{b})
289 ret += cn.connectionFlags()
291 if cn.peerInterested {
300 // func (cn *connection) String() string {
301 // var buf bytes.Buffer
302 // cn.writeStatus(&buf, nil)
303 // return buf.String()
306 func (cn *peer) downloadRate() float64 {
307 return float64(cn._stats.BytesReadUsefulData.Int64()) / cn.cumInterest().Seconds()
310 func (cn *peer) writeStatus(w io.Writer, t *Torrent) {
311 // \t isn't preserved in <pre> blocks?
312 fmt.Fprintln(w, cn.connStatusString())
313 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
314 eventAgeString(cn.lastMessageReceived),
315 eventAgeString(cn.completedHandshake),
316 eventAgeString(cn.lastHelpful()),
318 cn.totalExpectingTime(),
321 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: (%d,%d,%d]-%d, flags: %s, dr: %.1f KiB/s\n",
322 cn.completedString(),
323 len(cn.peerTouchedPieces),
324 &cn._stats.ChunksReadUseful,
325 &cn._stats.ChunksRead,
326 &cn._stats.ChunksWritten,
328 cn.numLocalRequests(),
329 cn.nominalMaxRequests(),
330 len(cn.peerRequests),
332 cn.downloadRate()/(1<<10),
334 fmt.Fprintf(w, " next pieces: %v%s\n",
335 iter.ToSlice(iter.Head(10, cn.iterPendingPiecesUntyped)),
337 if cn == t.fastestPeer {
346 func (cn *peer) close() {
347 if !cn.closed.Set() {
350 cn.discardPieceInclination()
351 cn._pieceRequestOrder.Clear()
352 cn.peerImpl.onClose()
355 func (cn *PeerConn) onClose() {
356 if cn.pex.IsEnabled() {
363 if cb := cn.callbacks.PeerConnClosed; cb != nil {
368 func (cn *peer) peerHasPiece(piece pieceIndex) bool {
369 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
372 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
373 // https://github.com/pion/datachannel/issues/59 is fixed.
374 const writeBufferHighWaterLen = 1 << 15
376 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Posting is
377 // done asynchronously, so it may be that we're not able to honour backpressure from this method. It
378 // might be possible to merge this with PeerConn.write down the track? They seem to be very similar.
379 func (cn *PeerConn) post(msg pp.Message) bool {
380 torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1)
381 // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
382 // (although there's some delay between us recording the message, and the connection writer
383 // flushing it out.).
384 cn.writeBuffer.Write(msg.MustMarshalBinary())
385 // Last I checked only Piece messages affect stats, and we don't post those.
388 return cn.writeBuffer.Len() < writeBufferHighWaterLen
391 // Returns true if there's room to write more.
392 func (cn *PeerConn) write(msg pp.Message) bool {
394 cn.writeBuffer.Write(msg.MustMarshalBinary())
395 torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1)
396 return cn.writeBuffer.Len() < writeBufferHighWaterLen
399 func (cn *PeerConn) requestMetadataPiece(index int) {
400 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
404 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
407 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
411 ExtendedPayload: func() []byte {
412 b, err := bencode.Marshal(map[string]int{
413 "msg_type": pp.RequestMetadataExtensionMsgType,
422 for index >= len(cn.metadataRequests) {
423 cn.metadataRequests = append(cn.metadataRequests, false)
425 cn.metadataRequests[index] = true
428 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
429 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
432 // The actual value to use as the maximum outbound requests.
433 func (cn *peer) nominalMaxRequests() (ret int) {
436 int64(cn.PeerMaxRequests),
437 int64(cn.t.requestStrategy.nominalMaxRequests(cn.requestStrategyConnection())),
441 func (cn *peer) totalExpectingTime() (ret time.Duration) {
442 ret = cn.cumulativeExpectedToReceiveChunks
443 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
444 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
450 func (cn *PeerConn) onPeerSentCancel(r request) {
451 if _, ok := cn.peerRequests[r]; !ok {
452 torrent.Add("unexpected cancels received", 1)
455 if cn.fastEnabled() {
458 delete(cn.peerRequests, r)
462 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
467 more = msg(pp.Message{
470 if cn.fastEnabled() {
471 for r := range cn.peerRequests {
472 // TODO: Don't reject pieces in allowed fast set.
476 cn.peerRequests = nil
481 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
486 return msg(pp.Message{
491 func (cn *peer) setInterested(interested bool) bool {
492 if cn.interested == interested {
495 cn.interested = interested
497 cn.lastBecameInterested = time.Now()
498 } else if !cn.lastBecameInterested.IsZero() {
499 cn.priorInterest += time.Since(cn.lastBecameInterested)
501 cn.updateExpectingChunks()
502 // log.Printf("%p: setting interest: %v", cn, interested)
503 return cn.writeInterested(interested)
506 func (pc *PeerConn) writeInterested(interested bool) bool {
507 return pc.write(pp.Message{
508 Type: func() pp.MessageType {
512 return pp.NotInterested
518 // The function takes a message to be sent, and returns true if more messages
520 type messageWriter func(pp.Message) bool
522 func (cn *peer) request(r request) bool {
523 if _, ok := cn.requests[r]; ok {
524 panic("chunk already requested")
526 if !cn.peerHasPiece(pieceIndex(r.Index)) {
527 panic("requesting piece peer doesn't have")
529 if !cn.t.peerIsActive(cn) {
530 panic("requesting but not in active conns")
532 if cn.closed.IsSet() {
533 panic("requesting when connection is closed")
536 if cn.peerAllowedFast.Get(int(r.Index)) {
537 torrent.Add("allowed fast requests sent", 1)
539 panic("requesting while choking and not allowed fast")
542 if cn.t.hashingPiece(pieceIndex(r.Index)) {
543 panic("piece is being hashed")
545 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
546 panic("piece is queued for hash")
548 if cn.requests == nil {
549 cn.requests = make(map[request]struct{})
551 cn.requests[r] = struct{}{}
552 if cn.validReceiveChunks == nil {
553 cn.validReceiveChunks = make(map[request]int)
555 cn.validReceiveChunks[r]++
556 cn.t.pendingRequests[r]++
557 cn.t.requestStrategy.hooks().sentRequest(r)
558 cn.updateExpectingChunks()
559 return cn.peerImpl.request(r)
562 func (me *PeerConn) request(r request) bool {
563 return me.write(pp.Message{
571 func (me *PeerConn) cancel(r request) bool {
572 return me.write(makeCancelMessage(r))
575 func (cn *peer) doRequestState() bool {
576 if !cn.t.networkingEnabled || cn.t.dataDownloadDisallowed {
577 if !cn.setInterested(false) {
580 if len(cn.requests) != 0 {
581 for r := range cn.requests {
583 // log.Printf("%p: cancelling request: %v", cn, r)
584 if !cn.peerImpl.cancel(r) {
589 } else if len(cn.requests) <= cn.requestsLowWater {
590 filledBuffer := false
591 cn.iterPendingPieces(func(pieceIndex pieceIndex) bool {
592 cn.iterPendingRequests(pieceIndex, func(r request) bool {
593 if !cn.setInterested(true) {
597 if len(cn.requests) >= cn.nominalMaxRequests() {
600 // Choking is looked at here because our interest is dependent
601 // on whether we'd make requests in its absence.
603 if !cn.peerAllowedFast.Get(bitmap.BitIndex(r.Index)) {
607 if _, ok := cn.requests[r]; ok {
610 filledBuffer = !cn.request(r)
616 // If we didn't completely top up the requests, we shouldn't mark
617 // the low water, since we'll want to top up the requests as soon
618 // as we have more write buffer space.
621 cn.requestsLowWater = len(cn.requests) / 2
626 func (cn *PeerConn) fillWriteBuffer() {
627 if !cn.doRequestState() {
630 if cn.pex.IsEnabled() {
631 if flow := cn.pex.Share(cn.write); !flow {
638 // Routine that writes to the peer. Some of what to write is buffered by
639 // activity elsewhere in the Client, and some is determined locally when the
640 // connection is writable.
641 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
643 lastWrite time.Time = time.Now()
644 keepAliveTimer *time.Timer
646 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
648 defer cn.locker().Unlock()
649 if time.Since(lastWrite) >= keepAliveTimeout {
652 keepAliveTimer.Reset(keepAliveTimeout)
655 defer cn.locker().Unlock()
657 defer keepAliveTimer.Stop()
658 frontBuf := new(bytes.Buffer)
660 if cn.closed.IsSet() {
663 if cn.writeBuffer.Len() == 0 {
666 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
667 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
668 postedKeepalives.Add(1)
670 if cn.writeBuffer.Len() == 0 {
671 // TODO: Minimize wakeups....
676 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
678 n, err := cn.w.Write(frontBuf.Bytes())
681 lastWrite = time.Now()
682 keepAliveTimer.Reset(keepAliveTimeout)
685 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
688 if n != frontBuf.Len() {
695 func (cn *PeerConn) have(piece pieceIndex) {
696 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
701 Index: pp.Integer(piece),
703 cn.sentHaves.Add(bitmap.BitIndex(piece))
706 func (cn *PeerConn) postBitfield() {
707 if cn.sentHaves.Len() != 0 {
708 panic("bitfield must be first have-related message sent")
710 if !cn.t.haveAnyPieces() {
715 Bitfield: cn.t.bitfield(),
717 cn.sentHaves = cn.t._completedPieces.Copy()
720 func (cn *PeerConn) updateRequests() {
721 // log.Print("update requests")
725 // Emits the indices in the Bitmaps bms in order, never repeating any index.
726 // skip is mutated during execution, and its initial values will never be
728 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
729 return func(cb iter.Callback) {
730 for _, bm := range bms {
732 func(i interface{}) bool {
736 bitmap.Sub(bm, *skip).Iter,
744 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
745 now, readahead := cn.torrent().readerPiecePriorities()
746 skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
747 skip.Union(cn.torrent().ignorePieces())
748 // Return an iterator over the different priority classes, minus the skip pieces.
750 func(_piece interface{}) bool {
751 return f(pieceIndex(_piece.(bitmap.BitIndex)))
753 iterBitmapsDistinct(&skip, now, readahead),
754 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
755 func(cb iter.Callback) {
756 cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
757 if skip.Contains(piece) {
768 // The connection should download highest priority pieces first, without any inclination toward
769 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
770 // fastest connection, and we have active readers that signal an ordering preference. It's
771 // conceivable that the best connection should do this, since it's least likely to waste our time if
772 // assigned to the highest priority pieces, and assigning more than one this role would cause
773 // significant wasted bandwidth.
774 func (cn *peer) shouldRequestWithoutBias() bool {
775 return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
778 func (cn *peer) iterPendingPieces(f func(pieceIndex) bool) bool {
779 if !cn.t.haveInfo() {
782 return cn.t.requestStrategy.iterPendingPieces(cn, f)
784 func (cn *peer) iterPendingPiecesUntyped(f iter.Callback) {
785 cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
788 func (cn *peer) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
789 return cn.t.requestStrategy.iterUndirtiedChunks(
790 cn.t.piece(piece).requestStrategyPiece(),
791 func(cs chunkSpec) bool {
792 return f(request{pp.Integer(piece), cs})
797 // check callers updaterequests
798 func (cn *peer) stopRequestingPiece(piece pieceIndex) bool {
799 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
802 // This is distinct from Torrent piece priority, which is the user's
803 // preference. Connection piece priority is specific to a connection and is
804 // used to pseudorandomly avoid connections always requesting the same pieces
805 // and thus wasting effort.
806 func (cn *peer) updatePiecePriority(piece pieceIndex) bool {
807 tpp := cn.t.piecePriority(piece)
808 if !cn.peerHasPiece(piece) {
809 tpp = PiecePriorityNone
811 if tpp == PiecePriorityNone {
812 return cn.stopRequestingPiece(piece)
814 prio := cn.getPieceInclination()[piece]
815 prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
816 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
819 func (cn *peer) getPieceInclination() []int {
820 if cn.pieceInclination == nil {
821 cn.pieceInclination = cn.t.getConnPieceInclination()
823 return cn.pieceInclination
826 func (cn *peer) discardPieceInclination() {
827 if cn.pieceInclination == nil {
830 cn.t.putPieceInclination(cn.pieceInclination)
831 cn.pieceInclination = nil
834 func (cn *PeerConn) peerPiecesChanged() {
836 prioritiesChanged := false
837 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
838 if cn.updatePiecePriority(i) {
839 prioritiesChanged = true
842 if prioritiesChanged {
848 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
849 if newMin > cn.peerMinPieces {
850 cn.peerMinPieces = newMin
854 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
855 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
856 return errors.New("invalid piece")
858 if cn.peerHasPiece(piece) {
861 cn.raisePeerMinPieces(piece + 1)
862 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
863 if cn.updatePiecePriority(piece) {
869 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
870 cn.peerSentHaveAll = false
872 panic("expected bitfield length divisible by 8")
874 // We know that the last byte means that at most the last 7 bits are
876 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
877 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
878 // Ignore known excess pieces.
879 bf = bf[:cn.t.numPieces()]
881 for i, have := range bf {
883 cn.raisePeerMinPieces(pieceIndex(i) + 1)
885 cn._peerPieces.Set(i, have)
887 cn.peerPiecesChanged()
891 func (cn *PeerConn) onPeerSentHaveAll() error {
892 cn.peerSentHaveAll = true
893 cn._peerPieces.Clear()
894 cn.peerPiecesChanged()
898 func (cn *PeerConn) peerSentHaveNone() error {
899 cn._peerPieces.Clear()
900 cn.peerSentHaveAll = false
901 cn.peerPiecesChanged()
905 func (c *PeerConn) requestPendingMetadata() {
909 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
910 // Peer doesn't support this.
913 // Request metadata pieces that we don't have in a random order.
915 for index := 0; index < c.t.metadataPieceCount(); index++ {
916 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
917 pending = append(pending, index)
920 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
921 for _, i := range pending {
922 c.requestMetadataPiece(i)
926 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
927 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
928 if msg.Type == pp.Extended {
929 for name, id := range cn.PeerExtensionIDs {
930 if id != msg.ExtendedID {
933 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
936 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
939 func (cn *PeerConn) readMsg(msg *pp.Message) {
940 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
943 // After handshake, we know what Torrent and Client stats to include for a
945 func (cn *peer) postHandshakeStats(f func(*ConnStats)) {
951 // All ConnStats that include this connection. Some objects are not known
952 // until the handshake is complete, after which it's expected to reconcile the
954 func (cn *peer) allStats(f func(*ConnStats)) {
956 if cn.reconciledHandshakeStats {
957 cn.postHandshakeStats(f)
961 func (cn *PeerConn) wroteBytes(n int64) {
962 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
965 func (cn *PeerConn) readBytes(n int64) {
966 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
969 // Returns whether the connection could be useful to us. We're seeding and
970 // they want data, we don't have metainfo and they can provide it, etc.
971 func (c *peer) useful() bool {
973 if c.closed.IsSet() {
977 return c.supportsExtension("ut_metadata")
979 if t.seeding() && c.peerInterested {
982 if c.peerHasWantedPieces() {
988 func (c *peer) lastHelpful() (ret time.Time) {
989 ret = c.lastUsefulChunkReceived
990 if c.t.seeding() && c.lastChunkSent.After(ret) {
991 ret = c.lastChunkSent
996 func (c *PeerConn) fastEnabled() bool {
997 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
1000 func (c *PeerConn) reject(r request) {
1001 if !c.fastEnabled() {
1002 panic("fast not enabled")
1004 c.post(r.ToMsg(pp.Reject))
1005 delete(c.peerRequests, r)
1008 func (c *PeerConn) onReadRequest(r request) error {
1009 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1010 if _, ok := c.peerRequests[r]; ok {
1011 torrent.Add("duplicate requests received", 1)
1015 torrent.Add("requests received while choking", 1)
1016 if c.fastEnabled() {
1017 torrent.Add("requests rejected while choking", 1)
1022 if len(c.peerRequests) >= maxRequests {
1023 torrent.Add("requests received while queue full", 1)
1024 if c.fastEnabled() {
1027 // BEP 6 says we may close here if we choose.
1030 if !c.t.havePiece(pieceIndex(r.Index)) {
1031 // This isn't necessarily them screwing up. We can drop pieces
1032 // from our storage, and can't communicate this to peers
1033 // except by reconnecting.
1034 requestsReceivedForMissingPieces.Add(1)
1035 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1037 // Check this after we know we have the piece, so that the piece length will be known.
1038 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1039 torrent.Add("bad requests received", 1)
1040 return errors.New("bad request")
1042 if c.peerRequests == nil {
1043 c.peerRequests = make(map[request]*peerRequestState, maxRequests)
1045 value := &peerRequestState{}
1046 c.peerRequests[r] = value
1047 go c.peerRequestDataReader(r, value)
1052 func (c *PeerConn) peerRequestDataReader(r request, prs *peerRequestState) {
1053 b, err := readPeerRequestData(r, c)
1055 defer c.locker().Unlock()
1057 c.peerRequestDataReadFailed(err, r)
1060 panic("data must be non-nil to trigger send")
1067 // If this is maintained correctly, we might be able to support optional synchronous reading for
1068 // chunk sending, the way it used to work.
1069 func (c *PeerConn) peerRequestDataReadFailed(err error, r request) {
1070 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer request %v: %v", r, err)
1071 i := pieceIndex(r.Index)
1072 if c.t.pieceComplete(i) {
1073 // There used to be more code here that just duplicated the following break. Piece
1074 // completions are currently cached, so I'm not sure how helpful this update is, except to
1075 // pull any completion changes pushed to the storage backend in failed reads that got us
1077 c.t.updatePieceCompletion(i)
1079 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1080 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1081 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1082 // next connect. TODO: Support rejecting here too.
1084 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1089 func readPeerRequestData(r request, c *PeerConn) ([]byte, error) {
1090 b := make([]byte, r.Length)
1091 p := c.t.info.Piece(int(r.Index))
1092 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1099 panic("expected error")
1105 func runSafeExtraneous(f func()) {
1113 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1114 // exit. Returning will end the connection.
1115 func (c *PeerConn) mainReadLoop() (err error) {
1118 torrent.Add("connection.mainReadLoop returned with error", 1)
1120 torrent.Add("connection.mainReadLoop returned with no error", 1)
1126 decoder := pp.Decoder{
1127 R: bufio.NewReaderSize(c.r, 1<<17),
1128 MaxLength: 256 * 1024,
1136 err = decoder.Decode(&msg)
1138 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1141 if t.closed.IsSet() || c.closed.IsSet() {
1148 c.lastMessageReceived = time.Now()
1150 receivedKeepalives.Add(1)
1153 messageTypesReceived.Add(msg.Type.String(), 1)
1154 if msg.Type.FastExtension() && !c.fastEnabled() {
1155 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1156 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1160 c.peerChoking = true
1161 if !c.fastEnabled() {
1162 c.deleteAllRequests()
1164 // We can then reset our interest.
1166 c.updateExpectingChunks()
1168 c.peerChoking = false
1170 c.updateExpectingChunks()
1172 c.peerInterested = true
1174 case pp.NotInterested:
1175 c.peerInterested = false
1176 // We don't clear their requests since it isn't clear in the spec.
1177 // We'll probably choke them for this, which will clear them if
1178 // appropriate, and is clearly specified.
1180 err = c.peerSentHave(pieceIndex(msg.Index))
1182 err = c.peerSentBitfield(msg.Bitfield)
1184 r := newRequestFromMessage(&msg)
1185 err = c.onReadRequest(r)
1187 err = c.receiveChunk(&msg)
1188 if len(msg.Piece) == int(t.chunkSize) {
1189 t.chunkPool.Put(&msg.Piece)
1192 err = fmt.Errorf("receiving chunk: %s", err)
1195 req := newRequestFromMessage(&msg)
1196 c.onPeerSentCancel(req)
1198 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1202 pingAddr := net.UDPAddr{
1207 pingAddr.Port = int(msg.Port)
1209 cl.eachDhtServer(func(s DhtServer) {
1210 go s.Ping(&pingAddr)
1213 torrent.Add("suggests received", 1)
1214 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1217 err = c.onPeerSentHaveAll()
1219 err = c.peerSentHaveNone()
1221 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1222 case pp.AllowedFast:
1223 torrent.Add("allowed fasts received", 1)
1224 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1225 c.peerAllowedFast.Add(int(msg.Index))
1228 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1230 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1238 func (c *peer) remoteRejectedRequest(r request) {
1239 if c.deleteRequest(r) {
1240 c.decExpectedChunkReceive(r)
1244 func (c *peer) decExpectedChunkReceive(r request) {
1245 count := c.validReceiveChunks[r]
1247 delete(c.validReceiveChunks, r)
1248 } else if count > 1 {
1249 c.validReceiveChunks[r] = count - 1
1255 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1257 // TODO: Should we still do this?
1259 // These clients use their own extension IDs for outgoing message
1260 // types, which is incorrect.
1261 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1269 case pp.HandshakeExtendedID:
1270 var d pp.ExtendedHandshakeMessage
1271 if err := bencode.Unmarshal(payload, &d); err != nil {
1272 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1273 return errors.Wrap(err, "unmarshalling extended handshake payload")
1275 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1278 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1280 c.PeerMaxRequests = d.Reqq
1282 c.PeerClientName = d.V
1283 if c.PeerExtensionIDs == nil {
1284 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1286 c.PeerListenPort = d.Port
1287 c.PeerPrefersEncryption = d.Encryption
1288 for name, id := range d.M {
1289 if _, ok := c.PeerExtensionIDs[name]; !ok {
1290 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1292 c.PeerExtensionIDs[name] = id
1294 if d.MetadataSize != 0 {
1295 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1296 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1299 c.requestPendingMetadata()
1300 if !t.cl.config.DisablePEX {
1301 t.pex.Add(c) // we learnt enough now
1305 case metadataExtendedId:
1306 err := cl.gotMetadataExtensionMsg(payload, t, c)
1308 return fmt.Errorf("handling metadata extension message: %w", err)
1312 if !c.pex.IsEnabled() {
1313 return nil // or hang-up maybe?
1315 return c.pex.Recv(payload)
1317 return fmt.Errorf("unexpected extended message ID: %v", id)
1321 // Set both the Reader and Writer for the connection from a single ReadWriter.
1322 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1327 // Returns the Reader and Writer as a combined ReadWriter.
1328 func (cn *PeerConn) rw() io.ReadWriter {
1335 // Handle a received chunk from a peer.
1336 func (c *peer) receiveChunk(msg *pp.Message) error {
1339 torrent.Add("chunks received", 1)
1341 req := newRequestFromMessage(msg)
1344 torrent.Add("chunks received while choking", 1)
1347 if c.validReceiveChunks[req] <= 0 {
1348 torrent.Add("chunks received unexpected", 1)
1349 return errors.New("received unexpected chunk")
1351 c.decExpectedChunkReceive(req)
1353 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1354 torrent.Add("chunks received due to allowed fast", 1)
1358 // Request has been satisfied.
1359 if c.deleteRequest(req) {
1360 if c.expectingChunks() {
1361 c._chunksReceivedWhileExpecting++
1364 torrent.Add("chunks received unwanted", 1)
1368 // Do we actually want this chunk?
1369 if t.haveChunk(req) {
1370 torrent.Add("chunks received wasted", 1)
1371 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1375 piece := &t.pieces[req.Index]
1377 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1378 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1379 c.lastUsefulChunkReceived = time.Now()
1380 // if t.fastestPeer != c {
1381 // log.Printf("setting fastest connection %p", c)
1385 // Need to record that it hasn't been written yet, before we attempt to do
1386 // anything with it.
1387 piece.incrementPendingWrites()
1388 // Record that we have the chunk, so we aren't trying to download it while
1389 // waiting for it to be written to storage.
1390 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1392 // Cancel pending requests for this chunk.
1393 for c := range t.conns {
1397 err := func() error {
1400 concurrentChunkWrites.Add(1)
1401 defer concurrentChunkWrites.Add(-1)
1402 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1403 // number of connections. We write inline with receiving the chunk (with this lock dance),
1404 // because we want to handle errors synchronously and I haven't thought of a nice way to
1405 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1407 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1410 piece.decrementPendingWrites()
1413 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1415 //t.updatePieceCompletion(pieceIndex(msg.Index))
1416 t.onWriteChunkErr(err)
1420 c.onDirtiedPiece(pieceIndex(req.Index))
1422 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1423 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1424 t.queuePieceCheck(pieceIndex(req.Index))
1425 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1426 // chunk status (such as the haveChunk call above) to have to check all the various other
1427 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1428 // that chunk pieces are pended at an appropriate time later however.
1431 cl.event.Broadcast()
1432 // We do this because we've written a chunk, and may change PieceState.Partial.
1433 t.publishPieceChange(pieceIndex(req.Index))
1438 func (c *peer) onDirtiedPiece(piece pieceIndex) {
1439 if c.peerTouchedPieces == nil {
1440 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1442 c.peerTouchedPieces[piece] = struct{}{}
1443 ds := &c.t.pieces[piece].dirtiers
1445 *ds = make(map[*peer]struct{})
1447 (*ds)[c] = struct{}{}
1450 func (c *PeerConn) uploadAllowed() bool {
1451 if c.t.cl.config.NoUpload {
1454 if c.t.dataUploadDisallowed {
1460 if !c.peerHasWantedPieces() {
1463 // Don't upload more than 100 KiB more than we download.
1464 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1470 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1471 if c.uploadTimer == nil {
1472 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1474 c.uploadTimer.Reset(delay)
1478 // Also handles choking and unchoking of the remote peer.
1479 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1480 // Breaking or completing this loop means we don't want to upload to the
1481 // peer anymore, and we choke them.
1483 for c.uploadAllowed() {
1484 // We want to upload to the peer.
1485 if !c.unchoke(msg) {
1488 for r, state := range c.peerRequests {
1489 if state.data == nil {
1492 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1494 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1496 delay := res.Delay()
1499 c.setRetryUploadTimer(delay)
1500 // Hard to say what to return here.
1503 more := c.sendChunk(r, msg, state)
1504 delete(c.peerRequests, r)
1515 func (cn *PeerConn) drop() {
1516 cn.t.dropConnection(cn)
1519 func (cn *peer) netGoodPiecesDirtied() int64 {
1520 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1523 func (c *peer) peerHasWantedPieces() bool {
1524 return !c._pieceRequestOrder.IsEmpty()
1527 func (c *peer) numLocalRequests() int {
1528 return len(c.requests)
1531 func (c *peer) deleteRequest(r request) bool {
1532 if _, ok := c.requests[r]; !ok {
1535 delete(c.requests, r)
1536 c.updateExpectingChunks()
1537 c.t.requestStrategy.hooks().deletedRequest(r)
1538 pr := c.t.pendingRequests
1547 // If a request fails, updating the requests for the current peer first may miss the opportunity
1548 // to try other peers for that request instead, depending on the request strategy. This might
1549 // only affect webseed peers though, since they synchronously issue new requests: PeerConns do
1550 // it in the writer routine.
1551 const updateCurrentConnRequestsFirst = false
1552 if updateCurrentConnRequestsFirst {
1555 // Give other conns a chance to pick up the request.
1556 c.t.iterPeers(func(_c *peer) {
1557 // We previously checked that the peer wasn't interested to to only wake connections that
1558 // were unable to issue requests due to starvation by the request strategy. There could be
1559 // performance ramifications.
1560 if _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1564 if !updateCurrentConnRequestsFirst {
1570 func (c *peer) deleteAllRequests() {
1571 for r := range c.requests {
1574 if len(c.requests) != 0 {
1575 panic(len(c.requests))
1577 // for c := range c.t.conns {
1582 // This is called when something has changed that should wake the writer, such as putting stuff into
1583 // the writeBuffer, or changing some state that the writer can act on.
1584 func (c *PeerConn) tickleWriter() {
1585 c.writerCond.Broadcast()
1588 func (c *peer) postCancel(r request) bool {
1589 if !c.deleteRequest(r) {
1592 c.peerImpl._postCancel(r)
1596 func (c *PeerConn) _postCancel(r request) {
1597 c.post(makeCancelMessage(r))
1600 func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1601 c.lastChunkSent = time.Now()
1602 return msg(pp.Message{
1610 func (c *PeerConn) setTorrent(t *Torrent) {
1612 panic("connection already associated with a torrent")
1615 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1616 t.reconcileHandshakeStats(c)
1619 func (c *peer) peerPriority() (peerPriority, error) {
1620 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1623 func (c *peer) remoteIp() net.IP {
1624 return addrIpOrNil(c.RemoteAddr)
1627 func (c *peer) remoteIpPort() IpPort {
1628 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1629 return IpPort{ipa.IP, uint16(ipa.Port)}
1632 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1633 f := pp.PexPeerFlags(0)
1634 if c.PeerPrefersEncryption {
1635 f |= pp.PexPrefersEncryption
1638 f |= pp.PexOutgoingConn
1640 if c.RemoteAddr != nil && strings.Contains(c.RemoteAddr.Network(), "udp") {
1641 f |= pp.PexSupportsUtp
1646 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1647 // advertised listen port.
1648 func (c *PeerConn) dialAddr() net.Addr {
1649 if !c.outgoing && c.PeerListenPort != 0 {
1650 switch addr := c.RemoteAddr.(type) {
1653 dialAddr.Port = c.PeerListenPort
1657 dialAddr.Port = c.PeerListenPort
1664 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1665 f := c.pexPeerFlags()
1666 addr := c.dialAddr()
1667 return pexEvent{t, addr, f}
1670 func (c *PeerConn) String() string {
1671 return fmt.Sprintf("connection %p", c)
1674 func (c *peer) trust() connectionTrust {
1675 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1678 type connectionTrust struct {
1680 NetGoodPiecesDirted int64
1683 func (l connectionTrust) Less(r connectionTrust) bool {
1684 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1687 func (cn *peer) requestStrategyConnection() requestStrategyConnection {
1691 func (cn *peer) chunksReceivedWhileExpecting() int64 {
1692 return cn._chunksReceivedWhileExpecting
1695 func (cn *peer) fastest() bool {
1696 return cn == cn.t.fastestPeer
1699 func (cn *peer) peerMaxRequests() int {
1700 return cn.PeerMaxRequests
1703 // Returns the pieces the peer has claimed to have.
1704 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1706 defer cn.locker().RUnlock()
1707 return cn.peerPieces()
1710 func (cn *peer) peerPieces() bitmap.Bitmap {
1711 ret := cn._peerPieces.Copy()
1712 if cn.peerSentHaveAll {
1713 ret.AddRange(0, cn.t.numPieces())
1718 func (cn *peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1719 return &cn._pieceRequestOrder
1722 func (cn *peer) stats() *ConnStats {
1726 func (cn *peer) torrent() requestStrategyTorrent {
1727 return cn.t.requestStrategyTorrent()