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