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