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