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() (ret string) {
188 ret += string([]byte{b})
190 if cn.cryptoMethod == mse.CryptoMethodRC4 {
192 } else if cn.headerEncrypted {
195 ret += string(cn.Discovery)
202 func (cn *PeerConn) utp() bool {
203 return parseNetworkString(cn.Network).Udp
206 func (cn *PeerConn) onClose() {
207 if cn.pex.IsEnabled() {
214 if cb := cn.callbacks.PeerConnClosed; cb != nil {
219 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
220 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
221 func (cn *PeerConn) write(msg pp.Message) bool {
222 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
223 // We don't need to track bytes here because the connection's Writer has that behaviour injected
224 // (although there's some delay between us buffering the message, and the connection writer
225 // flushing it out.).
226 notFull := cn.messageWriter.write(msg)
227 // Last I checked only Piece messages affect stats, and we don't write those.
233 func (cn *PeerConn) requestMetadataPiece(index int) {
234 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
235 if eID == pp.ExtensionDeleteNumber {
238 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
241 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
242 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
243 for index >= len(cn.metadataRequests) {
244 cn.metadataRequests = append(cn.metadataRequests, false)
246 cn.metadataRequests[index] = true
249 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
250 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
253 func (cn *PeerConn) onPeerSentCancel(r Request) {
254 if _, ok := cn.peerRequests[r]; !ok {
255 torrent.Add("unexpected cancels received", 1)
258 if cn.fastEnabled() {
261 delete(cn.peerRequests, r)
265 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
270 more = msg(pp.Message{
273 if !cn.fastEnabled() {
274 cn.deleteAllPeerRequests()
279 func (cn *PeerConn) deleteAllPeerRequests() {
280 for _, state := range cn.peerRequests {
281 state.allocReservation.Drop()
283 cn.peerRequests = nil
286 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
291 return msg(pp.Message{
296 func (pc *PeerConn) writeInterested(interested bool) bool {
297 return pc.write(pp.Message{
298 Type: func() pp.MessageType {
302 return pp.NotInterested
308 func (me *PeerConn) _request(r Request) bool {
309 return me.write(pp.Message{
317 func (me *PeerConn) _cancel(r RequestIndex) bool {
318 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
319 return me.remoteRejectsCancels()
322 // Whether we should expect a reject message after sending a cancel.
323 func (me *PeerConn) remoteRejectsCancels() bool {
324 if !me.fastEnabled() {
327 if me.remoteIsTransmission() {
328 // Transmission did not send rejects for received cancels. See
329 // https://github.com/transmission/transmission/pull/2275. Fixed in 4.0.0-beta.1 onward in
330 // https://github.com/transmission/transmission/commit/76719bf34c255da4fca991c2ad3fa4b65d2154b1.
331 // Peer ID prefix scheme described
332 // https://github.com/transmission/transmission/blob/7ec7607bbcf0fa99bd4b157b9b0f0c411d59f45d/CMakeLists.txt#L128-L149.
333 return me.PeerID[3] >= '4'
338 func (cn *PeerConn) fillWriteBuffer() {
339 if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
340 // Fully committing to our max requests requires sufficient space (see
341 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
342 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
343 // request reason will not be cleared, so we'll come right back here when there's space. We
344 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
345 // knowledge of write buffers.
348 cn.requestMissingHashes()
349 cn.maybeUpdateActualRequestState()
350 if cn.pex.IsEnabled() {
351 if flow := cn.pex.Share(cn.write); !flow {
358 func (cn *PeerConn) have(piece pieceIndex) {
359 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
364 Index: pp.Integer(piece),
366 cn.sentHaves.Add(bitmap.BitIndex(piece))
369 func (cn *PeerConn) postBitfield() {
370 if cn.sentHaves.Len() != 0 {
371 panic("bitfield must be first have-related message sent")
373 if !cn.t.haveAnyPieces() {
378 Bitfield: cn.t.bitfield(),
380 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
383 func (cn *PeerConn) handleUpdateRequests() {
384 // The writer determines the request state as needed when it can write.
388 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
389 if newMin > cn.peerMinPieces {
390 cn.peerMinPieces = newMin
394 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
395 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
396 return errors.New("invalid piece")
398 if cn.peerHasPiece(piece) {
401 cn.raisePeerMinPieces(piece + 1)
402 if !cn.peerHasPiece(piece) {
403 cn.t.incPieceAvailability(piece)
405 cn._peerPieces.Add(uint32(piece))
406 if cn.t.wantPieceIndex(piece) {
407 cn.updateRequests("have")
409 cn.peerPiecesChanged()
413 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
415 panic("expected bitfield length divisible by 8")
417 // We know that the last byte means that at most the last 7 bits are wasted.
418 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
419 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
420 // Ignore known excess pieces.
421 bf = bf[:cn.t.numPieces()]
423 bm := boolSliceToBitmap(bf)
424 if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
425 cn.onPeerHasAllPieces()
429 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
431 shouldUpdateRequests := false
432 if cn.peerSentHaveAll {
433 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
436 cn.peerSentHaveAll = false
437 if !cn._peerPieces.IsEmpty() {
438 panic("if peer has all, we expect no individual peer pieces to be set")
441 bm.Xor(&cn._peerPieces)
443 cn.peerSentHaveAll = false
444 // bm is now 'on' for pieces that are changing
445 bm.Iterate(func(x uint32) bool {
447 if cn._peerPieces.Contains(x) {
448 // Then we must be losing this piece
449 cn.t.decPieceAvailability(pi)
451 if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
452 shouldUpdateRequests = true
454 // We must be gaining this piece
455 cn.t.incPieceAvailability(pieceIndex(x))
459 // Apply the changes. If we had everything previously, this should be empty, so xor is the same
461 cn._peerPieces.Xor(&bm)
462 if shouldUpdateRequests {
463 cn.updateRequests("bitfield")
465 // We didn't guard this before, I see no reason to do it now.
466 cn.peerPiecesChanged()
470 func (cn *PeerConn) onPeerHasAllPiecesNoTriggers() {
473 cn._peerPieces.Iterate(func(x uint32) bool {
474 t.decPieceAvailability(pieceIndex(x))
478 t.addConnWithAllPieces(&cn.Peer)
479 cn.peerSentHaveAll = true
480 cn._peerPieces.Clear()
483 func (cn *PeerConn) onPeerHasAllPieces() {
484 cn.onPeerHasAllPiecesNoTriggers()
485 cn.peerHasAllPiecesTriggers()
488 func (cn *PeerConn) peerHasAllPiecesTriggers() {
489 if !cn.t._pendingPieces.IsEmpty() {
490 cn.updateRequests("Peer.onPeerHasAllPieces")
492 cn.peerPiecesChanged()
495 func (cn *PeerConn) onPeerSentHaveAll() error {
496 cn.onPeerHasAllPieces()
500 func (cn *PeerConn) peerSentHaveNone() error {
501 if !cn.peerSentHaveAll {
502 cn.t.decPeerPieceAvailability(&cn.Peer)
504 cn._peerPieces.Clear()
505 cn.peerSentHaveAll = false
506 cn.peerPiecesChanged()
510 func (c *PeerConn) requestPendingMetadata() {
514 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
515 // Peer doesn't support this.
518 // Request metadata pieces that we don't have in a random order.
520 for index := 0; index < c.t.metadataPieceCount(); index++ {
521 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
522 pending = append(pending, index)
525 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
526 for _, i := range pending {
527 c.requestMetadataPiece(i)
531 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
532 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
533 if msg.Type == pp.Extended {
534 for name, id := range cn.PeerExtensionIDs {
535 if id != msg.ExtendedID {
538 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
541 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
544 func (cn *PeerConn) wroteBytes(n int64) {
545 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
548 func (c *PeerConn) fastEnabled() bool {
549 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
552 func (c *PeerConn) reject(r Request) {
553 if !c.fastEnabled() {
554 panic("fast not enabled")
556 c.write(r.ToMsg(pp.Reject))
557 // It is possible to reject a request before it is added to peer requests due to being invalid.
558 if state, ok := c.peerRequests[r]; ok {
559 state.allocReservation.Drop()
560 delete(c.peerRequests, r)
564 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
565 uploadRateLimiter := c.t.cl.config.UploadRateLimiter
566 if uploadRateLimiter.Limit() == rate.Inf {
569 return Some(uploadRateLimiter.Burst())
572 // startFetch is for testing purposes currently.
573 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
574 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
575 if _, ok := c.peerRequests[r]; ok {
576 torrent.Add("duplicate requests received", 1)
578 return errors.New("received duplicate request with fast enabled")
583 torrent.Add("requests received while choking", 1)
585 torrent.Add("requests rejected while choking", 1)
590 // TODO: What if they've already requested this?
591 if len(c.peerRequests) >= localClientReqq {
592 torrent.Add("requests received while queue full", 1)
596 // BEP 6 says we may close here if we choose.
599 if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
600 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
601 c.logger.Levelf(log.Warning, err.Error())
609 if !c.t.havePiece(pieceIndex(r.Index)) {
610 // TODO: Tell the peer we don't have the piece, and reject this request.
611 requestsReceivedForMissingPieces.Add(1)
612 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
614 pieceLength := c.t.pieceLength(pieceIndex(r.Index))
615 // Check this after we know we have the piece, so that the piece length will be known.
616 if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
617 torrent.Add("bad requests received", 1)
618 return errors.New("chunk overflows piece")
620 if c.peerRequests == nil {
621 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
623 value := &peerRequestState{
624 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
626 c.peerRequests[r] = value
628 // TODO: Limit peer request data read concurrency.
629 go c.peerRequestDataReader(r, value)
634 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
635 // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
636 // or fail to read and then cleanup. Also, we used to hang here if the reservation was never
637 // dropped, that was fixed.
638 ctx := context.Background()
639 err := prs.allocReservation.Wait(ctx)
641 c.logger.WithDefaultLevel(log.Debug).Levelf(log.ErrorLevel(err), "waiting for alloc limit reservation: %v", err)
644 b, err := c.readPeerRequestData(r)
646 defer c.locker().Unlock()
648 c.peerRequestDataReadFailed(err, r)
651 panic("data must be non-nil to trigger send")
653 torrent.Add("peer request data read successes", 1)
655 // This might be required for the error case too (#752 and #753).
660 // If this is maintained correctly, we might be able to support optional synchronous reading for
661 // chunk sending, the way it used to work.
662 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
663 torrent.Add("peer request data read failures", 1)
664 logLevel := log.Warning
665 if c.t.hasStorageCap() {
666 // It's expected that pieces might drop. See
667 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
670 c.logger.Levelf(logLevel, "error reading chunk for peer Request %v: %v", r, err)
671 if c.t.closed.IsSet() {
674 i := pieceIndex(r.Index)
675 if c.t.pieceComplete(i) {
676 // There used to be more code here that just duplicated the following break. Piece
677 // completions are currently cached, so I'm not sure how helpful this update is, except to
678 // pull any completion changes pushed to the storage backend in failed reads that got us
680 c.t.updatePieceCompletion(i)
682 // We've probably dropped a piece from storage, but there's no way to communicate this to the
683 // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
684 // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
685 // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
691 // If fast isn't enabled, I think we would have wiped all peer requests when we last
692 // choked, and requests while we're choking would be ignored. It could be possible that
693 // a peer request data read completed concurrently to it being deleted elsewhere.
694 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
696 // Choking a non-fast peer should cause them to flush all their requests.
701 func (c *PeerConn) readPeerRequestData(r Request) ([]byte, error) {
702 b := make([]byte, r.Length)
703 p := c.t.info.Piece(int(r.Index))
704 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
711 panic("expected error")
717 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
718 c.logger.WithContextText(fmt.Sprintf(
719 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
720 )).SkipCallers(1).Levelf(level, format, arg...)
723 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
724 // exit. Returning will end the connection.
725 func (c *PeerConn) mainReadLoop() (err error) {
728 torrent.Add("connection.mainReadLoop returned with error", 1)
730 torrent.Add("connection.mainReadLoop returned with no error", 1)
736 decoder := pp.Decoder{
737 R: bufio.NewReaderSize(c.r, 1<<17),
738 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
746 err = decoder.Decode(&msg)
748 err = fmt.Errorf("decoding message: %w", err)
751 // Do this before checking closed.
752 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
755 if t.closed.IsSet() || c.closed.IsSet() {
759 err = log.WithLevel(log.Info, err)
762 c.lastMessageReceived = time.Now()
764 receivedKeepalives.Add(1)
767 messageTypesReceived.Add(msg.Type.String(), 1)
768 if msg.Type.FastExtension() && !c.fastEnabled() {
769 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
770 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
777 if !c.fastEnabled() {
778 c.deleteAllRequests("choked by non-fast PeerConn")
780 // We don't decrement pending requests here, let's wait for the peer to either
781 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
782 // us and resume where they left off, we don't want to have piled on to those chunks
783 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
784 // could let us request a lot of stuff, then choke us and never reject, but they're
785 // only a single peer, our chunk balancing should smooth over this abuse.
788 c.updateExpectingChunks()
791 // Some clients do this for some reason. Transmission doesn't error on this, so we
792 // won't for consistency.
793 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
796 c.peerChoking = false
798 c.requestState.Requests.Iterate(func(x RequestIndex) bool {
799 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
804 if preservedCount != 0 {
805 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
807 c.logger.Levelf(log.Debug,
808 "%v requests were preserved while being choked (fast=%v)",
812 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
814 if !c.t._pendingPieces.IsEmpty() {
815 c.updateRequests("unchoked")
817 c.updateExpectingChunks()
819 c.peerInterested = true
821 case pp.NotInterested:
822 c.peerInterested = false
823 // We don't clear their requests since it isn't clear in the spec.
824 // We'll probably choke them for this, which will clear them if
825 // appropriate, and is clearly specified.
827 err = c.peerSentHave(pieceIndex(msg.Index))
829 err = c.peerSentBitfield(msg.Bitfield)
831 r := newRequestFromMessage(&msg)
832 err = c.onReadRequest(r, true)
834 err = fmt.Errorf("on reading request %v: %w", r, err)
837 c.doChunkReadStats(int64(len(msg.Piece)))
838 err = c.receiveChunk(&msg)
839 if len(msg.Piece) == int(t.chunkSize) {
840 t.chunkPool.Put(&msg.Piece)
843 err = fmt.Errorf("receiving chunk: %w", err)
846 req := newRequestFromMessage(&msg)
847 c.onPeerSentCancel(req)
849 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
853 pingAddr := net.UDPAddr{
858 pingAddr.Port = int(msg.Port)
860 cl.eachDhtServer(func(s DhtServer) {
864 torrent.Add("suggests received", 1)
865 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
866 c.updateRequests("suggested")
868 err = c.onPeerSentHaveAll()
870 err = c.peerSentHaveNone()
872 req := newRequestFromMessage(&msg)
873 if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
874 err = fmt.Errorf("received invalid reject for request %v", req)
875 c.logger.Levelf(log.Debug, "%v", err)
878 torrent.Add("allowed fasts received", 1)
879 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
880 c.updateRequests("PeerConn.mainReadLoop allowed fast")
882 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
884 err = c.onReadHashes(&msg)
885 case pp.HashRequest, pp.HashReject:
886 c.logger.Levelf(log.Info, "received unimplemented BitTorrent v2 message: %v", msg.Type)
888 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
896 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
898 // TODO: Should we still do this?
900 // These clients use their own extension IDs for outgoing message
901 // types, which is incorrect.
902 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
910 event := PeerConnReadExtensionMessageEvent{
915 for _, cb := range c.callbacks.PeerConnReadExtensionMessage {
919 if id == pp.HandshakeExtendedID {
920 var d pp.ExtendedHandshakeMessage
921 if err := bencode.Unmarshal(payload, &d); err != nil {
922 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
923 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
925 // Trigger this callback after it's been processed. If you want to handle it yourself, you
926 // should hook PeerConnReadExtensionMessage.
927 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
931 c.PeerMaxRequests = d.Reqq
933 c.PeerClientName.Store(d.V)
934 if c.PeerExtensionIDs == nil {
935 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
937 c.PeerListenPort = d.Port
938 c.PeerPrefersEncryption = d.Encryption
939 for name, id := range d.M {
940 if _, ok := c.PeerExtensionIDs[name]; !ok {
941 peersSupportingExtension.Add(
942 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
943 // entered here which caused problems later when unmarshalling.
944 strconv.Quote(string(name)),
947 c.PeerExtensionIDs[name] = id
949 if d.MetadataSize != 0 {
950 if err = t.setMetadataSize(d.MetadataSize); err != nil {
951 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
954 c.requestPendingMetadata()
955 if !t.cl.config.DisablePEX {
956 t.pex.Add(c) // we learnt enough now
957 // This checks the extension is supported internally.
962 extensionName, builtin, err := c.LocalLtepProtocolMap.LookupId(id)
967 // User should have taken care of this in PeerConnReadExtensionMessage callback.
970 switch extensionName {
971 case pp.ExtensionNameMetadata:
972 err := cl.gotMetadataExtensionMsg(payload, t, c)
974 return fmt.Errorf("handling metadata extension message: %w", err)
977 case pp.ExtensionNamePex:
978 if !c.pex.IsEnabled() {
979 return nil // or hang-up maybe?
981 err = c.pex.Recv(payload)
983 err = fmt.Errorf("receiving pex message: %w", err)
986 case utHolepunch.ExtensionName:
987 var msg utHolepunch.Msg
988 err = msg.UnmarshalBinary(payload)
990 err = fmt.Errorf("unmarshalling ut_holepunch message: %w", err)
993 err = c.t.handleReceivedUtHolepunchMsg(msg, c)
996 panic(fmt.Sprintf("unhandled builtin extension protocol %q", extensionName))
1000 // Set both the Reader and Writer for the connection from a single ReadWriter.
1001 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1006 // Returns the Reader and Writer as a combined ReadWriter.
1007 func (cn *PeerConn) rw() io.ReadWriter {
1014 func (c *PeerConn) uploadAllowed() bool {
1015 if c.t.cl.config.NoUpload {
1018 if c.t.dataUploadDisallowed {
1024 if !c.peerHasWantedPieces() {
1027 // Don't upload more than 100 KiB more than we download.
1028 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1034 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1035 if c.uploadTimer == nil {
1036 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1038 c.uploadTimer.Reset(delay)
1042 // Also handles choking and unchoking of the remote peer.
1043 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1044 // Breaking or completing this loop means we don't want to upload to the peer anymore, and we
1047 for c.uploadAllowed() {
1048 // We want to upload to the peer.
1049 if !c.unchoke(msg) {
1052 for r, state := range c.peerRequests {
1053 if state.data == nil {
1056 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1058 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1060 delay := res.Delay()
1063 c.setRetryUploadTimer(delay)
1064 // Hard to say what to return here.
1067 more := c.sendChunk(r, msg, state)
1068 delete(c.peerRequests, r)
1079 func (cn *PeerConn) drop() {
1080 cn.t.dropConnection(cn)
1083 func (cn *PeerConn) ban() {
1084 cn.t.cl.banPeerIP(cn.remoteIp())
1087 // This is called when something has changed that should wake the writer, such as putting stuff into
1088 // the writeBuffer, or changing some state that the writer can act on.
1089 func (c *PeerConn) tickleWriter() {
1090 c.messageWriter.writeCond.Broadcast()
1093 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1094 c.lastChunkSent = time.Now()
1095 state.allocReservation.Release()
1096 return msg(pp.Message{
1104 func (c *Peer) setTorrent(t *Torrent) {
1106 panic("connection already associated with a torrent")
1109 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1110 t.reconcileHandshakeStats(c)
1113 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1114 f := pp.PexPeerFlags(0)
1115 if c.PeerPrefersEncryption {
1116 f |= pp.PexPrefersEncryption
1119 f |= pp.PexOutgoingConn
1122 f |= pp.PexSupportsUtp
1127 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1128 // advertised listen port.
1129 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1130 if c.outgoing || c.PeerListenPort == 0 {
1133 addrPort, err := addrPortFromPeerRemoteAddr(c.RemoteAddr)
1137 "error parsing %q for alternate dial port: %v",
1143 return netip.AddrPortFrom(addrPort.Addr(), uint16(c.PeerListenPort))
1146 func (c *PeerConn) pexEvent(t pexEventType) (_ pexEvent, err error) {
1147 f := c.pexPeerFlags()
1148 dialAddr := c.dialAddr()
1149 addr, err := addrPortFromPeerRemoteAddr(dialAddr)
1150 if err != nil || !addr.IsValid() {
1151 err = fmt.Errorf("parsing dial addr %q: %w", dialAddr, err)
1154 return pexEvent{t, addr, f, nil}, nil
1157 func (pc *PeerConn) String() string {
1158 return fmt.Sprintf("%T %p [id=%+q, exts=%v, v=%q]", pc, pc, pc.PeerID, pc.PeerExtensionBytes, pc.PeerClientName.Load())
1161 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1162 // are in the torrent, it could be a very large range if the peer has sent HaveAll.
1163 func (pc *PeerConn) PeerPieces() *roaring.Bitmap {
1165 defer pc.locker().RUnlock()
1166 return pc.newPeerPieces()
1169 func (pc *PeerConn) remoteIsTransmission() bool {
1170 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1173 func (pc *PeerConn) remoteDialAddrPort() (netip.AddrPort, error) {
1174 dialAddr := pc.dialAddr()
1175 return addrPortFromPeerRemoteAddr(dialAddr)
1178 func (pc *PeerConn) bitExtensionEnabled(bit pp.ExtensionBit) bool {
1179 return pc.t.cl.config.Extensions.GetBit(bit) && pc.PeerExtensionBytes.GetBit(bit)
1182 func (cn *PeerConn) peerPiecesChanged() {
1183 cn.t.maybeDropMutuallyCompletePeer(cn)
1186 // Returns whether the connection could be useful to us. We're seeding and
1187 // they want data, we don't have metainfo and they can provide it, etc.
1188 func (c *PeerConn) useful() bool {
1190 if c.closed.IsSet() {
1194 return c.supportsExtension("ut_metadata")
1196 if t.seeding() && c.peerInterested {
1199 if c.peerHasWantedPieces() {
1205 func makeBuiltinLtepProtocols(pex bool) LocalLtepProtocolMap {
1206 ps := []pp.ExtensionName{pp.ExtensionNameMetadata, utHolepunch.ExtensionName}
1208 ps = append(ps, pp.ExtensionNamePex)
1210 return LocalLtepProtocolMap{
1212 NumBuiltin: len(ps),
1216 func (c *PeerConn) addBuiltinLtepProtocols(pex bool) {
1217 c.LocalLtepProtocolMap = &c.t.cl.defaultLocalLtepProtocolMap
1220 func (pc *PeerConn) WriteExtendedMessage(extName pp.ExtensionName, payload []byte) error {
1222 defer pc.locker().Unlock()
1223 id := pc.PeerExtensionIDs[extName]
1225 return fmt.Errorf("peer does not support or has disabled extension %q", extName)
1227 pc.write(pp.Message{
1230 ExtendedPayload: payload,
1235 func (pc *PeerConn) requestMissingHashes() {
1239 if !pc.t.haveInfo() {
1246 baseLayer := pp.Integer(merkle.Log2RoundingUp(merkle.RoundUpToPowerOfTwo(
1247 uint((pc.t.usualPieceSize() + merkle.BlockSize - 1) / merkle.BlockSize)),
1249 nextFileBeginPiece := 0
1251 for _, file := range info.UpvertedFiles() {
1252 fileNumPieces := int((file.Length + info.PieceLength - 1) / info.PieceLength)
1253 curFileBeginPiece := nextFileBeginPiece
1254 nextFileBeginPiece += fileNumPieces
1255 haveAllHashes := true
1256 for i := range fileNumPieces {
1257 torrentPieceIndex := curFileBeginPiece + i
1258 if !pc.peerHasPiece(torrentPieceIndex) {
1261 if !pc.t.piece(torrentPieceIndex).hashV2.Ok {
1262 haveAllHashes = false
1268 // We would be requesting the leaves, the file must be short enough that we can just do with
1269 // the pieces root as the piece hash.
1270 if fileNumPieces <= 1 {
1273 piecesRoot := file.PiecesRoot.Unwrap()
1274 proofLayers := pp.Integer(0)
1275 for index := 0; index < fileNumPieces; index += 512 {
1276 // Minimizing to the number of pieces in a file conflicts with the BEP.
1277 length := merkle.RoundUpToPowerOfTwo(uint(min(512, fileNumPieces-index)))
1279 // This should have been filtered out by baseLayer and pieces root as piece hash
1284 pc.logger.Levelf(log.Warning, "requesting odd hashes length %d", length)
1287 Type: pp.HashRequest,
1288 PiecesRoot: piecesRoot,
1289 BaseLayer: baseLayer,
1290 Index: pp.Integer(index),
1291 Length: pp.Integer(length),
1292 ProofLayers: proofLayers,
1294 hr := hashRequestFromMessage(msg)
1295 if generics.MapContains(pc.sentHashRequests, hr) {
1299 generics.MakeMapIfNil(&pc.sentHashRequests)
1300 pc.sentHashRequests[hr] = struct{}{}
1305 func (pc *PeerConn) onReadHashes(msg *pp.Message) (err error) {
1306 file := pc.t.getFileByPiecesRoot(msg.PiecesRoot)
1307 filePieceHashes := pc.receivedHashPieces[msg.PiecesRoot]
1308 if filePieceHashes == nil {
1309 filePieceHashes = make([][32]byte, file.numPieces())
1310 generics.MakeMapIfNil(&pc.receivedHashPieces)
1311 pc.receivedHashPieces[msg.PiecesRoot] = filePieceHashes
1313 if msg.ProofLayers != 0 {
1314 // This isn't handled yet.
1315 panic(msg.ProofLayers)
1317 copy(filePieceHashes[msg.Index:], msg.Hashes)
1318 root := merkle.RootWithPadHash(
1320 metainfo.HashForPiecePad(int64(pc.t.usualPieceSize())))
1321 expectedPiecesRoot := file.piecesRoot.Unwrap()
1322 if root == expectedPiecesRoot {
1323 pc.logger.WithNames(v2HashesLogName).Levelf(
1325 "got piece hashes for file %v (num pieces %v)",
1326 file, file.numPieces())
1327 for filePieceIndex, peerHash := range filePieceHashes {
1328 torrentPieceIndex := file.BeginPieceIndex() + filePieceIndex
1329 pc.t.piece(torrentPieceIndex).hashV2.Set(peerHash)
1332 pc.logger.WithNames(v2HashesLogName).Levelf(
1334 "peer file piece hashes root mismatch: %x != %x",
1335 root, expectedPiecesRoot)
1340 type hashRequest struct {
1342 baseLayer, index, length, proofLayers pp.Integer
1345 func (hr hashRequest) toMessage() pp.Message {
1347 Type: pp.HashRequest,
1348 PiecesRoot: hr.piecesRoot,
1349 BaseLayer: hr.baseLayer,
1352 ProofLayers: hr.proofLayers,
1356 func hashRequestFromMessage(m pp.Message) hashRequest {
1358 piecesRoot: m.PiecesRoot,
1359 baseLayer: m.BaseLayer,
1362 proofLayers: m.ProofLayers,