18 "github.com/RoaringBitmap/roaring"
19 "github.com/anacrolix/generics"
20 . "github.com/anacrolix/generics"
21 "github.com/anacrolix/log"
22 "github.com/anacrolix/missinggo/v2/bitmap"
23 "github.com/anacrolix/multiless"
24 "golang.org/x/exp/maps"
25 "golang.org/x/time/rate"
27 "github.com/anacrolix/torrent/bencode"
28 "github.com/anacrolix/torrent/internal/alloclim"
29 "github.com/anacrolix/torrent/metainfo"
30 "github.com/anacrolix/torrent/mse"
31 pp "github.com/anacrolix/torrent/peer_protocol"
32 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
35 // Maintains the state of a BitTorrent-protocol based connection with a peer.
36 type PeerConn struct {
39 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
40 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
45 PeerExtensionBytes pp.PeerExtensionBits
48 // The local extended protocols to advertise in the extended handshake, and to support receiving
49 // from the peer. This will point to the Client default when the PeerConnAdded callback is
50 // invoked. Do not modify this, point it to your own instance. Do not modify the destination
51 // after returning from the callback.
52 LocalLtepProtocolMap *LocalLtepProtocolMap
54 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
55 // while holding any mutexes.
57 // The Reader and Writer for this Conn, with hooks installed for stats,
58 // limiting, deadlines etc.
62 messageWriter peerConnMsgWriter
64 // The peer's extension map, as sent in their extended handshake.
65 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
66 PeerClientName atomic.Value
67 uploadTimer *time.Timer
70 // The pieces the peer has claimed to have.
71 _peerPieces roaring.Bitmap
72 // The peer has everything. This can occur due to a special message, when
73 // we may not even know the number of pieces in the torrent yet.
76 peerRequestDataAllocLimiter alloclim.Limiter
78 outstandingHolepunchingRendezvous map[netip.AddrPort]struct{}
81 func (cn *PeerConn) pexStatus() string {
82 if !cn.bitExtensionEnabled(pp.ExtensionBitLtep) {
83 return "extended protocol disabled"
85 if cn.PeerExtensionIDs == nil {
86 return "pending extended handshake"
88 if !cn.supportsExtension(pp.ExtensionNamePex) {
93 "%v conns, %v unsent events",
94 len(cn.pex.remoteLiveConns),
98 // This alternative branch prints out the remote live conn addresses.
100 "%v conns, %v unsent events",
101 strings.Join(generics.SliceMap(
102 maps.Keys(cn.pex.remoteLiveConns),
103 func(from netip.AddrPort) string {
111 func (cn *PeerConn) peerImplStatusLines() []string {
114 fmt.Sprintf("peer id: %+q", cn.PeerID),
115 fmt.Sprintf("extensions: %v", cn.PeerExtensionBytes),
116 fmt.Sprintf("ltep extensions: %v", cn.PeerExtensionIDs),
117 fmt.Sprintf("pex: %s", cn.pexStatus()),
121 // Returns true if the connection is over IPv6.
122 func (cn *PeerConn) ipv6() bool {
127 return len(ip) == net.IPv6len
130 // Returns true the if the dialer/initiator has the higher client peer ID. See
131 // https://github.com/arvidn/libtorrent/blame/272828e1cc37b042dfbbafa539222d8533e99755/src/bt_peer_connection.cpp#L3536-L3557.
132 // As far as I can tell, Transmission just keeps the oldest connection.
133 func (cn *PeerConn) isPreferredDirection() bool {
134 // True if our client peer ID is higher than the remote's peer ID.
135 return bytes.Compare(cn.PeerID[:], cn.t.cl.peerID[:]) < 0 == cn.outgoing
138 // Returns whether the left connection should be preferred over the right one,
139 // considering only their networking properties. If ok is false, we can't
141 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
142 var ml multiless.Computation
143 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
144 ml = ml.Bool(l.utp(), r.utp())
145 ml = ml.Bool(r.ipv6(), l.ipv6())
149 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
150 if cn.peerSentHaveAll {
153 if !cn.t.haveInfo() {
156 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
159 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
160 cn.setNumPieces(info.NumPieces())
163 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
164 // receiving badly sized BITFIELD, or invalid HAVE messages.
165 func (cn *PeerConn) setNumPieces(num pieceIndex) {
166 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
167 cn.peerPiecesChanged()
170 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
171 return &cn._peerPieces
174 func (cn *PeerConn) connectionFlags() (ret string) {
176 ret += string([]byte{b})
178 if cn.cryptoMethod == mse.CryptoMethodRC4 {
180 } else if cn.headerEncrypted {
183 ret += string(cn.Discovery)
190 func (cn *PeerConn) utp() bool {
191 return parseNetworkString(cn.Network).Udp
194 func (cn *PeerConn) onClose() {
195 if cn.pex.IsEnabled() {
202 if cb := cn.callbacks.PeerConnClosed; cb != nil {
207 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
208 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
209 func (cn *PeerConn) write(msg pp.Message) bool {
210 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
211 // We don't need to track bytes here because the connection's Writer has that behaviour injected
212 // (although there's some delay between us buffering the message, and the connection writer
213 // flushing it out.).
214 notFull := cn.messageWriter.write(msg)
215 // Last I checked only Piece messages affect stats, and we don't write those.
221 func (cn *PeerConn) requestMetadataPiece(index int) {
222 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
223 if eID == pp.ExtensionDeleteNumber {
226 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
229 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
230 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
231 for index >= len(cn.metadataRequests) {
232 cn.metadataRequests = append(cn.metadataRequests, false)
234 cn.metadataRequests[index] = true
237 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
238 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
241 func (cn *PeerConn) onPeerSentCancel(r Request) {
242 if _, ok := cn.peerRequests[r]; !ok {
243 torrent.Add("unexpected cancels received", 1)
246 if cn.fastEnabled() {
249 delete(cn.peerRequests, r)
253 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
258 more = msg(pp.Message{
261 if !cn.fastEnabled() {
262 cn.deleteAllPeerRequests()
267 func (cn *PeerConn) deleteAllPeerRequests() {
268 for _, state := range cn.peerRequests {
269 state.allocReservation.Drop()
271 cn.peerRequests = nil
274 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
279 return msg(pp.Message{
284 func (pc *PeerConn) writeInterested(interested bool) bool {
285 return pc.write(pp.Message{
286 Type: func() pp.MessageType {
290 return pp.NotInterested
296 func (me *PeerConn) _request(r Request) bool {
297 return me.write(pp.Message{
305 func (me *PeerConn) _cancel(r RequestIndex) bool {
306 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
307 return me.remoteRejectsCancels()
310 // Whether we should expect a reject message after sending a cancel.
311 func (me *PeerConn) remoteRejectsCancels() bool {
312 if !me.fastEnabled() {
315 if me.remoteIsTransmission() {
316 // Transmission did not send rejects for received cancels. See
317 // https://github.com/transmission/transmission/pull/2275. Fixed in 4.0.0-beta.1 onward in
318 // https://github.com/transmission/transmission/commit/76719bf34c255da4fca991c2ad3fa4b65d2154b1.
319 // Peer ID prefix scheme described
320 // https://github.com/transmission/transmission/blob/7ec7607bbcf0fa99bd4b157b9b0f0c411d59f45d/CMakeLists.txt#L128-L149.
321 return me.PeerID[3] >= '4'
326 func (cn *PeerConn) fillWriteBuffer() {
327 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
328 // Fully committing to our max requests requires sufficient space (see
329 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
330 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
331 // request reason will not be cleared, so we'll come right back here when there's space. We
332 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
333 // knowledge of write buffers.
336 cn.maybeUpdateActualRequestState()
337 if cn.pex.IsEnabled() {
338 if flow := cn.pex.Share(cn.write); !flow {
345 func (cn *PeerConn) have(piece pieceIndex) {
346 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
351 Index: pp.Integer(piece),
353 cn.sentHaves.Add(bitmap.BitIndex(piece))
356 func (cn *PeerConn) postBitfield() {
357 if cn.sentHaves.Len() != 0 {
358 panic("bitfield must be first have-related message sent")
360 if !cn.t.haveAnyPieces() {
365 Bitfield: cn.t.bitfield(),
367 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
370 func (cn *PeerConn) handleUpdateRequests() {
371 // The writer determines the request state as needed when it can write.
375 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
376 if newMin > cn.peerMinPieces {
377 cn.peerMinPieces = newMin
381 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
382 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
383 return errors.New("invalid piece")
385 if cn.peerHasPiece(piece) {
388 cn.raisePeerMinPieces(piece + 1)
389 if !cn.peerHasPiece(piece) {
390 cn.t.incPieceAvailability(piece)
392 cn._peerPieces.Add(uint32(piece))
393 if cn.t.wantPieceIndex(piece) {
394 cn.updateRequests("have")
396 cn.peerPiecesChanged()
400 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
402 panic("expected bitfield length divisible by 8")
404 // We know that the last byte means that at most the last 7 bits are wasted.
405 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
406 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
407 // Ignore known excess pieces.
408 bf = bf[:cn.t.numPieces()]
410 bm := boolSliceToBitmap(bf)
411 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
412 cn.onPeerHasAllPieces()
416 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
418 shouldUpdateRequests := false
419 if cn.peerSentHaveAll {
420 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
423 cn.peerSentHaveAll = false
424 if !cn._peerPieces.IsEmpty() {
425 panic("if peer has all, we expect no individual peer pieces to be set")
428 bm.Xor(&cn._peerPieces)
430 cn.peerSentHaveAll = false
431 // bm is now 'on' for pieces that are changing
432 bm.Iterate(func(x uint32) bool {
434 if cn._peerPieces.Contains(x) {
435 // Then we must be losing this piece
436 cn.t.decPieceAvailability(pi)
438 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
439 shouldUpdateRequests = true
441 // We must be gaining this piece
442 cn.t.incPieceAvailability(pieceIndex(x))
446 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
448 cn._peerPieces.Xor(&bm)
449 if shouldUpdateRequests {
450 cn.updateRequests("bitfield")
452 // We didn't guard this before, I see no reason to do it now.
453 cn.peerPiecesChanged()
457 func (cn *PeerConn) onPeerHasAllPiecesNoTriggers() {
460 cn._peerPieces.Iterate(func(x uint32) bool {
461 t.decPieceAvailability(pieceIndex(x))
465 t.addConnWithAllPieces(&cn.Peer)
466 cn.peerSentHaveAll = true
467 cn._peerPieces.Clear()
470 func (cn *PeerConn) onPeerHasAllPieces() {
471 cn.onPeerHasAllPiecesNoTriggers()
472 cn.peerHasAllPiecesTriggers()
475 func (cn *PeerConn) peerHasAllPiecesTriggers() {
476 if !cn.t._pendingPieces.IsEmpty() {
477 cn.updateRequests("Peer.onPeerHasAllPieces")
479 cn.peerPiecesChanged()
482 func (cn *PeerConn) onPeerSentHaveAll() error {
483 cn.onPeerHasAllPieces()
487 func (cn *PeerConn) peerSentHaveNone() error {
488 if !cn.peerSentHaveAll {
489 cn.t.decPeerPieceAvailability(&cn.Peer)
491 cn._peerPieces.Clear()
492 cn.peerSentHaveAll = false
493 cn.peerPiecesChanged()
497 func (c *PeerConn) requestPendingMetadata() {
501 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
502 // Peer doesn't support this.
505 // Request metadata pieces that we don't have in a random order.
507 for index := 0; index < c.t.metadataPieceCount(); index++ {
508 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
509 pending = append(pending, index)
512 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
513 for _, i := range pending {
514 c.requestMetadataPiece(i)
518 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
519 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
520 if msg.Type == pp.Extended {
521 for name, id := range cn.PeerExtensionIDs {
522 if id != msg.ExtendedID {
525 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
528 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
531 func (cn *PeerConn) wroteBytes(n int64) {
532 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
535 func (c *PeerConn) fastEnabled() bool {
536 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
539 func (c *PeerConn) reject(r Request) {
540 if !c.fastEnabled() {
541 panic("fast not enabled")
543 c.write(r.ToMsg(pp.Reject))
544 // It is possible to reject a request before it is added to peer requests due to being invalid.
545 if state, ok := c.peerRequests[r]; ok {
546 state.allocReservation.Drop()
547 delete(c.peerRequests, r)
551 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
552 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
553 if uploadRateLimiter.Limit() == rate.Inf {
556 return Some(uploadRateLimiter.Burst())
559 // startFetch is for testing purposes currently.
560 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
561 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
562 if _, ok := c.peerRequests[r]; ok {
563 torrent.Add("duplicate requests received", 1)
565 return errors.New("received duplicate request with fast enabled")
570 torrent.Add("requests received while choking", 1)
572 torrent.Add("requests rejected while choking", 1)
577 // TODO: What if they've already requested this?
578 if len(c.peerRequests) >= localClientReqq {
579 torrent.Add("requests received while queue full", 1)
583 // BEP 6 says we may close here if we choose.
586 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
587 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
588 c.logger.Levelf(log.Warning, err.Error())
596 if !c.t.havePiece(pieceIndex(r.Index)) {
597 // TODO: Tell the peer we don't have the piece, and reject this request.
598 requestsReceivedForMissingPieces.Add(1)
599 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
601 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
602 // Check this after we know we have the piece, so that the piece length will be known.
603 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
604 torrent.Add("bad requests received", 1)
605 return errors.New("chunk overflows piece")
607 if c.peerRequests == nil {
608 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
610 value := &peerRequestState{
611 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
613 c.peerRequests[r] = value
615 // TODO: Limit peer request data read concurrency.
616 go c.peerRequestDataReader(r, value)
621 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
622 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
623 // or fail to read and then cleanup. Also, we used to hang here if the reservation was never
624 // dropped, that was fixed.
625 ctx := context.Background()
626 err := prs.allocReservation.Wait(ctx)
628 c.logger.WithDefaultLevel(log.Debug).Levelf(log.ErrorLevel(err), "waiting for alloc limit reservation: %v", err)
631 b, err := c.readPeerRequestData(r)
633 defer c.locker().Unlock()
635 c.peerRequestDataReadFailed(err, r)
638 panic("data must be non-nil to trigger send")
640 torrent.Add("peer request data read successes", 1)
642 // This might be required for the error case too (#752 and #753).
647 // If this is maintained correctly, we might be able to support optional synchronous reading for
648 // chunk sending, the way it used to work.
649 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
650 torrent.Add("peer request data read failures", 1)
651 logLevel := log.Warning
652 if c.t.hasStorageCap() {
653 // It's expected that pieces might drop. See
654 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
657 c.logger.Levelf(logLevel, "error reading chunk for peer Request %v: %v", r, err)
658 if c.t.closed.IsSet() {
661 i := pieceIndex(r.Index)
662 if c.t.pieceComplete(i) {
663 // There used to be more code here that just duplicated the following break. Piece
664 // completions are currently cached, so I'm not sure how helpful this update is, except to
665 // pull any completion changes pushed to the storage backend in failed reads that got us
667 c.t.updatePieceCompletion(i)
669 // We've probably dropped a piece from storage, but there's no way to communicate this to the
670 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
671 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
672 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
678 // If fast isn't enabled, I think we would have wiped all peer requests when we last
679 // choked, and requests while we're choking would be ignored. It could be possible that
680 // a peer request data read completed concurrently to it being deleted elsewhere.
681 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
683 // Choking a non-fast peer should cause them to flush all their requests.
688 func (c *PeerConn) readPeerRequestData(r Request) ([]byte, error) {
689 b := make([]byte, r.Length)
690 p := c.t.info.Piece(int(r.Index))
691 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
698 panic("expected error")
704 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
705 c.logger.WithContextText(fmt.Sprintf(
706 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
707 )).SkipCallers(1).Levelf(level, format, arg...)
710 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
711 // exit. Returning will end the connection.
712 func (c *PeerConn) mainReadLoop() (err error) {
715 torrent.Add("connection.mainReadLoop returned with error", 1)
717 torrent.Add("connection.mainReadLoop returned with no error", 1)
723 decoder := pp.Decoder{
724 R: bufio.NewReaderSize(c.r, 1<<17),
725 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
733 err = decoder.Decode(&msg)
735 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
738 if t.closed.IsSet() || c.closed.IsSet() {
744 c.lastMessageReceived = time.Now()
746 receivedKeepalives.Add(1)
749 messageTypesReceived.Add(msg.Type.String(), 1)
750 if msg.Type.FastExtension() && !c.fastEnabled() {
751 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
752 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
759 if !c.fastEnabled() {
760 c.deleteAllRequests("choked by non-fast PeerConn")
762 // We don't decrement pending requests here, let's wait for the peer to either
763 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
764 // us and resume where they left off, we don't want to have piled on to those chunks
765 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
766 // could let us request a lot of stuff, then choke us and never reject, but they're
767 // only a single peer, our chunk balancing should smooth over this abuse.
770 c.updateExpectingChunks()
773 // Some clients do this for some reason. Transmission doesn't error on this, so we
774 // won't for consistency.
775 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
778 c.peerChoking = false
780 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
781 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
786 if preservedCount != 0 {
787 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
789 c.logger.Levelf(log.Debug,
790 "%v requests were preserved while being choked (fast=%v)",
794 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
796 if !c.t._pendingPieces.IsEmpty() {
797 c.updateRequests("unchoked")
799 c.updateExpectingChunks()
801 c.peerInterested = true
803 case pp.NotInterested:
804 c.peerInterested = false
805 // We don't clear their requests since it isn't clear in the spec.
806 // We'll probably choke them for this, which will clear them if
807 // appropriate, and is clearly specified.
809 err = c.peerSentHave(pieceIndex(msg.Index))
811 err = c.peerSentBitfield(msg.Bitfield)
813 r := newRequestFromMessage(&msg)
814 err = c.onReadRequest(r, true)
816 err = fmt.Errorf("on reading request %v: %w", r, err)
819 c.doChunkReadStats(int64(len(msg.Piece)))
820 err = c.receiveChunk(&msg)
821 if len(msg.Piece) == int(t.chunkSize) {
822 t.chunkPool.Put(&msg.Piece)
825 err = fmt.Errorf("receiving chunk: %w", err)
828 req := newRequestFromMessage(&msg)
829 c.onPeerSentCancel(req)
831 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
835 pingAddr := net.UDPAddr{
840 pingAddr.Port = int(msg.Port)
842 cl.eachDhtServer(func(s DhtServer) {
846 torrent.Add("suggests received", 1)
847 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
848 c.updateRequests("suggested")
850 err = c.onPeerSentHaveAll()
852 err = c.peerSentHaveNone()
854 req := newRequestFromMessage(&msg)
855 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
856 err = fmt.Errorf("received invalid reject for request %v", req)
857 c.logger.Levelf(log.Debug, "%v", err)
860 torrent.Add("allowed fasts received", 1)
861 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
862 c.updateRequests("PeerConn.mainReadLoop allowed fast")
864 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
865 case pp.HashRequest, pp.Hashes, pp.HashReject:
866 err = log.WithLevel(log.Warning, fmt.Errorf("received unimplemented BitTorrent v2 message: %v", msg.Type))
868 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
876 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
878 // TODO: Should we still do this?
880 // These clients use their own extension IDs for outgoing message
881 // types, which is incorrect.
882 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
890 event := PeerConnReadExtensionMessageEvent{
895 for _, cb := range c.callbacks.PeerConnReadExtensionMessage {
899 if id == pp.HandshakeExtendedID {
900 var d pp.ExtendedHandshakeMessage
901 if err := bencode.Unmarshal(payload, &d); err != nil {
902 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
903 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
905 // Trigger this callback after it's been processed. If you want to handle it yourself, you
906 // should hook PeerConnReadExtensionMessage.
907 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
911 c.PeerMaxRequests = d.Reqq
913 c.PeerClientName.Store(d.V)
914 if c.PeerExtensionIDs == nil {
915 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
917 c.PeerListenPort = d.Port
918 c.PeerPrefersEncryption = d.Encryption
919 for name, id := range d.M {
920 if _, ok := c.PeerExtensionIDs[name]; !ok {
921 peersSupportingExtension.Add(
922 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
923 // entered here which caused problems later when unmarshalling.
924 strconv.Quote(string(name)),
927 c.PeerExtensionIDs[name] = id
929 if d.MetadataSize != 0 {
930 if err = t.setMetadataSize(d.MetadataSize); err != nil {
931 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
934 c.requestPendingMetadata()
935 if !t.cl.config.DisablePEX {
936 t.pex.Add(c) // we learnt enough now
937 // This checks the extension is supported internally.
942 extensionName, builtin, err := c.LocalLtepProtocolMap.LookupId(id)
947 // User should have taken care of this in PeerConnReadExtensionMessage callback.
950 switch extensionName {
951 case pp.ExtensionNameMetadata:
952 err := cl.gotMetadataExtensionMsg(payload, t, c)
954 return fmt.Errorf("handling metadata extension message: %w", err)
957 case pp.ExtensionNamePex:
958 if !c.pex.IsEnabled() {
959 return nil // or hang-up maybe?
961 err = c.pex.Recv(payload)
963 err = fmt.Errorf("receiving pex message: %w", err)
966 case utHolepunch.ExtensionName:
967 var msg utHolepunch.Msg
968 err = msg.UnmarshalBinary(payload)
970 err = fmt.Errorf("unmarshalling ut_holepunch message: %w", err)
973 err = c.t.handleReceivedUtHolepunchMsg(msg, c)
976 panic(fmt.Sprintf("unhandled builtin extension protocol %q", extensionName))
980 // Set both the Reader and Writer for the connection from a single ReadWriter.
981 func (cn *PeerConn) setRW(rw io.ReadWriter) {
986 // Returns the Reader and Writer as a combined ReadWriter.
987 func (cn *PeerConn) rw() io.ReadWriter {
994 func (c *PeerConn) uploadAllowed() bool {
995 if c.t.cl.config.NoUpload {
998 if c.t.dataUploadDisallowed {
1004 if !c.peerHasWantedPieces() {
1007 // Don't upload more than 100 KiB more than we download.
1008 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1014 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1015 if c.uploadTimer == nil {
1016 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1018 c.uploadTimer.Reset(delay)
1022 // Also handles choking and unchoking of the remote peer.
1023 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1024 // Breaking or completing this loop means we don't want to upload to the peer anymore, and we
1027 for c.uploadAllowed() {
1028 // We want to upload to the peer.
1029 if !c.unchoke(msg) {
1032 for r, state := range c.peerRequests {
1033 if state.data == nil {
1036 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1038 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1040 delay := res.Delay()
1043 c.setRetryUploadTimer(delay)
1044 // Hard to say what to return here.
1047 more := c.sendChunk(r, msg, state)
1048 delete(c.peerRequests, r)
1059 func (cn *PeerConn) drop() {
1060 cn.t.dropConnection(cn)
1063 func (cn *PeerConn) ban() {
1064 cn.t.cl.banPeerIP(cn.remoteIp())
1067 // This is called when something has changed that should wake the writer, such as putting stuff into
1068 // the writeBuffer, or changing some state that the writer can act on.
1069 func (c *PeerConn) tickleWriter() {
1070 c.messageWriter.writeCond.Broadcast()
1073 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1074 c.lastChunkSent = time.Now()
1075 state.allocReservation.Release()
1076 return msg(pp.Message{
1084 func (c *Peer) setTorrent(t *Torrent) {
1086 panic("connection already associated with a torrent")
1089 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1090 t.reconcileHandshakeStats(c)
1093 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1094 f := pp.PexPeerFlags(0)
1095 if c.PeerPrefersEncryption {
1096 f |= pp.PexPrefersEncryption
1099 f |= pp.PexOutgoingConn
1102 f |= pp.PexSupportsUtp
1107 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1108 // advertised listen port.
1109 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1110 if c.outgoing || c.PeerListenPort == 0 {
1113 addrPort, err := addrPortFromPeerRemoteAddr(c.RemoteAddr)
1117 "error parsing %q for alternate dial port: %v",
1123 return netip.AddrPortFrom(addrPort.Addr(), uint16(c.PeerListenPort))
1126 func (c *PeerConn) pexEvent(t pexEventType) (_ pexEvent, err error) {
1127 f := c.pexPeerFlags()
1128 dialAddr := c.dialAddr()
1129 addr, err := addrPortFromPeerRemoteAddr(dialAddr)
1130 if err != nil || !addr.IsValid() {
1131 err = fmt.Errorf("parsing dial addr %q: %w", dialAddr, err)
1134 return pexEvent{t, addr, f, nil}, nil
1137 func (pc *PeerConn) String() string {
1138 return fmt.Sprintf("%T %p [id=%+q, exts=%v, v=%q]", pc, pc, pc.PeerID, pc.PeerExtensionBytes, pc.PeerClientName.Load())
1141 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1142 // are in the torrent, it could be a very large range if the peer has sent HaveAll.
1143 func (pc *PeerConn) PeerPieces() *roaring.Bitmap {
1145 defer pc.locker().RUnlock()
1146 return pc.newPeerPieces()
1149 func (pc *PeerConn) remoteIsTransmission() bool {
1150 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1153 func (pc *PeerConn) remoteDialAddrPort() (netip.AddrPort, error) {
1154 dialAddr := pc.dialAddr()
1155 return addrPortFromPeerRemoteAddr(dialAddr)
1158 func (pc *PeerConn) bitExtensionEnabled(bit pp.ExtensionBit) bool {
1159 return pc.t.cl.config.Extensions.GetBit(bit) && pc.PeerExtensionBytes.GetBit(bit)
1162 func (cn *PeerConn) peerPiecesChanged() {
1163 cn.t.maybeDropMutuallyCompletePeer(cn)
1166 // Returns whether the connection could be useful to us. We're seeding and
1167 // they want data, we don't have metainfo and they can provide it, etc.
1168 func (c *PeerConn) useful() bool {
1170 if c.closed.IsSet() {
1174 return c.supportsExtension("ut_metadata")
1176 if t.seeding() && c.peerInterested {
1179 if c.peerHasWantedPieces() {
1185 func makeBuiltinLtepProtocols(pex bool) LocalLtepProtocolMap {
1186 ps := []pp.ExtensionName{pp.ExtensionNameMetadata, utHolepunch.ExtensionName}
1188 ps = append(ps, pp.ExtensionNamePex)
1190 return LocalLtepProtocolMap{
1192 NumBuiltin: len(ps),
1196 func (c *PeerConn) addBuiltinLtepProtocols(pex bool) {
1197 c.LocalLtepProtocolMap = &c.t.cl.defaultLocalLtepProtocolMap
1200 func (pc *PeerConn) WriteExtendedMessage(extName pp.ExtensionName, payload []byte) error {
1202 defer pc.locker().Unlock()
1203 id := pc.PeerExtensionIDs[extName]
1205 return fmt.Errorf("peer does not support or has disabled extension %q", extName)
1207 pc.write(pp.Message{
1210 ExtendedPayload: payload,