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