17 "github.com/RoaringBitmap/roaring"
18 . "github.com/anacrolix/generics"
19 "github.com/anacrolix/log"
20 "github.com/anacrolix/missinggo/v2/bitmap"
21 "github.com/anacrolix/multiless"
22 "golang.org/x/time/rate"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/internal/alloclim"
26 "github.com/anacrolix/torrent/metainfo"
27 "github.com/anacrolix/torrent/mse"
28 pp "github.com/anacrolix/torrent/peer_protocol"
29 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
32 // Maintains the state of a BitTorrent-protocol based connection with a peer.
33 type PeerConn struct {
36 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
37 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
42 PeerExtensionBytes pp.PeerExtensionBits
44 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
45 // while holding any mutexes.
47 // The Reader and Writer for this Conn, with hooks installed for stats,
48 // limiting, deadlines etc.
52 messageWriter peerConnMsgWriter
54 uploadTimer *time.Timer
57 // The pieces the peer has claimed to have.
58 _peerPieces roaring.Bitmap
59 // The peer has everything. This can occur due to a special message, when
60 // we may not even know the number of pieces in the torrent yet.
63 peerRequestDataAllocLimiter alloclim.Limiter
65 outstandingHolepunchingRendezvous map[netip.AddrPort]struct{}
68 func (cn *PeerConn) pexStatus() string {
69 if !cn.bitExtensionEnabled(pp.ExtensionBitExtended) {
70 return "extended protocol disabled"
72 if cn.PeerExtensionIDs == nil {
73 return "pending extended handshake"
75 if !cn.supportsExtension(pp.ExtensionNamePex) {
79 "%v conns, %v unsent events",
80 len(cn.pex.remoteLiveConns),
85 func (cn *PeerConn) peerImplStatusLines() []string {
88 fmt.Sprintf("peer id: %+q", cn.PeerID),
89 fmt.Sprintf("extensions: %v", cn.PeerExtensionBytes),
90 fmt.Sprintf("pex: %s", cn.pexStatus()),
94 // Returns true if the connection is over IPv6.
95 func (cn *PeerConn) ipv6() bool {
100 return len(ip) == net.IPv6len
103 // Returns true the if the dialer/initiator has the higher client peer ID. See
104 // https://github.com/arvidn/libtorrent/blame/272828e1cc37b042dfbbafa539222d8533e99755/src/bt_peer_connection.cpp#L3536-L3557.
105 // As far as I can tell, Transmission just keeps the oldest connection.
106 func (cn *PeerConn) isPreferredDirection() bool {
107 // True if our client peer ID is higher than the remote's peer ID.
108 return bytes.Compare(cn.PeerID[:], cn.t.cl.peerID[:]) < 0 == cn.outgoing
111 // Returns whether the left connection should be preferred over the right one,
112 // considering only their networking properties. If ok is false, we can't
114 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
115 var ml multiless.Computation
116 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
117 ml = ml.Bool(l.utp(), r.utp())
118 ml = ml.Bool(r.ipv6(), l.ipv6())
122 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
123 if cn.peerSentHaveAll {
126 if !cn.t.haveInfo() {
129 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
132 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
133 cn.setNumPieces(info.NumPieces())
136 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
137 // receiving badly sized BITFIELD, or invalid HAVE messages.
138 func (cn *PeerConn) setNumPieces(num pieceIndex) {
139 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
140 cn.peerPiecesChanged()
143 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
144 return &cn._peerPieces
147 func (cn *PeerConn) connectionFlags() (ret string) {
149 ret += string([]byte{b})
151 if cn.cryptoMethod == mse.CryptoMethodRC4 {
153 } else if cn.headerEncrypted {
156 ret += string(cn.Discovery)
163 func (cn *PeerConn) utp() bool {
164 return parseNetworkString(cn.Network).Udp
167 func (cn *PeerConn) onClose() {
168 if cn.pex.IsEnabled() {
175 if cb := cn.callbacks.PeerConnClosed; cb != nil {
180 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
181 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
182 func (cn *PeerConn) write(msg pp.Message) bool {
183 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
184 // We don't need to track bytes here because the connection's Writer has that behaviour injected
185 // (although there's some delay between us buffering the message, and the connection writer
186 // flushing it out.).
187 notFull := cn.messageWriter.write(msg)
188 // Last I checked only Piece messages affect stats, and we don't write those.
194 func (cn *PeerConn) requestMetadataPiece(index int) {
195 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
196 if eID == pp.ExtensionDeleteNumber {
199 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
202 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
203 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
204 for index >= len(cn.metadataRequests) {
205 cn.metadataRequests = append(cn.metadataRequests, false)
207 cn.metadataRequests[index] = true
210 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
211 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
214 func (cn *PeerConn) onPeerSentCancel(r Request) {
215 if _, ok := cn.peerRequests[r]; !ok {
216 torrent.Add("unexpected cancels received", 1)
219 if cn.fastEnabled() {
222 delete(cn.peerRequests, r)
226 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
231 more = msg(pp.Message{
234 if !cn.fastEnabled() {
235 cn.deleteAllPeerRequests()
240 func (cn *PeerConn) deleteAllPeerRequests() {
241 for _, state := range cn.peerRequests {
242 state.allocReservation.Drop()
244 cn.peerRequests = nil
247 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
252 return msg(pp.Message{
257 func (pc *PeerConn) writeInterested(interested bool) bool {
258 return pc.write(pp.Message{
259 Type: func() pp.MessageType {
263 return pp.NotInterested
269 func (me *PeerConn) _request(r Request) bool {
270 return me.write(pp.Message{
278 func (me *PeerConn) _cancel(r RequestIndex) bool {
279 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
280 // Transmission does not send rejects for received cancels. See
281 // https://github.com/transmission/transmission/pull/2275.
282 return me.fastEnabled() && !me.remoteIsTransmission()
285 func (cn *PeerConn) fillWriteBuffer() {
286 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
287 // Fully committing to our max requests requires sufficient space (see
288 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
289 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
290 // request reason will not be cleared, so we'll come right back here when there's space. We
291 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
292 // knowledge of write buffers.
294 cn.maybeUpdateActualRequestState()
295 if cn.pex.IsEnabled() {
296 if flow := cn.pex.Share(cn.write); !flow {
303 func (cn *PeerConn) have(piece pieceIndex) {
304 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
309 Index: pp.Integer(piece),
311 cn.sentHaves.Add(bitmap.BitIndex(piece))
314 func (cn *PeerConn) postBitfield() {
315 if cn.sentHaves.Len() != 0 {
316 panic("bitfield must be first have-related message sent")
318 if !cn.t.haveAnyPieces() {
323 Bitfield: cn.t.bitfield(),
325 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
328 func (cn *PeerConn) handleUpdateRequests() {
329 // The writer determines the request state as needed when it can write.
333 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
334 if newMin > cn.peerMinPieces {
335 cn.peerMinPieces = newMin
339 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
340 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
341 return errors.New("invalid piece")
343 if cn.peerHasPiece(piece) {
346 cn.raisePeerMinPieces(piece + 1)
347 if !cn.peerHasPiece(piece) {
348 cn.t.incPieceAvailability(piece)
350 cn._peerPieces.Add(uint32(piece))
351 if cn.t.wantPieceIndex(piece) {
352 cn.updateRequests("have")
354 cn.peerPiecesChanged()
358 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
360 panic("expected bitfield length divisible by 8")
362 // We know that the last byte means that at most the last 7 bits are wasted.
363 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
364 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
365 // Ignore known excess pieces.
366 bf = bf[:cn.t.numPieces()]
368 bm := boolSliceToBitmap(bf)
369 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
370 cn.onPeerHasAllPieces()
374 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
376 shouldUpdateRequests := false
377 if cn.peerSentHaveAll {
378 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
381 cn.peerSentHaveAll = false
382 if !cn._peerPieces.IsEmpty() {
383 panic("if peer has all, we expect no individual peer pieces to be set")
386 bm.Xor(&cn._peerPieces)
388 cn.peerSentHaveAll = false
389 // bm is now 'on' for pieces that are changing
390 bm.Iterate(func(x uint32) bool {
392 if cn._peerPieces.Contains(x) {
393 // Then we must be losing this piece
394 cn.t.decPieceAvailability(pi)
396 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
397 shouldUpdateRequests = true
399 // We must be gaining this piece
400 cn.t.incPieceAvailability(pieceIndex(x))
404 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
406 cn._peerPieces.Xor(&bm)
407 if shouldUpdateRequests {
408 cn.updateRequests("bitfield")
410 // We didn't guard this before, I see no reason to do it now.
411 cn.peerPiecesChanged()
415 func (cn *PeerConn) onPeerHasAllPieces() {
418 cn._peerPieces.Iterate(func(x uint32) bool {
419 t.decPieceAvailability(pieceIndex(x))
423 t.addConnWithAllPieces(&cn.Peer)
424 cn.peerSentHaveAll = true
425 cn._peerPieces.Clear()
426 if !cn.t._pendingPieces.IsEmpty() {
427 cn.updateRequests("Peer.onPeerHasAllPieces")
429 cn.peerPiecesChanged()
432 func (cn *PeerConn) onPeerSentHaveAll() error {
433 cn.onPeerHasAllPieces()
437 func (cn *PeerConn) peerSentHaveNone() error {
438 if !cn.peerSentHaveAll {
439 cn.t.decPeerPieceAvailability(&cn.Peer)
441 cn._peerPieces.Clear()
442 cn.peerSentHaveAll = false
443 cn.peerPiecesChanged()
447 func (c *PeerConn) requestPendingMetadata() {
451 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
452 // Peer doesn't support this.
455 // Request metadata pieces that we don't have in a random order.
457 for index := 0; index < c.t.metadataPieceCount(); index++ {
458 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
459 pending = append(pending, index)
462 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
463 for _, i := range pending {
464 c.requestMetadataPiece(i)
468 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
469 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
470 if msg.Type == pp.Extended {
471 for name, id := range cn.PeerExtensionIDs {
472 if id != msg.ExtendedID {
475 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
478 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
481 func (cn *PeerConn) wroteBytes(n int64) {
482 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
485 func (c *PeerConn) fastEnabled() bool {
486 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
489 func (c *PeerConn) reject(r Request) {
490 if !c.fastEnabled() {
491 panic("fast not enabled")
493 c.write(r.ToMsg(pp.Reject))
494 // It is possible to reject a request before it is added to peer requests due to being invalid.
495 if state, ok := c.peerRequests[r]; ok {
496 state.allocReservation.Drop()
497 delete(c.peerRequests, r)
501 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
502 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
503 if uploadRateLimiter.Limit() == rate.Inf {
506 return Some(uploadRateLimiter.Burst())
509 // startFetch is for testing purposes currently.
510 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
511 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
512 if _, ok := c.peerRequests[r]; ok {
513 torrent.Add("duplicate requests received", 1)
515 return errors.New("received duplicate request with fast enabled")
520 torrent.Add("requests received while choking", 1)
522 torrent.Add("requests rejected while choking", 1)
527 // TODO: What if they've already requested this?
528 if len(c.peerRequests) >= localClientReqq {
529 torrent.Add("requests received while queue full", 1)
533 // BEP 6 says we may close here if we choose.
536 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
537 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
538 c.logger.Levelf(log.Warning, err.Error())
546 if !c.t.havePiece(pieceIndex(r.Index)) {
547 // TODO: Tell the peer we don't have the piece, and reject this request.
548 requestsReceivedForMissingPieces.Add(1)
549 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
551 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
552 // Check this after we know we have the piece, so that the piece length will be known.
553 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
554 torrent.Add("bad requests received", 1)
555 return errors.New("chunk overflows piece")
557 if c.peerRequests == nil {
558 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
560 value := &peerRequestState{
561 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
563 c.peerRequests[r] = value
565 // TODO: Limit peer request data read concurrency.
566 go c.peerRequestDataReader(r, value)
571 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
572 b, err := c.readPeerRequestData(r, prs)
574 defer c.locker().Unlock()
576 c.peerRequestDataReadFailed(err, r)
579 panic("data must be non-nil to trigger send")
581 torrent.Add("peer request data read successes", 1)
583 // This might be required for the error case too (#752 and #753).
588 // If this is maintained correctly, we might be able to support optional synchronous reading for
589 // chunk sending, the way it used to work.
590 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
591 torrent.Add("peer request data read failures", 1)
592 logLevel := log.Warning
593 if c.t.hasStorageCap() {
594 // It's expected that pieces might drop. See
595 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
598 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
599 if c.t.closed.IsSet() {
602 i := pieceIndex(r.Index)
603 if c.t.pieceComplete(i) {
604 // There used to be more code here that just duplicated the following break. Piece
605 // completions are currently cached, so I'm not sure how helpful this update is, except to
606 // pull any completion changes pushed to the storage backend in failed reads that got us
608 c.t.updatePieceCompletion(i)
610 // We've probably dropped a piece from storage, but there's no way to communicate this to the
611 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
612 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
613 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
619 // If fast isn't enabled, I think we would have wiped all peer requests when we last
620 // choked, and requests while we're choking would be ignored. It could be possible that
621 // a peer request data read completed concurrently to it being deleted elsewhere.
622 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
624 // Choking a non-fast peer should cause them to flush all their requests.
629 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
630 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
631 // or fail to read and then cleanup.
632 ctx := context.Background()
633 err := prs.allocReservation.Wait(ctx)
635 if ctx.Err() == nil {
636 // The error is from the reservation itself. Something is very broken, or we're not
637 // guarding against excessively large requests.
638 err = log.WithLevel(log.Critical, err)
640 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
643 b := make([]byte, r.Length)
644 p := c.t.info.Piece(int(r.Index))
645 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
652 panic("expected error")
658 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
659 c.logger.WithContextText(fmt.Sprintf(
660 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
661 )).SkipCallers(1).Levelf(level, format, arg...)
664 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
665 // exit. Returning will end the connection.
666 func (c *PeerConn) mainReadLoop() (err error) {
669 torrent.Add("connection.mainReadLoop returned with error", 1)
671 torrent.Add("connection.mainReadLoop returned with no error", 1)
677 decoder := pp.Decoder{
678 R: bufio.NewReaderSize(c.r, 1<<17),
679 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
687 err = decoder.Decode(&msg)
689 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
692 if t.closed.IsSet() || c.closed.IsSet() {
698 c.lastMessageReceived = time.Now()
700 receivedKeepalives.Add(1)
703 messageTypesReceived.Add(msg.Type.String(), 1)
704 if msg.Type.FastExtension() && !c.fastEnabled() {
705 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
706 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
713 if !c.fastEnabled() {
714 c.deleteAllRequests("choked by non-fast PeerConn")
716 // We don't decrement pending requests here, let's wait for the peer to either
717 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
718 // us and resume where they left off, we don't want to have piled on to those chunks
719 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
720 // could let us request a lot of stuff, then choke us and never reject, but they're
721 // only a single peer, our chunk balancing should smooth over this abuse.
724 c.updateExpectingChunks()
727 // Some clients do this for some reason. Transmission doesn't error on this, so we
728 // won't for consistency.
729 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
732 c.peerChoking = false
734 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
735 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
740 if preservedCount != 0 {
741 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
743 c.logger.Levelf(log.Debug,
744 "%v requests were preserved while being choked (fast=%v)",
748 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
750 if !c.t._pendingPieces.IsEmpty() {
751 c.updateRequests("unchoked")
753 c.updateExpectingChunks()
755 c.peerInterested = true
757 case pp.NotInterested:
758 c.peerInterested = false
759 // We don't clear their requests since it isn't clear in the spec.
760 // We'll probably choke them for this, which will clear them if
761 // appropriate, and is clearly specified.
763 err = c.peerSentHave(pieceIndex(msg.Index))
765 err = c.peerSentBitfield(msg.Bitfield)
767 r := newRequestFromMessage(&msg)
768 err = c.onReadRequest(r, true)
770 err = fmt.Errorf("on reading request %v: %w", r, err)
773 c.doChunkReadStats(int64(len(msg.Piece)))
774 err = c.receiveChunk(&msg)
775 if len(msg.Piece) == int(t.chunkSize) {
776 t.chunkPool.Put(&msg.Piece)
779 err = fmt.Errorf("receiving chunk: %w", err)
782 req := newRequestFromMessage(&msg)
783 c.onPeerSentCancel(req)
785 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
789 pingAddr := net.UDPAddr{
794 pingAddr.Port = int(msg.Port)
796 cl.eachDhtServer(func(s DhtServer) {
800 torrent.Add("suggests received", 1)
801 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
802 c.updateRequests("suggested")
804 err = c.onPeerSentHaveAll()
806 err = c.peerSentHaveNone()
808 req := newRequestFromMessage(&msg)
809 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
810 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
811 err = fmt.Errorf("received invalid reject [request=%v]", req)
814 torrent.Add("allowed fasts received", 1)
815 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
816 c.updateRequests("PeerConn.mainReadLoop allowed fast")
818 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
820 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
828 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
830 // TODO: Should we still do this?
832 // These clients use their own extension IDs for outgoing message
833 // types, which is incorrect.
834 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
842 case pp.HandshakeExtendedID:
843 var d pp.ExtendedHandshakeMessage
844 if err := bencode.Unmarshal(payload, &d); err != nil {
845 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
846 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
848 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
851 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
853 c.PeerMaxRequests = d.Reqq
855 c.PeerClientName.Store(d.V)
856 if c.PeerExtensionIDs == nil {
857 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
859 c.PeerListenPort = d.Port
860 c.PeerPrefersEncryption = d.Encryption
861 for name, id := range d.M {
862 if _, ok := c.PeerExtensionIDs[name]; !ok {
863 peersSupportingExtension.Add(
864 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
865 // entered here which caused problems later when unmarshalling.
866 strconv.Quote(string(name)),
869 c.PeerExtensionIDs[name] = id
871 if d.MetadataSize != 0 {
872 if err = t.setMetadataSize(d.MetadataSize); err != nil {
873 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
876 c.requestPendingMetadata()
877 if !t.cl.config.DisablePEX {
878 t.pex.Add(c) // we learnt enough now
879 // This checks the extension is supported internally.
883 case metadataExtendedId:
884 err := cl.gotMetadataExtensionMsg(payload, t, c)
886 return fmt.Errorf("handling metadata extension message: %w", err)
890 if !c.pex.IsEnabled() {
891 return nil // or hang-up maybe?
893 err = c.pex.Recv(payload)
895 err = fmt.Errorf("receiving pex message: %w", err)
898 case utHolepunchExtendedId:
899 var msg utHolepunch.Msg
900 err = msg.UnmarshalBinary(payload)
902 err = fmt.Errorf("unmarshalling ut_holepunch message: %w", err)
905 err = c.t.handleReceivedUtHolepunchMsg(msg, c)
908 return fmt.Errorf("unexpected extended message ID: %v", id)
912 // Set both the Reader and Writer for the connection from a single ReadWriter.
913 func (cn *PeerConn) setRW(rw io.ReadWriter) {
918 // Returns the Reader and Writer as a combined ReadWriter.
919 func (cn *PeerConn) rw() io.ReadWriter {
926 func (c *PeerConn) uploadAllowed() bool {
927 if c.t.cl.config.NoUpload {
930 if c.t.dataUploadDisallowed {
936 if !c.peerHasWantedPieces() {
939 // Don't upload more than 100 KiB more than we download.
940 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
946 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
947 if c.uploadTimer == nil {
948 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
950 c.uploadTimer.Reset(delay)
954 // Also handles choking and unchoking of the remote peer.
955 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
956 // Breaking or completing this loop means we don't want to upload to the
957 // peer anymore, and we choke them.
959 for c.uploadAllowed() {
960 // We want to upload to the peer.
964 for r, state := range c.peerRequests {
965 if state.data == nil {
968 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
970 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
975 c.setRetryUploadTimer(delay)
976 // Hard to say what to return here.
979 more := c.sendChunk(r, msg, state)
980 delete(c.peerRequests, r)
991 func (cn *PeerConn) drop() {
992 cn.t.dropConnection(cn)
995 func (cn *PeerConn) ban() {
996 cn.t.cl.banPeerIP(cn.remoteIp())
999 // This is called when something has changed that should wake the writer, such as putting stuff into
1000 // the writeBuffer, or changing some state that the writer can act on.
1001 func (c *PeerConn) tickleWriter() {
1002 c.messageWriter.writeCond.Broadcast()
1005 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1006 c.lastChunkSent = time.Now()
1007 state.allocReservation.Release()
1008 return msg(pp.Message{
1016 func (c *PeerConn) setTorrent(t *Torrent) {
1018 panic("connection already associated with a torrent")
1021 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1022 t.reconcileHandshakeStats(c)
1025 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1026 f := pp.PexPeerFlags(0)
1027 if c.PeerPrefersEncryption {
1028 f |= pp.PexPrefersEncryption
1031 f |= pp.PexOutgoingConn
1034 f |= pp.PexSupportsUtp
1039 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1040 // advertised listen port.
1041 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1042 if !c.outgoing && c.PeerListenPort != 0 {
1043 switch addr := c.RemoteAddr.(type) {
1046 dialAddr.Port = c.PeerListenPort
1050 dialAddr.Port = c.PeerListenPort
1057 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1058 f := c.pexPeerFlags()
1059 addr := c.dialAddr()
1060 return pexEvent{t, addr, f, nil}
1063 func (c *PeerConn) String() string {
1064 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1067 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1068 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1069 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1071 defer cn.locker().RUnlock()
1072 return cn.newPeerPieces()
1075 func (pc *PeerConn) remoteIsTransmission() bool {
1076 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1079 func (pc *PeerConn) remoteAddrPort() Option[netip.AddrPort] {
1080 return Some(pc.conn.RemoteAddr().(interface {
1081 AddrPort() netip.AddrPort
1085 func (pc *PeerConn) bitExtensionEnabled(bit pp.ExtensionBit) bool {
1086 return pc.t.cl.config.Extensions.GetBit(bit) && pc.PeerExtensionBytes.GetBit(bit)