]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Set torrent logger default level to debug
[btrtrc.git] / peerconn.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "errors"
8         "fmt"
9         "io"
10         "math/rand"
11         "net"
12         "net/netip"
13         "strconv"
14         "strings"
15         "time"
16
17         "github.com/RoaringBitmap/roaring"
18         . "github.com/anacrolix/generics"
19         "github.com/anacrolix/log"
20         "github.com/anacrolix/missinggo/v2/bitmap"
21         "github.com/anacrolix/multiless"
22         "golang.org/x/time/rate"
23
24         "github.com/anacrolix/torrent/bencode"
25         "github.com/anacrolix/torrent/internal/alloclim"
26         "github.com/anacrolix/torrent/metainfo"
27         "github.com/anacrolix/torrent/mse"
28         pp "github.com/anacrolix/torrent/peer_protocol"
29         utHolepunch "github.com/anacrolix/torrent/peer_protocol/ut-holepunch"
30 )
31
32 // Maintains the state of a BitTorrent-protocol based connection with a peer.
33 type PeerConn struct {
34         Peer
35
36         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
37         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
38         connString string
39
40         // See BEP 3 etc.
41         PeerID             PeerID
42         PeerExtensionBytes pp.PeerExtensionBits
43
44         // The actual Conn, used for closing, and setting socket options. Do not use methods on this
45         // while holding any mutexes.
46         conn net.Conn
47         // The Reader and Writer for this Conn, with hooks installed for stats,
48         // limiting, deadlines etc.
49         w io.Writer
50         r io.Reader
51
52         messageWriter peerConnMsgWriter
53
54         uploadTimer *time.Timer
55         pex         pexConnState
56
57         // The pieces the peer has claimed to have.
58         _peerPieces roaring.Bitmap
59         // The peer has everything. This can occur due to a special message, when
60         // we may not even know the number of pieces in the torrent yet.
61         peerSentHaveAll bool
62
63         peerRequestDataAllocLimiter alloclim.Limiter
64
65         outstandingHolepunchingRendezvous map[netip.AddrPort]struct{}
66 }
67
68 func (cn *PeerConn) peerImplStatusLines() []string {
69         lines := make([]string, 0, 2)
70         lines = append(
71                 lines,
72                 fmt.Sprintf("%+-55q %v %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString))
73         if cn.supportsExtension(pp.ExtensionNamePex) {
74                 lines = append(
75                         lines,
76                         fmt.Sprintf(
77                                 "pex: %v conns, %v unsent events",
78                                 cn.pex.remoteLiveConns,
79                                 cn.pex.numPending()))
80         }
81         return lines
82 }
83
84 // Returns true if the connection is over IPv6.
85 func (cn *PeerConn) ipv6() bool {
86         ip := cn.remoteIp()
87         if ip.To4() != nil {
88                 return false
89         }
90         return len(ip) == net.IPv6len
91 }
92
93 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
94 // specification for this.
95 func (cn *PeerConn) isPreferredDirection() bool {
96         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
97 }
98
99 // Returns whether the left connection should be preferred over the right one,
100 // considering only their networking properties. If ok is false, we can't
101 // decide.
102 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
103         var ml multiless.Computation
104         ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
105         ml = ml.Bool(l.utp(), r.utp())
106         ml = ml.Bool(r.ipv6(), l.ipv6())
107         return ml.Less()
108 }
109
110 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
111         if cn.peerSentHaveAll {
112                 return true, true
113         }
114         if !cn.t.haveInfo() {
115                 return false, false
116         }
117         return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
118 }
119
120 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
121         cn.setNumPieces(info.NumPieces())
122 }
123
124 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
125 // receiving badly sized BITFIELD, or invalid HAVE messages.
126 func (cn *PeerConn) setNumPieces(num pieceIndex) {
127         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
128         cn.peerPiecesChanged()
129 }
130
131 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
132         return &cn._peerPieces
133 }
134
135 func (cn *PeerConn) connectionFlags() (ret string) {
136         c := func(b byte) {
137                 ret += string([]byte{b})
138         }
139         if cn.cryptoMethod == mse.CryptoMethodRC4 {
140                 c('E')
141         } else if cn.headerEncrypted {
142                 c('e')
143         }
144         ret += string(cn.Discovery)
145         if cn.utp() {
146                 c('U')
147         }
148         return
149 }
150
151 func (cn *PeerConn) utp() bool {
152         return parseNetworkString(cn.Network).Udp
153 }
154
155 func (cn *PeerConn) onClose() {
156         if cn.pex.IsEnabled() {
157                 cn.pex.Close()
158         }
159         cn.tickleWriter()
160         if cn.conn != nil {
161                 go cn.conn.Close()
162         }
163         if cb := cn.callbacks.PeerConnClosed; cb != nil {
164                 cb(cn)
165         }
166 }
167
168 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
169 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
170 func (cn *PeerConn) write(msg pp.Message) bool {
171         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
172         // We don't need to track bytes here because the connection's Writer has that behaviour injected
173         // (although there's some delay between us buffering the message, and the connection writer
174         // flushing it out.).
175         notFull := cn.messageWriter.write(msg)
176         // Last I checked only Piece messages affect stats, and we don't write those.
177         cn.wroteMsg(&msg)
178         cn.tickleWriter()
179         return notFull
180 }
181
182 func (cn *PeerConn) requestMetadataPiece(index int) {
183         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
184         if eID == pp.ExtensionDeleteNumber {
185                 return
186         }
187         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
188                 return
189         }
190         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
191         cn.write(pp.MetadataExtensionRequestMsg(eID, index))
192         for index >= len(cn.metadataRequests) {
193                 cn.metadataRequests = append(cn.metadataRequests, false)
194         }
195         cn.metadataRequests[index] = true
196 }
197
198 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
199         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
200 }
201
202 func (cn *PeerConn) onPeerSentCancel(r Request) {
203         if _, ok := cn.peerRequests[r]; !ok {
204                 torrent.Add("unexpected cancels received", 1)
205                 return
206         }
207         if cn.fastEnabled() {
208                 cn.reject(r)
209         } else {
210                 delete(cn.peerRequests, r)
211         }
212 }
213
214 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
215         if cn.choking {
216                 return true
217         }
218         cn.choking = true
219         more = msg(pp.Message{
220                 Type: pp.Choke,
221         })
222         if !cn.fastEnabled() {
223                 cn.deleteAllPeerRequests()
224         }
225         return
226 }
227
228 func (cn *PeerConn) deleteAllPeerRequests() {
229         for _, state := range cn.peerRequests {
230                 state.allocReservation.Drop()
231         }
232         cn.peerRequests = nil
233 }
234
235 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
236         if !cn.choking {
237                 return true
238         }
239         cn.choking = false
240         return msg(pp.Message{
241                 Type: pp.Unchoke,
242         })
243 }
244
245 func (pc *PeerConn) writeInterested(interested bool) bool {
246         return pc.write(pp.Message{
247                 Type: func() pp.MessageType {
248                         if interested {
249                                 return pp.Interested
250                         } else {
251                                 return pp.NotInterested
252                         }
253                 }(),
254         })
255 }
256
257 func (me *PeerConn) _request(r Request) bool {
258         return me.write(pp.Message{
259                 Type:   pp.Request,
260                 Index:  r.Index,
261                 Begin:  r.Begin,
262                 Length: r.Length,
263         })
264 }
265
266 func (me *PeerConn) _cancel(r RequestIndex) bool {
267         me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
268         // Transmission does not send rejects for received cancels. See
269         // https://github.com/transmission/transmission/pull/2275.
270         return me.fastEnabled() && !me.remoteIsTransmission()
271 }
272
273 func (cn *PeerConn) fillWriteBuffer() {
274         if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
275                 // Fully committing to our max requests requires sufficient space (see
276                 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
277                 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
278                 // request reason will not be cleared, so we'll come right back here when there's space. We
279                 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
280                 // knowledge of write buffers.
281         }
282         cn.maybeUpdateActualRequestState()
283         if cn.pex.IsEnabled() {
284                 if flow := cn.pex.Share(cn.write); !flow {
285                         return
286                 }
287         }
288         cn.upload(cn.write)
289 }
290
291 func (cn *PeerConn) have(piece pieceIndex) {
292         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
293                 return
294         }
295         cn.write(pp.Message{
296                 Type:  pp.Have,
297                 Index: pp.Integer(piece),
298         })
299         cn.sentHaves.Add(bitmap.BitIndex(piece))
300 }
301
302 func (cn *PeerConn) postBitfield() {
303         if cn.sentHaves.Len() != 0 {
304                 panic("bitfield must be first have-related message sent")
305         }
306         if !cn.t.haveAnyPieces() {
307                 return
308         }
309         cn.write(pp.Message{
310                 Type:     pp.Bitfield,
311                 Bitfield: cn.t.bitfield(),
312         })
313         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
314 }
315
316 func (cn *PeerConn) handleUpdateRequests() {
317         // The writer determines the request state as needed when it can write.
318         cn.tickleWriter()
319 }
320
321 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
322         if newMin > cn.peerMinPieces {
323                 cn.peerMinPieces = newMin
324         }
325 }
326
327 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
328         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
329                 return errors.New("invalid piece")
330         }
331         if cn.peerHasPiece(piece) {
332                 return nil
333         }
334         cn.raisePeerMinPieces(piece + 1)
335         if !cn.peerHasPiece(piece) {
336                 cn.t.incPieceAvailability(piece)
337         }
338         cn._peerPieces.Add(uint32(piece))
339         if cn.t.wantPieceIndex(piece) {
340                 cn.updateRequests("have")
341         }
342         cn.peerPiecesChanged()
343         return nil
344 }
345
346 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
347         if len(bf)%8 != 0 {
348                 panic("expected bitfield length divisible by 8")
349         }
350         // We know that the last byte means that at most the last 7 bits are wasted.
351         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
352         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
353                 // Ignore known excess pieces.
354                 bf = bf[:cn.t.numPieces()]
355         }
356         bm := boolSliceToBitmap(bf)
357         if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
358                 cn.onPeerHasAllPieces()
359                 return nil
360         }
361         if !bm.IsEmpty() {
362                 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
363         }
364         shouldUpdateRequests := false
365         if cn.peerSentHaveAll {
366                 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
367                         panic(cn)
368                 }
369                 cn.peerSentHaveAll = false
370                 if !cn._peerPieces.IsEmpty() {
371                         panic("if peer has all, we expect no individual peer pieces to be set")
372                 }
373         } else {
374                 bm.Xor(&cn._peerPieces)
375         }
376         cn.peerSentHaveAll = false
377         // bm is now 'on' for pieces that are changing
378         bm.Iterate(func(x uint32) bool {
379                 pi := pieceIndex(x)
380                 if cn._peerPieces.Contains(x) {
381                         // Then we must be losing this piece
382                         cn.t.decPieceAvailability(pi)
383                 } else {
384                         if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
385                                 shouldUpdateRequests = true
386                         }
387                         // We must be gaining this piece
388                         cn.t.incPieceAvailability(pieceIndex(x))
389                 }
390                 return true
391         })
392         // Apply the changes. If we had everything previously, this should be empty, so xor is the same
393         // as or.
394         cn._peerPieces.Xor(&bm)
395         if shouldUpdateRequests {
396                 cn.updateRequests("bitfield")
397         }
398         // We didn't guard this before, I see no reason to do it now.
399         cn.peerPiecesChanged()
400         return nil
401 }
402
403 func (cn *PeerConn) onPeerHasAllPieces() {
404         t := cn.t
405         if t.haveInfo() {
406                 cn._peerPieces.Iterate(func(x uint32) bool {
407                         t.decPieceAvailability(pieceIndex(x))
408                         return true
409                 })
410         }
411         t.addConnWithAllPieces(&cn.Peer)
412         cn.peerSentHaveAll = true
413         cn._peerPieces.Clear()
414         if !cn.t._pendingPieces.IsEmpty() {
415                 cn.updateRequests("Peer.onPeerHasAllPieces")
416         }
417         cn.peerPiecesChanged()
418 }
419
420 func (cn *PeerConn) onPeerSentHaveAll() error {
421         cn.onPeerHasAllPieces()
422         return nil
423 }
424
425 func (cn *PeerConn) peerSentHaveNone() error {
426         if !cn.peerSentHaveAll {
427                 cn.t.decPeerPieceAvailability(&cn.Peer)
428         }
429         cn._peerPieces.Clear()
430         cn.peerSentHaveAll = false
431         cn.peerPiecesChanged()
432         return nil
433 }
434
435 func (c *PeerConn) requestPendingMetadata() {
436         if c.t.haveInfo() {
437                 return
438         }
439         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
440                 // Peer doesn't support this.
441                 return
442         }
443         // Request metadata pieces that we don't have in a random order.
444         var pending []int
445         for index := 0; index < c.t.metadataPieceCount(); index++ {
446                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
447                         pending = append(pending, index)
448                 }
449         }
450         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
451         for _, i := range pending {
452                 c.requestMetadataPiece(i)
453         }
454 }
455
456 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
457         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
458         if msg.Type == pp.Extended {
459                 for name, id := range cn.PeerExtensionIDs {
460                         if id != msg.ExtendedID {
461                                 continue
462                         }
463                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
464                 }
465         }
466         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
467 }
468
469 func (cn *PeerConn) wroteBytes(n int64) {
470         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
471 }
472
473 func (c *PeerConn) fastEnabled() bool {
474         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
475 }
476
477 func (c *PeerConn) reject(r Request) {
478         if !c.fastEnabled() {
479                 panic("fast not enabled")
480         }
481         c.write(r.ToMsg(pp.Reject))
482         // It is possible to reject a request before it is added to peer requests due to being invalid.
483         if state, ok := c.peerRequests[r]; ok {
484                 state.allocReservation.Drop()
485                 delete(c.peerRequests, r)
486         }
487 }
488
489 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
490         uploadRateLimiter := c.t.cl.config.UploadRateLimiter
491         if uploadRateLimiter.Limit() == rate.Inf {
492                 return
493         }
494         return Some(uploadRateLimiter.Burst())
495 }
496
497 // startFetch is for testing purposes currently.
498 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
499         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
500         if _, ok := c.peerRequests[r]; ok {
501                 torrent.Add("duplicate requests received", 1)
502                 if c.fastEnabled() {
503                         return errors.New("received duplicate request with fast enabled")
504                 }
505                 return nil
506         }
507         if c.choking {
508                 torrent.Add("requests received while choking", 1)
509                 if c.fastEnabled() {
510                         torrent.Add("requests rejected while choking", 1)
511                         c.reject(r)
512                 }
513                 return nil
514         }
515         // TODO: What if they've already requested this?
516         if len(c.peerRequests) >= localClientReqq {
517                 torrent.Add("requests received while queue full", 1)
518                 if c.fastEnabled() {
519                         c.reject(r)
520                 }
521                 // BEP 6 says we may close here if we choose.
522                 return nil
523         }
524         if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
525                 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
526                 c.logger.Levelf(log.Warning, err.Error())
527                 if c.fastEnabled() {
528                         c.reject(r)
529                         return nil
530                 } else {
531                         return err
532                 }
533         }
534         if !c.t.havePiece(pieceIndex(r.Index)) {
535                 // TODO: Tell the peer we don't have the piece, and reject this request.
536                 requestsReceivedForMissingPieces.Add(1)
537                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
538         }
539         pieceLength := c.t.pieceLength(pieceIndex(r.Index))
540         // Check this after we know we have the piece, so that the piece length will be known.
541         if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
542                 torrent.Add("bad requests received", 1)
543                 return errors.New("chunk overflows piece")
544         }
545         if c.peerRequests == nil {
546                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
547         }
548         value := &peerRequestState{
549                 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
550         }
551         c.peerRequests[r] = value
552         if startFetch {
553                 // TODO: Limit peer request data read concurrency.
554                 go c.peerRequestDataReader(r, value)
555         }
556         return nil
557 }
558
559 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
560         b, err := c.readPeerRequestData(r, prs)
561         c.locker().Lock()
562         defer c.locker().Unlock()
563         if err != nil {
564                 c.peerRequestDataReadFailed(err, r)
565         } else {
566                 if b == nil {
567                         panic("data must be non-nil to trigger send")
568                 }
569                 torrent.Add("peer request data read successes", 1)
570                 prs.data = b
571                 // This might be required for the error case too (#752 and #753).
572                 c.tickleWriter()
573         }
574 }
575
576 // If this is maintained correctly, we might be able to support optional synchronous reading for
577 // chunk sending, the way it used to work.
578 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
579         torrent.Add("peer request data read failures", 1)
580         logLevel := log.Warning
581         if c.t.hasStorageCap() {
582                 // It's expected that pieces might drop. See
583                 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
584                 logLevel = log.Debug
585         }
586         c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
587         if c.t.closed.IsSet() {
588                 return
589         }
590         i := pieceIndex(r.Index)
591         if c.t.pieceComplete(i) {
592                 // There used to be more code here that just duplicated the following break. Piece
593                 // completions are currently cached, so I'm not sure how helpful this update is, except to
594                 // pull any completion changes pushed to the storage backend in failed reads that got us
595                 // here.
596                 c.t.updatePieceCompletion(i)
597         }
598         // We've probably dropped a piece from storage, but there's no way to communicate this to the
599         // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
600         // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
601         // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
602         // initially).
603         if c.fastEnabled() {
604                 c.reject(r)
605         } else {
606                 if c.choking {
607                         // If fast isn't enabled, I think we would have wiped all peer requests when we last
608                         // choked, and requests while we're choking would be ignored. It could be possible that
609                         // a peer request data read completed concurrently to it being deleted elsewhere.
610                         c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
611                 }
612                 // Choking a non-fast peer should cause them to flush all their requests.
613                 c.choke(c.write)
614         }
615 }
616
617 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
618         // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
619         // or fail to read and then cleanup.
620         ctx := context.Background()
621         err := prs.allocReservation.Wait(ctx)
622         if err != nil {
623                 if ctx.Err() == nil {
624                         // The error is from the reservation itself. Something is very broken, or we're not
625                         // guarding against excessively large requests.
626                         err = log.WithLevel(log.Critical, err)
627                 }
628                 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
629                 return nil, err
630         }
631         b := make([]byte, r.Length)
632         p := c.t.info.Piece(int(r.Index))
633         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
634         if n == len(b) {
635                 if err == io.EOF {
636                         err = nil
637                 }
638         } else {
639                 if err == nil {
640                         panic("expected error")
641                 }
642         }
643         return b, err
644 }
645
646 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
647         c.logger.WithContextText(fmt.Sprintf(
648                 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
649         )).SkipCallers(1).Levelf(level, format, arg...)
650 }
651
652 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
653 // exit. Returning will end the connection.
654 func (c *PeerConn) mainReadLoop() (err error) {
655         defer func() {
656                 if err != nil {
657                         torrent.Add("connection.mainReadLoop returned with error", 1)
658                 } else {
659                         torrent.Add("connection.mainReadLoop returned with no error", 1)
660                 }
661         }()
662         t := c.t
663         cl := t.cl
664
665         decoder := pp.Decoder{
666                 R:         bufio.NewReaderSize(c.r, 1<<17),
667                 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
668                 Pool:      &t.chunkPool,
669         }
670         for {
671                 var msg pp.Message
672                 func() {
673                         cl.unlock()
674                         defer cl.lock()
675                         err = decoder.Decode(&msg)
676                 }()
677                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
678                         cb(c, &msg)
679                 }
680                 if t.closed.IsSet() || c.closed.IsSet() {
681                         return nil
682                 }
683                 if err != nil {
684                         return err
685                 }
686                 c.lastMessageReceived = time.Now()
687                 if msg.Keepalive {
688                         receivedKeepalives.Add(1)
689                         continue
690                 }
691                 messageTypesReceived.Add(msg.Type.String(), 1)
692                 if msg.Type.FastExtension() && !c.fastEnabled() {
693                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
694                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
695                 }
696                 switch msg.Type {
697                 case pp.Choke:
698                         if c.peerChoking {
699                                 break
700                         }
701                         if !c.fastEnabled() {
702                                 c.deleteAllRequests("choked by non-fast PeerConn")
703                         } else {
704                                 // We don't decrement pending requests here, let's wait for the peer to either
705                                 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
706                                 // us and resume where they left off, we don't want to have piled on to those chunks
707                                 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
708                                 // could let us request a lot of stuff, then choke us and never reject, but they're
709                                 // only a single peer, our chunk balancing should smooth over this abuse.
710                         }
711                         c.peerChoking = true
712                         c.updateExpectingChunks()
713                 case pp.Unchoke:
714                         if !c.peerChoking {
715                                 // Some clients do this for some reason. Transmission doesn't error on this, so we
716                                 // won't for consistency.
717                                 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
718                                 break
719                         }
720                         c.peerChoking = false
721                         preservedCount := 0
722                         c.requestState.Requests.Iterate(func(x RequestIndex) bool {
723                                 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
724                                         preservedCount++
725                                 }
726                                 return true
727                         })
728                         if preservedCount != 0 {
729                                 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
730                                 // right now.
731                                 c.logger.Levelf(log.Debug,
732                                         "%v requests were preserved while being choked (fast=%v)",
733                                         preservedCount,
734                                         c.fastEnabled())
735
736                                 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
737                         }
738                         if !c.t._pendingPieces.IsEmpty() {
739                                 c.updateRequests("unchoked")
740                         }
741                         c.updateExpectingChunks()
742                 case pp.Interested:
743                         c.peerInterested = true
744                         c.tickleWriter()
745                 case pp.NotInterested:
746                         c.peerInterested = false
747                         // We don't clear their requests since it isn't clear in the spec.
748                         // We'll probably choke them for this, which will clear them if
749                         // appropriate, and is clearly specified.
750                 case pp.Have:
751                         err = c.peerSentHave(pieceIndex(msg.Index))
752                 case pp.Bitfield:
753                         err = c.peerSentBitfield(msg.Bitfield)
754                 case pp.Request:
755                         r := newRequestFromMessage(&msg)
756                         err = c.onReadRequest(r, true)
757                         if err != nil {
758                                 err = fmt.Errorf("on reading request %v: %w", r, err)
759                         }
760                 case pp.Piece:
761                         c.doChunkReadStats(int64(len(msg.Piece)))
762                         err = c.receiveChunk(&msg)
763                         if len(msg.Piece) == int(t.chunkSize) {
764                                 t.chunkPool.Put(&msg.Piece)
765                         }
766                         if err != nil {
767                                 err = fmt.Errorf("receiving chunk: %w", err)
768                         }
769                 case pp.Cancel:
770                         req := newRequestFromMessage(&msg)
771                         c.onPeerSentCancel(req)
772                 case pp.Port:
773                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
774                         if !ok {
775                                 break
776                         }
777                         pingAddr := net.UDPAddr{
778                                 IP:   ipa.IP,
779                                 Port: ipa.Port,
780                         }
781                         if msg.Port != 0 {
782                                 pingAddr.Port = int(msg.Port)
783                         }
784                         cl.eachDhtServer(func(s DhtServer) {
785                                 go s.Ping(&pingAddr)
786                         })
787                 case pp.Suggest:
788                         torrent.Add("suggests received", 1)
789                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
790                         c.updateRequests("suggested")
791                 case pp.HaveAll:
792                         err = c.onPeerSentHaveAll()
793                 case pp.HaveNone:
794                         err = c.peerSentHaveNone()
795                 case pp.Reject:
796                         req := newRequestFromMessage(&msg)
797                         if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
798                                 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
799                                 err = fmt.Errorf("received invalid reject [request=%v]", req)
800                         }
801                 case pp.AllowedFast:
802                         torrent.Add("allowed fasts received", 1)
803                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
804                         c.updateRequests("PeerConn.mainReadLoop allowed fast")
805                 case pp.Extended:
806                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
807                 default:
808                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
809                 }
810                 if err != nil {
811                         return err
812                 }
813         }
814 }
815
816 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
817         defer func() {
818                 // TODO: Should we still do this?
819                 if err != nil {
820                         // These clients use their own extension IDs for outgoing message
821                         // types, which is incorrect.
822                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
823                                 err = nil
824                         }
825                 }
826         }()
827         t := c.t
828         cl := t.cl
829         switch id {
830         case pp.HandshakeExtendedID:
831                 var d pp.ExtendedHandshakeMessage
832                 if err := bencode.Unmarshal(payload, &d); err != nil {
833                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
834                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
835                 }
836                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
837                         cb(c, &d)
838                 }
839                 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
840                 if d.Reqq != 0 {
841                         c.PeerMaxRequests = d.Reqq
842                 }
843                 c.PeerClientName.Store(d.V)
844                 if c.PeerExtensionIDs == nil {
845                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
846                 }
847                 c.PeerListenPort = d.Port
848                 c.PeerPrefersEncryption = d.Encryption
849                 for name, id := range d.M {
850                         if _, ok := c.PeerExtensionIDs[name]; !ok {
851                                 peersSupportingExtension.Add(
852                                         // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
853                                         // entered here which caused problems later when unmarshalling.
854                                         strconv.Quote(string(name)),
855                                         1)
856                         }
857                         c.PeerExtensionIDs[name] = id
858                 }
859                 if d.MetadataSize != 0 {
860                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
861                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
862                         }
863                 }
864                 c.requestPendingMetadata()
865                 if !t.cl.config.DisablePEX {
866                         t.pex.Add(c) // we learnt enough now
867                         // This checks the extension is supported internally.
868                         c.pex.Init(c)
869                 }
870                 return nil
871         case metadataExtendedId:
872                 err := cl.gotMetadataExtensionMsg(payload, t, c)
873                 if err != nil {
874                         return fmt.Errorf("handling metadata extension message: %w", err)
875                 }
876                 return nil
877         case pexExtendedId:
878                 if !c.pex.IsEnabled() {
879                         return nil // or hang-up maybe?
880                 }
881                 err = c.pex.Recv(payload)
882                 if err != nil {
883                         err = fmt.Errorf("receiving pex message: %w", err)
884                 }
885                 return
886         case utHolepunchExtendedId:
887                 var msg utHolepunch.Msg
888                 err = msg.UnmarshalBinary(payload)
889                 if err != nil {
890                         err = fmt.Errorf("unmarshalling ut_holepunch message: %w", err)
891                         return
892                 }
893                 err = c.t.handleReceivedUtHolepunchMsg(msg, c)
894                 return
895         default:
896                 return fmt.Errorf("unexpected extended message ID: %v", id)
897         }
898 }
899
900 // Set both the Reader and Writer for the connection from a single ReadWriter.
901 func (cn *PeerConn) setRW(rw io.ReadWriter) {
902         cn.r = rw
903         cn.w = rw
904 }
905
906 // Returns the Reader and Writer as a combined ReadWriter.
907 func (cn *PeerConn) rw() io.ReadWriter {
908         return struct {
909                 io.Reader
910                 io.Writer
911         }{cn.r, cn.w}
912 }
913
914 func (c *PeerConn) uploadAllowed() bool {
915         if c.t.cl.config.NoUpload {
916                 return false
917         }
918         if c.t.dataUploadDisallowed {
919                 return false
920         }
921         if c.t.seeding() {
922                 return true
923         }
924         if !c.peerHasWantedPieces() {
925                 return false
926         }
927         // Don't upload more than 100 KiB more than we download.
928         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
929                 return false
930         }
931         return true
932 }
933
934 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
935         if c.uploadTimer == nil {
936                 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
937         } else {
938                 c.uploadTimer.Reset(delay)
939         }
940 }
941
942 // Also handles choking and unchoking of the remote peer.
943 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
944         // Breaking or completing this loop means we don't want to upload to the
945         // peer anymore, and we choke them.
946 another:
947         for c.uploadAllowed() {
948                 // We want to upload to the peer.
949                 if !c.unchoke(msg) {
950                         return false
951                 }
952                 for r, state := range c.peerRequests {
953                         if state.data == nil {
954                                 continue
955                         }
956                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
957                         if !res.OK() {
958                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
959                         }
960                         delay := res.Delay()
961                         if delay > 0 {
962                                 res.Cancel()
963                                 c.setRetryUploadTimer(delay)
964                                 // Hard to say what to return here.
965                                 return true
966                         }
967                         more := c.sendChunk(r, msg, state)
968                         delete(c.peerRequests, r)
969                         if !more {
970                                 return false
971                         }
972                         goto another
973                 }
974                 return true
975         }
976         return c.choke(msg)
977 }
978
979 func (cn *PeerConn) drop() {
980         cn.t.dropConnection(cn)
981 }
982
983 func (cn *PeerConn) ban() {
984         cn.t.cl.banPeerIP(cn.remoteIp())
985 }
986
987 // This is called when something has changed that should wake the writer, such as putting stuff into
988 // the writeBuffer, or changing some state that the writer can act on.
989 func (c *PeerConn) tickleWriter() {
990         c.messageWriter.writeCond.Broadcast()
991 }
992
993 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
994         c.lastChunkSent = time.Now()
995         state.allocReservation.Release()
996         return msg(pp.Message{
997                 Type:  pp.Piece,
998                 Index: r.Index,
999                 Begin: r.Begin,
1000                 Piece: state.data,
1001         })
1002 }
1003
1004 func (c *PeerConn) setTorrent(t *Torrent) {
1005         if c.t != nil {
1006                 panic("connection already associated with a torrent")
1007         }
1008         c.t = t
1009         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1010         t.reconcileHandshakeStats(c)
1011 }
1012
1013 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1014         f := pp.PexPeerFlags(0)
1015         if c.PeerPrefersEncryption {
1016                 f |= pp.PexPrefersEncryption
1017         }
1018         if c.outgoing {
1019                 f |= pp.PexOutgoingConn
1020         }
1021         if c.utp() {
1022                 f |= pp.PexSupportsUtp
1023         }
1024         return f
1025 }
1026
1027 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1028 // advertised listen port.
1029 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1030         if !c.outgoing && c.PeerListenPort != 0 {
1031                 switch addr := c.RemoteAddr.(type) {
1032                 case *net.TCPAddr:
1033                         dialAddr := *addr
1034                         dialAddr.Port = c.PeerListenPort
1035                         return &dialAddr
1036                 case *net.UDPAddr:
1037                         dialAddr := *addr
1038                         dialAddr.Port = c.PeerListenPort
1039                         return &dialAddr
1040                 }
1041         }
1042         return c.RemoteAddr
1043 }
1044
1045 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1046         f := c.pexPeerFlags()
1047         addr := c.dialAddr()
1048         return pexEvent{t, addr, f, nil}
1049 }
1050
1051 func (c *PeerConn) String() string {
1052         return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1053 }
1054
1055 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1056 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1057 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1058         cn.locker().RLock()
1059         defer cn.locker().RUnlock()
1060         return cn.newPeerPieces()
1061 }
1062
1063 func (pc *PeerConn) remoteIsTransmission() bool {
1064         return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1065 }
1066
1067 func (pc *PeerConn) remoteAddrPort() Option[netip.AddrPort] {
1068         return Some(pc.conn.RemoteAddr().(interface {
1069                 AddrPort() netip.AddrPort
1070         }).AddrPort())
1071 }