17 "github.com/RoaringBitmap/roaring"
18 "github.com/anacrolix/generics"
19 . "github.com/anacrolix/generics"
20 "github.com/anacrolix/log"
21 "github.com/anacrolix/missinggo/v2/bitmap"
22 "github.com/anacrolix/multiless"
23 "golang.org/x/exp/maps"
24 "golang.org/x/time/rate"
26 "github.com/anacrolix/torrent/bencode"
27 "github.com/anacrolix/torrent/internal/alloclim"
28 "github.com/anacrolix/torrent/metainfo"
29 "github.com/anacrolix/torrent/mse"
30 pp "github.com/anacrolix/torrent/peer_protocol"
31 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
34 // Maintains the state of a BitTorrent-protocol based connection with a peer.
35 type PeerConn struct {
38 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
39 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
44 PeerExtensionBytes pp.PeerExtensionBits
47 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
48 // while holding any mutexes.
50 // The Reader and Writer for this Conn, with hooks installed for stats,
51 // limiting, deadlines etc.
55 messageWriter peerConnMsgWriter
57 uploadTimer *time.Timer
60 // The pieces the peer has claimed to have.
61 _peerPieces roaring.Bitmap
62 // The peer has everything. This can occur due to a special message, when
63 // we may not even know the number of pieces in the torrent yet.
66 peerRequestDataAllocLimiter alloclim.Limiter
68 outstandingHolepunchingRendezvous map[netip.AddrPort]struct{}
71 func (cn *PeerConn) pexStatus() string {
72 if !cn.bitExtensionEnabled(pp.ExtensionBitLtep) {
73 return "extended protocol disabled"
75 if cn.PeerExtensionIDs == nil {
76 return "pending extended handshake"
78 if !cn.supportsExtension(pp.ExtensionNamePex) {
83 "%v conns, %v unsent events",
84 len(cn.pex.remoteLiveConns),
88 // This alternative branch prints out the remote live conn addresses.
90 "%v conns, %v unsent events",
91 strings.Join(generics.SliceMap(
92 maps.Keys(cn.pex.remoteLiveConns),
93 func(from netip.AddrPort) string {
102 func (cn *PeerConn) peerImplStatusLines() []string {
105 fmt.Sprintf("peer id: %+q", cn.PeerID),
106 fmt.Sprintf("extensions: %v", cn.PeerExtensionBytes),
107 fmt.Sprintf("pex: %s", cn.pexStatus()),
111 // Returns true if the connection is over IPv6.
112 func (cn *PeerConn) ipv6() bool {
117 return len(ip) == net.IPv6len
120 // Returns true the if the dialer/initiator has the higher client peer ID. See
121 // https://github.com/arvidn/libtorrent/blame/272828e1cc37b042dfbbafa539222d8533e99755/src/bt_peer_connection.cpp#L3536-L3557.
122 // As far as I can tell, Transmission just keeps the oldest connection.
123 func (cn *PeerConn) isPreferredDirection() bool {
124 // True if our client peer ID is higher than the remote's peer ID.
125 return bytes.Compare(cn.PeerID[:], cn.t.cl.peerID[:]) < 0 == cn.outgoing
128 // Returns whether the left connection should be preferred over the right one,
129 // considering only their networking properties. If ok is false, we can't
131 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
132 var ml multiless.Computation
133 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
134 ml = ml.Bool(l.utp(), r.utp())
135 ml = ml.Bool(r.ipv6(), l.ipv6())
139 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
140 if cn.peerSentHaveAll {
143 if !cn.t.haveInfo() {
146 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
149 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
150 cn.setNumPieces(info.NumPieces())
153 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
154 // receiving badly sized BITFIELD, or invalid HAVE messages.
155 func (cn *PeerConn) setNumPieces(num pieceIndex) {
156 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
157 cn.peerPiecesChanged()
160 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
161 return &cn._peerPieces
164 func (cn *PeerConn) connectionFlags() (ret string) {
166 ret += string([]byte{b})
168 if cn.cryptoMethod == mse.CryptoMethodRC4 {
170 } else if cn.headerEncrypted {
173 ret += string(cn.Discovery)
180 func (cn *PeerConn) utp() bool {
181 return parseNetworkString(cn.Network).Udp
184 func (cn *PeerConn) onClose() {
185 if cn.pex.IsEnabled() {
192 if cb := cn.callbacks.PeerConnClosed; cb != nil {
197 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
198 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
199 func (cn *PeerConn) write(msg pp.Message) bool {
200 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
201 // We don't need to track bytes here because the connection's Writer has that behaviour injected
202 // (although there's some delay between us buffering the message, and the connection writer
203 // flushing it out.).
204 notFull := cn.messageWriter.write(msg)
205 // Last I checked only Piece messages affect stats, and we don't write those.
211 func (cn *PeerConn) requestMetadataPiece(index int) {
212 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
213 if eID == pp.ExtensionDeleteNumber {
216 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
219 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
220 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
221 for index >= len(cn.metadataRequests) {
222 cn.metadataRequests = append(cn.metadataRequests, false)
224 cn.metadataRequests[index] = true
227 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
228 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
231 func (cn *PeerConn) onPeerSentCancel(r Request) {
232 if _, ok := cn.peerRequests[r]; !ok {
233 torrent.Add("unexpected cancels received", 1)
236 if cn.fastEnabled() {
239 delete(cn.peerRequests, r)
243 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
248 more = msg(pp.Message{
251 if !cn.fastEnabled() {
252 cn.deleteAllPeerRequests()
257 func (cn *PeerConn) deleteAllPeerRequests() {
258 for _, state := range cn.peerRequests {
259 state.allocReservation.Drop()
261 cn.peerRequests = nil
264 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
269 return msg(pp.Message{
274 func (pc *PeerConn) writeInterested(interested bool) bool {
275 return pc.write(pp.Message{
276 Type: func() pp.MessageType {
280 return pp.NotInterested
286 func (me *PeerConn) _request(r Request) bool {
287 return me.write(pp.Message{
295 func (me *PeerConn) _cancel(r RequestIndex) bool {
296 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
297 // Transmission does not send rejects for received cancels. See
298 // https://github.com/transmission/transmission/pull/2275.
299 return me.fastEnabled() && !me.remoteIsTransmission()
302 func (cn *PeerConn) fillWriteBuffer() {
303 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
304 // Fully committing to our max requests requires sufficient space (see
305 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
306 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
307 // request reason will not be cleared, so we'll come right back here when there's space. We
308 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
309 // knowledge of write buffers.
311 cn.maybeUpdateActualRequestState()
312 if cn.pex.IsEnabled() {
313 if flow := cn.pex.Share(cn.write); !flow {
320 func (cn *PeerConn) have(piece pieceIndex) {
321 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
326 Index: pp.Integer(piece),
328 cn.sentHaves.Add(bitmap.BitIndex(piece))
331 func (cn *PeerConn) postBitfield() {
332 if cn.sentHaves.Len() != 0 {
333 panic("bitfield must be first have-related message sent")
335 if !cn.t.haveAnyPieces() {
340 Bitfield: cn.t.bitfield(),
342 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
345 func (cn *PeerConn) handleUpdateRequests() {
346 // The writer determines the request state as needed when it can write.
350 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
351 if newMin > cn.peerMinPieces {
352 cn.peerMinPieces = newMin
356 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
357 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
358 return errors.New("invalid piece")
360 if cn.peerHasPiece(piece) {
363 cn.raisePeerMinPieces(piece + 1)
364 if !cn.peerHasPiece(piece) {
365 cn.t.incPieceAvailability(piece)
367 cn._peerPieces.Add(uint32(piece))
368 if cn.t.wantPieceIndex(piece) {
369 cn.updateRequests("have")
371 cn.peerPiecesChanged()
375 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
377 panic("expected bitfield length divisible by 8")
379 // We know that the last byte means that at most the last 7 bits are wasted.
380 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
381 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
382 // Ignore known excess pieces.
383 bf = bf[:cn.t.numPieces()]
385 bm := boolSliceToBitmap(bf)
386 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
387 cn.onPeerHasAllPieces()
391 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
393 shouldUpdateRequests := false
394 if cn.peerSentHaveAll {
395 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
398 cn.peerSentHaveAll = false
399 if !cn._peerPieces.IsEmpty() {
400 panic("if peer has all, we expect no individual peer pieces to be set")
403 bm.Xor(&cn._peerPieces)
405 cn.peerSentHaveAll = false
406 // bm is now 'on' for pieces that are changing
407 bm.Iterate(func(x uint32) bool {
409 if cn._peerPieces.Contains(x) {
410 // Then we must be losing this piece
411 cn.t.decPieceAvailability(pi)
413 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
414 shouldUpdateRequests = true
416 // We must be gaining this piece
417 cn.t.incPieceAvailability(pieceIndex(x))
421 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
423 cn._peerPieces.Xor(&bm)
424 if shouldUpdateRequests {
425 cn.updateRequests("bitfield")
427 // We didn't guard this before, I see no reason to do it now.
428 cn.peerPiecesChanged()
432 func (cn *PeerConn) onPeerHasAllPieces() {
435 cn._peerPieces.Iterate(func(x uint32) bool {
436 t.decPieceAvailability(pieceIndex(x))
440 t.addConnWithAllPieces(&cn.Peer)
441 cn.peerSentHaveAll = true
442 cn._peerPieces.Clear()
443 if !cn.t._pendingPieces.IsEmpty() {
444 cn.updateRequests("Peer.onPeerHasAllPieces")
446 cn.peerPiecesChanged()
449 func (cn *PeerConn) onPeerSentHaveAll() error {
450 cn.onPeerHasAllPieces()
454 func (cn *PeerConn) peerSentHaveNone() error {
455 if !cn.peerSentHaveAll {
456 cn.t.decPeerPieceAvailability(&cn.Peer)
458 cn._peerPieces.Clear()
459 cn.peerSentHaveAll = false
460 cn.peerPiecesChanged()
464 func (c *PeerConn) requestPendingMetadata() {
468 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
469 // Peer doesn't support this.
472 // Request metadata pieces that we don't have in a random order.
474 for index := 0; index < c.t.metadataPieceCount(); index++ {
475 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
476 pending = append(pending, index)
479 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
480 for _, i := range pending {
481 c.requestMetadataPiece(i)
485 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
486 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
487 if msg.Type == pp.Extended {
488 for name, id := range cn.PeerExtensionIDs {
489 if id != msg.ExtendedID {
492 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
495 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
498 func (cn *PeerConn) wroteBytes(n int64) {
499 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
502 func (c *PeerConn) fastEnabled() bool {
503 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
506 func (c *PeerConn) reject(r Request) {
507 if !c.fastEnabled() {
508 panic("fast not enabled")
510 c.write(r.ToMsg(pp.Reject))
511 // It is possible to reject a request before it is added to peer requests due to being invalid.
512 if state, ok := c.peerRequests[r]; ok {
513 state.allocReservation.Drop()
514 delete(c.peerRequests, r)
518 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
519 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
520 if uploadRateLimiter.Limit() == rate.Inf {
523 return Some(uploadRateLimiter.Burst())
526 // startFetch is for testing purposes currently.
527 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
528 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
529 if _, ok := c.peerRequests[r]; ok {
530 torrent.Add("duplicate requests received", 1)
532 return errors.New("received duplicate request with fast enabled")
537 torrent.Add("requests received while choking", 1)
539 torrent.Add("requests rejected while choking", 1)
544 // TODO: What if they've already requested this?
545 if len(c.peerRequests) >= localClientReqq {
546 torrent.Add("requests received while queue full", 1)
550 // BEP 6 says we may close here if we choose.
553 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
554 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
555 c.logger.Levelf(log.Warning, err.Error())
563 if !c.t.havePiece(pieceIndex(r.Index)) {
564 // TODO: Tell the peer we don't have the piece, and reject this request.
565 requestsReceivedForMissingPieces.Add(1)
566 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
568 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
569 // Check this after we know we have the piece, so that the piece length will be known.
570 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
571 torrent.Add("bad requests received", 1)
572 return errors.New("chunk overflows piece")
574 if c.peerRequests == nil {
575 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
577 value := &peerRequestState{
578 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
580 c.peerRequests[r] = value
582 // TODO: Limit peer request data read concurrency.
583 go c.peerRequestDataReader(r, value)
588 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
589 b, err := c.readPeerRequestData(r, prs)
591 defer c.locker().Unlock()
593 c.peerRequestDataReadFailed(err, r)
596 panic("data must be non-nil to trigger send")
598 torrent.Add("peer request data read successes", 1)
600 // This might be required for the error case too (#752 and #753).
605 // If this is maintained correctly, we might be able to support optional synchronous reading for
606 // chunk sending, the way it used to work.
607 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
608 torrent.Add("peer request data read failures", 1)
609 logLevel := log.Warning
610 if c.t.hasStorageCap() {
611 // It's expected that pieces might drop. See
612 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
615 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
616 if c.t.closed.IsSet() {
619 i := pieceIndex(r.Index)
620 if c.t.pieceComplete(i) {
621 // There used to be more code here that just duplicated the following break. Piece
622 // completions are currently cached, so I'm not sure how helpful this update is, except to
623 // pull any completion changes pushed to the storage backend in failed reads that got us
625 c.t.updatePieceCompletion(i)
627 // We've probably dropped a piece from storage, but there's no way to communicate this to the
628 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
629 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
630 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
636 // If fast isn't enabled, I think we would have wiped all peer requests when we last
637 // choked, and requests while we're choking would be ignored. It could be possible that
638 // a peer request data read completed concurrently to it being deleted elsewhere.
639 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
641 // Choking a non-fast peer should cause them to flush all their requests.
646 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
647 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
648 // or fail to read and then cleanup.
649 ctx := context.Background()
650 err := prs.allocReservation.Wait(ctx)
652 if ctx.Err() == nil {
653 // The error is from the reservation itself. Something is very broken, or we're not
654 // guarding against excessively large requests.
655 err = log.WithLevel(log.Critical, err)
657 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
660 b := make([]byte, r.Length)
661 p := c.t.info.Piece(int(r.Index))
662 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
669 panic("expected error")
675 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
676 c.logger.WithContextText(fmt.Sprintf(
677 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
678 )).SkipCallers(1).Levelf(level, format, arg...)
681 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
682 // exit. Returning will end the connection.
683 func (c *PeerConn) mainReadLoop() (err error) {
686 torrent.Add("connection.mainReadLoop returned with error", 1)
688 torrent.Add("connection.mainReadLoop returned with no error", 1)
694 decoder := pp.Decoder{
695 R: bufio.NewReaderSize(c.r, 1<<17),
696 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
704 err = decoder.Decode(&msg)
706 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
709 if t.closed.IsSet() || c.closed.IsSet() {
715 c.lastMessageReceived = time.Now()
717 receivedKeepalives.Add(1)
720 messageTypesReceived.Add(msg.Type.String(), 1)
721 if msg.Type.FastExtension() && !c.fastEnabled() {
722 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
723 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
730 if !c.fastEnabled() {
731 c.deleteAllRequests("choked by non-fast PeerConn")
733 // We don't decrement pending requests here, let's wait for the peer to either
734 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
735 // us and resume where they left off, we don't want to have piled on to those chunks
736 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
737 // could let us request a lot of stuff, then choke us and never reject, but they're
738 // only a single peer, our chunk balancing should smooth over this abuse.
741 c.updateExpectingChunks()
744 // Some clients do this for some reason. Transmission doesn't error on this, so we
745 // won't for consistency.
746 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
749 c.peerChoking = false
751 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
752 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
757 if preservedCount != 0 {
758 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
760 c.logger.Levelf(log.Debug,
761 "%v requests were preserved while being choked (fast=%v)",
765 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
767 if !c.t._pendingPieces.IsEmpty() {
768 c.updateRequests("unchoked")
770 c.updateExpectingChunks()
772 c.peerInterested = true
774 case pp.NotInterested:
775 c.peerInterested = false
776 // We don't clear their requests since it isn't clear in the spec.
777 // We'll probably choke them for this, which will clear them if
778 // appropriate, and is clearly specified.
780 err = c.peerSentHave(pieceIndex(msg.Index))
782 err = c.peerSentBitfield(msg.Bitfield)
784 r := newRequestFromMessage(&msg)
785 err = c.onReadRequest(r, true)
787 err = fmt.Errorf("on reading request %v: %w", r, err)
790 c.doChunkReadStats(int64(len(msg.Piece)))
791 err = c.receiveChunk(&msg)
792 if len(msg.Piece) == int(t.chunkSize) {
793 t.chunkPool.Put(&msg.Piece)
796 err = fmt.Errorf("receiving chunk: %w", err)
799 req := newRequestFromMessage(&msg)
800 c.onPeerSentCancel(req)
802 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
806 pingAddr := net.UDPAddr{
811 pingAddr.Port = int(msg.Port)
813 cl.eachDhtServer(func(s DhtServer) {
817 torrent.Add("suggests received", 1)
818 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
819 c.updateRequests("suggested")
821 err = c.onPeerSentHaveAll()
823 err = c.peerSentHaveNone()
825 req := newRequestFromMessage(&msg)
826 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
827 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
828 err = fmt.Errorf("received invalid reject [request=%v]", req)
831 torrent.Add("allowed fasts received", 1)
832 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
833 c.updateRequests("PeerConn.mainReadLoop allowed fast")
835 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
837 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
845 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
847 // TODO: Should we still do this?
849 // These clients use their own extension IDs for outgoing message
850 // types, which is incorrect.
851 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
859 case pp.HandshakeExtendedID:
860 var d pp.ExtendedHandshakeMessage
861 if err := bencode.Unmarshal(payload, &d); err != nil {
862 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
863 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
865 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
868 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
870 c.PeerMaxRequests = d.Reqq
872 c.PeerClientName.Store(d.V)
873 if c.PeerExtensionIDs == nil {
874 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
876 c.PeerListenPort = d.Port
877 c.PeerPrefersEncryption = d.Encryption
878 for name, id := range d.M {
879 if _, ok := c.PeerExtensionIDs[name]; !ok {
880 peersSupportingExtension.Add(
881 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
882 // entered here which caused problems later when unmarshalling.
883 strconv.Quote(string(name)),
886 c.PeerExtensionIDs[name] = id
888 if d.MetadataSize != 0 {
889 if err = t.setMetadataSize(d.MetadataSize); err != nil {
890 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
893 c.requestPendingMetadata()
894 if !t.cl.config.DisablePEX {
895 t.pex.Add(c) // we learnt enough now
896 // This checks the extension is supported internally.
900 case metadataExtendedId:
901 err := cl.gotMetadataExtensionMsg(payload, t, c)
903 return fmt.Errorf("handling metadata extension message: %w", err)
907 if !c.pex.IsEnabled() {
908 return nil // or hang-up maybe?
910 err = c.pex.Recv(payload)
912 err = fmt.Errorf("receiving pex message: %w", err)
915 case utHolepunchExtendedId:
916 var msg utHolepunch.Msg
917 err = msg.UnmarshalBinary(payload)
919 err = fmt.Errorf("unmarshalling ut_holepunch message: %w", err)
922 err = c.t.handleReceivedUtHolepunchMsg(msg, c)
925 return fmt.Errorf("unexpected extended message ID: %v", id)
929 // Set both the Reader and Writer for the connection from a single ReadWriter.
930 func (cn *PeerConn) setRW(rw io.ReadWriter) {
935 // Returns the Reader and Writer as a combined ReadWriter.
936 func (cn *PeerConn) rw() io.ReadWriter {
943 func (c *PeerConn) uploadAllowed() bool {
944 if c.t.cl.config.NoUpload {
947 if c.t.dataUploadDisallowed {
953 if !c.peerHasWantedPieces() {
956 // Don't upload more than 100 KiB more than we download.
957 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
963 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
964 if c.uploadTimer == nil {
965 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
967 c.uploadTimer.Reset(delay)
971 // Also handles choking and unchoking of the remote peer.
972 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
973 // Breaking or completing this loop means we don't want to upload to the
974 // peer anymore, and we choke them.
976 for c.uploadAllowed() {
977 // We want to upload to the peer.
981 for r, state := range c.peerRequests {
982 if state.data == nil {
985 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
987 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
992 c.setRetryUploadTimer(delay)
993 // Hard to say what to return here.
996 more := c.sendChunk(r, msg, state)
997 delete(c.peerRequests, r)
1008 func (cn *PeerConn) drop() {
1009 cn.t.dropConnection(cn)
1012 func (cn *PeerConn) ban() {
1013 cn.t.cl.banPeerIP(cn.remoteIp())
1016 // This is called when something has changed that should wake the writer, such as putting stuff into
1017 // the writeBuffer, or changing some state that the writer can act on.
1018 func (c *PeerConn) tickleWriter() {
1019 c.messageWriter.writeCond.Broadcast()
1022 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1023 c.lastChunkSent = time.Now()
1024 state.allocReservation.Release()
1025 return msg(pp.Message{
1033 func (c *PeerConn) setTorrent(t *Torrent) {
1035 panic("connection already associated with a torrent")
1038 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1039 t.reconcileHandshakeStats(c)
1042 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1043 f := pp.PexPeerFlags(0)
1044 if c.PeerPrefersEncryption {
1045 f |= pp.PexPrefersEncryption
1048 f |= pp.PexOutgoingConn
1051 f |= pp.PexSupportsUtp
1056 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1057 // advertised listen port.
1058 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1059 if c.outgoing || c.PeerListenPort == 0 {
1062 addrPort, err := addrPortFromPeerRemoteAddr(c.RemoteAddr)
1066 "error parsing %q for alternate dial port: %v",
1072 return netip.AddrPortFrom(addrPort.Addr(), uint16(c.PeerListenPort))
1075 func (c *PeerConn) pexEvent(t pexEventType) (_ pexEvent, err error) {
1076 f := c.pexPeerFlags()
1077 dialAddr := c.dialAddr()
1078 addr, err := addrPortFromPeerRemoteAddr(dialAddr)
1079 if err != nil || !addr.IsValid() {
1080 err = fmt.Errorf("parsing dial addr %q: %w", dialAddr, err)
1083 return pexEvent{t, addr, f, nil}, nil
1086 func (c *PeerConn) String() string {
1087 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1090 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1091 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1092 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1094 defer cn.locker().RUnlock()
1095 return cn.newPeerPieces()
1098 func (pc *PeerConn) remoteIsTransmission() bool {
1099 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1102 func (pc *PeerConn) remoteDialAddrPort() (netip.AddrPort, error) {
1103 dialAddr := pc.dialAddr()
1104 return addrPortFromPeerRemoteAddr(dialAddr)
1107 func (pc *PeerConn) bitExtensionEnabled(bit pp.ExtensionBit) bool {
1108 return pc.t.cl.config.Extensions.GetBit(bit) && pc.PeerExtensionBytes.GetBit(bit)