16 "github.com/RoaringBitmap/roaring"
17 . "github.com/anacrolix/generics"
18 "github.com/anacrolix/log"
19 "github.com/anacrolix/missinggo/v2/bitmap"
20 "github.com/anacrolix/multiless"
21 "golang.org/x/time/rate"
23 "github.com/anacrolix/torrent/bencode"
24 "github.com/anacrolix/torrent/internal/alloclim"
25 "github.com/anacrolix/torrent/metainfo"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
30 // Maintains the state of a BitTorrent-protocol based connection with a peer.
31 type PeerConn struct {
34 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
35 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
40 PeerExtensionBytes pp.PeerExtensionBits
42 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
43 // while holding any mutexes.
45 // The Reader and Writer for this Conn, with hooks installed for stats,
46 // limiting, deadlines etc.
50 messageWriter peerConnMsgWriter
52 uploadTimer *time.Timer
55 // The pieces the peer has claimed to have.
56 _peerPieces roaring.Bitmap
57 // The peer has everything. This can occur due to a special message, when
58 // we may not even know the number of pieces in the torrent yet.
61 peerRequestDataAllocLimiter alloclim.Limiter
64 func (cn *PeerConn) peerImplStatusLines() []string {
65 return []string{fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)}
68 // Returns true if the connection is over IPv6.
69 func (cn *PeerConn) ipv6() bool {
74 return len(ip) == net.IPv6len
77 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
78 // specification for this.
79 func (cn *PeerConn) isPreferredDirection() bool {
80 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
83 // Returns whether the left connection should be preferred over the right one,
84 // considering only their networking properties. If ok is false, we can't
86 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
87 var ml multiless.Computation
88 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
89 ml = ml.Bool(l.utp(), r.utp())
90 ml = ml.Bool(r.ipv6(), l.ipv6())
94 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
95 if cn.peerSentHaveAll {
101 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
104 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
105 cn.setNumPieces(info.NumPieces())
108 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
109 // receiving badly sized BITFIELD, or invalid HAVE messages.
110 func (cn *PeerConn) setNumPieces(num pieceIndex) {
111 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
112 cn.peerPiecesChanged()
115 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
116 return &cn._peerPieces
119 func (cn *PeerConn) connectionFlags() (ret string) {
121 ret += string([]byte{b})
123 if cn.cryptoMethod == mse.CryptoMethodRC4 {
125 } else if cn.headerEncrypted {
128 ret += string(cn.Discovery)
135 func (cn *PeerConn) utp() bool {
136 return parseNetworkString(cn.Network).Udp
139 func (cn *PeerConn) onClose() {
140 if cn.pex.IsEnabled() {
147 if cb := cn.callbacks.PeerConnClosed; cb != nil {
152 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
153 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
154 func (cn *PeerConn) write(msg pp.Message) bool {
155 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
156 // We don't need to track bytes here because the connection's Writer has that behaviour injected
157 // (although there's some delay between us buffering the message, and the connection writer
158 // flushing it out.).
159 notFull := cn.messageWriter.write(msg)
160 // Last I checked only Piece messages affect stats, and we don't write those.
166 func (cn *PeerConn) requestMetadataPiece(index int) {
167 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
168 if eID == pp.ExtensionDeleteNumber {
171 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
174 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
175 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
176 for index >= len(cn.metadataRequests) {
177 cn.metadataRequests = append(cn.metadataRequests, false)
179 cn.metadataRequests[index] = true
182 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
183 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
186 func (cn *PeerConn) onPeerSentCancel(r Request) {
187 if _, ok := cn.peerRequests[r]; !ok {
188 torrent.Add("unexpected cancels received", 1)
191 if cn.fastEnabled() {
194 delete(cn.peerRequests, r)
198 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
203 more = msg(pp.Message{
206 if !cn.fastEnabled() {
207 cn.deleteAllPeerRequests()
212 func (cn *PeerConn) deleteAllPeerRequests() {
213 for _, state := range cn.peerRequests {
214 state.allocReservation.Drop()
216 cn.peerRequests = nil
219 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
224 return msg(pp.Message{
229 func (pc *PeerConn) writeInterested(interested bool) bool {
230 return pc.write(pp.Message{
231 Type: func() pp.MessageType {
235 return pp.NotInterested
241 func (me *PeerConn) _request(r Request) bool {
242 return me.write(pp.Message{
250 func (me *PeerConn) _cancel(r RequestIndex) bool {
251 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
252 // Transmission does not send rejects for received cancels. See
253 // https://github.com/transmission/transmission/pull/2275.
254 return me.fastEnabled() && !me.remoteIsTransmission()
257 func (cn *PeerConn) fillWriteBuffer() {
258 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
259 // Fully committing to our max requests requires sufficient space (see
260 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
261 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
262 // request reason will not be cleared, so we'll come right back here when there's space. We
263 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
264 // knowledge of write buffers.
266 cn.maybeUpdateActualRequestState()
267 if cn.pex.IsEnabled() {
268 if flow := cn.pex.Share(cn.write); !flow {
275 func (cn *PeerConn) have(piece pieceIndex) {
276 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
281 Index: pp.Integer(piece),
283 cn.sentHaves.Add(bitmap.BitIndex(piece))
286 func (cn *PeerConn) postBitfield() {
287 if cn.sentHaves.Len() != 0 {
288 panic("bitfield must be first have-related message sent")
290 if !cn.t.haveAnyPieces() {
295 Bitfield: cn.t.bitfield(),
297 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
300 func (cn *PeerConn) handleUpdateRequests() {
301 // The writer determines the request state as needed when it can write.
305 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
306 if newMin > cn.peerMinPieces {
307 cn.peerMinPieces = newMin
311 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
312 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
313 return errors.New("invalid piece")
315 if cn.peerHasPiece(piece) {
318 cn.raisePeerMinPieces(piece + 1)
319 if !cn.peerHasPiece(piece) {
320 cn.t.incPieceAvailability(piece)
322 cn._peerPieces.Add(uint32(piece))
323 if cn.t.wantPieceIndex(piece) {
324 cn.updateRequests("have")
326 cn.peerPiecesChanged()
330 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
332 panic("expected bitfield length divisible by 8")
334 // We know that the last byte means that at most the last 7 bits are wasted.
335 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
336 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
337 // Ignore known excess pieces.
338 bf = bf[:cn.t.numPieces()]
340 bm := boolSliceToBitmap(bf)
341 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
342 cn.onPeerHasAllPieces()
346 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
348 shouldUpdateRequests := false
349 if cn.peerSentHaveAll {
350 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
353 cn.peerSentHaveAll = false
354 if !cn._peerPieces.IsEmpty() {
355 panic("if peer has all, we expect no individual peer pieces to be set")
358 bm.Xor(&cn._peerPieces)
360 cn.peerSentHaveAll = false
361 // bm is now 'on' for pieces that are changing
362 bm.Iterate(func(x uint32) bool {
364 if cn._peerPieces.Contains(x) {
365 // Then we must be losing this piece
366 cn.t.decPieceAvailability(pi)
368 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
369 shouldUpdateRequests = true
371 // We must be gaining this piece
372 cn.t.incPieceAvailability(pieceIndex(x))
376 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
378 cn._peerPieces.Xor(&bm)
379 if shouldUpdateRequests {
380 cn.updateRequests("bitfield")
382 // We didn't guard this before, I see no reason to do it now.
383 cn.peerPiecesChanged()
387 func (cn *PeerConn) onPeerHasAllPieces() {
390 cn._peerPieces.Iterate(func(x uint32) bool {
391 t.decPieceAvailability(pieceIndex(x))
395 t.addConnWithAllPieces(&cn.Peer)
396 cn.peerSentHaveAll = true
397 cn._peerPieces.Clear()
398 if !cn.t._pendingPieces.IsEmpty() {
399 cn.updateRequests("Peer.onPeerHasAllPieces")
401 cn.peerPiecesChanged()
404 func (cn *PeerConn) onPeerSentHaveAll() error {
405 cn.onPeerHasAllPieces()
409 func (cn *PeerConn) peerSentHaveNone() error {
410 if !cn.peerSentHaveAll {
411 cn.t.decPeerPieceAvailability(&cn.Peer)
413 cn._peerPieces.Clear()
414 cn.peerSentHaveAll = false
415 cn.peerPiecesChanged()
419 func (c *PeerConn) requestPendingMetadata() {
423 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
424 // Peer doesn't support this.
427 // Request metadata pieces that we don't have in a random order.
429 for index := 0; index < c.t.metadataPieceCount(); index++ {
430 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
431 pending = append(pending, index)
434 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
435 for _, i := range pending {
436 c.requestMetadataPiece(i)
440 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
441 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
442 if msg.Type == pp.Extended {
443 for name, id := range cn.PeerExtensionIDs {
444 if id != msg.ExtendedID {
447 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
450 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
453 func (cn *PeerConn) wroteBytes(n int64) {
454 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
457 func (c *PeerConn) fastEnabled() bool {
458 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
461 func (c *PeerConn) reject(r Request) {
462 if !c.fastEnabled() {
463 panic("fast not enabled")
465 c.write(r.ToMsg(pp.Reject))
466 // It is possible to reject a request before it is added to peer requests due to being invalid.
467 if state, ok := c.peerRequests[r]; ok {
468 state.allocReservation.Drop()
469 delete(c.peerRequests, r)
473 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
474 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
475 if uploadRateLimiter.Limit() == rate.Inf {
478 return Some(uploadRateLimiter.Burst())
481 // startFetch is for testing purposes currently.
482 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
483 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
484 if _, ok := c.peerRequests[r]; ok {
485 torrent.Add("duplicate requests received", 1)
487 return errors.New("received duplicate request with fast enabled")
492 torrent.Add("requests received while choking", 1)
494 torrent.Add("requests rejected while choking", 1)
499 // TODO: What if they've already requested this?
500 if len(c.peerRequests) >= localClientReqq {
501 torrent.Add("requests received while queue full", 1)
505 // BEP 6 says we may close here if we choose.
508 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
509 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
510 c.logger.Levelf(log.Warning, err.Error())
518 if !c.t.havePiece(pieceIndex(r.Index)) {
519 // TODO: Tell the peer we don't have the piece, and reject this request.
520 requestsReceivedForMissingPieces.Add(1)
521 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
523 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
524 // Check this after we know we have the piece, so that the piece length will be known.
525 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
526 torrent.Add("bad requests received", 1)
527 return errors.New("chunk overflows piece")
529 if c.peerRequests == nil {
530 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
532 value := &peerRequestState{
533 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
535 c.peerRequests[r] = value
537 // TODO: Limit peer request data read concurrency.
538 go c.peerRequestDataReader(r, value)
543 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
544 b, err := c.readPeerRequestData(r, prs)
546 defer c.locker().Unlock()
548 c.peerRequestDataReadFailed(err, r)
551 panic("data must be non-nil to trigger send")
553 torrent.Add("peer request data read successes", 1)
555 // This might be required for the error case too (#752 and #753).
560 // If this is maintained correctly, we might be able to support optional synchronous reading for
561 // chunk sending, the way it used to work.
562 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
563 torrent.Add("peer request data read failures", 1)
564 logLevel := log.Warning
565 if c.t.hasStorageCap() {
566 // It's expected that pieces might drop. See
567 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
570 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
571 if c.t.closed.IsSet() {
574 i := pieceIndex(r.Index)
575 if c.t.pieceComplete(i) {
576 // There used to be more code here that just duplicated the following break. Piece
577 // completions are currently cached, so I'm not sure how helpful this update is, except to
578 // pull any completion changes pushed to the storage backend in failed reads that got us
580 c.t.updatePieceCompletion(i)
582 // We've probably dropped a piece from storage, but there's no way to communicate this to the
583 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
584 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
585 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
591 // If fast isn't enabled, I think we would have wiped all peer requests when we last
592 // choked, and requests while we're choking would be ignored. It could be possible that
593 // a peer request data read completed concurrently to it being deleted elsewhere.
594 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
596 // Choking a non-fast peer should cause them to flush all their requests.
601 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
602 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
603 // or fail to read and then cleanup.
604 ctx := context.Background()
605 err := prs.allocReservation.Wait(ctx)
607 if ctx.Err() == nil {
608 // The error is from the reservation itself. Something is very broken, or we're not
609 // guarding against excessively large requests.
610 err = log.WithLevel(log.Critical, err)
612 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
615 b := make([]byte, r.Length)
616 p := c.t.info.Piece(int(r.Index))
617 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
624 panic("expected error")
630 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
631 c.logger.WithContextText(fmt.Sprintf(
632 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
633 )).SkipCallers(1).Levelf(level, format, arg...)
636 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
637 // exit. Returning will end the connection.
638 func (c *PeerConn) mainReadLoop() (err error) {
641 torrent.Add("connection.mainReadLoop returned with error", 1)
643 torrent.Add("connection.mainReadLoop returned with no error", 1)
649 decoder := pp.Decoder{
650 R: bufio.NewReaderSize(c.r, 1<<17),
651 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
659 err = decoder.Decode(&msg)
661 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
664 if t.closed.IsSet() || c.closed.IsSet() {
670 c.lastMessageReceived = time.Now()
672 receivedKeepalives.Add(1)
675 messageTypesReceived.Add(msg.Type.String(), 1)
676 if msg.Type.FastExtension() && !c.fastEnabled() {
677 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
678 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
685 if !c.fastEnabled() {
686 c.deleteAllRequests("choked by non-fast PeerConn")
688 // We don't decrement pending requests here, let's wait for the peer to either
689 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
690 // us and resume where they left off, we don't want to have piled on to those chunks
691 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
692 // could let us request a lot of stuff, then choke us and never reject, but they're
693 // only a single peer, our chunk balancing should smooth over this abuse.
696 c.updateExpectingChunks()
699 // Some clients do this for some reason. Transmission doesn't error on this, so we
700 // won't for consistency.
701 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
704 c.peerChoking = false
706 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
707 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
712 if preservedCount != 0 {
713 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
715 c.logger.Levelf(log.Debug,
716 "%v requests were preserved while being choked (fast=%v)",
720 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
722 if !c.t._pendingPieces.IsEmpty() {
723 c.updateRequests("unchoked")
725 c.updateExpectingChunks()
727 c.peerInterested = true
729 case pp.NotInterested:
730 c.peerInterested = false
731 // We don't clear their requests since it isn't clear in the spec.
732 // We'll probably choke them for this, which will clear them if
733 // appropriate, and is clearly specified.
735 err = c.peerSentHave(pieceIndex(msg.Index))
737 err = c.peerSentBitfield(msg.Bitfield)
739 r := newRequestFromMessage(&msg)
740 err = c.onReadRequest(r, true)
742 err = fmt.Errorf("on reading request %v: %w", r, err)
745 c.doChunkReadStats(int64(len(msg.Piece)))
746 err = c.receiveChunk(&msg)
747 if len(msg.Piece) == int(t.chunkSize) {
748 t.chunkPool.Put(&msg.Piece)
751 err = fmt.Errorf("receiving chunk: %w", err)
754 req := newRequestFromMessage(&msg)
755 c.onPeerSentCancel(req)
757 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
761 pingAddr := net.UDPAddr{
766 pingAddr.Port = int(msg.Port)
768 cl.eachDhtServer(func(s DhtServer) {
772 torrent.Add("suggests received", 1)
773 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
774 c.updateRequests("suggested")
776 err = c.onPeerSentHaveAll()
778 err = c.peerSentHaveNone()
780 req := newRequestFromMessage(&msg)
781 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
782 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
783 err = fmt.Errorf("received invalid reject [request=%v]", req)
786 torrent.Add("allowed fasts received", 1)
787 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
788 c.updateRequests("PeerConn.mainReadLoop allowed fast")
790 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
792 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
800 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
802 // TODO: Should we still do this?
804 // These clients use their own extension IDs for outgoing message
805 // types, which is incorrect.
806 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
814 case pp.HandshakeExtendedID:
815 var d pp.ExtendedHandshakeMessage
816 if err := bencode.Unmarshal(payload, &d); err != nil {
817 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
818 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
820 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
823 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
825 c.PeerMaxRequests = d.Reqq
827 c.PeerClientName.Store(d.V)
828 if c.PeerExtensionIDs == nil {
829 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
831 c.PeerListenPort = d.Port
832 c.PeerPrefersEncryption = d.Encryption
833 for name, id := range d.M {
834 if _, ok := c.PeerExtensionIDs[name]; !ok {
835 peersSupportingExtension.Add(
836 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
837 // entered here which caused problems later when unmarshalling.
838 strconv.Quote(string(name)),
841 c.PeerExtensionIDs[name] = id
843 if d.MetadataSize != 0 {
844 if err = t.setMetadataSize(d.MetadataSize); err != nil {
845 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
848 c.requestPendingMetadata()
849 if !t.cl.config.DisablePEX {
850 t.pex.Add(c) // we learnt enough now
854 case metadataExtendedId:
855 err := cl.gotMetadataExtensionMsg(payload, t, c)
857 return fmt.Errorf("handling metadata extension message: %w", err)
861 if !c.pex.IsEnabled() {
862 return nil // or hang-up maybe?
864 return c.pex.Recv(payload)
866 return fmt.Errorf("unexpected extended message ID: %v", id)
870 // Set both the Reader and Writer for the connection from a single ReadWriter.
871 func (cn *PeerConn) setRW(rw io.ReadWriter) {
876 // Returns the Reader and Writer as a combined ReadWriter.
877 func (cn *PeerConn) rw() io.ReadWriter {
884 func (c *PeerConn) uploadAllowed() bool {
885 if c.t.cl.config.NoUpload {
888 if c.t.dataUploadDisallowed {
894 if !c.peerHasWantedPieces() {
897 // Don't upload more than 100 KiB more than we download.
898 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
904 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
905 if c.uploadTimer == nil {
906 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
908 c.uploadTimer.Reset(delay)
912 // Also handles choking and unchoking of the remote peer.
913 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
914 // Breaking or completing this loop means we don't want to upload to the
915 // peer anymore, and we choke them.
917 for c.uploadAllowed() {
918 // We want to upload to the peer.
922 for r, state := range c.peerRequests {
923 if state.data == nil {
926 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
928 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
933 c.setRetryUploadTimer(delay)
934 // Hard to say what to return here.
937 more := c.sendChunk(r, msg, state)
938 delete(c.peerRequests, r)
949 func (cn *PeerConn) drop() {
950 cn.t.dropConnection(cn)
953 func (cn *PeerConn) ban() {
954 cn.t.cl.banPeerIP(cn.remoteIp())
957 // This is called when something has changed that should wake the writer, such as putting stuff into
958 // the writeBuffer, or changing some state that the writer can act on.
959 func (c *PeerConn) tickleWriter() {
960 c.messageWriter.writeCond.Broadcast()
963 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
964 c.lastChunkSent = time.Now()
965 state.allocReservation.Release()
966 return msg(pp.Message{
974 func (c *PeerConn) setTorrent(t *Torrent) {
976 panic("connection already associated with a torrent")
979 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
980 t.reconcileHandshakeStats(c)
983 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
984 f := pp.PexPeerFlags(0)
985 if c.PeerPrefersEncryption {
986 f |= pp.PexPrefersEncryption
989 f |= pp.PexOutgoingConn
992 f |= pp.PexSupportsUtp
997 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
998 // advertised listen port.
999 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1000 if !c.outgoing && c.PeerListenPort != 0 {
1001 switch addr := c.RemoteAddr.(type) {
1004 dialAddr.Port = c.PeerListenPort
1008 dialAddr.Port = c.PeerListenPort
1015 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1016 f := c.pexPeerFlags()
1017 addr := c.dialAddr()
1018 return pexEvent{t, addr, f, nil}
1021 func (c *PeerConn) String() string {
1022 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1025 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1026 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1027 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1029 defer cn.locker().RUnlock()
1030 return cn.newPeerPieces()
1033 func (pc *PeerConn) remoteIsTransmission() bool {
1034 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'