]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Limit peer request data allocation
[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         "strconv"
13         "strings"
14         "sync/atomic"
15         "time"
16
17         "github.com/RoaringBitmap/roaring"
18         "github.com/anacrolix/chansync"
19         . "github.com/anacrolix/generics"
20         "github.com/anacrolix/log"
21         "github.com/anacrolix/missinggo/iter"
22         "github.com/anacrolix/missinggo/v2/bitmap"
23         "github.com/anacrolix/multiless"
24         "github.com/anacrolix/torrent/internal/alloclim"
25         "golang.org/x/time/rate"
26
27         "github.com/anacrolix/torrent/bencode"
28         "github.com/anacrolix/torrent/metainfo"
29         "github.com/anacrolix/torrent/mse"
30         pp "github.com/anacrolix/torrent/peer_protocol"
31         request_strategy "github.com/anacrolix/torrent/request-strategy"
32         "github.com/anacrolix/torrent/typed-roaring"
33 )
34
35 type PeerSource string
36
37 const (
38         PeerSourceTracker         = "Tr"
39         PeerSourceIncoming        = "I"
40         PeerSourceDhtGetPeers     = "Hg" // Peers we found by searching a DHT.
41         PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
42         PeerSourcePex             = "X"
43         // The peer was given directly, such as through a magnet link.
44         PeerSourceDirect = "M"
45 )
46
47 type peerRequestState struct {
48         data             []byte
49         allocReservation *alloclim.Reservation
50 }
51
52 type PeerRemoteAddr interface {
53         String() string
54 }
55
56 type (
57         // Since we have to store all the requests in memory, we can't reasonably exceed what could be
58         // indexed with the memory space available.
59         maxRequests = int
60 )
61
62 type Peer struct {
63         // First to ensure 64-bit alignment for atomics. See #262.
64         _stats ConnStats
65
66         t *Torrent
67
68         peerImpl
69         callbacks *Callbacks
70
71         outgoing   bool
72         Network    string
73         RemoteAddr PeerRemoteAddr
74         // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
75         // config.
76         localPublicAddr peerLocalPublicAddr
77         bannableAddr    Option[bannableAddr]
78         // True if the connection is operating over MSE obfuscation.
79         headerEncrypted bool
80         cryptoMethod    mse.CryptoMethod
81         Discovery       PeerSource
82         trusted         bool
83         closed          chansync.SetOnce
84         // Set true after we've added our ConnStats generated during handshake to
85         // other ConnStat instances as determined when the *Torrent became known.
86         reconciledHandshakeStats bool
87
88         lastMessageReceived     time.Time
89         completedHandshake      time.Time
90         lastUsefulChunkReceived time.Time
91         lastChunkSent           time.Time
92
93         // Stuff controlled by the local peer.
94         needRequestUpdate    string
95         requestState         request_strategy.PeerRequestState
96         updateRequestsTimer  *time.Timer
97         lastRequestUpdate    time.Time
98         peakRequests         maxRequests
99         lastBecameInterested time.Time
100         priorInterest        time.Duration
101
102         lastStartedExpectingToReceiveChunks time.Time
103         cumulativeExpectedToReceiveChunks   time.Duration
104         _chunksReceivedWhileExpecting       int64
105
106         choking                                bool
107         piecesReceivedSinceLastRequestUpdate   maxRequests
108         maxPiecesReceivedBetweenRequestUpdates maxRequests
109         // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
110         // and implementation differences, we may receive chunks that are no longer in the set of
111         // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
112         validReceiveChunks map[RequestIndex]int
113         // Indexed by metadata piece, set to true if posted and pending a
114         // response.
115         metadataRequests []bool
116         sentHaves        bitmap.Bitmap
117
118         // Stuff controlled by the remote peer.
119         peerInterested        bool
120         peerChoking           bool
121         peerRequests          map[Request]*peerRequestState
122         PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
123         PeerListenPort        int
124         // The highest possible number of pieces the torrent could have based on
125         // communication with the peer. Generally only useful until we have the
126         // torrent info.
127         peerMinPieces pieceIndex
128         // Pieces we've accepted chunks for from the peer.
129         peerTouchedPieces map[pieceIndex]struct{}
130         peerAllowedFast   typedRoaring.Bitmap[pieceIndex]
131
132         PeerMaxRequests  maxRequests // Maximum pending requests the peer allows.
133         PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
134         PeerClientName   atomic.Value
135
136         logger log.Logger
137 }
138
139 type peerRequests = orderedBitmap[RequestIndex]
140
141 func (p *Peer) initRequestState() {
142         p.requestState.Requests = &peerRequests{}
143 }
144
145 // Maintains the state of a BitTorrent-protocol based connection with a peer.
146 type PeerConn struct {
147         Peer
148
149         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
150         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
151         connString string
152
153         // See BEP 3 etc.
154         PeerID             PeerID
155         PeerExtensionBytes pp.PeerExtensionBits
156
157         // The actual Conn, used for closing, and setting socket options. Do not use methods on this
158         // while holding any mutexes.
159         conn net.Conn
160         // The Reader and Writer for this Conn, with hooks installed for stats,
161         // limiting, deadlines etc.
162         w io.Writer
163         r io.Reader
164
165         messageWriter peerConnMsgWriter
166
167         uploadTimer *time.Timer
168         pex         pexConnState
169
170         // The pieces the peer has claimed to have.
171         _peerPieces roaring.Bitmap
172         // The peer has everything. This can occur due to a special message, when
173         // we may not even know the number of pieces in the torrent yet.
174         peerSentHaveAll bool
175
176         peerRequestDataAllocLimiter alloclim.Limiter
177 }
178
179 func (cn *PeerConn) peerImplStatusLines() []string {
180         return []string{fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)}
181 }
182
183 func (cn *Peer) updateExpectingChunks() {
184         if cn.expectingChunks() {
185                 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
186                         cn.lastStartedExpectingToReceiveChunks = time.Now()
187                 }
188         } else {
189                 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
190                         cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
191                         cn.lastStartedExpectingToReceiveChunks = time.Time{}
192                 }
193         }
194 }
195
196 func (cn *Peer) expectingChunks() bool {
197         if cn.requestState.Requests.IsEmpty() {
198                 return false
199         }
200         if !cn.requestState.Interested {
201                 return false
202         }
203         if !cn.peerChoking {
204                 return true
205         }
206         haveAllowedFastRequests := false
207         cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
208                 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
209                         cn.requestState.Requests,
210                         cn.t.pieceRequestIndexOffset(i),
211                         cn.t.pieceRequestIndexOffset(i+1),
212                 ) == 0
213                 return !haveAllowedFastRequests
214         })
215         return haveAllowedFastRequests
216 }
217
218 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
219         return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
220 }
221
222 // Returns true if the connection is over IPv6.
223 func (cn *PeerConn) ipv6() bool {
224         ip := cn.remoteIp()
225         if ip.To4() != nil {
226                 return false
227         }
228         return len(ip) == net.IPv6len
229 }
230
231 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
232 // specification for this.
233 func (cn *PeerConn) isPreferredDirection() bool {
234         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
235 }
236
237 // Returns whether the left connection should be preferred over the right one,
238 // considering only their networking properties. If ok is false, we can't
239 // decide.
240 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
241         var ml multiless.Computation
242         ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
243         ml = ml.Bool(l.utp(), r.utp())
244         ml = ml.Bool(r.ipv6(), l.ipv6())
245         return ml.Less()
246 }
247
248 func (cn *Peer) cumInterest() time.Duration {
249         ret := cn.priorInterest
250         if cn.requestState.Interested {
251                 ret += time.Since(cn.lastBecameInterested)
252         }
253         return ret
254 }
255
256 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
257         if cn.peerSentHaveAll {
258                 return true, true
259         }
260         if !cn.t.haveInfo() {
261                 return false, false
262         }
263         return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
264 }
265
266 func (cn *Peer) locker() *lockWithDeferreds {
267         return cn.t.cl.locker()
268 }
269
270 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
271         _, ok := cn.PeerExtensionIDs[ext]
272         return ok
273 }
274
275 // The best guess at number of pieces in the torrent for this peer.
276 func (cn *Peer) bestPeerNumPieces() pieceIndex {
277         if cn.t.haveInfo() {
278                 return cn.t.numPieces()
279         }
280         return cn.peerMinPieces
281 }
282
283 func (cn *Peer) completedString() string {
284         have := pieceIndex(cn.peerPieces().GetCardinality())
285         if all, _ := cn.peerHasAllPieces(); all {
286                 have = cn.bestPeerNumPieces()
287         }
288         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
289 }
290
291 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
292         cn.setNumPieces(info.NumPieces())
293 }
294
295 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
296 // receiving badly sized BITFIELD, or invalid HAVE messages.
297 func (cn *PeerConn) setNumPieces(num pieceIndex) {
298         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
299         cn.peerPiecesChanged()
300 }
301
302 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
303         return &cn._peerPieces
304 }
305
306 func eventAgeString(t time.Time) string {
307         if t.IsZero() {
308                 return "never"
309         }
310         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
311 }
312
313 func (cn *PeerConn) connectionFlags() (ret string) {
314         c := func(b byte) {
315                 ret += string([]byte{b})
316         }
317         if cn.cryptoMethod == mse.CryptoMethodRC4 {
318                 c('E')
319         } else if cn.headerEncrypted {
320                 c('e')
321         }
322         ret += string(cn.Discovery)
323         if cn.utp() {
324                 c('U')
325         }
326         return
327 }
328
329 func (cn *PeerConn) utp() bool {
330         return parseNetworkString(cn.Network).Udp
331 }
332
333 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
334 func (cn *Peer) statusFlags() (ret string) {
335         c := func(b byte) {
336                 ret += string([]byte{b})
337         }
338         if cn.requestState.Interested {
339                 c('i')
340         }
341         if cn.choking {
342                 c('c')
343         }
344         c('-')
345         ret += cn.connectionFlags()
346         c('-')
347         if cn.peerInterested {
348                 c('i')
349         }
350         if cn.peerChoking {
351                 c('c')
352         }
353         return
354 }
355
356 func (cn *Peer) downloadRate() float64 {
357         num := cn._stats.BytesReadUsefulData.Int64()
358         if num == 0 {
359                 return 0
360         }
361         return float64(num) / cn.totalExpectingTime().Seconds()
362 }
363
364 func (cn *Peer) DownloadRate() float64 {
365         cn.locker().RLock()
366         defer cn.locker().RUnlock()
367
368         return cn.downloadRate()
369 }
370
371 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
372         var last Option[pieceIndex]
373         var count int
374         next := func(item Option[pieceIndex]) {
375                 if item == last {
376                         count++
377                 } else {
378                         if count != 0 {
379                                 f(last.Value, count)
380                         }
381                         last = item
382                         count = 1
383                 }
384         }
385         cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
386                 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
387                 return true
388         })
389         next(None[pieceIndex]())
390 }
391
392 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
393         // \t isn't preserved in <pre> blocks?
394         if cn.closed.IsSet() {
395                 fmt.Fprint(w, "CLOSED: ")
396         }
397         fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
398         prio, err := cn.peerPriority()
399         prioStr := fmt.Sprintf("%08x", prio)
400         if err != nil {
401                 prioStr += ": " + err.Error()
402         }
403         fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
404         fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
405                 eventAgeString(cn.lastMessageReceived),
406                 eventAgeString(cn.completedHandshake),
407                 eventAgeString(cn.lastHelpful()),
408                 cn.cumInterest(),
409                 cn.totalExpectingTime(),
410         )
411         fmt.Fprintf(w,
412                 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
413                 cn.completedString(),
414                 len(cn.peerTouchedPieces),
415                 &cn._stats.ChunksReadUseful,
416                 &cn._stats.ChunksRead,
417                 &cn._stats.ChunksWritten,
418                 cn.requestState.Requests.GetCardinality(),
419                 cn.requestState.Cancelled.GetCardinality(),
420                 cn.nominalMaxRequests(),
421                 cn.PeerMaxRequests,
422                 len(cn.peerRequests),
423                 localClientReqq,
424                 cn.statusFlags(),
425                 cn.downloadRate()/(1<<10),
426         )
427         fmt.Fprintf(w, "requested pieces:")
428         cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
429                 fmt.Fprintf(w, " %v(%v)", piece, count)
430         })
431         fmt.Fprintf(w, "\n")
432 }
433
434 func (p *Peer) close() {
435         if !p.closed.Set() {
436                 return
437         }
438         if p.updateRequestsTimer != nil {
439                 p.updateRequestsTimer.Stop()
440         }
441         p.peerImpl.onClose()
442         if p.t != nil {
443                 p.t.decPeerPieceAvailability(p)
444         }
445         for _, f := range p.callbacks.PeerClosed {
446                 f(p)
447         }
448 }
449
450 func (cn *PeerConn) onClose() {
451         if cn.pex.IsEnabled() {
452                 cn.pex.Close()
453         }
454         cn.tickleWriter()
455         if cn.conn != nil {
456                 go cn.conn.Close()
457         }
458         if cb := cn.callbacks.PeerConnClosed; cb != nil {
459                 cb(cn)
460         }
461 }
462
463 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
464 // they do (known=true).
465 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
466         if all, known := cn.peerHasAllPieces(); all && known {
467                 return true
468         }
469         return cn.peerPieces().ContainsInt(piece)
470 }
471
472 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
473 // https://github.com/pion/datachannel/issues/59 is fixed.
474 const (
475         writeBufferHighWaterLen = 1 << 15
476         writeBufferLowWaterLen  = writeBufferHighWaterLen / 2
477 )
478
479 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
480 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
481 func (cn *PeerConn) write(msg pp.Message) bool {
482         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
483         // We don't need to track bytes here because the connection's Writer has that behaviour injected
484         // (although there's some delay between us buffering the message, and the connection writer
485         // flushing it out.).
486         notFull := cn.messageWriter.write(msg)
487         // Last I checked only Piece messages affect stats, and we don't write those.
488         cn.wroteMsg(&msg)
489         cn.tickleWriter()
490         return notFull
491 }
492
493 func (cn *PeerConn) requestMetadataPiece(index int) {
494         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
495         if eID == pp.ExtensionDeleteNumber {
496                 return
497         }
498         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
499                 return
500         }
501         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
502         cn.write(pp.MetadataExtensionRequestMsg(eID, index))
503         for index >= len(cn.metadataRequests) {
504                 cn.metadataRequests = append(cn.metadataRequests, false)
505         }
506         cn.metadataRequests[index] = true
507 }
508
509 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
510         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
511 }
512
513 var (
514         interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
515         requestMsgLen    = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
516         // This is the maximum request count that could fit in the write buffer if it's at or below the
517         // low water mark when we run maybeUpdateActualRequestState.
518         maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
519 )
520
521 // The actual value to use as the maximum outbound requests.
522 func (cn *Peer) nominalMaxRequests() maxRequests {
523         return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
524 }
525
526 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
527         ret = cn.cumulativeExpectedToReceiveChunks
528         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
529                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
530         }
531         return
532 }
533
534 func (cn *PeerConn) onPeerSentCancel(r Request) {
535         if _, ok := cn.peerRequests[r]; !ok {
536                 torrent.Add("unexpected cancels received", 1)
537                 return
538         }
539         if cn.fastEnabled() {
540                 cn.reject(r)
541         } else {
542                 delete(cn.peerRequests, r)
543         }
544 }
545
546 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
547         if cn.choking {
548                 return true
549         }
550         cn.choking = true
551         more = msg(pp.Message{
552                 Type: pp.Choke,
553         })
554         if !cn.fastEnabled() {
555                 cn.deleteAllPeerRequests()
556         }
557         return
558 }
559
560 func (cn *PeerConn) deleteAllPeerRequests() {
561         for _, state := range cn.peerRequests {
562                 state.allocReservation.Drop()
563         }
564         cn.peerRequests = nil
565 }
566
567 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
568         if !cn.choking {
569                 return true
570         }
571         cn.choking = false
572         return msg(pp.Message{
573                 Type: pp.Unchoke,
574         })
575 }
576
577 func (cn *Peer) setInterested(interested bool) bool {
578         if cn.requestState.Interested == interested {
579                 return true
580         }
581         cn.requestState.Interested = interested
582         if interested {
583                 cn.lastBecameInterested = time.Now()
584         } else if !cn.lastBecameInterested.IsZero() {
585                 cn.priorInterest += time.Since(cn.lastBecameInterested)
586         }
587         cn.updateExpectingChunks()
588         // log.Printf("%p: setting interest: %v", cn, interested)
589         return cn.writeInterested(interested)
590 }
591
592 func (pc *PeerConn) writeInterested(interested bool) bool {
593         return pc.write(pp.Message{
594                 Type: func() pp.MessageType {
595                         if interested {
596                                 return pp.Interested
597                         } else {
598                                 return pp.NotInterested
599                         }
600                 }(),
601         })
602 }
603
604 // The function takes a message to be sent, and returns true if more messages
605 // are okay.
606 type messageWriter func(pp.Message) bool
607
608 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
609 // when we want to go fast.
610 func (cn *Peer) shouldRequest(r RequestIndex) error {
611         err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
612         if err != nil {
613                 return err
614         }
615         pi := cn.t.pieceIndexOfRequestIndex(r)
616         if cn.requestState.Cancelled.Contains(r) {
617                 return errors.New("request is cancelled and waiting acknowledgement")
618         }
619         if !cn.peerHasPiece(pi) {
620                 return errors.New("requesting piece peer doesn't have")
621         }
622         if !cn.t.peerIsActive(cn) {
623                 panic("requesting but not in active conns")
624         }
625         if cn.closed.IsSet() {
626                 panic("requesting when connection is closed")
627         }
628         if cn.t.hashingPiece(pi) {
629                 panic("piece is being hashed")
630         }
631         if cn.t.pieceQueuedForHash(pi) {
632                 panic("piece is queued for hash")
633         }
634         if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
635                 // This could occur if we made a request with the fast extension, and then got choked and
636                 // haven't had the request rejected yet.
637                 if !cn.requestState.Requests.Contains(r) {
638                         panic("peer choking and piece not allowed fast")
639                 }
640         }
641         return nil
642 }
643
644 func (cn *Peer) mustRequest(r RequestIndex) bool {
645         more, err := cn.request(r)
646         if err != nil {
647                 panic(err)
648         }
649         return more
650 }
651
652 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
653         if err := cn.shouldRequest(r); err != nil {
654                 panic(err)
655         }
656         if cn.requestState.Requests.Contains(r) {
657                 return true, nil
658         }
659         if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
660                 return true, errors.New("too many outstanding requests")
661         }
662         cn.requestState.Requests.Add(r)
663         if cn.validReceiveChunks == nil {
664                 cn.validReceiveChunks = make(map[RequestIndex]int)
665         }
666         cn.validReceiveChunks[r]++
667         cn.t.requestState[r] = requestState{
668                 peer: cn,
669                 when: time.Now(),
670         }
671         cn.updateExpectingChunks()
672         ppReq := cn.t.requestIndexToRequest(r)
673         for _, f := range cn.callbacks.SentRequest {
674                 f(PeerRequestEvent{cn, ppReq})
675         }
676         return cn.peerImpl._request(ppReq), nil
677 }
678
679 func (me *PeerConn) _request(r Request) bool {
680         return me.write(pp.Message{
681                 Type:   pp.Request,
682                 Index:  r.Index,
683                 Begin:  r.Begin,
684                 Length: r.Length,
685         })
686 }
687
688 func (me *Peer) cancel(r RequestIndex) {
689         if !me.deleteRequest(r) {
690                 panic("request not existing should have been guarded")
691         }
692         if me._cancel(r) {
693                 if !me.requestState.Cancelled.CheckedAdd(r) {
694                         panic("request already cancelled")
695                 }
696         }
697         me.decPeakRequests()
698         if me.isLowOnRequests() {
699                 me.updateRequests("Peer.cancel")
700         }
701 }
702
703 func (me *PeerConn) _cancel(r RequestIndex) bool {
704         me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
705         // Transmission does not send rejects for received cancels. See
706         // https://github.com/transmission/transmission/pull/2275.
707         return me.fastEnabled() && !me.remoteIsTransmission()
708 }
709
710 func (cn *PeerConn) fillWriteBuffer() {
711         if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
712                 // Fully committing to our max requests requires sufficient space (see
713                 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
714                 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
715                 // request reason will not be cleared, so we'll come right back here when there's space. We
716                 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
717                 // knowledge of write buffers.
718         }
719         cn.maybeUpdateActualRequestState()
720         if cn.pex.IsEnabled() {
721                 if flow := cn.pex.Share(cn.write); !flow {
722                         return
723                 }
724         }
725         cn.upload(cn.write)
726 }
727
728 func (cn *PeerConn) have(piece pieceIndex) {
729         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
730                 return
731         }
732         cn.write(pp.Message{
733                 Type:  pp.Have,
734                 Index: pp.Integer(piece),
735         })
736         cn.sentHaves.Add(bitmap.BitIndex(piece))
737 }
738
739 func (cn *PeerConn) postBitfield() {
740         if cn.sentHaves.Len() != 0 {
741                 panic("bitfield must be first have-related message sent")
742         }
743         if !cn.t.haveAnyPieces() {
744                 return
745         }
746         cn.write(pp.Message{
747                 Type:     pp.Bitfield,
748                 Bitfield: cn.t.bitfield(),
749         })
750         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
751 }
752
753 // Sets a reason to update requests, and if there wasn't already one, handle it.
754 func (cn *Peer) updateRequests(reason string) {
755         if cn.needRequestUpdate != "" {
756                 return
757         }
758         if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
759                 return
760         }
761         cn.needRequestUpdate = reason
762         cn.handleUpdateRequests()
763 }
764
765 func (cn *PeerConn) handleUpdateRequests() {
766         // The writer determines the request state as needed when it can write.
767         cn.tickleWriter()
768 }
769
770 // Emits the indices in the Bitmaps bms in order, never repeating any index.
771 // skip is mutated during execution, and its initial values will never be
772 // emitted.
773 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
774         return func(cb iter.Callback) {
775                 for _, bm := range bms {
776                         if !iter.All(
777                                 func(_i interface{}) bool {
778                                         i := _i.(int)
779                                         if skip.Contains(bitmap.BitIndex(i)) {
780                                                 return true
781                                         }
782                                         skip.Add(bitmap.BitIndex(i))
783                                         return cb(i)
784                                 },
785                                 bm.Iter,
786                         ) {
787                                 return
788                         }
789                 }
790         }
791 }
792
793 func (cn *Peer) peerPiecesChanged() {
794         cn.t.maybeDropMutuallyCompletePeer(cn)
795 }
796
797 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
798         if newMin > cn.peerMinPieces {
799                 cn.peerMinPieces = newMin
800         }
801 }
802
803 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
804         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
805                 return errors.New("invalid piece")
806         }
807         if cn.peerHasPiece(piece) {
808                 return nil
809         }
810         cn.raisePeerMinPieces(piece + 1)
811         if !cn.peerHasPiece(piece) {
812                 cn.t.incPieceAvailability(piece)
813         }
814         cn._peerPieces.Add(uint32(piece))
815         if cn.t.wantPieceIndex(piece) {
816                 cn.updateRequests("have")
817         }
818         cn.peerPiecesChanged()
819         return nil
820 }
821
822 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
823         if len(bf)%8 != 0 {
824                 panic("expected bitfield length divisible by 8")
825         }
826         // We know that the last byte means that at most the last 7 bits are wasted.
827         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
828         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
829                 // Ignore known excess pieces.
830                 bf = bf[:cn.t.numPieces()]
831         }
832         bm := boolSliceToBitmap(bf)
833         if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
834                 cn.onPeerHasAllPieces()
835                 return nil
836         }
837         if !bm.IsEmpty() {
838                 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
839         }
840         shouldUpdateRequests := false
841         if cn.peerSentHaveAll {
842                 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
843                         panic(cn)
844                 }
845                 cn.peerSentHaveAll = false
846                 if !cn._peerPieces.IsEmpty() {
847                         panic("if peer has all, we expect no individual peer pieces to be set")
848                 }
849         } else {
850                 bm.Xor(&cn._peerPieces)
851         }
852         cn.peerSentHaveAll = false
853         // bm is now 'on' for pieces that are changing
854         bm.Iterate(func(x uint32) bool {
855                 pi := pieceIndex(x)
856                 if cn._peerPieces.Contains(x) {
857                         // Then we must be losing this piece
858                         cn.t.decPieceAvailability(pi)
859                 } else {
860                         if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
861                                 shouldUpdateRequests = true
862                         }
863                         // We must be gaining this piece
864                         cn.t.incPieceAvailability(pieceIndex(x))
865                 }
866                 return true
867         })
868         // Apply the changes. If we had everything previously, this should be empty, so xor is the same
869         // as or.
870         cn._peerPieces.Xor(&bm)
871         if shouldUpdateRequests {
872                 cn.updateRequests("bitfield")
873         }
874         // We didn't guard this before, I see no reason to do it now.
875         cn.peerPiecesChanged()
876         return nil
877 }
878
879 func (cn *PeerConn) onPeerHasAllPieces() {
880         t := cn.t
881         if t.haveInfo() {
882                 cn._peerPieces.Iterate(func(x uint32) bool {
883                         t.decPieceAvailability(pieceIndex(x))
884                         return true
885                 })
886         }
887         t.addConnWithAllPieces(&cn.Peer)
888         cn.peerSentHaveAll = true
889         cn._peerPieces.Clear()
890         if !cn.t._pendingPieces.IsEmpty() {
891                 cn.updateRequests("Peer.onPeerHasAllPieces")
892         }
893         cn.peerPiecesChanged()
894 }
895
896 func (cn *PeerConn) onPeerSentHaveAll() error {
897         cn.onPeerHasAllPieces()
898         return nil
899 }
900
901 func (cn *PeerConn) peerSentHaveNone() error {
902         if cn.peerSentHaveAll {
903                 cn.t.decPeerPieceAvailability(&cn.Peer)
904         }
905         cn._peerPieces.Clear()
906         cn.peerSentHaveAll = false
907         cn.peerPiecesChanged()
908         return nil
909 }
910
911 func (c *PeerConn) requestPendingMetadata() {
912         if c.t.haveInfo() {
913                 return
914         }
915         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
916                 // Peer doesn't support this.
917                 return
918         }
919         // Request metadata pieces that we don't have in a random order.
920         var pending []int
921         for index := 0; index < c.t.metadataPieceCount(); index++ {
922                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
923                         pending = append(pending, index)
924                 }
925         }
926         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
927         for _, i := range pending {
928                 c.requestMetadataPiece(i)
929         }
930 }
931
932 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
933         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
934         if msg.Type == pp.Extended {
935                 for name, id := range cn.PeerExtensionIDs {
936                         if id != msg.ExtendedID {
937                                 continue
938                         }
939                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
940                 }
941         }
942         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
943 }
944
945 // After handshake, we know what Torrent and Client stats to include for a
946 // connection.
947 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
948         t := cn.t
949         f(&t.stats)
950         f(&t.cl.stats)
951 }
952
953 // All ConnStats that include this connection. Some objects are not known
954 // until the handshake is complete, after which it's expected to reconcile the
955 // differences.
956 func (cn *Peer) allStats(f func(*ConnStats)) {
957         f(&cn._stats)
958         if cn.reconciledHandshakeStats {
959                 cn.postHandshakeStats(f)
960         }
961 }
962
963 func (cn *PeerConn) wroteBytes(n int64) {
964         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
965 }
966
967 func (cn *Peer) readBytes(n int64) {
968         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
969 }
970
971 // Returns whether the connection could be useful to us. We're seeding and
972 // they want data, we don't have metainfo and they can provide it, etc.
973 func (c *Peer) useful() bool {
974         t := c.t
975         if c.closed.IsSet() {
976                 return false
977         }
978         if !t.haveInfo() {
979                 return c.supportsExtension("ut_metadata")
980         }
981         if t.seeding() && c.peerInterested {
982                 return true
983         }
984         if c.peerHasWantedPieces() {
985                 return true
986         }
987         return false
988 }
989
990 func (c *Peer) lastHelpful() (ret time.Time) {
991         ret = c.lastUsefulChunkReceived
992         if c.t.seeding() && c.lastChunkSent.After(ret) {
993                 ret = c.lastChunkSent
994         }
995         return
996 }
997
998 func (c *PeerConn) fastEnabled() bool {
999         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
1000 }
1001
1002 func (c *PeerConn) reject(r Request) {
1003         if !c.fastEnabled() {
1004                 panic("fast not enabled")
1005         }
1006         c.write(r.ToMsg(pp.Reject))
1007         // It is possible to reject a request before it is added to peer requests due to being invalid.
1008         if state, ok := c.peerRequests[r]; ok {
1009                 state.allocReservation.Drop()
1010                 delete(c.peerRequests, r)
1011         }
1012 }
1013
1014 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
1015         uploadRateLimiter := c.t.cl.config.UploadRateLimiter
1016         if uploadRateLimiter.Limit() == rate.Inf {
1017                 return
1018         }
1019         return Some(uploadRateLimiter.Burst())
1020 }
1021
1022 // Returns whether any part of the chunk would lie outside a piece of the given length.
1023 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
1024         switch {
1025         default:
1026                 return false
1027         case cs.Begin+cs.Length > pieceLength:
1028         // Check for integer overflow
1029         case cs.Begin > pp.IntegerMax-cs.Length:
1030         }
1031         return true
1032 }
1033
1034 // startFetch is for testing purposes currently.
1035 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
1036         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
1037         if _, ok := c.peerRequests[r]; ok {
1038                 torrent.Add("duplicate requests received", 1)
1039                 if c.fastEnabled() {
1040                         return errors.New("received duplicate request with fast enabled")
1041                 }
1042                 return nil
1043         }
1044         if c.choking {
1045                 torrent.Add("requests received while choking", 1)
1046                 if c.fastEnabled() {
1047                         torrent.Add("requests rejected while choking", 1)
1048                         c.reject(r)
1049                 }
1050                 return nil
1051         }
1052         // TODO: What if they've already requested this?
1053         if len(c.peerRequests) >= localClientReqq {
1054                 torrent.Add("requests received while queue full", 1)
1055                 if c.fastEnabled() {
1056                         c.reject(r)
1057                 }
1058                 // BEP 6 says we may close here if we choose.
1059                 return nil
1060         }
1061         if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
1062                 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
1063                 c.logger.Levelf(log.Warning, err.Error())
1064                 if c.fastEnabled() {
1065                         c.reject(r)
1066                         return nil
1067                 } else {
1068                         return err
1069                 }
1070         }
1071         if !c.t.havePiece(pieceIndex(r.Index)) {
1072                 // TODO: Tell the peer we don't have the piece, and reject this request.
1073                 requestsReceivedForMissingPieces.Add(1)
1074                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1075         }
1076         pieceLength := c.t.pieceLength(pieceIndex(r.Index))
1077         // Check this after we know we have the piece, so that the piece length will be known.
1078         if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
1079                 torrent.Add("bad requests received", 1)
1080                 return errors.New("chunk overflows piece")
1081         }
1082         if c.peerRequests == nil {
1083                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1084         }
1085         value := &peerRequestState{
1086                 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
1087         }
1088         c.peerRequests[r] = value
1089         if startFetch {
1090                 // TODO: Limit peer request data read concurrency.
1091                 go c.peerRequestDataReader(r, value)
1092         }
1093         return nil
1094 }
1095
1096 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1097         b, err := c.readPeerRequestData(r, prs)
1098         c.locker().Lock()
1099         defer c.locker().Unlock()
1100         if err != nil {
1101                 c.peerRequestDataReadFailed(err, r)
1102         } else {
1103                 if b == nil {
1104                         panic("data must be non-nil to trigger send")
1105                 }
1106                 torrent.Add("peer request data read successes", 1)
1107                 prs.data = b
1108                 // This might be required for the error case too (#752 and #753).
1109                 c.tickleWriter()
1110         }
1111 }
1112
1113 // If this is maintained correctly, we might be able to support optional synchronous reading for
1114 // chunk sending, the way it used to work.
1115 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1116         torrent.Add("peer request data read failures", 1)
1117         logLevel := log.Warning
1118         if c.t.hasStorageCap() {
1119                 // It's expected that pieces might drop. See
1120                 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1121                 logLevel = log.Debug
1122         }
1123         c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1124         if c.t.closed.IsSet() {
1125                 return
1126         }
1127         i := pieceIndex(r.Index)
1128         if c.t.pieceComplete(i) {
1129                 // There used to be more code here that just duplicated the following break. Piece
1130                 // completions are currently cached, so I'm not sure how helpful this update is, except to
1131                 // pull any completion changes pushed to the storage backend in failed reads that got us
1132                 // here.
1133                 c.t.updatePieceCompletion(i)
1134         }
1135         // We've probably dropped a piece from storage, but there's no way to communicate this to the
1136         // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1137         // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1138         // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1139         // initially).
1140         if c.fastEnabled() {
1141                 c.reject(r)
1142         } else {
1143                 if c.choking {
1144                         // If fast isn't enabled, I think we would have wiped all peer requests when we last
1145                         // choked, and requests while we're choking would be ignored. It could be possible that
1146                         // a peer request data read completed concurrently to it being deleted elsewhere.
1147                         c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1148                 }
1149                 // Choking a non-fast peer should cause them to flush all their requests.
1150                 c.choke(c.write)
1151         }
1152 }
1153
1154 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
1155         // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
1156         // or fail to read and then cleanup.
1157         ctx := context.Background()
1158         err := prs.allocReservation.Wait(ctx)
1159         if err != nil {
1160                 if ctx.Err() == nil {
1161                         // The error is from the reservation itself. Something is very broken, or we're not
1162                         // guarding against excessively large requests.
1163                         err = log.WithLevel(log.Critical, err)
1164                 }
1165                 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
1166                 return nil, err
1167         }
1168         b := make([]byte, r.Length)
1169         p := c.t.info.Piece(int(r.Index))
1170         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1171         if n == len(b) {
1172                 if err == io.EOF {
1173                         err = nil
1174                 }
1175         } else {
1176                 if err == nil {
1177                         panic("expected error")
1178                 }
1179         }
1180         return b, err
1181 }
1182
1183 func runSafeExtraneous(f func()) {
1184         if true {
1185                 go f()
1186         } else {
1187                 f()
1188         }
1189 }
1190
1191 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1192         c.logger.WithContextText(fmt.Sprintf(
1193                 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1194         )).SkipCallers(1).Levelf(level, format, arg...)
1195 }
1196
1197 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1198 // exit. Returning will end the connection.
1199 func (c *PeerConn) mainReadLoop() (err error) {
1200         defer func() {
1201                 if err != nil {
1202                         torrent.Add("connection.mainReadLoop returned with error", 1)
1203                 } else {
1204                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1205                 }
1206         }()
1207         t := c.t
1208         cl := t.cl
1209
1210         decoder := pp.Decoder{
1211                 R:         bufio.NewReaderSize(c.r, 1<<17),
1212                 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
1213                 Pool:      &t.chunkPool,
1214         }
1215         for {
1216                 var msg pp.Message
1217                 func() {
1218                         cl.unlock()
1219                         defer cl.lock()
1220                         err = decoder.Decode(&msg)
1221                 }()
1222                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1223                         cb(c, &msg)
1224                 }
1225                 if t.closed.IsSet() || c.closed.IsSet() {
1226                         return nil
1227                 }
1228                 if err != nil {
1229                         return err
1230                 }
1231                 c.lastMessageReceived = time.Now()
1232                 if msg.Keepalive {
1233                         receivedKeepalives.Add(1)
1234                         continue
1235                 }
1236                 messageTypesReceived.Add(msg.Type.String(), 1)
1237                 if msg.Type.FastExtension() && !c.fastEnabled() {
1238                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1239                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1240                 }
1241                 switch msg.Type {
1242                 case pp.Choke:
1243                         if c.peerChoking {
1244                                 break
1245                         }
1246                         if !c.fastEnabled() {
1247                                 c.deleteAllRequests("choked by non-fast PeerConn")
1248                         } else {
1249                                 // We don't decrement pending requests here, let's wait for the peer to either
1250                                 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1251                                 // us and resume where they left off, we don't want to have piled on to those chunks
1252                                 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1253                                 // could let us request a lot of stuff, then choke us and never reject, but they're
1254                                 // only a single peer, our chunk balancing should smooth over this abuse.
1255                         }
1256                         c.peerChoking = true
1257                         c.updateExpectingChunks()
1258                 case pp.Unchoke:
1259                         if !c.peerChoking {
1260                                 // Some clients do this for some reason. Transmission doesn't error on this, so we
1261                                 // won't for consistency.
1262                                 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1263                                 break
1264                         }
1265                         c.peerChoking = false
1266                         preservedCount := 0
1267                         c.requestState.Requests.Iterate(func(x RequestIndex) bool {
1268                                 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
1269                                         preservedCount++
1270                                 }
1271                                 return true
1272                         })
1273                         if preservedCount != 0 {
1274                                 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1275                                 // right now.
1276                                 c.logger.Levelf(log.Debug,
1277                                         "%v requests were preserved while being choked (fast=%v)",
1278                                         preservedCount,
1279                                         c.fastEnabled())
1280
1281                                 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1282                         }
1283                         if !c.t._pendingPieces.IsEmpty() {
1284                                 c.updateRequests("unchoked")
1285                         }
1286                         c.updateExpectingChunks()
1287                 case pp.Interested:
1288                         c.peerInterested = true
1289                         c.tickleWriter()
1290                 case pp.NotInterested:
1291                         c.peerInterested = false
1292                         // We don't clear their requests since it isn't clear in the spec.
1293                         // We'll probably choke them for this, which will clear them if
1294                         // appropriate, and is clearly specified.
1295                 case pp.Have:
1296                         err = c.peerSentHave(pieceIndex(msg.Index))
1297                 case pp.Bitfield:
1298                         err = c.peerSentBitfield(msg.Bitfield)
1299                 case pp.Request:
1300                         r := newRequestFromMessage(&msg)
1301                         err = c.onReadRequest(r, true)
1302                         if err != nil {
1303                                 err = fmt.Errorf("on reading request %v: %w", r, err)
1304                         }
1305                 case pp.Piece:
1306                         c.doChunkReadStats(int64(len(msg.Piece)))
1307                         err = c.receiveChunk(&msg)
1308                         if len(msg.Piece) == int(t.chunkSize) {
1309                                 t.chunkPool.Put(&msg.Piece)
1310                         }
1311                         if err != nil {
1312                                 err = fmt.Errorf("receiving chunk: %w", err)
1313                         }
1314                 case pp.Cancel:
1315                         req := newRequestFromMessage(&msg)
1316                         c.onPeerSentCancel(req)
1317                 case pp.Port:
1318                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1319                         if !ok {
1320                                 break
1321                         }
1322                         pingAddr := net.UDPAddr{
1323                                 IP:   ipa.IP,
1324                                 Port: ipa.Port,
1325                         }
1326                         if msg.Port != 0 {
1327                                 pingAddr.Port = int(msg.Port)
1328                         }
1329                         cl.eachDhtServer(func(s DhtServer) {
1330                                 go s.Ping(&pingAddr)
1331                         })
1332                 case pp.Suggest:
1333                         torrent.Add("suggests received", 1)
1334                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
1335                         c.updateRequests("suggested")
1336                 case pp.HaveAll:
1337                         err = c.onPeerSentHaveAll()
1338                 case pp.HaveNone:
1339                         err = c.peerSentHaveNone()
1340                 case pp.Reject:
1341                         req := newRequestFromMessage(&msg)
1342                         if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
1343                                 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
1344                                 err = fmt.Errorf("received invalid reject [request=%v]", req)
1345                         }
1346                 case pp.AllowedFast:
1347                         torrent.Add("allowed fasts received", 1)
1348                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
1349                         c.updateRequests("PeerConn.mainReadLoop allowed fast")
1350                 case pp.Extended:
1351                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1352                 default:
1353                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1354                 }
1355                 if err != nil {
1356                         return err
1357                 }
1358         }
1359 }
1360
1361 // Returns true if it was valid to reject the request.
1362 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
1363         if c.deleteRequest(r) {
1364                 c.decPeakRequests()
1365         } else if !c.requestState.Cancelled.CheckedRemove(r) {
1366                 return false
1367         }
1368         if c.isLowOnRequests() {
1369                 c.updateRequests("Peer.remoteRejectedRequest")
1370         }
1371         c.decExpectedChunkReceive(r)
1372         return true
1373 }
1374
1375 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1376         count := c.validReceiveChunks[r]
1377         if count == 1 {
1378                 delete(c.validReceiveChunks, r)
1379         } else if count > 1 {
1380                 c.validReceiveChunks[r] = count - 1
1381         } else {
1382                 panic(r)
1383         }
1384 }
1385
1386 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1387         defer func() {
1388                 // TODO: Should we still do this?
1389                 if err != nil {
1390                         // These clients use their own extension IDs for outgoing message
1391                         // types, which is incorrect.
1392                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1393                                 err = nil
1394                         }
1395                 }
1396         }()
1397         t := c.t
1398         cl := t.cl
1399         switch id {
1400         case pp.HandshakeExtendedID:
1401                 var d pp.ExtendedHandshakeMessage
1402                 if err := bencode.Unmarshal(payload, &d); err != nil {
1403                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1404                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1405                 }
1406                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1407                         cb(c, &d)
1408                 }
1409                 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1410                 if d.Reqq != 0 {
1411                         c.PeerMaxRequests = d.Reqq
1412                 }
1413                 c.PeerClientName.Store(d.V)
1414                 if c.PeerExtensionIDs == nil {
1415                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1416                 }
1417                 c.PeerListenPort = d.Port
1418                 c.PeerPrefersEncryption = d.Encryption
1419                 for name, id := range d.M {
1420                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1421                                 peersSupportingExtension.Add(
1422                                         // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1423                                         // entered here which caused problems later when unmarshalling.
1424                                         strconv.Quote(string(name)),
1425                                         1)
1426                         }
1427                         c.PeerExtensionIDs[name] = id
1428                 }
1429                 if d.MetadataSize != 0 {
1430                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1431                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1432                         }
1433                 }
1434                 c.requestPendingMetadata()
1435                 if !t.cl.config.DisablePEX {
1436                         t.pex.Add(c) // we learnt enough now
1437                         c.pex.Init(c)
1438                 }
1439                 return nil
1440         case metadataExtendedId:
1441                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1442                 if err != nil {
1443                         return fmt.Errorf("handling metadata extension message: %w", err)
1444                 }
1445                 return nil
1446         case pexExtendedId:
1447                 if !c.pex.IsEnabled() {
1448                         return nil // or hang-up maybe?
1449                 }
1450                 return c.pex.Recv(payload)
1451         default:
1452                 return fmt.Errorf("unexpected extended message ID: %v", id)
1453         }
1454 }
1455
1456 // Set both the Reader and Writer for the connection from a single ReadWriter.
1457 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1458         cn.r = rw
1459         cn.w = rw
1460 }
1461
1462 // Returns the Reader and Writer as a combined ReadWriter.
1463 func (cn *PeerConn) rw() io.ReadWriter {
1464         return struct {
1465                 io.Reader
1466                 io.Writer
1467         }{cn.r, cn.w}
1468 }
1469
1470 func (c *Peer) doChunkReadStats(size int64) {
1471         c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1472 }
1473
1474 // Handle a received chunk from a peer.
1475 func (c *Peer) receiveChunk(msg *pp.Message) error {
1476         chunksReceived.Add("total", 1)
1477
1478         ppReq := newRequestFromMessage(msg)
1479         t := c.t
1480         err := t.checkValidReceiveChunk(ppReq)
1481         if err != nil {
1482                 err = log.WithLevel(log.Warning, err)
1483                 return err
1484         }
1485         req := c.t.requestIndexFromRequest(ppReq)
1486
1487         if c.bannableAddr.Ok {
1488                 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
1489         }
1490
1491         if c.peerChoking {
1492                 chunksReceived.Add("while choked", 1)
1493         }
1494
1495         if c.validReceiveChunks[req] <= 0 {
1496                 chunksReceived.Add("unexpected", 1)
1497                 return errors.New("received unexpected chunk")
1498         }
1499         c.decExpectedChunkReceive(req)
1500
1501         if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
1502                 chunksReceived.Add("due to allowed fast", 1)
1503         }
1504
1505         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1506         // have actually already received the piece, while we have the Client unlocked to write the data
1507         // out.
1508         intended := false
1509         {
1510                 if c.requestState.Requests.Contains(req) {
1511                         for _, f := range c.callbacks.ReceivedRequested {
1512                                 f(PeerMessageEvent{c, msg})
1513                         }
1514                 }
1515                 // Request has been satisfied.
1516                 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
1517                         intended = true
1518                         if !c.peerChoking {
1519                                 c._chunksReceivedWhileExpecting++
1520                         }
1521                         if c.isLowOnRequests() {
1522                                 c.updateRequests("Peer.receiveChunk deleted request")
1523                         }
1524                 } else {
1525                         chunksReceived.Add("unintended", 1)
1526                 }
1527         }
1528
1529         cl := t.cl
1530
1531         // Do we actually want this chunk?
1532         if t.haveChunk(ppReq) {
1533                 // panic(fmt.Sprintf("%+v", ppReq))
1534                 chunksReceived.Add("redundant", 1)
1535                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1536                 return nil
1537         }
1538
1539         piece := &t.pieces[ppReq.Index]
1540
1541         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1542         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1543         if intended {
1544                 c.piecesReceivedSinceLastRequestUpdate++
1545                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1546         }
1547         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1548                 f(ReceivedUsefulDataEvent{c, msg})
1549         }
1550         c.lastUsefulChunkReceived = time.Now()
1551
1552         // Need to record that it hasn't been written yet, before we attempt to do
1553         // anything with it.
1554         piece.incrementPendingWrites()
1555         // Record that we have the chunk, so we aren't trying to download it while
1556         // waiting for it to be written to storage.
1557         piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1558
1559         // Cancel pending requests for this chunk from *other* peers.
1560         if p := t.requestingPeer(req); p != nil {
1561                 if p == c {
1562                         panic("should not be pending request from conn that just received it")
1563                 }
1564                 p.cancel(req)
1565         }
1566
1567         err = func() error {
1568                 cl.unlock()
1569                 defer cl.lock()
1570                 concurrentChunkWrites.Add(1)
1571                 defer concurrentChunkWrites.Add(-1)
1572                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1573                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1574                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1575                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1576                 // that instead.
1577                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1578         }()
1579
1580         piece.decrementPendingWrites()
1581
1582         if err != nil {
1583                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1584                 t.pendRequest(req)
1585                 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1586                 // request update runs while we're writing the chunk that just failed. Then we never do a
1587                 // fresh update after pending the failed request.
1588                 c.updateRequests("Peer.receiveChunk error writing chunk")
1589                 t.onWriteChunkErr(err)
1590                 return nil
1591         }
1592
1593         c.onDirtiedPiece(pieceIndex(ppReq.Index))
1594
1595         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1596         if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1597                 t.queuePieceCheck(pieceIndex(ppReq.Index))
1598                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1599                 // chunk status (such as the haveChunk call above) to have to check all the various other
1600                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1601                 // that chunk pieces are pended at an appropriate time later however.
1602         }
1603
1604         cl.event.Broadcast()
1605         // We do this because we've written a chunk, and may change PieceState.Partial.
1606         t.publishPieceChange(pieceIndex(ppReq.Index))
1607
1608         return nil
1609 }
1610
1611 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1612         if c.peerTouchedPieces == nil {
1613                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1614         }
1615         c.peerTouchedPieces[piece] = struct{}{}
1616         ds := &c.t.pieces[piece].dirtiers
1617         if *ds == nil {
1618                 *ds = make(map[*Peer]struct{})
1619         }
1620         (*ds)[c] = struct{}{}
1621 }
1622
1623 func (c *PeerConn) uploadAllowed() bool {
1624         if c.t.cl.config.NoUpload {
1625                 return false
1626         }
1627         if c.t.dataUploadDisallowed {
1628                 return false
1629         }
1630         if c.t.seeding() {
1631                 return true
1632         }
1633         if !c.peerHasWantedPieces() {
1634                 return false
1635         }
1636         // Don't upload more than 100 KiB more than we download.
1637         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1638                 return false
1639         }
1640         return true
1641 }
1642
1643 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1644         if c.uploadTimer == nil {
1645                 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1646         } else {
1647                 c.uploadTimer.Reset(delay)
1648         }
1649 }
1650
1651 // Also handles choking and unchoking of the remote peer.
1652 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1653         // Breaking or completing this loop means we don't want to upload to the
1654         // peer anymore, and we choke them.
1655 another:
1656         for c.uploadAllowed() {
1657                 // We want to upload to the peer.
1658                 if !c.unchoke(msg) {
1659                         return false
1660                 }
1661                 for r, state := range c.peerRequests {
1662                         if state.data == nil {
1663                                 continue
1664                         }
1665                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1666                         if !res.OK() {
1667                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1668                         }
1669                         delay := res.Delay()
1670                         if delay > 0 {
1671                                 res.Cancel()
1672                                 c.setRetryUploadTimer(delay)
1673                                 // Hard to say what to return here.
1674                                 return true
1675                         }
1676                         more := c.sendChunk(r, msg, state)
1677                         delete(c.peerRequests, r)
1678                         if !more {
1679                                 return false
1680                         }
1681                         goto another
1682                 }
1683                 return true
1684         }
1685         return c.choke(msg)
1686 }
1687
1688 func (cn *PeerConn) drop() {
1689         cn.t.dropConnection(cn)
1690 }
1691
1692 func (cn *PeerConn) ban() {
1693         cn.t.cl.banPeerIP(cn.remoteIp())
1694 }
1695
1696 func (cn *Peer) netGoodPiecesDirtied() int64 {
1697         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1698 }
1699
1700 func (c *Peer) peerHasWantedPieces() bool {
1701         if all, _ := c.peerHasAllPieces(); all {
1702                 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1703         }
1704         if !c.t.haveInfo() {
1705                 return !c.peerPieces().IsEmpty()
1706         }
1707         return c.peerPieces().Intersects(&c.t._pendingPieces)
1708 }
1709
1710 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1711 // separately.
1712 func (c *Peer) deleteRequest(r RequestIndex) bool {
1713         if !c.requestState.Requests.CheckedRemove(r) {
1714                 return false
1715         }
1716         for _, f := range c.callbacks.DeletedRequest {
1717                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1718         }
1719         c.updateExpectingChunks()
1720         if c.t.requestingPeer(r) != c {
1721                 panic("only one peer should have a given request at a time")
1722         }
1723         delete(c.t.requestState, r)
1724         // c.t.iterPeers(func(p *Peer) {
1725         //      if p.isLowOnRequests() {
1726         //              p.updateRequests("Peer.deleteRequest")
1727         //      }
1728         // })
1729         return true
1730 }
1731
1732 func (c *Peer) deleteAllRequests(reason string) {
1733         if c.requestState.Requests.IsEmpty() {
1734                 return
1735         }
1736         c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1737                 if !c.deleteRequest(x) {
1738                         panic("request should exist")
1739                 }
1740                 return true
1741         })
1742         c.assertNoRequests()
1743         c.t.iterPeers(func(p *Peer) {
1744                 if p.isLowOnRequests() {
1745                         p.updateRequests(reason)
1746                 }
1747         })
1748         return
1749 }
1750
1751 func (c *Peer) assertNoRequests() {
1752         if !c.requestState.Requests.IsEmpty() {
1753                 panic(c.requestState.Requests.GetCardinality())
1754         }
1755 }
1756
1757 func (c *Peer) cancelAllRequests() {
1758         c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
1759                 c.cancel(x)
1760                 return true
1761         })
1762         c.assertNoRequests()
1763         return
1764 }
1765
1766 // This is called when something has changed that should wake the writer, such as putting stuff into
1767 // the writeBuffer, or changing some state that the writer can act on.
1768 func (c *PeerConn) tickleWriter() {
1769         c.messageWriter.writeCond.Broadcast()
1770 }
1771
1772 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1773         c.lastChunkSent = time.Now()
1774         state.allocReservation.Release()
1775         return msg(pp.Message{
1776                 Type:  pp.Piece,
1777                 Index: r.Index,
1778                 Begin: r.Begin,
1779                 Piece: state.data,
1780         })
1781 }
1782
1783 func (c *PeerConn) setTorrent(t *Torrent) {
1784         if c.t != nil {
1785                 panic("connection already associated with a torrent")
1786         }
1787         c.t = t
1788         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1789         t.reconcileHandshakeStats(c)
1790 }
1791
1792 func (c *Peer) peerPriority() (peerPriority, error) {
1793         return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
1794 }
1795
1796 func (c *Peer) remoteIp() net.IP {
1797         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1798         return net.ParseIP(host)
1799 }
1800
1801 func (c *Peer) remoteIpPort() IpPort {
1802         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1803         return IpPort{ipa.IP, uint16(ipa.Port)}
1804 }
1805
1806 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1807         f := pp.PexPeerFlags(0)
1808         if c.PeerPrefersEncryption {
1809                 f |= pp.PexPrefersEncryption
1810         }
1811         if c.outgoing {
1812                 f |= pp.PexOutgoingConn
1813         }
1814         if c.utp() {
1815                 f |= pp.PexSupportsUtp
1816         }
1817         return f
1818 }
1819
1820 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1821 // advertised listen port.
1822 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1823         if !c.outgoing && c.PeerListenPort != 0 {
1824                 switch addr := c.RemoteAddr.(type) {
1825                 case *net.TCPAddr:
1826                         dialAddr := *addr
1827                         dialAddr.Port = c.PeerListenPort
1828                         return &dialAddr
1829                 case *net.UDPAddr:
1830                         dialAddr := *addr
1831                         dialAddr.Port = c.PeerListenPort
1832                         return &dialAddr
1833                 }
1834         }
1835         return c.RemoteAddr
1836 }
1837
1838 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1839         f := c.pexPeerFlags()
1840         addr := c.dialAddr()
1841         return pexEvent{t, addr, f, nil}
1842 }
1843
1844 func (c *PeerConn) String() string {
1845         return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1846 }
1847
1848 func (c *Peer) trust() connectionTrust {
1849         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1850 }
1851
1852 type connectionTrust struct {
1853         Implicit            bool
1854         NetGoodPiecesDirted int64
1855 }
1856
1857 func (l connectionTrust) Less(r connectionTrust) bool {
1858         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1859 }
1860
1861 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1862 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1863 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1864         cn.locker().RLock()
1865         defer cn.locker().RUnlock()
1866         return cn.newPeerPieces()
1867 }
1868
1869 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1870 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1871         // TODO: Can we use copy on write?
1872         ret := cn.peerPieces().Clone()
1873         if all, _ := cn.peerHasAllPieces(); all {
1874                 if cn.t.haveInfo() {
1875                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1876                 } else {
1877                         ret.AddRange(0, bitmap.ToEnd)
1878                 }
1879         }
1880         return ret
1881 }
1882
1883 func (cn *Peer) stats() *ConnStats {
1884         return &cn._stats
1885 }
1886
1887 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1888         pc, ok := p.peerImpl.(*PeerConn)
1889         return pc, ok
1890 }
1891
1892 func (p *Peer) uncancelledRequests() uint64 {
1893         return p.requestState.Requests.GetCardinality()
1894 }
1895
1896 func (pc *PeerConn) remoteIsTransmission() bool {
1897         return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1898 }