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.BitIndex(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.BitIndex(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()
399 p.t.decPeerPieceAvailability(p)
400 for _, f := range p.callbacks.PeerClosed {
405 func (cn *PeerConn) onClose() {
406 if cn.pex.IsEnabled() {
413 if cb := cn.callbacks.PeerConnClosed; cb != nil {
418 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
419 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
422 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
423 // https://github.com/pion/datachannel/issues/59 is fixed.
424 const writeBufferHighWaterLen = 1 << 15
426 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
427 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
428 func (cn *PeerConn) write(msg pp.Message) bool {
429 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
430 // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
431 // (although there's some delay between us recording the message, and the connection writer
432 // flushing it out.).
433 cn.writeBuffer.Write(msg.MustMarshalBinary())
434 // Last I checked only Piece messages affect stats, and we don't write those.
437 return !cn.writeBufferFull()
440 func (cn *PeerConn) writeBufferFull() bool {
441 return cn.writeBuffer.Len() >= writeBufferHighWaterLen
444 func (cn *PeerConn) requestMetadataPiece(index int) {
445 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
449 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
452 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
456 ExtendedPayload: func() []byte {
457 b, err := bencode.Marshal(map[string]int{
458 "msg_type": pp.RequestMetadataExtensionMsgType,
467 for index >= len(cn.metadataRequests) {
468 cn.metadataRequests = append(cn.metadataRequests, false)
470 cn.metadataRequests[index] = true
473 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
474 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
477 // The actual value to use as the maximum outbound requests.
478 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
479 return int(clamp(1, 2*int64(cn.maxPiecesReceivedBetweenRequestUpdates), int64(cn.PeerMaxRequests)))
482 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
483 ret = cn.cumulativeExpectedToReceiveChunks
484 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
485 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
491 func (cn *PeerConn) onPeerSentCancel(r Request) {
492 if _, ok := cn.peerRequests[r]; !ok {
493 torrent.Add("unexpected cancels received", 1)
496 if cn.fastEnabled() {
499 delete(cn.peerRequests, r)
503 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
508 more = msg(pp.Message{
511 if cn.fastEnabled() {
512 for r := range cn.peerRequests {
513 // TODO: Don't reject pieces in allowed fast set.
517 cn.peerRequests = nil
522 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
527 return msg(pp.Message{
532 func (cn *Peer) setInterested(interested bool) bool {
533 if cn.interested == interested {
536 cn.interested = interested
538 cn.lastBecameInterested = time.Now()
539 } else if !cn.lastBecameInterested.IsZero() {
540 cn.priorInterest += time.Since(cn.lastBecameInterested)
542 cn.updateExpectingChunks()
543 // log.Printf("%p: setting interest: %v", cn, interested)
544 return cn.writeInterested(interested)
547 func (pc *PeerConn) writeInterested(interested bool) bool {
548 return pc.write(pp.Message{
549 Type: func() pp.MessageType {
553 return pp.NotInterested
559 // The function takes a message to be sent, and returns true if more messages
561 type messageWriter func(pp.Message) bool
563 func (cn *Peer) shouldRequest(r Request) error {
564 if !cn.peerHasPiece(pieceIndex(r.Index)) {
565 return errors.New("requesting piece peer doesn't have")
567 if !cn.t.peerIsActive(cn) {
568 panic("requesting but not in active conns")
570 if cn.closed.IsSet() {
571 panic("requesting when connection is closed")
573 if cn.t.hashingPiece(pieceIndex(r.Index)) {
574 panic("piece is being hashed")
576 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
577 panic("piece is queued for hash")
582 func (cn *Peer) request(r Request) error {
583 if err := cn.shouldRequest(r); err != nil {
586 if _, ok := cn.requests[r]; ok {
589 if cn.numLocalRequests() >= cn.nominalMaxRequests() {
590 return errors.New("too many outstanding requests")
592 if cn.requests == nil {
593 cn.requests = make(map[Request]struct{})
595 cn.requests[r] = struct{}{}
596 if cn.validReceiveChunks == nil {
597 cn.validReceiveChunks = make(map[Request]int)
599 cn.validReceiveChunks[r]++
600 cn.t.pendingRequests[r]++
601 cn.updateExpectingChunks()
602 for _, f := range cn.callbacks.SentRequest {
603 f(PeerRequestEvent{cn, r})
605 cn.peerImpl._request(r)
609 func (me *PeerConn) _request(r Request) {
618 func (me *Peer) cancel(r Request) {
619 if me.deleteRequest(r) {
620 me.peerImpl._cancel(r)
624 func (me *PeerConn) _cancel(r Request) {
625 me.write(makeCancelMessage(r))
628 func (cn *PeerConn) fillWriteBuffer() {
629 if cn.pex.IsEnabled() {
630 if flow := cn.pex.Share(cn.write); !flow {
637 // Routine that writes to the peer. Some of what to write is buffered by
638 // activity elsewhere in the Client, and some is determined locally when the
639 // connection is writable.
640 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
642 lastWrite time.Time = time.Now()
643 keepAliveTimer *time.Timer
645 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
647 defer cn.locker().Unlock()
648 if time.Since(lastWrite) >= keepAliveTimeout {
651 keepAliveTimer.Reset(keepAliveTimeout)
654 defer cn.locker().Unlock()
656 defer keepAliveTimer.Stop()
657 frontBuf := new(bytes.Buffer)
659 if cn.closed.IsSet() {
662 if cn.writeBuffer.Len() == 0 {
665 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
666 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
667 torrent.Add("written keepalives", 1)
669 if cn.writeBuffer.Len() == 0 {
670 // TODO: Minimize wakeups....
675 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
677 n, err := cn.w.Write(frontBuf.Bytes())
680 lastWrite = time.Now()
681 keepAliveTimer.Reset(keepAliveTimeout)
684 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
687 if n != frontBuf.Len() {
694 func (cn *PeerConn) have(piece pieceIndex) {
695 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
700 Index: pp.Integer(piece),
702 cn.sentHaves.Add(bitmap.BitIndex(piece))
705 func (cn *PeerConn) postBitfield() {
706 if cn.sentHaves.Len() != 0 {
707 panic("bitfield must be first have-related message sent")
709 if !cn.t.haveAnyPieces() {
714 Bitfield: cn.t.bitfield(),
716 cn.sentHaves = cn.t._completedPieces.Copy()
719 func (cn *PeerConn) updateRequests() {
720 // log.Print("update requests")
724 // Emits the indices in the Bitmaps bms in order, never repeating any index.
725 // skip is mutated during execution, and its initial values will never be
727 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
728 return func(cb iter.Callback) {
729 for _, bm := range bms {
731 func(_i interface{}) bool {
733 if skip.Contains(i) {
747 // check callers updaterequests
748 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
749 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
752 // This is distinct from Torrent piece priority, which is the user's
753 // preference. Connection piece priority is specific to a connection and is
754 // used to pseudorandomly avoid connections always requesting the same pieces
755 // and thus wasting effort.
756 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
757 tpp := cn.t.piecePriority(piece)
758 if !cn.peerHasPiece(piece) {
759 tpp = PiecePriorityNone
761 if tpp == PiecePriorityNone {
762 return cn.stopRequestingPiece(piece)
764 prio := cn.getPieceInclination()[piece]
765 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio)
768 func (cn *Peer) getPieceInclination() []int {
769 if cn.pieceInclination == nil {
770 cn.pieceInclination = cn.t.getConnPieceInclination()
772 return cn.pieceInclination
775 func (cn *Peer) discardPieceInclination() {
776 if cn.pieceInclination == nil {
779 cn.t.putPieceInclination(cn.pieceInclination)
780 cn.pieceInclination = nil
783 func (cn *Peer) peerPiecesChanged() {
785 prioritiesChanged := false
786 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
787 if cn.updatePiecePriority(i) {
788 prioritiesChanged = true
791 if prioritiesChanged {
795 cn.t.maybeDropMutuallyCompletePeer(cn)
798 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
799 if newMin > cn.peerMinPieces {
800 cn.peerMinPieces = newMin
804 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
805 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
806 return errors.New("invalid piece")
808 if cn.peerHasPiece(piece) {
811 cn.raisePeerMinPieces(piece + 1)
812 if !cn.peerHasPiece(piece) {
813 cn.t.incPieceAvailability(piece)
815 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
816 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
817 if cn.updatePiecePriority(piece) {
823 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
825 panic("expected bitfield length divisible by 8")
827 // We know that the last byte means that at most the last 7 bits are wasted.
828 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
829 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
830 // Ignore known excess pieces.
831 bf = bf[:cn.t.numPieces()]
833 pp := cn.newPeerPieces()
834 cn.peerSentHaveAll = false
835 for i, have := range bf {
837 cn.raisePeerMinPieces(pieceIndex(i) + 1)
839 cn.t.incPieceAvailability(i)
843 cn.t.decPieceAvailability(i)
846 cn._peerPieces.Set(i, have)
848 cn.peerPiecesChanged()
852 func (cn *Peer) onPeerHasAllPieces() {
855 pp := cn.newPeerPieces()
856 for i := range iter.N(t.numPieces()) {
858 t.incPieceAvailability(i)
862 cn.peerSentHaveAll = true
863 cn._peerPieces.Clear()
864 cn.peerPiecesChanged()
867 func (cn *PeerConn) onPeerSentHaveAll() error {
868 cn.onPeerHasAllPieces()
872 func (cn *PeerConn) peerSentHaveNone() error {
873 cn.t.decPeerPieceAvailability(&cn.Peer)
874 cn._peerPieces.Clear()
875 cn.peerSentHaveAll = false
876 cn.peerPiecesChanged()
880 func (c *PeerConn) requestPendingMetadata() {
884 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
885 // Peer doesn't support this.
888 // Request metadata pieces that we don't have in a random order.
890 for index := 0; index < c.t.metadataPieceCount(); index++ {
891 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
892 pending = append(pending, index)
895 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
896 for _, i := range pending {
897 c.requestMetadataPiece(i)
901 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
902 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
903 if msg.Type == pp.Extended {
904 for name, id := range cn.PeerExtensionIDs {
905 if id != msg.ExtendedID {
908 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
911 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
914 func (cn *PeerConn) readMsg(msg *pp.Message) {
915 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
918 // After handshake, we know what Torrent and Client stats to include for a
920 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
926 // All ConnStats that include this connection. Some objects are not known
927 // until the handshake is complete, after which it's expected to reconcile the
929 func (cn *Peer) allStats(f func(*ConnStats)) {
931 if cn.reconciledHandshakeStats {
932 cn.postHandshakeStats(f)
936 func (cn *PeerConn) wroteBytes(n int64) {
937 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
940 func (cn *PeerConn) readBytes(n int64) {
941 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
944 // Returns whether the connection could be useful to us. We're seeding and
945 // they want data, we don't have metainfo and they can provide it, etc.
946 func (c *Peer) useful() bool {
948 if c.closed.IsSet() {
952 return c.supportsExtension("ut_metadata")
954 if t.seeding() && c.peerInterested {
957 if c.peerHasWantedPieces() {
963 func (c *Peer) lastHelpful() (ret time.Time) {
964 ret = c.lastUsefulChunkReceived
965 if c.t.seeding() && c.lastChunkSent.After(ret) {
966 ret = c.lastChunkSent
971 func (c *PeerConn) fastEnabled() bool {
972 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
975 func (c *PeerConn) reject(r Request) {
976 if !c.fastEnabled() {
977 panic("fast not enabled")
979 c.write(r.ToMsg(pp.Reject))
980 delete(c.peerRequests, r)
983 func (c *PeerConn) onReadRequest(r Request) error {
984 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
985 if _, ok := c.peerRequests[r]; ok {
986 torrent.Add("duplicate requests received", 1)
990 torrent.Add("requests received while choking", 1)
992 torrent.Add("requests rejected while choking", 1)
997 // TODO: What if they've already requested this?
998 if len(c.peerRequests) >= localClientReqq {
999 torrent.Add("requests received while queue full", 1)
1000 if c.fastEnabled() {
1003 // BEP 6 says we may close here if we choose.
1006 if !c.t.havePiece(pieceIndex(r.Index)) {
1007 // This isn't necessarily them screwing up. We can drop pieces
1008 // from our storage, and can't communicate this to peers
1009 // except by reconnecting.
1010 requestsReceivedForMissingPieces.Add(1)
1011 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1013 // Check this after we know we have the piece, so that the piece length will be known.
1014 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1015 torrent.Add("bad requests received", 1)
1016 return errors.New("bad Request")
1018 if c.peerRequests == nil {
1019 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1021 value := &peerRequestState{}
1022 c.peerRequests[r] = value
1023 go c.peerRequestDataReader(r, value)
1028 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1029 b, err := readPeerRequestData(r, c)
1031 defer c.locker().Unlock()
1033 c.peerRequestDataReadFailed(err, r)
1036 panic("data must be non-nil to trigger send")
1043 // If this is maintained correctly, we might be able to support optional synchronous reading for
1044 // chunk sending, the way it used to work.
1045 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1046 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1047 i := pieceIndex(r.Index)
1048 if c.t.pieceComplete(i) {
1049 // There used to be more code here that just duplicated the following break. Piece
1050 // completions are currently cached, so I'm not sure how helpful this update is, except to
1051 // pull any completion changes pushed to the storage backend in failed reads that got us
1053 c.t.updatePieceCompletion(i)
1055 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1056 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1057 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1058 // next connect. TODO: Support rejecting here too.
1060 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1065 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1066 b := make([]byte, r.Length)
1067 p := c.t.info.Piece(int(r.Index))
1068 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1075 panic("expected error")
1081 func runSafeExtraneous(f func()) {
1089 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1090 // exit. Returning will end the connection.
1091 func (c *PeerConn) mainReadLoop() (err error) {
1094 torrent.Add("connection.mainReadLoop returned with error", 1)
1096 torrent.Add("connection.mainReadLoop returned with no error", 1)
1102 decoder := pp.Decoder{
1103 R: bufio.NewReaderSize(c.r, 1<<17),
1104 MaxLength: 256 * 1024,
1112 err = decoder.Decode(&msg)
1114 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1117 if t.closed.IsSet() || c.closed.IsSet() {
1124 c.lastMessageReceived = time.Now()
1126 receivedKeepalives.Add(1)
1129 messageTypesReceived.Add(msg.Type.String(), 1)
1130 if msg.Type.FastExtension() && !c.fastEnabled() {
1131 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1132 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1136 c.peerChoking = true
1137 if !c.fastEnabled() {
1138 c.deleteAllRequests()
1140 // We can then reset our interest.
1142 c.updateExpectingChunks()
1144 c.peerChoking = false
1146 c.updateExpectingChunks()
1148 c.peerInterested = true
1150 case pp.NotInterested:
1151 c.peerInterested = false
1152 // We don't clear their requests since it isn't clear in the spec.
1153 // We'll probably choke them for this, which will clear them if
1154 // appropriate, and is clearly specified.
1156 err = c.peerSentHave(pieceIndex(msg.Index))
1158 err = c.peerSentBitfield(msg.Bitfield)
1160 r := newRequestFromMessage(&msg)
1161 err = c.onReadRequest(r)
1163 err = c.receiveChunk(&msg)
1164 if len(msg.Piece) == int(t.chunkSize) {
1165 t.chunkPool.Put(&msg.Piece)
1168 err = fmt.Errorf("receiving chunk: %s", err)
1171 req := newRequestFromMessage(&msg)
1172 c.onPeerSentCancel(req)
1174 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1178 pingAddr := net.UDPAddr{
1183 pingAddr.Port = int(msg.Port)
1185 cl.eachDhtServer(func(s DhtServer) {
1186 go s.Ping(&pingAddr)
1189 torrent.Add("suggests received", 1)
1190 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1193 err = c.onPeerSentHaveAll()
1195 err = c.peerSentHaveNone()
1197 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1198 case pp.AllowedFast:
1199 torrent.Add("allowed fasts received", 1)
1200 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1201 c.peerAllowedFast.Add(int(msg.Index))
1204 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1206 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1214 func (c *Peer) remoteRejectedRequest(r Request) {
1215 if c.deleteRequest(r) {
1216 c.decExpectedChunkReceive(r)
1220 func (c *Peer) decExpectedChunkReceive(r Request) {
1221 count := c.validReceiveChunks[r]
1223 delete(c.validReceiveChunks, r)
1224 } else if count > 1 {
1225 c.validReceiveChunks[r] = count - 1
1231 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1233 // TODO: Should we still do this?
1235 // These clients use their own extension IDs for outgoing message
1236 // types, which is incorrect.
1237 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1245 case pp.HandshakeExtendedID:
1246 var d pp.ExtendedHandshakeMessage
1247 if err := bencode.Unmarshal(payload, &d); err != nil {
1248 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1249 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1251 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1254 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1256 c.PeerMaxRequests = d.Reqq
1258 c.PeerClientName = d.V
1259 if c.PeerExtensionIDs == nil {
1260 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1262 c.PeerListenPort = d.Port
1263 c.PeerPrefersEncryption = d.Encryption
1264 for name, id := range d.M {
1265 if _, ok := c.PeerExtensionIDs[name]; !ok {
1266 peersSupportingExtension.Add(string(name), 1)
1268 c.PeerExtensionIDs[name] = id
1270 if d.MetadataSize != 0 {
1271 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1272 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1275 c.requestPendingMetadata()
1276 if !t.cl.config.DisablePEX {
1277 t.pex.Add(c) // we learnt enough now
1281 case metadataExtendedId:
1282 err := cl.gotMetadataExtensionMsg(payload, t, c)
1284 return fmt.Errorf("handling metadata extension message: %w", err)
1288 if !c.pex.IsEnabled() {
1289 return nil // or hang-up maybe?
1291 return c.pex.Recv(payload)
1293 return fmt.Errorf("unexpected extended message ID: %v", id)
1297 // Set both the Reader and Writer for the connection from a single ReadWriter.
1298 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1303 // Returns the Reader and Writer as a combined ReadWriter.
1304 func (cn *PeerConn) rw() io.ReadWriter {
1311 // Handle a received chunk from a peer.
1312 func (c *Peer) receiveChunk(msg *pp.Message) error {
1315 chunksReceived.Add("total", 1)
1317 req := newRequestFromMessage(msg)
1320 chunksReceived.Add("while choked", 1)
1323 if c.validReceiveChunks[req] <= 0 {
1324 chunksReceived.Add("unexpected", 1)
1325 return errors.New("received unexpected chunk")
1327 c.decExpectedChunkReceive(req)
1329 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1330 chunksReceived.Add("due to allowed fast", 1)
1333 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1334 // have actually already received the piece, while we have the Client unlocked to write the data
1336 deletedRequest := false
1338 if _, ok := c.requests[req]; ok {
1339 for _, f := range c.callbacks.ReceivedRequested {
1340 f(PeerMessageEvent{c, msg})
1343 // Request has been satisfied.
1344 if c.deleteRequest(req) {
1345 deletedRequest = true
1347 c._chunksReceivedWhileExpecting++
1350 chunksReceived.Add("unwanted", 1)
1354 // Do we actually want this chunk?
1355 if t.haveChunk(req) {
1356 chunksReceived.Add("wasted", 1)
1357 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1361 piece := &t.pieces[req.Index]
1363 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1364 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1366 c.piecesReceivedSinceLastRequestUpdate++
1367 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1369 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1370 f(ReceivedUsefulDataEvent{c, msg})
1372 c.lastUsefulChunkReceived = time.Now()
1374 // Need to record that it hasn't been written yet, before we attempt to do
1375 // anything with it.
1376 piece.incrementPendingWrites()
1377 // Record that we have the chunk, so we aren't trying to download it while
1378 // waiting for it to be written to storage.
1379 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1381 // Cancel pending requests for this chunk from *other* peers.
1382 t.iterPeers(func(p *Peer) {
1389 err := func() error {
1392 concurrentChunkWrites.Add(1)
1393 defer concurrentChunkWrites.Add(-1)
1394 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1395 // number of connections. We write inline with receiving the chunk (with this lock dance),
1396 // because we want to handle errors synchronously and I haven't thought of a nice way to
1397 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1399 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1402 piece.decrementPendingWrites()
1405 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1407 //t.updatePieceCompletion(pieceIndex(msg.Index))
1408 t.onWriteChunkErr(err)
1412 c.onDirtiedPiece(pieceIndex(req.Index))
1414 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1415 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1416 t.queuePieceCheck(pieceIndex(req.Index))
1417 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1418 // chunk status (such as the haveChunk call above) to have to check all the various other
1419 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1420 // that chunk pieces are pended at an appropriate time later however.
1423 cl.event.Broadcast()
1424 // We do this because we've written a chunk, and may change PieceState.Partial.
1425 t.publishPieceChange(pieceIndex(req.Index))
1430 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1431 if c.peerTouchedPieces == nil {
1432 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1434 c.peerTouchedPieces[piece] = struct{}{}
1435 ds := &c.t.pieces[piece].dirtiers
1437 *ds = make(map[*Peer]struct{})
1439 (*ds)[c] = struct{}{}
1442 func (c *PeerConn) uploadAllowed() bool {
1443 if c.t.cl.config.NoUpload {
1446 if c.t.dataUploadDisallowed {
1452 if !c.peerHasWantedPieces() {
1455 // Don't upload more than 100 KiB more than we download.
1456 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1462 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1463 if c.uploadTimer == nil {
1464 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1466 c.uploadTimer.Reset(delay)
1470 // Also handles choking and unchoking of the remote peer.
1471 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1472 // Breaking or completing this loop means we don't want to upload to the
1473 // peer anymore, and we choke them.
1475 for c.uploadAllowed() {
1476 // We want to upload to the peer.
1477 if !c.unchoke(msg) {
1480 for r, state := range c.peerRequests {
1481 if state.data == nil {
1484 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1486 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1488 delay := res.Delay()
1491 c.setRetryUploadTimer(delay)
1492 // Hard to say what to return here.
1495 more := c.sendChunk(r, msg, state)
1496 delete(c.peerRequests, r)
1507 func (cn *PeerConn) drop() {
1508 cn.t.dropConnection(cn)
1511 func (cn *Peer) netGoodPiecesDirtied() int64 {
1512 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1515 func (c *Peer) peerHasWantedPieces() bool {
1516 return !c._pieceRequestOrder.IsEmpty()
1519 func (c *Peer) numLocalRequests() int {
1520 return len(c.requests)
1523 func (c *Peer) deleteRequest(r Request) bool {
1524 if _, ok := c.requests[r]; !ok {
1527 delete(c.requests, r)
1528 for _, f := range c.callbacks.DeletedRequest {
1529 f(PeerRequestEvent{c, r})
1531 c.updateExpectingChunks()
1532 pr := c.t.pendingRequests
1544 func (c *Peer) deleteAllRequests() {
1545 for r := range c.requests {
1548 if len(c.requests) != 0 {
1549 panic(len(c.requests))
1551 // for c := range c.t.conns {
1556 // This is called when something has changed that should wake the writer, such as putting stuff into
1557 // the writeBuffer, or changing some state that the writer can act on.
1558 func (c *PeerConn) tickleWriter() {
1559 c.writerCond.Broadcast()
1562 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1563 c.lastChunkSent = time.Now()
1564 return msg(pp.Message{
1572 func (c *PeerConn) setTorrent(t *Torrent) {
1574 panic("connection already associated with a torrent")
1577 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1578 t.reconcileHandshakeStats(c)
1581 func (c *Peer) peerPriority() (peerPriority, error) {
1582 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1585 func (c *Peer) remoteIp() net.IP {
1586 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1587 return net.ParseIP(host)
1590 func (c *Peer) remoteIpPort() IpPort {
1591 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1592 return IpPort{ipa.IP, uint16(ipa.Port)}
1595 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1596 f := pp.PexPeerFlags(0)
1597 if c.PeerPrefersEncryption {
1598 f |= pp.PexPrefersEncryption
1601 f |= pp.PexOutgoingConn
1604 f |= pp.PexSupportsUtp
1609 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1610 // advertised listen port.
1611 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1612 if !c.outgoing && c.PeerListenPort != 0 {
1613 switch addr := c.RemoteAddr.(type) {
1616 dialAddr.Port = c.PeerListenPort
1620 dialAddr.Port = c.PeerListenPort
1627 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1628 f := c.pexPeerFlags()
1629 addr := c.dialAddr()
1630 return pexEvent{t, addr, f}
1633 func (c *PeerConn) String() string {
1634 return fmt.Sprintf("connection %p", c)
1637 func (c *Peer) trust() connectionTrust {
1638 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1641 type connectionTrust struct {
1643 NetGoodPiecesDirted int64
1646 func (l connectionTrust) Less(r connectionTrust) bool {
1647 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1650 func (cn *Peer) peerMaxRequests() int {
1651 return cn.PeerMaxRequests
1654 // Returns the pieces the peer has claimed to have.
1655 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1657 defer cn.locker().RUnlock()
1658 return cn.newPeerPieces()
1661 // Returns a new Bitmap that includes bits for all pieces we have.
1662 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1663 ret := cn._peerPieces.Copy()
1664 if cn.peerSentHaveAll {
1665 ret.AddRange(0, cn.t.numPieces())
1670 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1671 return &cn._pieceRequestOrder
1674 func (cn *Peer) stats() *ConnStats {
1678 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1679 pc, ok := p.peerImpl.(*PeerConn)