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 lines := make([]string, 0, 2)
68 fmt.Sprintf("%+-55q %v %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString))
69 if cn.supportsExtension(pp.ExtensionNamePex) {
73 "pex: %v conns, %v unsent events",
74 cn.pex.remoteLiveConns,
80 // Returns true if the connection is over IPv6.
81 func (cn *PeerConn) ipv6() bool {
86 return len(ip) == net.IPv6len
89 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
90 // specification for this.
91 func (cn *PeerConn) isPreferredDirection() bool {
92 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
95 // Returns whether the left connection should be preferred over the right one,
96 // considering only their networking properties. If ok is false, we can't
98 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
99 var ml multiless.Computation
100 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
101 ml = ml.Bool(l.utp(), r.utp())
102 ml = ml.Bool(r.ipv6(), l.ipv6())
106 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
107 if cn.peerSentHaveAll {
110 if !cn.t.haveInfo() {
113 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
116 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
117 cn.setNumPieces(info.NumPieces())
120 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
121 // receiving badly sized BITFIELD, or invalid HAVE messages.
122 func (cn *PeerConn) setNumPieces(num pieceIndex) {
123 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
124 cn.peerPiecesChanged()
127 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
128 return &cn._peerPieces
131 func (cn *PeerConn) connectionFlags() (ret string) {
133 ret += string([]byte{b})
135 if cn.cryptoMethod == mse.CryptoMethodRC4 {
137 } else if cn.headerEncrypted {
140 ret += string(cn.Discovery)
147 func (cn *PeerConn) utp() bool {
148 return parseNetworkString(cn.Network).Udp
151 func (cn *PeerConn) onClose() {
152 if cn.pex.IsEnabled() {
159 if cb := cn.callbacks.PeerConnClosed; cb != nil {
164 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
165 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
166 func (cn *PeerConn) write(msg pp.Message) bool {
167 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
168 // We don't need to track bytes here because the connection's Writer has that behaviour injected
169 // (although there's some delay between us buffering the message, and the connection writer
170 // flushing it out.).
171 notFull := cn.messageWriter.write(msg)
172 // Last I checked only Piece messages affect stats, and we don't write those.
178 func (cn *PeerConn) requestMetadataPiece(index int) {
179 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
180 if eID == pp.ExtensionDeleteNumber {
183 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
186 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
187 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
188 for index >= len(cn.metadataRequests) {
189 cn.metadataRequests = append(cn.metadataRequests, false)
191 cn.metadataRequests[index] = true
194 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
195 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
198 func (cn *PeerConn) onPeerSentCancel(r Request) {
199 if _, ok := cn.peerRequests[r]; !ok {
200 torrent.Add("unexpected cancels received", 1)
203 if cn.fastEnabled() {
206 delete(cn.peerRequests, r)
210 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
215 more = msg(pp.Message{
218 if !cn.fastEnabled() {
219 cn.deleteAllPeerRequests()
224 func (cn *PeerConn) deleteAllPeerRequests() {
225 for _, state := range cn.peerRequests {
226 state.allocReservation.Drop()
228 cn.peerRequests = nil
231 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
236 return msg(pp.Message{
241 func (pc *PeerConn) writeInterested(interested bool) bool {
242 return pc.write(pp.Message{
243 Type: func() pp.MessageType {
247 return pp.NotInterested
253 func (me *PeerConn) _request(r Request) bool {
254 return me.write(pp.Message{
262 func (me *PeerConn) _cancel(r RequestIndex) bool {
263 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
264 // Transmission does not send rejects for received cancels. See
265 // https://github.com/transmission/transmission/pull/2275.
266 return me.fastEnabled() && !me.remoteIsTransmission()
269 func (cn *PeerConn) fillWriteBuffer() {
270 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
271 // Fully committing to our max requests requires sufficient space (see
272 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
273 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
274 // request reason will not be cleared, so we'll come right back here when there's space. We
275 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
276 // knowledge of write buffers.
278 cn.maybeUpdateActualRequestState()
279 if cn.pex.IsEnabled() {
280 if flow := cn.pex.Share(cn.write); !flow {
287 func (cn *PeerConn) have(piece pieceIndex) {
288 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
293 Index: pp.Integer(piece),
295 cn.sentHaves.Add(bitmap.BitIndex(piece))
298 func (cn *PeerConn) postBitfield() {
299 if cn.sentHaves.Len() != 0 {
300 panic("bitfield must be first have-related message sent")
302 if !cn.t.haveAnyPieces() {
307 Bitfield: cn.t.bitfield(),
309 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
312 func (cn *PeerConn) handleUpdateRequests() {
313 // The writer determines the request state as needed when it can write.
317 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
318 if newMin > cn.peerMinPieces {
319 cn.peerMinPieces = newMin
323 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
324 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
325 return errors.New("invalid piece")
327 if cn.peerHasPiece(piece) {
330 cn.raisePeerMinPieces(piece + 1)
331 if !cn.peerHasPiece(piece) {
332 cn.t.incPieceAvailability(piece)
334 cn._peerPieces.Add(uint32(piece))
335 if cn.t.wantPieceIndex(piece) {
336 cn.updateRequests("have")
338 cn.peerPiecesChanged()
342 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
344 panic("expected bitfield length divisible by 8")
346 // We know that the last byte means that at most the last 7 bits are wasted.
347 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
348 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
349 // Ignore known excess pieces.
350 bf = bf[:cn.t.numPieces()]
352 bm := boolSliceToBitmap(bf)
353 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
354 cn.onPeerHasAllPieces()
358 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
360 shouldUpdateRequests := false
361 if cn.peerSentHaveAll {
362 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
365 cn.peerSentHaveAll = false
366 if !cn._peerPieces.IsEmpty() {
367 panic("if peer has all, we expect no individual peer pieces to be set")
370 bm.Xor(&cn._peerPieces)
372 cn.peerSentHaveAll = false
373 // bm is now 'on' for pieces that are changing
374 bm.Iterate(func(x uint32) bool {
376 if cn._peerPieces.Contains(x) {
377 // Then we must be losing this piece
378 cn.t.decPieceAvailability(pi)
380 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
381 shouldUpdateRequests = true
383 // We must be gaining this piece
384 cn.t.incPieceAvailability(pieceIndex(x))
388 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
390 cn._peerPieces.Xor(&bm)
391 if shouldUpdateRequests {
392 cn.updateRequests("bitfield")
394 // We didn't guard this before, I see no reason to do it now.
395 cn.peerPiecesChanged()
399 func (cn *PeerConn) onPeerHasAllPieces() {
402 cn._peerPieces.Iterate(func(x uint32) bool {
403 t.decPieceAvailability(pieceIndex(x))
407 t.addConnWithAllPieces(&cn.Peer)
408 cn.peerSentHaveAll = true
409 cn._peerPieces.Clear()
410 if !cn.t._pendingPieces.IsEmpty() {
411 cn.updateRequests("Peer.onPeerHasAllPieces")
413 cn.peerPiecesChanged()
416 func (cn *PeerConn) onPeerSentHaveAll() error {
417 cn.onPeerHasAllPieces()
421 func (cn *PeerConn) peerSentHaveNone() error {
422 if !cn.peerSentHaveAll {
423 cn.t.decPeerPieceAvailability(&cn.Peer)
425 cn._peerPieces.Clear()
426 cn.peerSentHaveAll = false
427 cn.peerPiecesChanged()
431 func (c *PeerConn) requestPendingMetadata() {
435 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
436 // Peer doesn't support this.
439 // Request metadata pieces that we don't have in a random order.
441 for index := 0; index < c.t.metadataPieceCount(); index++ {
442 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
443 pending = append(pending, index)
446 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
447 for _, i := range pending {
448 c.requestMetadataPiece(i)
452 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
453 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
454 if msg.Type == pp.Extended {
455 for name, id := range cn.PeerExtensionIDs {
456 if id != msg.ExtendedID {
459 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
462 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
465 func (cn *PeerConn) wroteBytes(n int64) {
466 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
469 func (c *PeerConn) fastEnabled() bool {
470 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
473 func (c *PeerConn) reject(r Request) {
474 if !c.fastEnabled() {
475 panic("fast not enabled")
477 c.write(r.ToMsg(pp.Reject))
478 // It is possible to reject a request before it is added to peer requests due to being invalid.
479 if state, ok := c.peerRequests[r]; ok {
480 state.allocReservation.Drop()
481 delete(c.peerRequests, r)
485 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
486 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
487 if uploadRateLimiter.Limit() == rate.Inf {
490 return Some(uploadRateLimiter.Burst())
493 // startFetch is for testing purposes currently.
494 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
495 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
496 if _, ok := c.peerRequests[r]; ok {
497 torrent.Add("duplicate requests received", 1)
499 return errors.New("received duplicate request with fast enabled")
504 torrent.Add("requests received while choking", 1)
506 torrent.Add("requests rejected while choking", 1)
511 // TODO: What if they've already requested this?
512 if len(c.peerRequests) >= localClientReqq {
513 torrent.Add("requests received while queue full", 1)
517 // BEP 6 says we may close here if we choose.
520 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
521 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
522 c.logger.Levelf(log.Warning, err.Error())
530 if !c.t.havePiece(pieceIndex(r.Index)) {
531 // TODO: Tell the peer we don't have the piece, and reject this request.
532 requestsReceivedForMissingPieces.Add(1)
533 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
535 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
536 // Check this after we know we have the piece, so that the piece length will be known.
537 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
538 torrent.Add("bad requests received", 1)
539 return errors.New("chunk overflows piece")
541 if c.peerRequests == nil {
542 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
544 value := &peerRequestState{
545 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
547 c.peerRequests[r] = value
549 // TODO: Limit peer request data read concurrency.
550 go c.peerRequestDataReader(r, value)
555 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
556 b, err := c.readPeerRequestData(r, prs)
558 defer c.locker().Unlock()
560 c.peerRequestDataReadFailed(err, r)
563 panic("data must be non-nil to trigger send")
565 torrent.Add("peer request data read successes", 1)
567 // This might be required for the error case too (#752 and #753).
572 // If this is maintained correctly, we might be able to support optional synchronous reading for
573 // chunk sending, the way it used to work.
574 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
575 torrent.Add("peer request data read failures", 1)
576 logLevel := log.Warning
577 if c.t.hasStorageCap() {
578 // It's expected that pieces might drop. See
579 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
582 c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
583 if c.t.closed.IsSet() {
586 i := pieceIndex(r.Index)
587 if c.t.pieceComplete(i) {
588 // There used to be more code here that just duplicated the following break. Piece
589 // completions are currently cached, so I'm not sure how helpful this update is, except to
590 // pull any completion changes pushed to the storage backend in failed reads that got us
592 c.t.updatePieceCompletion(i)
594 // We've probably dropped a piece from storage, but there's no way to communicate this to the
595 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
596 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
597 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
603 // If fast isn't enabled, I think we would have wiped all peer requests when we last
604 // choked, and requests while we're choking would be ignored. It could be possible that
605 // a peer request data read completed concurrently to it being deleted elsewhere.
606 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
608 // Choking a non-fast peer should cause them to flush all their requests.
613 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
614 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
615 // or fail to read and then cleanup.
616 ctx := context.Background()
617 err := prs.allocReservation.Wait(ctx)
619 if ctx.Err() == nil {
620 // The error is from the reservation itself. Something is very broken, or we're not
621 // guarding against excessively large requests.
622 err = log.WithLevel(log.Critical, err)
624 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
627 b := make([]byte, r.Length)
628 p := c.t.info.Piece(int(r.Index))
629 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
636 panic("expected error")
642 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
643 c.logger.WithContextText(fmt.Sprintf(
644 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
645 )).SkipCallers(1).Levelf(level, format, arg...)
648 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
649 // exit. Returning will end the connection.
650 func (c *PeerConn) mainReadLoop() (err error) {
653 torrent.Add("connection.mainReadLoop returned with error", 1)
655 torrent.Add("connection.mainReadLoop returned with no error", 1)
661 decoder := pp.Decoder{
662 R: bufio.NewReaderSize(c.r, 1<<17),
663 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
671 err = decoder.Decode(&msg)
673 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
676 if t.closed.IsSet() || c.closed.IsSet() {
682 c.lastMessageReceived = time.Now()
684 receivedKeepalives.Add(1)
687 messageTypesReceived.Add(msg.Type.String(), 1)
688 if msg.Type.FastExtension() && !c.fastEnabled() {
689 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
690 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
697 if !c.fastEnabled() {
698 c.deleteAllRequests("choked by non-fast PeerConn")
700 // We don't decrement pending requests here, let's wait for the peer to either
701 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
702 // us and resume where they left off, we don't want to have piled on to those chunks
703 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
704 // could let us request a lot of stuff, then choke us and never reject, but they're
705 // only a single peer, our chunk balancing should smooth over this abuse.
708 c.updateExpectingChunks()
711 // Some clients do this for some reason. Transmission doesn't error on this, so we
712 // won't for consistency.
713 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
716 c.peerChoking = false
718 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
719 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
724 if preservedCount != 0 {
725 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
727 c.logger.Levelf(log.Debug,
728 "%v requests were preserved while being choked (fast=%v)",
732 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
734 if !c.t._pendingPieces.IsEmpty() {
735 c.updateRequests("unchoked")
737 c.updateExpectingChunks()
739 c.peerInterested = true
741 case pp.NotInterested:
742 c.peerInterested = false
743 // We don't clear their requests since it isn't clear in the spec.
744 // We'll probably choke them for this, which will clear them if
745 // appropriate, and is clearly specified.
747 err = c.peerSentHave(pieceIndex(msg.Index))
749 err = c.peerSentBitfield(msg.Bitfield)
751 r := newRequestFromMessage(&msg)
752 err = c.onReadRequest(r, true)
754 err = fmt.Errorf("on reading request %v: %w", r, err)
757 c.doChunkReadStats(int64(len(msg.Piece)))
758 err = c.receiveChunk(&msg)
759 if len(msg.Piece) == int(t.chunkSize) {
760 t.chunkPool.Put(&msg.Piece)
763 err = fmt.Errorf("receiving chunk: %w", err)
766 req := newRequestFromMessage(&msg)
767 c.onPeerSentCancel(req)
769 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
773 pingAddr := net.UDPAddr{
778 pingAddr.Port = int(msg.Port)
780 cl.eachDhtServer(func(s DhtServer) {
784 torrent.Add("suggests received", 1)
785 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
786 c.updateRequests("suggested")
788 err = c.onPeerSentHaveAll()
790 err = c.peerSentHaveNone()
792 req := newRequestFromMessage(&msg)
793 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
794 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
795 err = fmt.Errorf("received invalid reject [request=%v]", req)
798 torrent.Add("allowed fasts received", 1)
799 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
800 c.updateRequests("PeerConn.mainReadLoop allowed fast")
802 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
804 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
812 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
814 // TODO: Should we still do this?
816 // These clients use their own extension IDs for outgoing message
817 // types, which is incorrect.
818 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
826 case pp.HandshakeExtendedID:
827 var d pp.ExtendedHandshakeMessage
828 if err := bencode.Unmarshal(payload, &d); err != nil {
829 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
830 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
832 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
835 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
837 c.PeerMaxRequests = d.Reqq
839 c.PeerClientName.Store(d.V)
840 if c.PeerExtensionIDs == nil {
841 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
843 c.PeerListenPort = d.Port
844 c.PeerPrefersEncryption = d.Encryption
845 for name, id := range d.M {
846 if _, ok := c.PeerExtensionIDs[name]; !ok {
847 peersSupportingExtension.Add(
848 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
849 // entered here which caused problems later when unmarshalling.
850 strconv.Quote(string(name)),
853 c.PeerExtensionIDs[name] = id
855 if d.MetadataSize != 0 {
856 if err = t.setMetadataSize(d.MetadataSize); err != nil {
857 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
860 c.requestPendingMetadata()
861 if !t.cl.config.DisablePEX {
862 t.pex.Add(c) // we learnt enough now
863 // This checks the extension is supported internally.
867 case metadataExtendedId:
868 err := cl.gotMetadataExtensionMsg(payload, t, c)
870 return fmt.Errorf("handling metadata extension message: %w", err)
874 if !c.pex.IsEnabled() {
875 return nil // or hang-up maybe?
877 return c.pex.Recv(payload)
879 return fmt.Errorf("unexpected extended message ID: %v", id)
883 // Set both the Reader and Writer for the connection from a single ReadWriter.
884 func (cn *PeerConn) setRW(rw io.ReadWriter) {
889 // Returns the Reader and Writer as a combined ReadWriter.
890 func (cn *PeerConn) rw() io.ReadWriter {
897 func (c *PeerConn) uploadAllowed() bool {
898 if c.t.cl.config.NoUpload {
901 if c.t.dataUploadDisallowed {
907 if !c.peerHasWantedPieces() {
910 // Don't upload more than 100 KiB more than we download.
911 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
917 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
918 if c.uploadTimer == nil {
919 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
921 c.uploadTimer.Reset(delay)
925 // Also handles choking and unchoking of the remote peer.
926 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
927 // Breaking or completing this loop means we don't want to upload to the
928 // peer anymore, and we choke them.
930 for c.uploadAllowed() {
931 // We want to upload to the peer.
935 for r, state := range c.peerRequests {
936 if state.data == nil {
939 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
941 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
946 c.setRetryUploadTimer(delay)
947 // Hard to say what to return here.
950 more := c.sendChunk(r, msg, state)
951 delete(c.peerRequests, r)
962 func (cn *PeerConn) drop() {
963 cn.t.dropConnection(cn)
966 func (cn *PeerConn) ban() {
967 cn.t.cl.banPeerIP(cn.remoteIp())
970 // This is called when something has changed that should wake the writer, such as putting stuff into
971 // the writeBuffer, or changing some state that the writer can act on.
972 func (c *PeerConn) tickleWriter() {
973 c.messageWriter.writeCond.Broadcast()
976 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
977 c.lastChunkSent = time.Now()
978 state.allocReservation.Release()
979 return msg(pp.Message{
987 func (c *PeerConn) setTorrent(t *Torrent) {
989 panic("connection already associated with a torrent")
992 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
993 t.reconcileHandshakeStats(c)
996 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
997 f := pp.PexPeerFlags(0)
998 if c.PeerPrefersEncryption {
999 f |= pp.PexPrefersEncryption
1002 f |= pp.PexOutgoingConn
1005 f |= pp.PexSupportsUtp
1010 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1011 // advertised listen port.
1012 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1013 if !c.outgoing && c.PeerListenPort != 0 {
1014 switch addr := c.RemoteAddr.(type) {
1017 dialAddr.Port = c.PeerListenPort
1021 dialAddr.Port = c.PeerListenPort
1028 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1029 f := c.pexPeerFlags()
1030 addr := c.dialAddr()
1031 return pexEvent{t, addr, f, nil}
1034 func (c *PeerConn) String() string {
1035 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1038 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1039 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1040 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1042 defer cn.locker().RUnlock()
1043 return cn.newPeerPieces()
1046 func (pc *PeerConn) remoteIsTransmission() bool {
1047 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'