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/merkle"
30 "github.com/anacrolix/torrent/metainfo"
31 "github.com/anacrolix/torrent/mse"
32 pp "github.com/anacrolix/torrent/peer_protocol"
33 utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
36 // Maintains the state of a BitTorrent-protocol based connection with a peer.
37 type PeerConn struct {
43 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
44 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
49 PeerExtensionBytes pp.PeerExtensionBits
52 // The local extended protocols to advertise in the extended handshake, and to support receiving
53 // from the peer. This will point to the Client default when the PeerConnAdded callback is
54 // invoked. Do not modify this, point it to your own instance. Do not modify the destination
55 // after returning from the callback.
56 LocalLtepProtocolMap *LocalLtepProtocolMap
58 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
59 // while holding any mutexes.
61 // The Reader and Writer for this Conn, with hooks installed for stats,
62 // limiting, deadlines etc.
66 messageWriter peerConnMsgWriter
68 // The peer's extension map, as sent in their extended handshake.
69 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
70 PeerClientName atomic.Value
71 uploadTimer *time.Timer
74 // The pieces the peer has claimed to have.
75 _peerPieces roaring.Bitmap
76 // The peer has everything. This can occur due to a special message, when
77 // we may not even know the number of pieces in the torrent yet.
80 peerRequestDataAllocLimiter alloclim.Limiter
82 outstandingHolepunchingRendezvous map[netip.AddrPort]struct{}
84 // Hash requests sent to the peer. If there's an issue we probably don't want to reissue these,
85 // because I haven't implemented it smart enough yet.
86 sentHashRequests map[hashRequest]struct{}
87 // Hash pieces received from the peer, mapped from pieces root to piece layer hashes. This way
88 // we can verify all the pieces for a file when they're all arrived before submitting them to
90 receivedHashPieces map[[32]byte][][32]byte
93 func (cn *PeerConn) pexStatus() string {
94 if !cn.bitExtensionEnabled(pp.ExtensionBitLtep) {
95 return "extended protocol disabled"
97 if cn.PeerExtensionIDs == nil {
98 return "pending extended handshake"
100 if !cn.supportsExtension(pp.ExtensionNamePex) {
105 "%v conns, %v unsent events",
106 len(cn.pex.remoteLiveConns),
110 // This alternative branch prints out the remote live conn addresses.
112 "%v conns, %v unsent events",
113 strings.Join(generics.SliceMap(
114 maps.Keys(cn.pex.remoteLiveConns),
115 func(from netip.AddrPort) string {
123 func (cn *PeerConn) peerImplStatusLines() []string {
126 fmt.Sprintf("peer id: %+q", cn.PeerID),
127 fmt.Sprintf("extensions: %v", cn.PeerExtensionBytes),
128 fmt.Sprintf("ltep extensions: %v", cn.PeerExtensionIDs),
129 fmt.Sprintf("pex: %s", cn.pexStatus()),
133 // Returns true if the connection is over IPv6.
134 func (cn *PeerConn) ipv6() bool {
139 return len(ip) == net.IPv6len
142 // Returns true the if the dialer/initiator has the higher client peer ID. See
143 // https://github.com/arvidn/libtorrent/blame/272828e1cc37b042dfbbafa539222d8533e99755/src/bt_peer_connection.cpp#L3536-L3557.
144 // As far as I can tell, Transmission just keeps the oldest connection.
145 func (cn *PeerConn) isPreferredDirection() bool {
146 // True if our client peer ID is higher than the remote's peer ID.
147 return bytes.Compare(cn.PeerID[:], cn.t.cl.peerID[:]) < 0 == cn.outgoing
150 // Returns whether the left connection should be preferred over the right one,
151 // considering only their networking properties. If ok is false, we can't
153 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
154 var ml multiless.Computation
155 ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
156 ml = ml.Bool(l.utp(), r.utp())
157 ml = ml.Bool(r.ipv6(), l.ipv6())
161 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
162 if cn.peerSentHaveAll {
165 if !cn.t.haveInfo() {
168 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
171 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
172 cn.setNumPieces(info.NumPieces())
175 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
176 // receiving badly sized BITFIELD, or invalid HAVE messages.
177 func (cn *PeerConn) setNumPieces(num pieceIndex) {
178 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
179 cn.peerPiecesChanged()
182 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
183 return &cn._peerPieces
186 func (cn *PeerConn) connectionFlags() string {
187 var sb strings.Builder
188 add := func(s string) {
194 // From first relevant to last.
195 add(string(cn.Discovery))
199 if cn.cryptoMethod == mse.CryptoMethodRC4 {
201 } else if cn.headerEncrypted {
212 func (cn *PeerConn) utp() bool {
213 return parseNetworkString(cn.Network).Udp
216 func (cn *PeerConn) onClose() {
217 if cn.pex.IsEnabled() {
224 if cb := cn.callbacks.PeerConnClosed; cb != nil {
229 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
230 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
231 func (cn *PeerConn) write(msg pp.Message) bool {
232 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
233 // We don't need to track bytes here because the connection's Writer has that behaviour injected
234 // (although there's some delay between us buffering the message, and the connection writer
235 // flushing it out.).
236 notFull := cn.messageWriter.write(msg)
237 // Last I checked only Piece messages affect stats, and we don't write those.
243 func (cn *PeerConn) requestMetadataPiece(index int) {
244 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
245 if eID == pp.ExtensionDeleteNumber {
248 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
251 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
252 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
253 for index >= len(cn.metadataRequests) {
254 cn.metadataRequests = append(cn.metadataRequests, false)
256 cn.metadataRequests[index] = true
259 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
260 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
263 func (cn *PeerConn) onPeerSentCancel(r Request) {
264 if _, ok := cn.peerRequests[r]; !ok {
265 torrent.Add("unexpected cancels received", 1)
268 if cn.fastEnabled() {
271 delete(cn.peerRequests, r)
275 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
280 more = msg(pp.Message{
283 if !cn.fastEnabled() {
284 cn.deleteAllPeerRequests()
289 func (cn *PeerConn) deleteAllPeerRequests() {
290 for _, state := range cn.peerRequests {
291 state.allocReservation.Drop()
293 cn.peerRequests = nil
296 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
301 return msg(pp.Message{
306 func (pc *PeerConn) writeInterested(interested bool) bool {
307 return pc.write(pp.Message{
308 Type: func() pp.MessageType {
312 return pp.NotInterested
318 func (me *PeerConn) _request(r Request) bool {
319 return me.write(pp.Message{
327 func (me *PeerConn) _cancel(r RequestIndex) bool {
328 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
329 return me.remoteRejectsCancels()
332 // Whether we should expect a reject message after sending a cancel.
333 func (me *PeerConn) remoteRejectsCancels() bool {
334 if !me.fastEnabled() {
337 if me.remoteIsTransmission() {
338 // Transmission did not send rejects for received cancels. See
339 // https://github.com/transmission/transmission/pull/2275. Fixed in 4.0.0-beta.1 onward in
340 // https://github.com/transmission/transmission/commit/76719bf34c255da4fca991c2ad3fa4b65d2154b1.
341 // Peer ID prefix scheme described
342 // https://github.com/transmission/transmission/blob/7ec7607bbcf0fa99bd4b157b9b0f0c411d59f45d/CMakeLists.txt#L128-L149.
343 return me.PeerID[3] >= '4'
348 func (cn *PeerConn) fillWriteBuffer() {
349 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
350 // Fully committing to our max requests requires sufficient space (see
351 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
352 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
353 // request reason will not be cleared, so we'll come right back here when there's space. We
354 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
355 // knowledge of write buffers.
358 cn.requestMissingHashes()
359 cn.maybeUpdateActualRequestState()
360 if cn.pex.IsEnabled() {
361 if flow := cn.pex.Share(cn.write); !flow {
368 func (cn *PeerConn) have(piece pieceIndex) {
369 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
374 Index: pp.Integer(piece),
376 cn.sentHaves.Add(bitmap.BitIndex(piece))
379 func (cn *PeerConn) postBitfield() {
380 if cn.sentHaves.Len() != 0 {
381 panic("bitfield must be first have-related message sent")
383 if !cn.t.haveAnyPieces() {
388 Bitfield: cn.t.bitfield(),
390 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
393 func (cn *PeerConn) handleUpdateRequests() {
394 // The writer determines the request state as needed when it can write.
398 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
399 if newMin > cn.peerMinPieces {
400 cn.peerMinPieces = newMin
404 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
405 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
406 return errors.New("invalid piece")
408 if cn.peerHasPiece(piece) {
411 cn.raisePeerMinPieces(piece + 1)
412 if !cn.peerHasPiece(piece) {
413 cn.t.incPieceAvailability(piece)
415 cn._peerPieces.Add(uint32(piece))
416 if cn.t.wantPieceIndex(piece) {
417 cn.updateRequests("have")
419 cn.peerPiecesChanged()
423 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
425 panic("expected bitfield length divisible by 8")
427 // We know that the last byte means that at most the last 7 bits are wasted.
428 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
429 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
430 // Ignore known excess pieces.
431 bf = bf[:cn.t.numPieces()]
433 bm := boolSliceToBitmap(bf)
434 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
435 cn.onPeerHasAllPieces()
439 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
441 shouldUpdateRequests := false
442 if cn.peerSentHaveAll {
443 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
446 cn.peerSentHaveAll = false
447 if !cn._peerPieces.IsEmpty() {
448 panic("if peer has all, we expect no individual peer pieces to be set")
451 bm.Xor(&cn._peerPieces)
453 cn.peerSentHaveAll = false
454 // bm is now 'on' for pieces that are changing
455 bm.Iterate(func(x uint32) bool {
457 if cn._peerPieces.Contains(x) {
458 // Then we must be losing this piece
459 cn.t.decPieceAvailability(pi)
461 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
462 shouldUpdateRequests = true
464 // We must be gaining this piece
465 cn.t.incPieceAvailability(pieceIndex(x))
469 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
471 cn._peerPieces.Xor(&bm)
472 if shouldUpdateRequests {
473 cn.updateRequests("bitfield")
475 // We didn't guard this before, I see no reason to do it now.
476 cn.peerPiecesChanged()
480 func (cn *PeerConn) onPeerHasAllPiecesNoTriggers() {
483 cn._peerPieces.Iterate(func(x uint32) bool {
484 t.decPieceAvailability(pieceIndex(x))
488 t.addConnWithAllPieces(&cn.Peer)
489 cn.peerSentHaveAll = true
490 cn._peerPieces.Clear()
493 func (cn *PeerConn) onPeerHasAllPieces() {
494 cn.onPeerHasAllPiecesNoTriggers()
495 cn.peerHasAllPiecesTriggers()
498 func (cn *PeerConn) peerHasAllPiecesTriggers() {
499 if !cn.t._pendingPieces.IsEmpty() {
500 cn.updateRequests("Peer.onPeerHasAllPieces")
502 cn.peerPiecesChanged()
505 func (cn *PeerConn) onPeerSentHaveAll() error {
506 cn.onPeerHasAllPieces()
510 func (cn *PeerConn) peerSentHaveNone() error {
511 if !cn.peerSentHaveAll {
512 cn.t.decPeerPieceAvailability(&cn.Peer)
514 cn._peerPieces.Clear()
515 cn.peerSentHaveAll = false
516 cn.peerPiecesChanged()
520 func (c *PeerConn) requestPendingMetadata() {
524 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
525 // Peer doesn't support this.
528 // Request metadata pieces that we don't have in a random order.
530 for index := 0; index < c.t.metadataPieceCount(); index++ {
531 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
532 pending = append(pending, index)
535 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
536 for _, i := range pending {
537 c.requestMetadataPiece(i)
541 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
542 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
543 if msg.Type == pp.Extended {
544 for name, id := range cn.PeerExtensionIDs {
545 if id != msg.ExtendedID {
548 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
551 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
554 func (cn *PeerConn) wroteBytes(n int64) {
555 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
558 func (c *PeerConn) fastEnabled() bool {
559 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
562 func (c *PeerConn) reject(r Request) {
563 if !c.fastEnabled() {
564 panic("fast not enabled")
566 c.write(r.ToMsg(pp.Reject))
567 // It is possible to reject a request before it is added to peer requests due to being invalid.
568 if state, ok := c.peerRequests[r]; ok {
569 state.allocReservation.Drop()
570 delete(c.peerRequests, r)
574 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
575 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
576 if uploadRateLimiter.Limit() == rate.Inf {
579 return Some(uploadRateLimiter.Burst())
582 // startFetch is for testing purposes currently.
583 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
584 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
585 if _, ok := c.peerRequests[r]; ok {
586 torrent.Add("duplicate requests received", 1)
588 return errors.New("received duplicate request with fast enabled")
593 torrent.Add("requests received while choking", 1)
595 torrent.Add("requests rejected while choking", 1)
600 // TODO: What if they've already requested this?
601 if len(c.peerRequests) >= localClientReqq {
602 torrent.Add("requests received while queue full", 1)
606 // BEP 6 says we may close here if we choose.
609 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
610 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
611 c.logger.Levelf(log.Warning, err.Error())
619 if !c.t.havePiece(pieceIndex(r.Index)) {
620 // TODO: Tell the peer we don't have the piece, and reject this request.
621 requestsReceivedForMissingPieces.Add(1)
622 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
624 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
625 // Check this after we know we have the piece, so that the piece length will be known.
626 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
627 torrent.Add("bad requests received", 1)
628 return errors.New("chunk overflows piece")
630 if c.peerRequests == nil {
631 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
633 value := &peerRequestState{
634 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
636 c.peerRequests[r] = value
638 // TODO: Limit peer request data read concurrency.
639 go c.peerRequestDataReader(r, value)
644 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
645 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
646 // or fail to read and then cleanup. Also, we used to hang here if the reservation was never
647 // dropped, that was fixed.
648 ctx := context.Background()
649 err := prs.allocReservation.Wait(ctx)
651 c.logger.WithDefaultLevel(log.Debug).Levelf(log.ErrorLevel(err), "waiting for alloc limit reservation: %v", err)
654 b, err := c.readPeerRequestData(r)
656 defer c.locker().Unlock()
658 c.peerRequestDataReadFailed(err, r)
661 panic("data must be non-nil to trigger send")
663 torrent.Add("peer request data read successes", 1)
665 // This might be required for the error case too (#752 and #753).
670 // If this is maintained correctly, we might be able to support optional synchronous reading for
671 // chunk sending, the way it used to work.
672 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
673 torrent.Add("peer request data read failures", 1)
674 logLevel := log.Warning
675 if c.t.hasStorageCap() {
676 // It's expected that pieces might drop. See
677 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
680 c.logger.Levelf(logLevel, "error reading chunk for peer Request %v: %v", r, err)
681 if c.t.closed.IsSet() {
684 i := pieceIndex(r.Index)
685 if c.t.pieceComplete(i) {
686 // There used to be more code here that just duplicated the following break. Piece
687 // completions are currently cached, so I'm not sure how helpful this update is, except to
688 // pull any completion changes pushed to the storage backend in failed reads that got us
690 c.t.updatePieceCompletion(i)
692 // We've probably dropped a piece from storage, but there's no way to communicate this to the
693 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
694 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
695 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
701 // If fast isn't enabled, I think we would have wiped all peer requests when we last
702 // choked, and requests while we're choking would be ignored. It could be possible that
703 // a peer request data read completed concurrently to it being deleted elsewhere.
704 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
706 // Choking a non-fast peer should cause them to flush all their requests.
711 func (c *PeerConn) readPeerRequestData(r Request) ([]byte, error) {
712 b := make([]byte, r.Length)
713 p := c.t.info.Piece(int(r.Index))
714 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
721 panic("expected error")
727 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
728 c.logger.WithContextText(fmt.Sprintf(
729 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
730 )).SkipCallers(1).Levelf(level, format, arg...)
733 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
734 // exit. Returning will end the connection.
735 func (c *PeerConn) mainReadLoop() (err error) {
738 torrent.Add("connection.mainReadLoop returned with error", 1)
740 torrent.Add("connection.mainReadLoop returned with no error", 1)
746 decoder := pp.Decoder{
747 R: bufio.NewReaderSize(c.r, 1<<17),
748 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
756 err = decoder.Decode(&msg)
758 err = fmt.Errorf("decoding message: %w", err)
761 // Do this before checking closed.
762 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
765 if t.closed.IsSet() || c.closed.IsSet() {
769 err = log.WithLevel(log.Info, err)
772 c.lastMessageReceived = time.Now()
774 receivedKeepalives.Add(1)
777 messageTypesReceived.Add(msg.Type.String(), 1)
778 if msg.Type.FastExtension() && !c.fastEnabled() {
779 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
780 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
787 if !c.fastEnabled() {
788 c.deleteAllRequests("choked by non-fast PeerConn")
790 // We don't decrement pending requests here, let's wait for the peer to either
791 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
792 // us and resume where they left off, we don't want to have piled on to those chunks
793 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
794 // could let us request a lot of stuff, then choke us and never reject, but they're
795 // only a single peer, our chunk balancing should smooth over this abuse.
798 c.updateExpectingChunks()
801 // Some clients do this for some reason. Transmission doesn't error on this, so we
802 // won't for consistency.
803 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
806 c.peerChoking = false
808 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
809 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
814 if preservedCount != 0 {
815 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
817 c.logger.Levelf(log.Debug,
818 "%v requests were preserved while being choked (fast=%v)",
822 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
824 if !c.t._pendingPieces.IsEmpty() {
825 c.updateRequests("unchoked")
827 c.updateExpectingChunks()
829 c.peerInterested = true
831 case pp.NotInterested:
832 c.peerInterested = false
833 // We don't clear their requests since it isn't clear in the spec.
834 // We'll probably choke them for this, which will clear them if
835 // appropriate, and is clearly specified.
837 err = c.peerSentHave(pieceIndex(msg.Index))
839 err = c.peerSentBitfield(msg.Bitfield)
841 r := newRequestFromMessage(&msg)
842 err = c.onReadRequest(r, true)
844 err = fmt.Errorf("on reading request %v: %w", r, err)
847 c.doChunkReadStats(int64(len(msg.Piece)))
848 err = c.receiveChunk(&msg)
849 if len(msg.Piece) == int(t.chunkSize) {
850 t.chunkPool.Put(&msg.Piece)
853 err = fmt.Errorf("receiving chunk: %w", err)
856 req := newRequestFromMessage(&msg)
857 c.onPeerSentCancel(req)
859 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
863 pingAddr := net.UDPAddr{
868 pingAddr.Port = int(msg.Port)
870 cl.eachDhtServer(func(s DhtServer) {
874 torrent.Add("suggests received", 1)
875 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
876 c.updateRequests("suggested")
878 err = c.onPeerSentHaveAll()
880 err = c.peerSentHaveNone()
882 req := newRequestFromMessage(&msg)
883 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
884 err = fmt.Errorf("received invalid reject for request %v", req)
885 c.logger.Levelf(log.Debug, "%v", err)
888 torrent.Add("allowed fasts received", 1)
889 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
890 c.updateRequests("PeerConn.mainReadLoop allowed fast")
892 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
894 err = c.onReadHashes(&msg)
895 case pp.HashRequest, pp.HashReject:
896 c.protocolLogger.Levelf(log.Info, "received unimplemented BitTorrent v2 message: %v", msg.Type)
898 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
906 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
908 // TODO: Should we still do this?
910 // These clients use their own extension IDs for outgoing message
911 // types, which is incorrect.
912 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
920 event := PeerConnReadExtensionMessageEvent{
925 for _, cb := range c.callbacks.PeerConnReadExtensionMessage {
929 if id == pp.HandshakeExtendedID {
930 var d pp.ExtendedHandshakeMessage
931 if err := bencode.Unmarshal(payload, &d); err != nil {
932 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
933 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
935 // Trigger this callback after it's been processed. If you want to handle it yourself, you
936 // should hook PeerConnReadExtensionMessage.
937 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
941 c.PeerMaxRequests = d.Reqq
943 c.PeerClientName.Store(d.V)
944 if c.PeerExtensionIDs == nil {
945 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
947 c.PeerListenPort = d.Port
948 c.PeerPrefersEncryption = d.Encryption
949 for name, id := range d.M {
950 if _, ok := c.PeerExtensionIDs[name]; !ok {
951 peersSupportingExtension.Add(
952 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
953 // entered here which caused problems later when unmarshalling.
954 strconv.Quote(string(name)),
957 c.PeerExtensionIDs[name] = id
959 if d.MetadataSize != 0 {
960 if err = t.setMetadataSize(d.MetadataSize); err != nil {
961 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
964 c.requestPendingMetadata()
965 if !t.cl.config.DisablePEX {
966 t.pex.Add(c) // we learnt enough now
967 // This checks the extension is supported internally.
972 extensionName, builtin, err := c.LocalLtepProtocolMap.LookupId(id)
977 // User should have taken care of this in PeerConnReadExtensionMessage callback.
980 switch extensionName {
981 case pp.ExtensionNameMetadata:
982 err := cl.gotMetadataExtensionMsg(payload, t, c)
984 return fmt.Errorf("handling metadata extension message: %w", err)
987 case pp.ExtensionNamePex:
988 if !c.pex.IsEnabled() {
989 return nil // or hang-up maybe?
991 err = c.pex.Recv(payload)
993 err = fmt.Errorf("receiving pex message: %w", err)
996 case utHolepunch.ExtensionName:
997 var msg utHolepunch.Msg
998 err = msg.UnmarshalBinary(payload)
1000 err = fmt.Errorf("unmarshalling ut_holepunch message: %w", err)
1003 err = c.t.handleReceivedUtHolepunchMsg(msg, c)
1006 panic(fmt.Sprintf("unhandled builtin extension protocol %q", extensionName))
1010 // Set both the Reader and Writer for the connection from a single ReadWriter.
1011 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1016 // Returns the Reader and Writer as a combined ReadWriter.
1017 func (cn *PeerConn) rw() io.ReadWriter {
1024 func (c *PeerConn) uploadAllowed() bool {
1025 if c.t.cl.config.NoUpload {
1028 if c.t.dataUploadDisallowed {
1034 if !c.peerHasWantedPieces() {
1037 // Don't upload more than 100 KiB more than we download.
1038 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1044 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1045 if c.uploadTimer == nil {
1046 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1048 c.uploadTimer.Reset(delay)
1052 // Also handles choking and unchoking of the remote peer.
1053 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1054 // Breaking or completing this loop means we don't want to upload to the peer anymore, and we
1057 for c.uploadAllowed() {
1058 // We want to upload to the peer.
1059 if !c.unchoke(msg) {
1062 for r, state := range c.peerRequests {
1063 if state.data == nil {
1066 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1068 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1070 delay := res.Delay()
1073 c.setRetryUploadTimer(delay)
1074 // Hard to say what to return here.
1077 more := c.sendChunk(r, msg, state)
1078 delete(c.peerRequests, r)
1089 func (cn *PeerConn) drop() {
1090 cn.t.dropConnection(cn)
1093 func (cn *PeerConn) ban() {
1094 cn.t.cl.banPeerIP(cn.remoteIp())
1097 // This is called when something has changed that should wake the writer, such as putting stuff into
1098 // the writeBuffer, or changing some state that the writer can act on.
1099 func (c *PeerConn) tickleWriter() {
1100 c.messageWriter.writeCond.Broadcast()
1103 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1104 c.lastChunkSent = time.Now()
1105 state.allocReservation.Release()
1106 return msg(pp.Message{
1114 func (c *Peer) setTorrent(t *Torrent) {
1116 panic("connection already associated with a torrent")
1119 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1120 t.reconcileHandshakeStats(c)
1123 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1124 f := pp.PexPeerFlags(0)
1125 if c.PeerPrefersEncryption {
1126 f |= pp.PexPrefersEncryption
1129 f |= pp.PexOutgoingConn
1132 f |= pp.PexSupportsUtp
1137 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1138 // advertised listen port.
1139 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1140 if c.outgoing || c.PeerListenPort == 0 {
1143 addrPort, err := addrPortFromPeerRemoteAddr(c.RemoteAddr)
1147 "error parsing %q for alternate dial port: %v",
1153 return netip.AddrPortFrom(addrPort.Addr(), uint16(c.PeerListenPort))
1156 func (c *PeerConn) pexEvent(t pexEventType) (_ pexEvent, err error) {
1157 f := c.pexPeerFlags()
1158 dialAddr := c.dialAddr()
1159 addr, err := addrPortFromPeerRemoteAddr(dialAddr)
1160 if err != nil || !addr.IsValid() {
1161 err = fmt.Errorf("parsing dial addr %q: %w", dialAddr, err)
1164 return pexEvent{t, addr, f, nil}, nil
1167 func (pc *PeerConn) String() string {
1168 return fmt.Sprintf("%T %p [id=%+q, exts=%v, v=%q]", pc, pc, pc.PeerID, pc.PeerExtensionBytes, pc.PeerClientName.Load())
1171 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1172 // are in the torrent, it could be a very large range if the peer has sent HaveAll.
1173 func (pc *PeerConn) PeerPieces() *roaring.Bitmap {
1175 defer pc.locker().RUnlock()
1176 return pc.newPeerPieces()
1179 func (pc *PeerConn) remoteIsTransmission() bool {
1180 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1183 func (pc *PeerConn) remoteDialAddrPort() (netip.AddrPort, error) {
1184 dialAddr := pc.dialAddr()
1185 return addrPortFromPeerRemoteAddr(dialAddr)
1188 func (pc *PeerConn) bitExtensionEnabled(bit pp.ExtensionBit) bool {
1189 return pc.t.cl.config.Extensions.GetBit(bit) && pc.PeerExtensionBytes.GetBit(bit)
1192 func (cn *PeerConn) peerPiecesChanged() {
1193 cn.t.maybeDropMutuallyCompletePeer(cn)
1196 // Returns whether the connection could be useful to us. We're seeding and
1197 // they want data, we don't have metainfo and they can provide it, etc.
1198 func (c *PeerConn) useful() bool {
1200 if c.closed.IsSet() {
1204 return c.supportsExtension("ut_metadata")
1206 if t.seeding() && c.peerInterested {
1209 if c.peerHasWantedPieces() {
1215 func makeBuiltinLtepProtocols(pex bool) LocalLtepProtocolMap {
1216 ps := []pp.ExtensionName{pp.ExtensionNameMetadata, utHolepunch.ExtensionName}
1218 ps = append(ps, pp.ExtensionNamePex)
1220 return LocalLtepProtocolMap{
1222 NumBuiltin: len(ps),
1226 func (c *PeerConn) addBuiltinLtepProtocols(pex bool) {
1227 c.LocalLtepProtocolMap = &c.t.cl.defaultLocalLtepProtocolMap
1230 func (pc *PeerConn) WriteExtendedMessage(extName pp.ExtensionName, payload []byte) error {
1232 defer pc.locker().Unlock()
1233 id := pc.PeerExtensionIDs[extName]
1235 return fmt.Errorf("peer does not support or has disabled extension %q", extName)
1237 pc.write(pp.Message{
1240 ExtendedPayload: payload,
1245 func (pc *PeerConn) requestMissingHashes() {
1249 if !pc.t.haveInfo() {
1259 baseLayer := pp.Integer(merkle.Log2RoundingUp(merkle.RoundUpToPowerOfTwo(
1260 uint((pc.t.usualPieceSize() + merkle.BlockSize - 1) / merkle.BlockSize)),
1262 nextFileBeginPiece := 0
1264 for _, file := range info.UpvertedFiles() {
1265 fileNumPieces := int((file.Length + info.PieceLength - 1) / info.PieceLength)
1266 curFileBeginPiece := nextFileBeginPiece
1267 nextFileBeginPiece += fileNumPieces
1268 haveAllHashes := true
1269 for i := range fileNumPieces {
1270 torrentPieceIndex := curFileBeginPiece + i
1271 if !pc.peerHasPiece(torrentPieceIndex) {
1274 if !pc.t.piece(torrentPieceIndex).hashV2.Ok {
1275 haveAllHashes = false
1281 // We would be requesting the leaves, the file must be short enough that we can just do with
1282 // the pieces root as the piece hash.
1283 if fileNumPieces <= 1 {
1286 piecesRoot := file.PiecesRoot.Unwrap()
1287 proofLayers := pp.Integer(0)
1288 for index := 0; index < fileNumPieces; index += 512 {
1289 // Minimizing to the number of pieces in a file conflicts with the BEP.
1290 length := merkle.RoundUpToPowerOfTwo(uint(min(512, fileNumPieces-index)))
1292 // This should have been filtered out by baseLayer and pieces root as piece hash
1297 pc.logger.Levelf(log.Warning, "requesting odd hashes length %d", length)
1300 Type: pp.HashRequest,
1301 PiecesRoot: piecesRoot,
1302 BaseLayer: baseLayer,
1303 Index: pp.Integer(index),
1304 Length: pp.Integer(length),
1305 ProofLayers: proofLayers,
1307 hr := hashRequestFromMessage(msg)
1308 if generics.MapContains(pc.sentHashRequests, hr) {
1312 generics.MakeMapIfNil(&pc.sentHashRequests)
1313 pc.sentHashRequests[hr] = struct{}{}
1318 func (pc *PeerConn) onReadHashes(msg *pp.Message) (err error) {
1319 file := pc.t.getFileByPiecesRoot(msg.PiecesRoot)
1320 filePieceHashes := pc.receivedHashPieces[msg.PiecesRoot]
1321 if filePieceHashes == nil {
1322 filePieceHashes = make([][32]byte, file.numPieces())
1323 generics.MakeMapIfNil(&pc.receivedHashPieces)
1324 pc.receivedHashPieces[msg.PiecesRoot] = filePieceHashes
1326 if msg.ProofLayers != 0 {
1327 // This isn't handled yet.
1328 panic(msg.ProofLayers)
1330 copy(filePieceHashes[msg.Index:], msg.Hashes)
1331 root := merkle.RootWithPadHash(
1333 metainfo.HashForPiecePad(int64(pc.t.usualPieceSize())))
1334 expectedPiecesRoot := file.piecesRoot.Unwrap()
1335 if root == expectedPiecesRoot {
1336 pc.logger.WithNames(v2HashesLogName).Levelf(
1338 "got piece hashes for file %v (num pieces %v)",
1339 file, file.numPieces())
1340 for filePieceIndex, peerHash := range filePieceHashes {
1341 torrentPieceIndex := file.BeginPieceIndex() + filePieceIndex
1342 pc.t.piece(torrentPieceIndex).hashV2.Set(peerHash)
1345 pc.logger.WithNames(v2HashesLogName).Levelf(
1347 "peer file piece hashes root mismatch: %x != %x",
1348 root, expectedPiecesRoot)
1353 type hashRequest struct {
1355 baseLayer, index, length, proofLayers pp.Integer
1358 func (hr hashRequest) toMessage() pp.Message {
1360 Type: pp.HashRequest,
1361 PiecesRoot: hr.piecesRoot,
1362 BaseLayer: hr.baseLayer,
1365 ProofLayers: hr.proofLayers,
1369 func hashRequestFromMessage(m pp.Message) hashRequest {
1371 piecesRoot: m.PiecesRoot,
1372 baseLayer: m.BaseLayer,
1375 proofLayers: m.ProofLayers,