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