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