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