17 "github.com/anacrolix/log"
18 "github.com/anacrolix/missinggo"
19 "github.com/anacrolix/missinggo/iter"
20 "github.com/anacrolix/missinggo/v2/bitmap"
21 "github.com/anacrolix/missinggo/v2/prioritybitmap"
22 "github.com/anacrolix/multiless"
23 "github.com/anacrolix/torrent/metainfo"
25 "github.com/anacrolix/torrent/bencode"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
30 type PeerSource string
33 PeerSourceTracker = "Tr"
34 PeerSourceIncoming = "I"
35 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
36 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
38 // The peer was given directly, such as through a magnet link.
39 PeerSourceDirect = "M"
42 type peerRequestState struct {
46 type PeerRemoteAddr interface {
50 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
51 // indexable with the memory space available.
52 type maxRequests = int
55 // First to ensure 64-bit alignment for atomics. See #262.
65 RemoteAddr PeerRemoteAddr
66 // True if the connection is operating over MSE obfuscation.
68 cryptoMethod mse.CryptoMethod
71 closed missinggo.Event
72 // Set true after we've added our ConnStats generated during handshake to
73 // other ConnStat instances as determined when the *Torrent became known.
74 reconciledHandshakeStats bool
76 lastMessageReceived time.Time
77 completedHandshake time.Time
78 lastUsefulChunkReceived time.Time
79 lastChunkSent time.Time
81 // Stuff controlled by the local peer.
83 lastBecameInterested time.Time
84 priorInterest time.Duration
86 lastStartedExpectingToReceiveChunks time.Time
87 cumulativeExpectedToReceiveChunks time.Duration
88 _chunksReceivedWhileExpecting int64
91 requests map[Request]struct{}
92 piecesReceivedSinceLastRequestUpdate maxRequests
93 maxPiecesReceivedBetweenRequestUpdates maxRequests
94 // Chunks that we might reasonably expect to receive from the peer. Due to
95 // latency, buffering, and implementation differences, we may receive
96 // chunks that are no longer in the set of requests actually want.
97 validReceiveChunks map[Request]int
98 // Indexed by metadata piece, set to true if posted and pending a
100 metadataRequests []bool
101 sentHaves bitmap.Bitmap
103 // Stuff controlled by the remote peer.
106 peerRequests map[Request]*peerRequestState
107 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
109 // The pieces the peer has claimed to have.
110 _peerPieces bitmap.Bitmap
111 // The peer has everything. This can occur due to a special message, when
112 // we may not even know the number of pieces in the torrent yet.
114 // The highest possible number of pieces the torrent could have based on
115 // communication with the peer. Generally only useful until we have the
117 peerMinPieces pieceIndex
118 // Pieces we've accepted chunks for from the peer.
119 peerTouchedPieces map[pieceIndex]struct{}
120 peerAllowedFast bitmap.Bitmap
122 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
123 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
124 PeerClientName string
126 pieceInclination []int
127 _pieceRequestOrder prioritybitmap.PriorityBitmap
132 // Maintains the state of a BitTorrent-protocol based connection with a peer.
133 type PeerConn struct {
136 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
137 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
142 PeerExtensionBytes pp.PeerExtensionBits
144 // The actual Conn, used for closing, and setting socket options.
146 // The Reader and Writer for this Conn, with hooks installed for stats,
147 // limiting, deadlines etc.
151 writeBuffer *bytes.Buffer
152 uploadTimer *time.Timer
158 func (cn *PeerConn) connStatusString() string {
159 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
162 func (cn *Peer) updateExpectingChunks() {
163 if cn.expectingChunks() {
164 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
165 cn.lastStartedExpectingToReceiveChunks = time.Now()
168 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
169 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
170 cn.lastStartedExpectingToReceiveChunks = time.Time{}
175 func (cn *Peer) expectingChunks() bool {
176 if len(cn.requests) == 0 {
182 for r := range cn.requests {
183 if !cn.remoteChokingPiece(r.Index.Int()) {
190 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
191 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
194 // Returns true if the connection is over IPv6.
195 func (cn *PeerConn) ipv6() bool {
200 return len(ip) == net.IPv6len
203 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
204 // specification for this.
205 func (cn *PeerConn) isPreferredDirection() bool {
206 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
209 // Returns whether the left connection should be preferred over the right one,
210 // considering only their networking properties. If ok is false, we can't
212 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
214 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
215 ml.NextBool(!l.utp(), !r.utp())
216 ml.NextBool(l.ipv6(), r.ipv6())
220 func (cn *Peer) cumInterest() time.Duration {
221 ret := cn.priorInterest
223 ret += time.Since(cn.lastBecameInterested)
228 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
229 if cn.peerSentHaveAll {
232 if !cn.t.haveInfo() {
235 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
238 func (cn *PeerConn) locker() *lockWithDeferreds {
239 return cn.t.cl.locker()
242 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
243 _, ok := cn.PeerExtensionIDs[ext]
247 // The best guess at number of pieces in the torrent for this peer.
248 func (cn *Peer) bestPeerNumPieces() pieceIndex {
250 return cn.t.numPieces()
252 return cn.peerMinPieces
255 func (cn *Peer) completedString() string {
256 have := pieceIndex(cn._peerPieces.Len())
257 if cn.peerSentHaveAll {
258 have = cn.bestPeerNumPieces()
260 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
263 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
264 cn.setNumPieces(info.NumPieces())
267 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
268 // receiving badly sized BITFIELD, or invalid HAVE messages.
269 func (cn *PeerConn) setNumPieces(num pieceIndex) {
270 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
271 cn.peerPiecesChanged()
274 func eventAgeString(t time.Time) string {
278 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
281 func (cn *PeerConn) connectionFlags() (ret string) {
283 ret += string([]byte{b})
285 if cn.cryptoMethod == mse.CryptoMethodRC4 {
287 } else if cn.headerEncrypted {
290 ret += string(cn.Discovery)
297 func (cn *PeerConn) utp() bool {
298 return parseNetworkString(cn.Network).Udp
301 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
302 func (cn *Peer) statusFlags() (ret string) {
304 ret += string([]byte{b})
313 ret += cn.connectionFlags()
315 if cn.peerInterested {
324 func (cn *Peer) downloadRate() float64 {
325 num := cn._stats.BytesReadUsefulData.Int64()
329 return float64(num) / cn.totalExpectingTime().Seconds()
332 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
333 ret = make(map[pieceIndex]int)
334 for r := range cn.requests {
335 ret[pieceIndex(r.Index)]++
340 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
341 // \t isn't preserved in <pre> blocks?
342 if cn.closed.IsSet() {
343 fmt.Fprint(w, "CLOSED: ")
345 fmt.Fprintln(w, cn.connStatusString())
346 prio, err := cn.peerPriority()
347 prioStr := fmt.Sprintf("%08x", prio)
349 prioStr += ": " + err.Error()
351 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
352 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
353 eventAgeString(cn.lastMessageReceived),
354 eventAgeString(cn.completedHandshake),
355 eventAgeString(cn.lastHelpful()),
357 cn.totalExpectingTime(),
360 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
361 cn.completedString(),
362 len(cn.peerTouchedPieces),
363 &cn._stats.ChunksReadUseful,
364 &cn._stats.ChunksRead,
365 &cn._stats.ChunksWritten,
366 cn.numLocalRequests(),
367 cn.nominalMaxRequests(),
369 len(cn.peerRequests),
372 cn.downloadRate()/(1<<10),
374 fmt.Fprintf(w, " requested pieces:")
375 type pieceNumRequestsType struct {
379 var pieceNumRequests []pieceNumRequestsType
380 for piece, count := range cn.numRequestsByPiece() {
381 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
383 sort.Slice(pieceNumRequests, func(i, j int) bool {
384 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
386 for _, elem := range pieceNumRequests {
387 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
392 func (p *Peer) close() {
396 p.discardPieceInclination()
397 p._pieceRequestOrder.Clear()
400 p.t.decPeerPieceAvailability(p)
402 for _, f := range p.callbacks.PeerClosed {
407 func (cn *PeerConn) onClose() {
408 if cn.pex.IsEnabled() {
415 if cb := cn.callbacks.PeerConnClosed; cb != nil {
420 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
421 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
424 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
425 // https://github.com/pion/datachannel/issues/59 is fixed.
426 const writeBufferHighWaterLen = 1 << 15
428 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
429 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
430 func (cn *PeerConn) write(msg pp.Message) bool {
431 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
432 // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
433 // (although there's some delay between us recording the message, and the connection writer
434 // flushing it out.).
435 cn.writeBuffer.Write(msg.MustMarshalBinary())
436 // Last I checked only Piece messages affect stats, and we don't write those.
439 return !cn.writeBufferFull()
442 func (cn *PeerConn) writeBufferFull() bool {
443 return cn.writeBuffer.Len() >= writeBufferHighWaterLen
446 func (cn *PeerConn) requestMetadataPiece(index int) {
447 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
451 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
454 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
458 ExtendedPayload: func() []byte {
459 b, err := bencode.Marshal(map[string]int{
460 "msg_type": pp.RequestMetadataExtensionMsgType,
469 for index >= len(cn.metadataRequests) {
470 cn.metadataRequests = append(cn.metadataRequests, false)
472 cn.metadataRequests[index] = true
475 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
476 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
479 // The actual value to use as the maximum outbound requests.
480 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
481 return int(clamp(1, 2*int64(cn.maxPiecesReceivedBetweenRequestUpdates), int64(cn.PeerMaxRequests)))
484 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
485 ret = cn.cumulativeExpectedToReceiveChunks
486 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
487 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
493 func (cn *PeerConn) onPeerSentCancel(r Request) {
494 if _, ok := cn.peerRequests[r]; !ok {
495 torrent.Add("unexpected cancels received", 1)
498 if cn.fastEnabled() {
501 delete(cn.peerRequests, r)
505 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
510 more = msg(pp.Message{
513 if cn.fastEnabled() {
514 for r := range cn.peerRequests {
515 // TODO: Don't reject pieces in allowed fast set.
519 cn.peerRequests = nil
524 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
529 return msg(pp.Message{
534 func (cn *Peer) setInterested(interested bool) bool {
535 if cn.interested == interested {
538 cn.interested = interested
540 cn.lastBecameInterested = time.Now()
541 } else if !cn.lastBecameInterested.IsZero() {
542 cn.priorInterest += time.Since(cn.lastBecameInterested)
544 cn.updateExpectingChunks()
545 // log.Printf("%p: setting interest: %v", cn, interested)
546 return cn.writeInterested(interested)
549 func (pc *PeerConn) writeInterested(interested bool) bool {
550 return pc.write(pp.Message{
551 Type: func() pp.MessageType {
555 return pp.NotInterested
561 // The function takes a message to be sent, and returns true if more messages
563 type messageWriter func(pp.Message) bool
565 func (cn *Peer) shouldRequest(r Request) error {
566 if !cn.peerHasPiece(pieceIndex(r.Index)) {
567 return errors.New("requesting piece peer doesn't have")
569 if !cn.t.peerIsActive(cn) {
570 panic("requesting but not in active conns")
572 if cn.closed.IsSet() {
573 panic("requesting when connection is closed")
575 if cn.t.hashingPiece(pieceIndex(r.Index)) {
576 panic("piece is being hashed")
578 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
579 panic("piece is queued for hash")
584 func (cn *Peer) request(r Request) error {
585 if err := cn.shouldRequest(r); err != nil {
588 if _, ok := cn.requests[r]; ok {
591 if cn.numLocalRequests() >= cn.nominalMaxRequests() {
592 return errors.New("too many outstanding requests")
594 if cn.requests == nil {
595 cn.requests = make(map[Request]struct{})
597 cn.requests[r] = struct{}{}
598 if cn.validReceiveChunks == nil {
599 cn.validReceiveChunks = make(map[Request]int)
601 cn.validReceiveChunks[r]++
602 cn.t.pendingRequests[r]++
603 cn.updateExpectingChunks()
604 for _, f := range cn.callbacks.SentRequest {
605 f(PeerRequestEvent{cn, r})
607 cn.peerImpl._request(r)
611 func (me *PeerConn) _request(r Request) {
620 func (me *Peer) cancel(r Request) {
621 if me.deleteRequest(r) {
622 me.peerImpl._cancel(r)
626 func (me *PeerConn) _cancel(r Request) {
627 me.write(makeCancelMessage(r))
630 func (cn *PeerConn) fillWriteBuffer() {
631 if cn.pex.IsEnabled() {
632 if flow := cn.pex.Share(cn.write); !flow {
639 // Routine that writes to the peer. Some of what to write is buffered by
640 // activity elsewhere in the Client, and some is determined locally when the
641 // connection is writable.
642 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
644 lastWrite time.Time = time.Now()
645 keepAliveTimer *time.Timer
647 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
649 defer cn.locker().Unlock()
650 if time.Since(lastWrite) >= keepAliveTimeout {
653 keepAliveTimer.Reset(keepAliveTimeout)
656 defer cn.locker().Unlock()
658 defer keepAliveTimer.Stop()
659 frontBuf := new(bytes.Buffer)
661 if cn.closed.IsSet() {
664 if cn.writeBuffer.Len() == 0 {
667 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
668 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
669 torrent.Add("written keepalives", 1)
671 if cn.writeBuffer.Len() == 0 {
672 // TODO: Minimize wakeups....
677 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
679 n, err := cn.w.Write(frontBuf.Bytes())
682 lastWrite = time.Now()
683 keepAliveTimer.Reset(keepAliveTimeout)
686 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
689 if n != frontBuf.Len() {
696 func (cn *PeerConn) have(piece pieceIndex) {
697 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
702 Index: pp.Integer(piece),
704 cn.sentHaves.Add(bitmap.BitIndex(piece))
707 func (cn *PeerConn) postBitfield() {
708 if cn.sentHaves.Len() != 0 {
709 panic("bitfield must be first have-related message sent")
711 if !cn.t.haveAnyPieces() {
716 Bitfield: cn.t.bitfield(),
718 cn.sentHaves = cn.t._completedPieces.Copy()
721 func (cn *PeerConn) updateRequests() {
722 // log.Print("update requests")
726 // Emits the indices in the Bitmaps bms in order, never repeating any index.
727 // skip is mutated during execution, and its initial values will never be
729 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
730 return func(cb iter.Callback) {
731 for _, bm := range bms {
733 func(_i interface{}) bool {
735 if skip.Contains(bitmap.BitIndex(i)) {
738 skip.Add(bitmap.BitIndex(i))
749 // check callers updaterequests
750 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
751 return cn._pieceRequestOrder.Remove(piece)
754 // This is distinct from Torrent piece priority, which is the user's
755 // preference. Connection piece priority is specific to a connection and is
756 // used to pseudorandomly avoid connections always requesting the same pieces
757 // and thus wasting effort.
758 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
759 tpp := cn.t.piecePriority(piece)
760 if !cn.peerHasPiece(piece) {
761 tpp = PiecePriorityNone
763 if tpp == PiecePriorityNone {
764 return cn.stopRequestingPiece(piece)
766 prio := cn.getPieceInclination()[piece]
767 return cn._pieceRequestOrder.Set(piece, prio)
770 func (cn *Peer) getPieceInclination() []int {
771 if cn.pieceInclination == nil {
772 cn.pieceInclination = cn.t.getConnPieceInclination()
774 return cn.pieceInclination
777 func (cn *Peer) discardPieceInclination() {
778 if cn.pieceInclination == nil {
781 cn.t.putPieceInclination(cn.pieceInclination)
782 cn.pieceInclination = nil
785 func (cn *Peer) peerPiecesChanged() {
787 prioritiesChanged := false
788 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
789 if cn.updatePiecePriority(i) {
790 prioritiesChanged = true
793 if prioritiesChanged {
797 cn.t.maybeDropMutuallyCompletePeer(cn)
800 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
801 if newMin > cn.peerMinPieces {
802 cn.peerMinPieces = newMin
806 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
807 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
808 return errors.New("invalid piece")
810 if cn.peerHasPiece(piece) {
813 cn.raisePeerMinPieces(piece + 1)
814 if !cn.peerHasPiece(piece) {
815 cn.t.incPieceAvailability(piece)
817 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
818 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
819 if cn.updatePiecePriority(piece) {
825 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
827 panic("expected bitfield length divisible by 8")
829 // We know that the last byte means that at most the last 7 bits are wasted.
830 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
831 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
832 // Ignore known excess pieces.
833 bf = bf[:cn.t.numPieces()]
835 pp := cn.newPeerPieces()
836 cn.peerSentHaveAll = false
837 for i, have := range bf {
839 cn.raisePeerMinPieces(pieceIndex(i) + 1)
840 if !pp.Contains(bitmap.BitIndex(i)) {
841 cn.t.incPieceAvailability(i)
844 if pp.Contains(bitmap.BitIndex(i)) {
845 cn.t.decPieceAvailability(i)
848 cn._peerPieces.Set(bitmap.BitIndex(i), have)
850 cn.peerPiecesChanged()
854 func (cn *Peer) onPeerHasAllPieces() {
857 pp := cn.newPeerPieces()
858 for i := range iter.N(t.numPieces()) {
859 if !pp.Contains(bitmap.BitIndex(i)) {
860 t.incPieceAvailability(i)
864 cn.peerSentHaveAll = true
865 cn._peerPieces.Clear()
866 cn.peerPiecesChanged()
869 func (cn *PeerConn) onPeerSentHaveAll() error {
870 cn.onPeerHasAllPieces()
874 func (cn *PeerConn) peerSentHaveNone() error {
875 cn.t.decPeerPieceAvailability(&cn.Peer)
876 cn._peerPieces.Clear()
877 cn.peerSentHaveAll = false
878 cn.peerPiecesChanged()
882 func (c *PeerConn) requestPendingMetadata() {
886 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
887 // Peer doesn't support this.
890 // Request metadata pieces that we don't have in a random order.
892 for index := 0; index < c.t.metadataPieceCount(); index++ {
893 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
894 pending = append(pending, index)
897 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
898 for _, i := range pending {
899 c.requestMetadataPiece(i)
903 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
904 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
905 if msg.Type == pp.Extended {
906 for name, id := range cn.PeerExtensionIDs {
907 if id != msg.ExtendedID {
910 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
913 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
916 func (cn *PeerConn) readMsg(msg *pp.Message) {
917 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
920 // After handshake, we know what Torrent and Client stats to include for a
922 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
928 // All ConnStats that include this connection. Some objects are not known
929 // until the handshake is complete, after which it's expected to reconcile the
931 func (cn *Peer) allStats(f func(*ConnStats)) {
933 if cn.reconciledHandshakeStats {
934 cn.postHandshakeStats(f)
938 func (cn *PeerConn) wroteBytes(n int64) {
939 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
942 func (cn *PeerConn) readBytes(n int64) {
943 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
946 // Returns whether the connection could be useful to us. We're seeding and
947 // they want data, we don't have metainfo and they can provide it, etc.
948 func (c *Peer) useful() bool {
950 if c.closed.IsSet() {
954 return c.supportsExtension("ut_metadata")
956 if t.seeding() && c.peerInterested {
959 if c.peerHasWantedPieces() {
965 func (c *Peer) lastHelpful() (ret time.Time) {
966 ret = c.lastUsefulChunkReceived
967 if c.t.seeding() && c.lastChunkSent.After(ret) {
968 ret = c.lastChunkSent
973 func (c *PeerConn) fastEnabled() bool {
974 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
977 func (c *PeerConn) reject(r Request) {
978 if !c.fastEnabled() {
979 panic("fast not enabled")
981 c.write(r.ToMsg(pp.Reject))
982 delete(c.peerRequests, r)
985 func (c *PeerConn) onReadRequest(r Request) error {
986 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
987 if _, ok := c.peerRequests[r]; ok {
988 torrent.Add("duplicate requests received", 1)
992 torrent.Add("requests received while choking", 1)
994 torrent.Add("requests rejected while choking", 1)
999 // TODO: What if they've already requested this?
1000 if len(c.peerRequests) >= localClientReqq {
1001 torrent.Add("requests received while queue full", 1)
1002 if c.fastEnabled() {
1005 // BEP 6 says we may close here if we choose.
1008 if !c.t.havePiece(pieceIndex(r.Index)) {
1009 // This isn't necessarily them screwing up. We can drop pieces
1010 // from our storage, and can't communicate this to peers
1011 // except by reconnecting.
1012 requestsReceivedForMissingPieces.Add(1)
1013 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1015 // Check this after we know we have the piece, so that the piece length will be known.
1016 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1017 torrent.Add("bad requests received", 1)
1018 return errors.New("bad Request")
1020 if c.peerRequests == nil {
1021 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1023 value := &peerRequestState{}
1024 c.peerRequests[r] = value
1025 go c.peerRequestDataReader(r, value)
1030 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1031 b, err := readPeerRequestData(r, c)
1033 defer c.locker().Unlock()
1035 c.peerRequestDataReadFailed(err, r)
1038 panic("data must be non-nil to trigger send")
1045 // If this is maintained correctly, we might be able to support optional synchronous reading for
1046 // chunk sending, the way it used to work.
1047 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1048 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1049 i := pieceIndex(r.Index)
1050 if c.t.pieceComplete(i) {
1051 // There used to be more code here that just duplicated the following break. Piece
1052 // completions are currently cached, so I'm not sure how helpful this update is, except to
1053 // pull any completion changes pushed to the storage backend in failed reads that got us
1055 c.t.updatePieceCompletion(i)
1057 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1058 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1059 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1060 // next connect. TODO: Support rejecting here too.
1062 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1067 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1068 b := make([]byte, r.Length)
1069 p := c.t.info.Piece(int(r.Index))
1070 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1077 panic("expected error")
1083 func runSafeExtraneous(f func()) {
1091 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1092 // exit. Returning will end the connection.
1093 func (c *PeerConn) mainReadLoop() (err error) {
1096 torrent.Add("connection.mainReadLoop returned with error", 1)
1098 torrent.Add("connection.mainReadLoop returned with no error", 1)
1104 decoder := pp.Decoder{
1105 R: bufio.NewReaderSize(c.r, 1<<17),
1106 MaxLength: 256 * 1024,
1114 err = decoder.Decode(&msg)
1116 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1119 if t.closed.IsSet() || c.closed.IsSet() {
1126 c.lastMessageReceived = time.Now()
1128 receivedKeepalives.Add(1)
1131 messageTypesReceived.Add(msg.Type.String(), 1)
1132 if msg.Type.FastExtension() && !c.fastEnabled() {
1133 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1134 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1138 c.peerChoking = true
1139 if !c.fastEnabled() {
1140 c.deleteAllRequests()
1142 // We can then reset our interest.
1144 c.updateExpectingChunks()
1146 c.peerChoking = false
1148 c.updateExpectingChunks()
1150 c.peerInterested = true
1152 case pp.NotInterested:
1153 c.peerInterested = false
1154 // We don't clear their requests since it isn't clear in the spec.
1155 // We'll probably choke them for this, which will clear them if
1156 // appropriate, and is clearly specified.
1158 err = c.peerSentHave(pieceIndex(msg.Index))
1160 err = c.peerSentBitfield(msg.Bitfield)
1162 r := newRequestFromMessage(&msg)
1163 err = c.onReadRequest(r)
1165 err = c.receiveChunk(&msg)
1166 if len(msg.Piece) == int(t.chunkSize) {
1167 t.chunkPool.Put(&msg.Piece)
1170 err = fmt.Errorf("receiving chunk: %s", err)
1173 req := newRequestFromMessage(&msg)
1174 c.onPeerSentCancel(req)
1176 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1180 pingAddr := net.UDPAddr{
1185 pingAddr.Port = int(msg.Port)
1187 cl.eachDhtServer(func(s DhtServer) {
1188 go s.Ping(&pingAddr)
1191 torrent.Add("suggests received", 1)
1192 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1195 err = c.onPeerSentHaveAll()
1197 err = c.peerSentHaveNone()
1199 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1200 case pp.AllowedFast:
1201 torrent.Add("allowed fasts received", 1)
1202 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1203 c.peerAllowedFast.Add(bitmap.BitIndex(msg.Index))
1206 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1208 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1216 func (c *Peer) remoteRejectedRequest(r Request) {
1217 if c.deleteRequest(r) {
1218 c.decExpectedChunkReceive(r)
1222 func (c *Peer) decExpectedChunkReceive(r Request) {
1223 count := c.validReceiveChunks[r]
1225 delete(c.validReceiveChunks, r)
1226 } else if count > 1 {
1227 c.validReceiveChunks[r] = count - 1
1233 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1235 // TODO: Should we still do this?
1237 // These clients use their own extension IDs for outgoing message
1238 // types, which is incorrect.
1239 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1247 case pp.HandshakeExtendedID:
1248 var d pp.ExtendedHandshakeMessage
1249 if err := bencode.Unmarshal(payload, &d); err != nil {
1250 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1251 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1253 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1256 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1258 c.PeerMaxRequests = d.Reqq
1260 c.PeerClientName = d.V
1261 if c.PeerExtensionIDs == nil {
1262 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1264 c.PeerListenPort = d.Port
1265 c.PeerPrefersEncryption = d.Encryption
1266 for name, id := range d.M {
1267 if _, ok := c.PeerExtensionIDs[name]; !ok {
1268 peersSupportingExtension.Add(string(name), 1)
1270 c.PeerExtensionIDs[name] = id
1272 if d.MetadataSize != 0 {
1273 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1274 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1277 c.requestPendingMetadata()
1278 if !t.cl.config.DisablePEX {
1279 t.pex.Add(c) // we learnt enough now
1283 case metadataExtendedId:
1284 err := cl.gotMetadataExtensionMsg(payload, t, c)
1286 return fmt.Errorf("handling metadata extension message: %w", err)
1290 if !c.pex.IsEnabled() {
1291 return nil // or hang-up maybe?
1293 return c.pex.Recv(payload)
1295 return fmt.Errorf("unexpected extended message ID: %v", id)
1299 // Set both the Reader and Writer for the connection from a single ReadWriter.
1300 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1305 // Returns the Reader and Writer as a combined ReadWriter.
1306 func (cn *PeerConn) rw() io.ReadWriter {
1313 // Handle a received chunk from a peer.
1314 func (c *Peer) receiveChunk(msg *pp.Message) error {
1317 chunksReceived.Add("total", 1)
1319 req := newRequestFromMessage(msg)
1322 chunksReceived.Add("while choked", 1)
1325 if c.validReceiveChunks[req] <= 0 {
1326 chunksReceived.Add("unexpected", 1)
1327 return errors.New("received unexpected chunk")
1329 c.decExpectedChunkReceive(req)
1331 if c.peerChoking && c.peerAllowedFast.Get(bitmap.BitIndex(req.Index)) {
1332 chunksReceived.Add("due to allowed fast", 1)
1335 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1336 // have actually already received the piece, while we have the Client unlocked to write the data
1338 deletedRequest := false
1340 if _, ok := c.requests[req]; ok {
1341 for _, f := range c.callbacks.ReceivedRequested {
1342 f(PeerMessageEvent{c, msg})
1345 // Request has been satisfied.
1346 if c.deleteRequest(req) {
1347 deletedRequest = true
1349 c._chunksReceivedWhileExpecting++
1352 chunksReceived.Add("unwanted", 1)
1356 // Do we actually want this chunk?
1357 if t.haveChunk(req) {
1358 chunksReceived.Add("wasted", 1)
1359 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1363 piece := &t.pieces[req.Index]
1365 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1366 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1368 c.piecesReceivedSinceLastRequestUpdate++
1369 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1371 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1372 f(ReceivedUsefulDataEvent{c, msg})
1374 c.lastUsefulChunkReceived = time.Now()
1376 // Need to record that it hasn't been written yet, before we attempt to do
1377 // anything with it.
1378 piece.incrementPendingWrites()
1379 // Record that we have the chunk, so we aren't trying to download it while
1380 // waiting for it to be written to storage.
1381 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1383 // Cancel pending requests for this chunk from *other* peers.
1384 t.iterPeers(func(p *Peer) {
1391 err := func() error {
1394 concurrentChunkWrites.Add(1)
1395 defer concurrentChunkWrites.Add(-1)
1396 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1397 // number of connections. We write inline with receiving the chunk (with this lock dance),
1398 // because we want to handle errors synchronously and I haven't thought of a nice way to
1399 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1401 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1404 piece.decrementPendingWrites()
1407 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1409 //t.updatePieceCompletion(pieceIndex(msg.Index))
1410 t.onWriteChunkErr(err)
1414 c.onDirtiedPiece(pieceIndex(req.Index))
1416 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1417 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1418 t.queuePieceCheck(pieceIndex(req.Index))
1419 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1420 // chunk status (such as the haveChunk call above) to have to check all the various other
1421 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1422 // that chunk pieces are pended at an appropriate time later however.
1425 cl.event.Broadcast()
1426 // We do this because we've written a chunk, and may change PieceState.Partial.
1427 t.publishPieceChange(pieceIndex(req.Index))
1432 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1433 if c.peerTouchedPieces == nil {
1434 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1436 c.peerTouchedPieces[piece] = struct{}{}
1437 ds := &c.t.pieces[piece].dirtiers
1439 *ds = make(map[*Peer]struct{})
1441 (*ds)[c] = struct{}{}
1444 func (c *PeerConn) uploadAllowed() bool {
1445 if c.t.cl.config.NoUpload {
1448 if c.t.dataUploadDisallowed {
1454 if !c.peerHasWantedPieces() {
1457 // Don't upload more than 100 KiB more than we download.
1458 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1464 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1465 if c.uploadTimer == nil {
1466 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1468 c.uploadTimer.Reset(delay)
1472 // Also handles choking and unchoking of the remote peer.
1473 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1474 // Breaking or completing this loop means we don't want to upload to the
1475 // peer anymore, and we choke them.
1477 for c.uploadAllowed() {
1478 // We want to upload to the peer.
1479 if !c.unchoke(msg) {
1482 for r, state := range c.peerRequests {
1483 if state.data == nil {
1486 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1488 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1490 delay := res.Delay()
1493 c.setRetryUploadTimer(delay)
1494 // Hard to say what to return here.
1497 more := c.sendChunk(r, msg, state)
1498 delete(c.peerRequests, r)
1509 func (cn *PeerConn) drop() {
1510 cn.t.dropConnection(cn)
1513 func (cn *Peer) netGoodPiecesDirtied() int64 {
1514 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1517 func (c *Peer) peerHasWantedPieces() bool {
1518 return !c._pieceRequestOrder.IsEmpty()
1521 func (c *Peer) numLocalRequests() int {
1522 return len(c.requests)
1525 func (c *Peer) deleteRequest(r Request) bool {
1526 if _, ok := c.requests[r]; !ok {
1529 delete(c.requests, r)
1530 for _, f := range c.callbacks.DeletedRequest {
1531 f(PeerRequestEvent{c, r})
1533 c.updateExpectingChunks()
1534 pr := c.t.pendingRequests
1546 func (c *Peer) deleteAllRequests() {
1547 for r := range c.requests {
1550 if len(c.requests) != 0 {
1551 panic(len(c.requests))
1553 // for c := range c.t.conns {
1558 // This is called when something has changed that should wake the writer, such as putting stuff into
1559 // the writeBuffer, or changing some state that the writer can act on.
1560 func (c *PeerConn) tickleWriter() {
1561 c.writerCond.Broadcast()
1564 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1565 c.lastChunkSent = time.Now()
1566 return msg(pp.Message{
1574 func (c *PeerConn) setTorrent(t *Torrent) {
1576 panic("connection already associated with a torrent")
1579 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1580 t.reconcileHandshakeStats(c)
1583 func (c *Peer) peerPriority() (peerPriority, error) {
1584 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1587 func (c *Peer) remoteIp() net.IP {
1588 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1589 return net.ParseIP(host)
1592 func (c *Peer) remoteIpPort() IpPort {
1593 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1594 return IpPort{ipa.IP, uint16(ipa.Port)}
1597 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1598 f := pp.PexPeerFlags(0)
1599 if c.PeerPrefersEncryption {
1600 f |= pp.PexPrefersEncryption
1603 f |= pp.PexOutgoingConn
1606 f |= pp.PexSupportsUtp
1611 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1612 // advertised listen port.
1613 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1614 if !c.outgoing && c.PeerListenPort != 0 {
1615 switch addr := c.RemoteAddr.(type) {
1618 dialAddr.Port = c.PeerListenPort
1622 dialAddr.Port = c.PeerListenPort
1629 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1630 f := c.pexPeerFlags()
1631 addr := c.dialAddr()
1632 return pexEvent{t, addr, f}
1635 func (c *PeerConn) String() string {
1636 return fmt.Sprintf("connection %p", c)
1639 func (c *Peer) trust() connectionTrust {
1640 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1643 type connectionTrust struct {
1645 NetGoodPiecesDirted int64
1648 func (l connectionTrust) Less(r connectionTrust) bool {
1649 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1652 func (cn *Peer) peerMaxRequests() int {
1653 return cn.PeerMaxRequests
1656 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1657 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1658 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1660 defer cn.locker().RUnlock()
1661 return cn.newPeerPieces()
1664 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1665 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1666 ret := cn._peerPieces.Copy()
1667 if cn.peerSentHaveAll {
1668 if cn.t.haveInfo() {
1669 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1671 ret.AddRange(0, bitmap.ToEnd)
1677 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1678 return &cn._pieceRequestOrder
1681 func (cn *Peer) stats() *ConnStats {
1685 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1686 pc, ok := p.peerImpl.(*PeerConn)