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