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 {
51 // First to ensure 64-bit alignment for atomics. See #262.
61 RemoteAddr PeerRemoteAddr
62 // True if the connection is operating over MSE obfuscation.
64 cryptoMethod mse.CryptoMethod
67 closed missinggo.Event
68 // Set true after we've added our ConnStats generated during handshake to
69 // other ConnStat instances as determined when the *Torrent became known.
70 reconciledHandshakeStats bool
72 lastMessageReceived time.Time
73 completedHandshake time.Time
74 lastUsefulChunkReceived time.Time
75 lastChunkSent time.Time
77 // Stuff controlled by the local peer.
79 lastBecameInterested time.Time
80 priorInterest time.Duration
82 lastStartedExpectingToReceiveChunks time.Time
83 cumulativeExpectedToReceiveChunks time.Duration
84 _chunksReceivedWhileExpecting int64
87 requests map[Request]struct{}
89 // Chunks that we might reasonably expect to receive from the peer. Due to
90 // latency, buffering, and implementation differences, we may receive
91 // chunks that are no longer in the set of requests actually want.
92 validReceiveChunks map[Request]int
93 // Indexed by metadata piece, set to true if posted and pending a
95 metadataRequests []bool
96 sentHaves bitmap.Bitmap
98 // Stuff controlled by the remote peer.
101 peerRequests map[Request]*peerRequestState
102 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
104 // The pieces the peer has claimed to have.
105 _peerPieces bitmap.Bitmap
106 // The peer has everything. This can occur due to a special message, when
107 // we may not even know the number of pieces in the torrent yet.
109 // The highest possible number of pieces the torrent could have based on
110 // communication with the peer. Generally only useful until we have the
112 peerMinPieces pieceIndex
113 // Pieces we've accepted chunks for from the peer.
114 peerTouchedPieces map[pieceIndex]struct{}
115 peerAllowedFast bitmap.Bitmap
117 PeerMaxRequests int // Maximum pending requests the peer allows.
118 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
119 PeerClientName string
121 pieceInclination []int
122 _pieceRequestOrder prioritybitmap.PriorityBitmap
127 // Maintains the state of a BitTorrent-protocol based connection with a peer.
128 type PeerConn struct {
131 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
132 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
137 PeerExtensionBytes pp.PeerExtensionBits
139 // The actual Conn, used for closing, and setting socket options.
141 // The Reader and Writer for this Conn, with hooks installed for stats,
142 // limiting, deadlines etc.
146 writeBuffer *bytes.Buffer
147 uploadTimer *time.Timer
153 func (cn *PeerConn) connStatusString() string {
154 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
157 func (cn *Peer) updateExpectingChunks() {
158 if cn.expectingChunks() {
159 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
160 cn.lastStartedExpectingToReceiveChunks = time.Now()
163 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
164 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
165 cn.lastStartedExpectingToReceiveChunks = time.Time{}
170 func (cn *Peer) expectingChunks() bool {
171 if len(cn.requests) == 0 {
177 for r := range cn.requests {
178 if !cn.remoteChokingPiece(r.Index.Int()) {
185 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
186 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
189 // Returns true if the connection is over IPv6.
190 func (cn *PeerConn) ipv6() bool {
195 return len(ip) == net.IPv6len
198 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
199 // specification for this.
200 func (cn *PeerConn) isPreferredDirection() bool {
201 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
204 // Returns whether the left connection should be preferred over the right one,
205 // considering only their networking properties. If ok is false, we can't
207 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
209 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
210 ml.NextBool(!l.utp(), !r.utp())
211 ml.NextBool(l.ipv6(), r.ipv6())
215 func (cn *Peer) cumInterest() time.Duration {
216 ret := cn.priorInterest
218 ret += time.Since(cn.lastBecameInterested)
223 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
224 if cn.peerSentHaveAll {
227 if !cn.t.haveInfo() {
230 return bitmap.Flip(cn._peerPieces, 0, bitmap.BitIndex(cn.t.numPieces())).IsEmpty(), true
233 func (cn *PeerConn) locker() *lockWithDeferreds {
234 return cn.t.cl.locker()
237 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
238 _, ok := cn.PeerExtensionIDs[ext]
242 // The best guess at number of pieces in the torrent for this peer.
243 func (cn *Peer) bestPeerNumPieces() pieceIndex {
245 return cn.t.numPieces()
247 return cn.peerMinPieces
250 func (cn *Peer) completedString() string {
251 have := pieceIndex(cn._peerPieces.Len())
252 if cn.peerSentHaveAll {
253 have = cn.bestPeerNumPieces()
255 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
258 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
259 cn.setNumPieces(info.NumPieces())
262 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
263 // receiving badly sized BITFIELD, or invalid HAVE messages.
264 func (cn *PeerConn) setNumPieces(num pieceIndex) {
265 cn._peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd)
266 cn.peerPiecesChanged()
269 func eventAgeString(t time.Time) string {
273 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
276 func (cn *PeerConn) connectionFlags() (ret string) {
278 ret += string([]byte{b})
280 if cn.cryptoMethod == mse.CryptoMethodRC4 {
282 } else if cn.headerEncrypted {
285 ret += string(cn.Discovery)
292 func (cn *PeerConn) utp() bool {
293 return parseNetworkString(cn.Network).Udp
296 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
297 func (cn *Peer) statusFlags() (ret string) {
299 ret += string([]byte{b})
308 ret += cn.connectionFlags()
310 if cn.peerInterested {
319 func (cn *Peer) downloadRate() float64 {
320 num := cn._stats.BytesReadUsefulData.Int64()
324 return float64(num) / cn.totalExpectingTime().Seconds()
327 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
328 ret = make(map[pieceIndex]int)
329 for r := range cn.requests {
330 ret[pieceIndex(r.Index)]++
335 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
336 // \t isn't preserved in <pre> blocks?
337 if cn.closed.IsSet() {
338 fmt.Fprint(w, "CLOSED: ")
340 fmt.Fprintln(w, cn.connStatusString())
341 prio, err := cn.peerPriority()
342 prioStr := fmt.Sprintf("%08x", prio)
344 prioStr += ": " + err.Error()
346 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
347 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
348 eventAgeString(cn.lastMessageReceived),
349 eventAgeString(cn.completedHandshake),
350 eventAgeString(cn.lastHelpful()),
352 cn.totalExpectingTime(),
355 " %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
356 cn.completedString(),
357 len(cn.peerTouchedPieces),
358 &cn._stats.ChunksReadUseful,
359 &cn._stats.ChunksRead,
360 &cn._stats.ChunksWritten,
361 cn.numLocalRequests(),
362 cn.nominalMaxRequests(),
364 len(cn.peerRequests),
367 cn.downloadRate()/(1<<10),
369 fmt.Fprintf(w, " requested pieces:")
370 type pieceNumRequestsType struct {
374 var pieceNumRequests []pieceNumRequestsType
375 for piece, count := range cn.numRequestsByPiece() {
376 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
378 sort.Slice(pieceNumRequests, func(i, j int) bool {
379 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
381 for _, elem := range pieceNumRequests {
382 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
387 func (p *Peer) close() {
391 p.discardPieceInclination()
392 p._pieceRequestOrder.Clear()
394 p.t.decPeerPieceAvailability(p)
395 for _, f := range p.callbacks.PeerClosed {
400 func (cn *PeerConn) onClose() {
401 if cn.pex.IsEnabled() {
408 if cb := cn.callbacks.PeerConnClosed; cb != nil {
413 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
414 return cn.peerSentHaveAll || cn._peerPieces.Contains(bitmap.BitIndex(piece))
417 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
418 // https://github.com/pion/datachannel/issues/59 is fixed.
419 const writeBufferHighWaterLen = 1 << 15
421 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
422 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
423 func (cn *PeerConn) write(msg pp.Message) bool {
424 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
425 // We don't need to track bytes here because a connection.w Writer wrapper takes care of that
426 // (although there's some delay between us recording the message, and the connection writer
427 // flushing it out.).
428 cn.writeBuffer.Write(msg.MustMarshalBinary())
429 // Last I checked only Piece messages affect stats, and we don't write those.
432 return !cn.writeBufferFull()
435 func (cn *PeerConn) writeBufferFull() bool {
436 return cn.writeBuffer.Len() >= writeBufferHighWaterLen
439 func (cn *PeerConn) requestMetadataPiece(index int) {
440 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
444 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
447 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
451 ExtendedPayload: func() []byte {
452 b, err := bencode.Marshal(map[string]int{
453 "msg_type": pp.RequestMetadataExtensionMsgType,
462 for index >= len(cn.metadataRequests) {
463 cn.metadataRequests = append(cn.metadataRequests, false)
465 cn.metadataRequests[index] = true
468 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
469 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
472 // The actual value to use as the maximum outbound requests.
473 func (cn *Peer) nominalMaxRequests() (ret int) {
474 return int(clamp(1, int64(cn.PeerMaxRequests), 64))
477 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
478 ret = cn.cumulativeExpectedToReceiveChunks
479 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
480 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
486 func (cn *PeerConn) onPeerSentCancel(r Request) {
487 if _, ok := cn.peerRequests[r]; !ok {
488 torrent.Add("unexpected cancels received", 1)
491 if cn.fastEnabled() {
494 delete(cn.peerRequests, r)
498 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
503 more = msg(pp.Message{
506 if cn.fastEnabled() {
507 for r := range cn.peerRequests {
508 // TODO: Don't reject pieces in allowed fast set.
512 cn.peerRequests = nil
517 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
522 return msg(pp.Message{
527 func (cn *Peer) setInterested(interested bool) bool {
528 if cn.interested == interested {
531 cn.interested = interested
533 cn.lastBecameInterested = time.Now()
534 } else if !cn.lastBecameInterested.IsZero() {
535 cn.priorInterest += time.Since(cn.lastBecameInterested)
537 cn.updateExpectingChunks()
538 // log.Printf("%p: setting interest: %v", cn, interested)
539 return cn.writeInterested(interested)
542 func (pc *PeerConn) writeInterested(interested bool) bool {
543 return pc.write(pp.Message{
544 Type: func() pp.MessageType {
548 return pp.NotInterested
554 // The function takes a message to be sent, and returns true if more messages
556 type messageWriter func(pp.Message) bool
558 func (cn *Peer) shouldRequest(r Request) error {
559 if !cn.peerHasPiece(pieceIndex(r.Index)) {
560 return errors.New("requesting piece peer doesn't have")
562 if !cn.t.peerIsActive(cn) {
563 panic("requesting but not in active conns")
565 if cn.closed.IsSet() {
566 panic("requesting when connection is closed")
568 if cn.t.hashingPiece(pieceIndex(r.Index)) {
569 panic("piece is being hashed")
571 if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) {
572 panic("piece is queued for hash")
577 func (cn *Peer) request(r Request) error {
578 if err := cn.shouldRequest(r); err != nil {
581 if _, ok := cn.requests[r]; ok {
584 if cn.numLocalRequests() >= cn.nominalMaxRequests() {
585 return errors.New("too many outstanding requests")
587 if cn.requests == nil {
588 cn.requests = make(map[Request]struct{})
590 cn.requests[r] = struct{}{}
591 if cn.validReceiveChunks == nil {
592 cn.validReceiveChunks = make(map[Request]int)
594 cn.validReceiveChunks[r]++
595 cn.t.pendingRequests[r]++
596 cn.updateExpectingChunks()
597 for _, f := range cn.callbacks.SentRequest {
598 f(PeerRequestEvent{cn, r})
600 cn.peerImpl._request(r)
604 func (me *PeerConn) _request(r Request) {
613 func (me *Peer) cancel(r Request) {
614 if me.deleteRequest(r) {
615 me.peerImpl._cancel(r)
619 func (me *PeerConn) _cancel(r Request) {
620 me.write(makeCancelMessage(r))
623 func (cn *PeerConn) fillWriteBuffer() {
624 if cn.pex.IsEnabled() {
625 if flow := cn.pex.Share(cn.write); !flow {
632 // Routine that writes to the peer. Some of what to write is buffered by
633 // activity elsewhere in the Client, and some is determined locally when the
634 // connection is writable.
635 func (cn *PeerConn) writer(keepAliveTimeout time.Duration) {
637 lastWrite time.Time = time.Now()
638 keepAliveTimer *time.Timer
640 keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() {
642 defer cn.locker().Unlock()
643 if time.Since(lastWrite) >= keepAliveTimeout {
646 keepAliveTimer.Reset(keepAliveTimeout)
649 defer cn.locker().Unlock()
651 defer keepAliveTimer.Stop()
652 frontBuf := new(bytes.Buffer)
654 if cn.closed.IsSet() {
657 if cn.writeBuffer.Len() == 0 {
660 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout && cn.useful() {
661 cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
662 torrent.Add("written keepalives", 1)
664 if cn.writeBuffer.Len() == 0 {
665 // TODO: Minimize wakeups....
670 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
672 n, err := cn.w.Write(frontBuf.Bytes())
675 lastWrite = time.Now()
676 keepAliveTimer.Reset(keepAliveTimeout)
679 cn.logger.WithDefaultLevel(log.Debug).Printf("error writing: %v", err)
682 if n != frontBuf.Len() {
689 func (cn *PeerConn) have(piece pieceIndex) {
690 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
695 Index: pp.Integer(piece),
697 cn.sentHaves.Add(bitmap.BitIndex(piece))
700 func (cn *PeerConn) postBitfield() {
701 if cn.sentHaves.Len() != 0 {
702 panic("bitfield must be first have-related message sent")
704 if !cn.t.haveAnyPieces() {
709 Bitfield: cn.t.bitfield(),
711 cn.sentHaves = cn.t._completedPieces.Copy()
714 func (cn *PeerConn) updateRequests() {
715 // log.Print("update requests")
719 // Emits the indices in the Bitmaps bms in order, never repeating any index.
720 // skip is mutated during execution, and its initial values will never be
722 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
723 return func(cb iter.Callback) {
724 for _, bm := range bms {
726 func(_i interface{}) bool {
728 if skip.Contains(i) {
742 // check callers updaterequests
743 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
744 return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
747 // This is distinct from Torrent piece priority, which is the user's
748 // preference. Connection piece priority is specific to a connection and is
749 // used to pseudorandomly avoid connections always requesting the same pieces
750 // and thus wasting effort.
751 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
752 tpp := cn.t.piecePriority(piece)
753 if !cn.peerHasPiece(piece) {
754 tpp = PiecePriorityNone
756 if tpp == PiecePriorityNone {
757 return cn.stopRequestingPiece(piece)
759 prio := cn.getPieceInclination()[piece]
760 return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio)
763 func (cn *Peer) getPieceInclination() []int {
764 if cn.pieceInclination == nil {
765 cn.pieceInclination = cn.t.getConnPieceInclination()
767 return cn.pieceInclination
770 func (cn *Peer) discardPieceInclination() {
771 if cn.pieceInclination == nil {
774 cn.t.putPieceInclination(cn.pieceInclination)
775 cn.pieceInclination = nil
778 func (cn *Peer) peerPiecesChanged() {
780 prioritiesChanged := false
781 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
782 if cn.updatePiecePriority(i) {
783 prioritiesChanged = true
786 if prioritiesChanged {
790 cn.t.maybeDropMutuallyCompletePeer(cn)
793 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
794 if newMin > cn.peerMinPieces {
795 cn.peerMinPieces = newMin
799 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
800 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
801 return errors.New("invalid piece")
803 if cn.peerHasPiece(piece) {
806 cn.raisePeerMinPieces(piece + 1)
807 if !cn.peerHasPiece(piece) {
808 cn.t.incPieceAvailability(piece)
810 cn._peerPieces.Set(bitmap.BitIndex(piece), true)
811 cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
812 if cn.updatePiecePriority(piece) {
818 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
820 panic("expected bitfield length divisible by 8")
822 // We know that the last byte means that at most the last 7 bits are wasted.
823 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
824 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
825 // Ignore known excess pieces.
826 bf = bf[:cn.t.numPieces()]
828 pp := cn.newPeerPieces()
829 cn.peerSentHaveAll = false
830 for i, have := range bf {
832 cn.raisePeerMinPieces(pieceIndex(i) + 1)
834 cn.t.incPieceAvailability(i)
838 cn.t.decPieceAvailability(i)
841 cn._peerPieces.Set(i, have)
843 cn.peerPiecesChanged()
847 func (cn *Peer) onPeerHasAllPieces() {
850 pp := cn.newPeerPieces()
851 for i := range iter.N(t.numPieces()) {
853 t.incPieceAvailability(i)
857 cn.peerSentHaveAll = true
858 cn._peerPieces.Clear()
859 cn.peerPiecesChanged()
862 func (cn *PeerConn) onPeerSentHaveAll() error {
863 cn.onPeerHasAllPieces()
867 func (cn *PeerConn) peerSentHaveNone() error {
868 cn.t.decPeerPieceAvailability(&cn.Peer)
869 cn._peerPieces.Clear()
870 cn.peerSentHaveAll = false
871 cn.peerPiecesChanged()
875 func (c *PeerConn) requestPendingMetadata() {
879 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
880 // Peer doesn't support this.
883 // Request metadata pieces that we don't have in a random order.
885 for index := 0; index < c.t.metadataPieceCount(); index++ {
886 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
887 pending = append(pending, index)
890 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
891 for _, i := range pending {
892 c.requestMetadataPiece(i)
896 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
897 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
898 if msg.Type == pp.Extended {
899 for name, id := range cn.PeerExtensionIDs {
900 if id != msg.ExtendedID {
903 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
906 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
909 func (cn *PeerConn) readMsg(msg *pp.Message) {
910 cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
913 // After handshake, we know what Torrent and Client stats to include for a
915 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
921 // All ConnStats that include this connection. Some objects are not known
922 // until the handshake is complete, after which it's expected to reconcile the
924 func (cn *Peer) allStats(f func(*ConnStats)) {
926 if cn.reconciledHandshakeStats {
927 cn.postHandshakeStats(f)
931 func (cn *PeerConn) wroteBytes(n int64) {
932 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
935 func (cn *PeerConn) readBytes(n int64) {
936 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
939 // Returns whether the connection could be useful to us. We're seeding and
940 // they want data, we don't have metainfo and they can provide it, etc.
941 func (c *Peer) useful() bool {
943 if c.closed.IsSet() {
947 return c.supportsExtension("ut_metadata")
949 if t.seeding() && c.peerInterested {
952 if c.peerHasWantedPieces() {
958 func (c *Peer) lastHelpful() (ret time.Time) {
959 ret = c.lastUsefulChunkReceived
960 if c.t.seeding() && c.lastChunkSent.After(ret) {
961 ret = c.lastChunkSent
966 func (c *PeerConn) fastEnabled() bool {
967 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
970 func (c *PeerConn) reject(r Request) {
971 if !c.fastEnabled() {
972 panic("fast not enabled")
974 c.write(r.ToMsg(pp.Reject))
975 delete(c.peerRequests, r)
978 func (c *PeerConn) onReadRequest(r Request) error {
979 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
980 if _, ok := c.peerRequests[r]; ok {
981 torrent.Add("duplicate requests received", 1)
985 torrent.Add("requests received while choking", 1)
987 torrent.Add("requests rejected while choking", 1)
992 // TODO: What if they've already requested this?
993 if len(c.peerRequests) >= localClientReqq {
994 torrent.Add("requests received while queue full", 1)
998 // BEP 6 says we may close here if we choose.
1001 if !c.t.havePiece(pieceIndex(r.Index)) {
1002 // This isn't necessarily them screwing up. We can drop pieces
1003 // from our storage, and can't communicate this to peers
1004 // except by reconnecting.
1005 requestsReceivedForMissingPieces.Add(1)
1006 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1008 // Check this after we know we have the piece, so that the piece length will be known.
1009 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1010 torrent.Add("bad requests received", 1)
1011 return errors.New("bad Request")
1013 if c.peerRequests == nil {
1014 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1016 value := &peerRequestState{}
1017 c.peerRequests[r] = value
1018 go c.peerRequestDataReader(r, value)
1023 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1024 b, err := readPeerRequestData(r, c)
1026 defer c.locker().Unlock()
1028 c.peerRequestDataReadFailed(err, r)
1031 panic("data must be non-nil to trigger send")
1038 // If this is maintained correctly, we might be able to support optional synchronous reading for
1039 // chunk sending, the way it used to work.
1040 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1041 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1042 i := pieceIndex(r.Index)
1043 if c.t.pieceComplete(i) {
1044 // There used to be more code here that just duplicated the following break. Piece
1045 // completions are currently cached, so I'm not sure how helpful this update is, except to
1046 // pull any completion changes pushed to the storage backend in failed reads that got us
1048 c.t.updatePieceCompletion(i)
1050 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1051 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1052 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1053 // next connect. TODO: Support rejecting here too.
1055 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1060 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1061 b := make([]byte, r.Length)
1062 p := c.t.info.Piece(int(r.Index))
1063 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1070 panic("expected error")
1076 func runSafeExtraneous(f func()) {
1084 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1085 // exit. Returning will end the connection.
1086 func (c *PeerConn) mainReadLoop() (err error) {
1089 torrent.Add("connection.mainReadLoop returned with error", 1)
1091 torrent.Add("connection.mainReadLoop returned with no error", 1)
1097 decoder := pp.Decoder{
1098 R: bufio.NewReaderSize(c.r, 1<<17),
1099 MaxLength: 256 * 1024,
1107 err = decoder.Decode(&msg)
1109 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1112 if t.closed.IsSet() || c.closed.IsSet() {
1119 c.lastMessageReceived = time.Now()
1121 receivedKeepalives.Add(1)
1124 messageTypesReceived.Add(msg.Type.String(), 1)
1125 if msg.Type.FastExtension() && !c.fastEnabled() {
1126 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1127 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1131 c.peerChoking = true
1132 if !c.fastEnabled() {
1133 c.deleteAllRequests()
1135 // We can then reset our interest.
1137 c.updateExpectingChunks()
1139 c.peerChoking = false
1141 c.updateExpectingChunks()
1143 c.peerInterested = true
1145 case pp.NotInterested:
1146 c.peerInterested = false
1147 // We don't clear their requests since it isn't clear in the spec.
1148 // We'll probably choke them for this, which will clear them if
1149 // appropriate, and is clearly specified.
1151 err = c.peerSentHave(pieceIndex(msg.Index))
1153 err = c.peerSentBitfield(msg.Bitfield)
1155 r := newRequestFromMessage(&msg)
1156 err = c.onReadRequest(r)
1158 err = c.receiveChunk(&msg)
1159 if len(msg.Piece) == int(t.chunkSize) {
1160 t.chunkPool.Put(&msg.Piece)
1163 err = fmt.Errorf("receiving chunk: %s", err)
1166 req := newRequestFromMessage(&msg)
1167 c.onPeerSentCancel(req)
1169 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1173 pingAddr := net.UDPAddr{
1178 pingAddr.Port = int(msg.Port)
1180 cl.eachDhtServer(func(s DhtServer) {
1181 go s.Ping(&pingAddr)
1184 torrent.Add("suggests received", 1)
1185 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1188 err = c.onPeerSentHaveAll()
1190 err = c.peerSentHaveNone()
1192 c.remoteRejectedRequest(newRequestFromMessage(&msg))
1193 case pp.AllowedFast:
1194 torrent.Add("allowed fasts received", 1)
1195 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1196 c.peerAllowedFast.Add(int(msg.Index))
1199 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1201 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1209 func (c *Peer) remoteRejectedRequest(r Request) {
1210 if c.deleteRequest(r) {
1211 c.decExpectedChunkReceive(r)
1215 func (c *Peer) decExpectedChunkReceive(r Request) {
1216 count := c.validReceiveChunks[r]
1218 delete(c.validReceiveChunks, r)
1219 } else if count > 1 {
1220 c.validReceiveChunks[r] = count - 1
1226 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1228 // TODO: Should we still do this?
1230 // These clients use their own extension IDs for outgoing message
1231 // types, which is incorrect.
1232 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1240 case pp.HandshakeExtendedID:
1241 var d pp.ExtendedHandshakeMessage
1242 if err := bencode.Unmarshal(payload, &d); err != nil {
1243 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1244 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1246 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1249 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1251 c.PeerMaxRequests = d.Reqq
1253 c.PeerClientName = d.V
1254 if c.PeerExtensionIDs == nil {
1255 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1257 c.PeerListenPort = d.Port
1258 c.PeerPrefersEncryption = d.Encryption
1259 for name, id := range d.M {
1260 if _, ok := c.PeerExtensionIDs[name]; !ok {
1261 peersSupportingExtension.Add(string(name), 1)
1263 c.PeerExtensionIDs[name] = id
1265 if d.MetadataSize != 0 {
1266 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1267 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1270 c.requestPendingMetadata()
1271 if !t.cl.config.DisablePEX {
1272 t.pex.Add(c) // we learnt enough now
1276 case metadataExtendedId:
1277 err := cl.gotMetadataExtensionMsg(payload, t, c)
1279 return fmt.Errorf("handling metadata extension message: %w", err)
1283 if !c.pex.IsEnabled() {
1284 return nil // or hang-up maybe?
1286 return c.pex.Recv(payload)
1288 return fmt.Errorf("unexpected extended message ID: %v", id)
1292 // Set both the Reader and Writer for the connection from a single ReadWriter.
1293 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1298 // Returns the Reader and Writer as a combined ReadWriter.
1299 func (cn *PeerConn) rw() io.ReadWriter {
1306 // Handle a received chunk from a peer.
1307 func (c *Peer) receiveChunk(msg *pp.Message) error {
1310 chunksReceived.Add("total", 1)
1312 req := newRequestFromMessage(msg)
1315 chunksReceived.Add("while choked", 1)
1318 if c.validReceiveChunks[req] <= 0 {
1319 chunksReceived.Add("unexpected", 1)
1320 return errors.New("received unexpected chunk")
1322 c.decExpectedChunkReceive(req)
1324 if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1325 chunksReceived.Add("due to allowed fast", 1)
1328 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1329 // have actually already received the piece, while we have the Client unlocked to write the data
1331 deletedRequest := false
1333 if _, ok := c.requests[req]; ok {
1334 for _, f := range c.callbacks.ReceivedRequested {
1335 f(PeerMessageEvent{c, msg})
1338 // Request has been satisfied.
1339 if c.deleteRequest(req) {
1340 deletedRequest = true
1342 c._chunksReceivedWhileExpecting++
1345 chunksReceived.Add("unwanted", 1)
1349 // Do we actually want this chunk?
1350 if t.haveChunk(req) {
1351 chunksReceived.Add("wasted", 1)
1352 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1356 piece := &t.pieces[req.Index]
1358 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1359 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1361 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1363 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1364 f(ReceivedUsefulDataEvent{c, msg})
1366 c.lastUsefulChunkReceived = time.Now()
1368 // Need to record that it hasn't been written yet, before we attempt to do
1369 // anything with it.
1370 piece.incrementPendingWrites()
1371 // Record that we have the chunk, so we aren't trying to download it while
1372 // waiting for it to be written to storage.
1373 piece.unpendChunkIndex(chunkIndex(req.ChunkSpec, t.chunkSize))
1375 // Cancel pending requests for this chunk from *other* peers.
1376 t.iterPeers(func(p *Peer) {
1383 err := func() error {
1386 concurrentChunkWrites.Add(1)
1387 defer concurrentChunkWrites.Add(-1)
1388 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1389 // number of connections. We write inline with receiving the chunk (with this lock dance),
1390 // because we want to handle errors synchronously and I haven't thought of a nice way to
1391 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1393 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1396 piece.decrementPendingWrites()
1399 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1401 //t.updatePieceCompletion(pieceIndex(msg.Index))
1402 t.onWriteChunkErr(err)
1406 c.onDirtiedPiece(pieceIndex(req.Index))
1408 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1409 if t.pieceAllDirty(pieceIndex(req.Index)) && piece.pendingWrites == 0 {
1410 t.queuePieceCheck(pieceIndex(req.Index))
1411 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1412 // chunk status (such as the haveChunk call above) to have to check all the various other
1413 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1414 // that chunk pieces are pended at an appropriate time later however.
1417 cl.event.Broadcast()
1418 // We do this because we've written a chunk, and may change PieceState.Partial.
1419 t.publishPieceChange(pieceIndex(req.Index))
1424 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1425 if c.peerTouchedPieces == nil {
1426 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1428 c.peerTouchedPieces[piece] = struct{}{}
1429 ds := &c.t.pieces[piece].dirtiers
1431 *ds = make(map[*Peer]struct{})
1433 (*ds)[c] = struct{}{}
1436 func (c *PeerConn) uploadAllowed() bool {
1437 if c.t.cl.config.NoUpload {
1440 if c.t.dataUploadDisallowed {
1446 if !c.peerHasWantedPieces() {
1449 // Don't upload more than 100 KiB more than we download.
1450 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1456 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1457 if c.uploadTimer == nil {
1458 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1460 c.uploadTimer.Reset(delay)
1464 // Also handles choking and unchoking of the remote peer.
1465 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1466 // Breaking or completing this loop means we don't want to upload to the
1467 // peer anymore, and we choke them.
1469 for c.uploadAllowed() {
1470 // We want to upload to the peer.
1471 if !c.unchoke(msg) {
1474 for r, state := range c.peerRequests {
1475 if state.data == nil {
1478 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1480 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1482 delay := res.Delay()
1485 c.setRetryUploadTimer(delay)
1486 // Hard to say what to return here.
1489 more := c.sendChunk(r, msg, state)
1490 delete(c.peerRequests, r)
1501 func (cn *PeerConn) drop() {
1502 cn.t.dropConnection(cn)
1505 func (cn *Peer) netGoodPiecesDirtied() int64 {
1506 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1509 func (c *Peer) peerHasWantedPieces() bool {
1510 return !c._pieceRequestOrder.IsEmpty()
1513 func (c *Peer) numLocalRequests() int {
1514 return len(c.requests)
1517 func (c *Peer) deleteRequest(r Request) bool {
1518 if _, ok := c.requests[r]; !ok {
1521 delete(c.requests, r)
1522 for _, f := range c.callbacks.DeletedRequest {
1523 f(PeerRequestEvent{c, r})
1525 c.updateExpectingChunks()
1526 pr := c.t.pendingRequests
1538 func (c *Peer) deleteAllRequests() {
1539 for r := range c.requests {
1542 if len(c.requests) != 0 {
1543 panic(len(c.requests))
1545 // for c := range c.t.conns {
1550 // This is called when something has changed that should wake the writer, such as putting stuff into
1551 // the writeBuffer, or changing some state that the writer can act on.
1552 func (c *PeerConn) tickleWriter() {
1553 c.writerCond.Broadcast()
1556 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1557 c.lastChunkSent = time.Now()
1558 return msg(pp.Message{
1566 func (c *PeerConn) setTorrent(t *Torrent) {
1568 panic("connection already associated with a torrent")
1571 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1572 t.reconcileHandshakeStats(c)
1575 func (c *Peer) peerPriority() (peerPriority, error) {
1576 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1579 func (c *Peer) remoteIp() net.IP {
1580 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1581 return net.ParseIP(host)
1584 func (c *Peer) remoteIpPort() IpPort {
1585 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1586 return IpPort{ipa.IP, uint16(ipa.Port)}
1589 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1590 f := pp.PexPeerFlags(0)
1591 if c.PeerPrefersEncryption {
1592 f |= pp.PexPrefersEncryption
1595 f |= pp.PexOutgoingConn
1598 f |= pp.PexSupportsUtp
1603 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1604 // advertised listen port.
1605 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1606 if !c.outgoing && c.PeerListenPort != 0 {
1607 switch addr := c.RemoteAddr.(type) {
1610 dialAddr.Port = c.PeerListenPort
1614 dialAddr.Port = c.PeerListenPort
1621 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1622 f := c.pexPeerFlags()
1623 addr := c.dialAddr()
1624 return pexEvent{t, addr, f}
1627 func (c *PeerConn) String() string {
1628 return fmt.Sprintf("connection %p", c)
1631 func (c *Peer) trust() connectionTrust {
1632 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1635 type connectionTrust struct {
1637 NetGoodPiecesDirted int64
1640 func (l connectionTrust) Less(r connectionTrust) bool {
1641 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1644 func (cn *Peer) peerMaxRequests() int {
1645 return cn.PeerMaxRequests
1648 // Returns the pieces the peer has claimed to have.
1649 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1651 defer cn.locker().RUnlock()
1652 return cn.newPeerPieces()
1655 // Returns a new Bitmap that includes bits for all pieces we have.
1656 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1657 ret := cn._peerPieces.Copy()
1658 if cn.peerSentHaveAll {
1659 ret.AddRange(0, cn.t.numPieces())
1664 func (cn *Peer) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1665 return &cn._pieceRequestOrder
1668 func (cn *Peer) stats() *ConnStats {
1672 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1673 pc, ok := p.peerImpl.(*PeerConn)