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