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