]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Do smart banning on existing badPeerIPs
[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/log"
19         "github.com/anacrolix/missinggo/iter"
20         "github.com/anacrolix/missinggo/v2/bitmap"
21         "github.com/anacrolix/multiless"
22         "github.com/anacrolix/torrent/option"
23
24         "github.com/anacrolix/chansync"
25         "github.com/anacrolix/torrent/bencode"
26         "github.com/anacrolix/torrent/metainfo"
27         "github.com/anacrolix/torrent/mse"
28         pp "github.com/anacrolix/torrent/peer_protocol"
29         request_strategy "github.com/anacrolix/torrent/request-strategy"
30 )
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 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
53 // indexable with the memory space available.
54 type (
55         maxRequests  = int
56         requestState = request_strategy.PeerRequestState
57 )
58
59 type Peer struct {
60         // First to ensure 64-bit alignment for atomics. See #262.
61         _stats ConnStats
62
63         t *Torrent
64
65         peerImpl
66         callbacks *Callbacks
67
68         outgoing     bool
69         Network      string
70         RemoteAddr   PeerRemoteAddr
71         bannableAddr option.T[bannableAddr]
72         // True if the connection is operating over MSE obfuscation.
73         headerEncrypted bool
74         cryptoMethod    mse.CryptoMethod
75         Discovery       PeerSource
76         trusted         bool
77         closed          chansync.SetOnce
78         // Set true after we've added our ConnStats generated during handshake to
79         // other ConnStat instances as determined when the *Torrent became known.
80         reconciledHandshakeStats bool
81
82         lastMessageReceived     time.Time
83         completedHandshake      time.Time
84         lastUsefulChunkReceived time.Time
85         lastChunkSent           time.Time
86
87         // Stuff controlled by the local peer.
88         needRequestUpdate    string
89         requestState         requestState
90         updateRequestsTimer  *time.Timer
91         lastRequestUpdate    time.Time
92         peakRequests         maxRequests
93         lastBecameInterested time.Time
94         priorInterest        time.Duration
95
96         lastStartedExpectingToReceiveChunks time.Time
97         cumulativeExpectedToReceiveChunks   time.Duration
98         _chunksReceivedWhileExpecting       int64
99
100         choking                                bool
101         piecesReceivedSinceLastRequestUpdate   maxRequests
102         maxPiecesReceivedBetweenRequestUpdates maxRequests
103         // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
104         // and implementation differences, we may receive chunks that are no longer in the set of
105         // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
106         validReceiveChunks map[RequestIndex]int
107         // Indexed by metadata piece, set to true if posted and pending a
108         // response.
109         metadataRequests []bool
110         sentHaves        bitmap.Bitmap
111
112         // Stuff controlled by the remote peer.
113         peerInterested        bool
114         peerChoking           bool
115         peerRequests          map[Request]*peerRequestState
116         PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
117         PeerListenPort        int
118         // The highest possible number of pieces the torrent could have based on
119         // communication with the peer. Generally only useful until we have the
120         // torrent info.
121         peerMinPieces pieceIndex
122         // Pieces we've accepted chunks for from the peer.
123         peerTouchedPieces map[pieceIndex]struct{}
124         peerAllowedFast   roaring.Bitmap
125
126         PeerMaxRequests  maxRequests // Maximum pending requests the peer allows.
127         PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
128         PeerClientName   atomic.Value
129
130         logger log.Logger
131 }
132
133 // Maintains the state of a BitTorrent-protocol based connection with a peer.
134 type PeerConn struct {
135         Peer
136
137         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
138         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
139         connString string
140
141         // See BEP 3 etc.
142         PeerID             PeerID
143         PeerExtensionBytes pp.PeerExtensionBits
144
145         // The actual Conn, used for closing, and setting socket options. Do not use methods on this
146         // while holding any mutexes.
147         conn net.Conn
148         // The Reader and Writer for this Conn, with hooks installed for stats,
149         // limiting, deadlines etc.
150         w io.Writer
151         r io.Reader
152
153         messageWriter peerConnMsgWriter
154
155         uploadTimer *time.Timer
156         pex         pexConnState
157
158         // The pieces the peer has claimed to have.
159         _peerPieces roaring.Bitmap
160         // The peer has everything. This can occur due to a special message, when
161         // we may not even know the number of pieces in the torrent yet.
162         peerSentHaveAll bool
163 }
164
165 func (cn *PeerConn) connStatusString() string {
166         return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
167 }
168
169 func (cn *Peer) updateExpectingChunks() {
170         if cn.expectingChunks() {
171                 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
172                         cn.lastStartedExpectingToReceiveChunks = time.Now()
173                 }
174         } else {
175                 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
176                         cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
177                         cn.lastStartedExpectingToReceiveChunks = time.Time{}
178                 }
179         }
180 }
181
182 func (cn *Peer) expectingChunks() bool {
183         if cn.requestState.Requests.IsEmpty() {
184                 return false
185         }
186         if !cn.requestState.Interested {
187                 return false
188         }
189         if !cn.peerChoking {
190                 return true
191         }
192         haveAllowedFastRequests := false
193         cn.peerAllowedFast.Iterate(func(i uint32) bool {
194                 haveAllowedFastRequests = roaringBitmapRangeCardinality(
195                         &cn.requestState.Requests,
196                         cn.t.pieceRequestIndexOffset(pieceIndex(i)),
197                         cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
198                 ) == 0
199                 return !haveAllowedFastRequests
200         })
201         return haveAllowedFastRequests
202 }
203
204 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
205         return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
206 }
207
208 // Returns true if the connection is over IPv6.
209 func (cn *PeerConn) ipv6() bool {
210         ip := cn.remoteIp()
211         if ip.To4() != nil {
212                 return false
213         }
214         return len(ip) == net.IPv6len
215 }
216
217 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
218 // specification for this.
219 func (cn *PeerConn) isPreferredDirection() bool {
220         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
221 }
222
223 // Returns whether the left connection should be preferred over the right one,
224 // considering only their networking properties. If ok is false, we can't
225 // decide.
226 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
227         var ml multiless.Computation
228         ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
229         ml = ml.Bool(l.utp(), r.utp())
230         ml = ml.Bool(r.ipv6(), l.ipv6())
231         return ml.Less()
232 }
233
234 func (cn *Peer) cumInterest() time.Duration {
235         ret := cn.priorInterest
236         if cn.requestState.Interested {
237                 ret += time.Since(cn.lastBecameInterested)
238         }
239         return ret
240 }
241
242 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
243         if cn.peerSentHaveAll {
244                 return true, true
245         }
246         if !cn.t.haveInfo() {
247                 return false, false
248         }
249         return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
250 }
251
252 func (cn *Peer) locker() *lockWithDeferreds {
253         return cn.t.cl.locker()
254 }
255
256 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
257         _, ok := cn.PeerExtensionIDs[ext]
258         return ok
259 }
260
261 // The best guess at number of pieces in the torrent for this peer.
262 func (cn *Peer) bestPeerNumPieces() pieceIndex {
263         if cn.t.haveInfo() {
264                 return cn.t.numPieces()
265         }
266         return cn.peerMinPieces
267 }
268
269 func (cn *Peer) completedString() string {
270         have := pieceIndex(cn.peerPieces().GetCardinality())
271         if all, _ := cn.peerHasAllPieces(); all {
272                 have = cn.bestPeerNumPieces()
273         }
274         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
275 }
276
277 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
278         cn.setNumPieces(info.NumPieces())
279 }
280
281 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
282 // receiving badly sized BITFIELD, or invalid HAVE messages.
283 func (cn *PeerConn) setNumPieces(num pieceIndex) {
284         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
285         cn.peerPiecesChanged()
286 }
287
288 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
289         return &cn._peerPieces
290 }
291
292 func eventAgeString(t time.Time) string {
293         if t.IsZero() {
294                 return "never"
295         }
296         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
297 }
298
299 func (cn *PeerConn) connectionFlags() (ret string) {
300         c := func(b byte) {
301                 ret += string([]byte{b})
302         }
303         if cn.cryptoMethod == mse.CryptoMethodRC4 {
304                 c('E')
305         } else if cn.headerEncrypted {
306                 c('e')
307         }
308         ret += string(cn.Discovery)
309         if cn.utp() {
310                 c('U')
311         }
312         return
313 }
314
315 func (cn *PeerConn) utp() bool {
316         return parseNetworkString(cn.Network).Udp
317 }
318
319 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
320 func (cn *Peer) statusFlags() (ret string) {
321         c := func(b byte) {
322                 ret += string([]byte{b})
323         }
324         if cn.requestState.Interested {
325                 c('i')
326         }
327         if cn.choking {
328                 c('c')
329         }
330         c('-')
331         ret += cn.connectionFlags()
332         c('-')
333         if cn.peerInterested {
334                 c('i')
335         }
336         if cn.peerChoking {
337                 c('c')
338         }
339         return
340 }
341
342 func (cn *Peer) downloadRate() float64 {
343         num := cn._stats.BytesReadUsefulData.Int64()
344         if num == 0 {
345                 return 0
346         }
347         return float64(num) / cn.totalExpectingTime().Seconds()
348 }
349
350 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
351         ret = make(map[pieceIndex]int)
352         cn.requestState.Requests.Iterate(func(x uint32) bool {
353                 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
354                 return true
355         })
356         return
357 }
358
359 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
360         // \t isn't preserved in <pre> blocks?
361         if cn.closed.IsSet() {
362                 fmt.Fprint(w, "CLOSED: ")
363         }
364         fmt.Fprintln(w, cn.connStatusString())
365         prio, err := cn.peerPriority()
366         prioStr := fmt.Sprintf("%08x", prio)
367         if err != nil {
368                 prioStr += ": " + err.Error()
369         }
370         fmt.Fprintf(w, "    bep40-prio: %v\n", prioStr)
371         fmt.Fprintf(w, "    last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
372                 eventAgeString(cn.lastMessageReceived),
373                 eventAgeString(cn.completedHandshake),
374                 eventAgeString(cn.lastHelpful()),
375                 cn.cumInterest(),
376                 cn.totalExpectingTime(),
377         )
378         fmt.Fprintf(w,
379                 "    %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
380                 cn.completedString(),
381                 len(cn.peerTouchedPieces),
382                 &cn._stats.ChunksReadUseful,
383                 &cn._stats.ChunksRead,
384                 &cn._stats.ChunksWritten,
385                 cn.requestState.Requests.GetCardinality(),
386                 cn.requestState.Cancelled.GetCardinality(),
387                 cn.nominalMaxRequests(),
388                 cn.PeerMaxRequests,
389                 len(cn.peerRequests),
390                 localClientReqq,
391                 cn.statusFlags(),
392                 cn.downloadRate()/(1<<10),
393         )
394         fmt.Fprintf(w, "    requested pieces:")
395         type pieceNumRequestsType struct {
396                 piece       pieceIndex
397                 numRequests int
398         }
399         var pieceNumRequests []pieceNumRequestsType
400         for piece, count := range cn.numRequestsByPiece() {
401                 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
402         }
403         sort.Slice(pieceNumRequests, func(i, j int) bool {
404                 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
405         })
406         for _, elem := range pieceNumRequests {
407                 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
408         }
409         fmt.Fprintf(w, "\n")
410 }
411
412 func (p *Peer) close() {
413         if !p.closed.Set() {
414                 return
415         }
416         if p.updateRequestsTimer != nil {
417                 p.updateRequestsTimer.Stop()
418         }
419         p.peerImpl.onClose()
420         if p.t != nil {
421                 p.t.decPeerPieceAvailability(p)
422         }
423         for _, f := range p.callbacks.PeerClosed {
424                 f(p)
425         }
426 }
427
428 func (cn *PeerConn) onClose() {
429         if cn.pex.IsEnabled() {
430                 cn.pex.Close()
431         }
432         cn.tickleWriter()
433         if cn.conn != nil {
434                 go cn.conn.Close()
435         }
436         if cb := cn.callbacks.PeerConnClosed; cb != nil {
437                 cb(cn)
438         }
439 }
440
441 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
442 // they do (known=true).
443 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
444         if all, known := cn.peerHasAllPieces(); all && known {
445                 return true
446         }
447         return cn.peerPieces().ContainsInt(piece)
448 }
449
450 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
451 // https://github.com/pion/datachannel/issues/59 is fixed.
452 const (
453         writeBufferHighWaterLen = 1 << 15
454         writeBufferLowWaterLen  = writeBufferHighWaterLen / 2
455 )
456
457 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
458 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
459 func (cn *PeerConn) write(msg pp.Message) bool {
460         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
461         // We don't need to track bytes here because the connection's Writer has that behaviour injected
462         // (although there's some delay between us buffering the message, and the connection writer
463         // flushing it out.).
464         notFull := cn.messageWriter.write(msg)
465         // Last I checked only Piece messages affect stats, and we don't write those.
466         cn.wroteMsg(&msg)
467         cn.tickleWriter()
468         return notFull
469 }
470
471 func (cn *PeerConn) requestMetadataPiece(index int) {
472         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
473         if eID == pp.ExtensionDeleteNumber {
474                 return
475         }
476         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
477                 return
478         }
479         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
480         cn.write(pp.MetadataExtensionRequestMsg(eID, index))
481         for index >= len(cn.metadataRequests) {
482                 cn.metadataRequests = append(cn.metadataRequests, false)
483         }
484         cn.metadataRequests[index] = true
485 }
486
487 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
488         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
489 }
490
491 var (
492         interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
493         requestMsgLen    = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
494         // This is the maximum request count that could fit in the write buffer if it's at or below the
495         // low water mark when we run maybeUpdateActualRequestState.
496         maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
497 )
498
499 // The actual value to use as the maximum outbound requests.
500 func (cn *Peer) nominalMaxRequests() maxRequests {
501         return maxRequests(maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests)))
502 }
503
504 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
505         ret = cn.cumulativeExpectedToReceiveChunks
506         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
507                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
508         }
509         return
510 }
511
512 func (cn *PeerConn) onPeerSentCancel(r Request) {
513         if _, ok := cn.peerRequests[r]; !ok {
514                 torrent.Add("unexpected cancels received", 1)
515                 return
516         }
517         if cn.fastEnabled() {
518                 cn.reject(r)
519         } else {
520                 delete(cn.peerRequests, r)
521         }
522 }
523
524 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
525         if cn.choking {
526                 return true
527         }
528         cn.choking = true
529         more = msg(pp.Message{
530                 Type: pp.Choke,
531         })
532         if !cn.fastEnabled() {
533                 cn.peerRequests = nil
534         }
535         return
536 }
537
538 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
539         if !cn.choking {
540                 return true
541         }
542         cn.choking = false
543         return msg(pp.Message{
544                 Type: pp.Unchoke,
545         })
546 }
547
548 func (cn *Peer) setInterested(interested bool) bool {
549         if cn.requestState.Interested == interested {
550                 return true
551         }
552         cn.requestState.Interested = interested
553         if interested {
554                 cn.lastBecameInterested = time.Now()
555         } else if !cn.lastBecameInterested.IsZero() {
556                 cn.priorInterest += time.Since(cn.lastBecameInterested)
557         }
558         cn.updateExpectingChunks()
559         // log.Printf("%p: setting interest: %v", cn, interested)
560         return cn.writeInterested(interested)
561 }
562
563 func (pc *PeerConn) writeInterested(interested bool) bool {
564         return pc.write(pp.Message{
565                 Type: func() pp.MessageType {
566                         if interested {
567                                 return pp.Interested
568                         } else {
569                                 return pp.NotInterested
570                         }
571                 }(),
572         })
573 }
574
575 // The function takes a message to be sent, and returns true if more messages
576 // are okay.
577 type messageWriter func(pp.Message) bool
578
579 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
580 // when we want to go fast.
581 func (cn *Peer) shouldRequest(r RequestIndex) error {
582         pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
583         if cn.requestState.Cancelled.Contains(r) {
584                 return errors.New("request is cancelled and waiting acknowledgement")
585         }
586         if !cn.peerHasPiece(pi) {
587                 return errors.New("requesting piece peer doesn't have")
588         }
589         if !cn.t.peerIsActive(cn) {
590                 panic("requesting but not in active conns")
591         }
592         if cn.closed.IsSet() {
593                 panic("requesting when connection is closed")
594         }
595         if cn.t.hashingPiece(pi) {
596                 panic("piece is being hashed")
597         }
598         if cn.t.pieceQueuedForHash(pi) {
599                 panic("piece is queued for hash")
600         }
601         if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
602                 // This could occur if we made a request with the fast extension, and then got choked and
603                 // haven't had the request rejected yet.
604                 if !cn.requestState.Requests.Contains(r) {
605                         panic("peer choking and piece not allowed fast")
606                 }
607         }
608         return nil
609 }
610
611 func (cn *Peer) mustRequest(r RequestIndex) bool {
612         more, err := cn.request(r)
613         if err != nil {
614                 panic(err)
615         }
616         return more
617 }
618
619 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
620         if err := cn.shouldRequest(r); err != nil {
621                 panic(err)
622         }
623         if cn.requestState.Requests.Contains(r) {
624                 return true, nil
625         }
626         if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
627                 return true, errors.New("too many outstanding requests")
628         }
629         cn.requestState.Requests.Add(r)
630         if cn.validReceiveChunks == nil {
631                 cn.validReceiveChunks = make(map[RequestIndex]int)
632         }
633         cn.validReceiveChunks[r]++
634         cn.t.pendingRequests[r] = cn
635         cn.t.lastRequested[r] = time.Now()
636         cn.updateExpectingChunks()
637         ppReq := cn.t.requestIndexToRequest(r)
638         for _, f := range cn.callbacks.SentRequest {
639                 f(PeerRequestEvent{cn, ppReq})
640         }
641         return cn.peerImpl._request(ppReq), nil
642 }
643
644 func (me *PeerConn) _request(r Request) bool {
645         return me.write(pp.Message{
646                 Type:   pp.Request,
647                 Index:  r.Index,
648                 Begin:  r.Begin,
649                 Length: r.Length,
650         })
651 }
652
653 func (me *Peer) cancel(r RequestIndex) {
654         if !me.deleteRequest(r) {
655                 panic("request not existing should have been guarded")
656         }
657         if me._cancel(r) {
658                 if !me.requestState.Cancelled.CheckedAdd(r) {
659                         panic("request already cancelled")
660                 }
661         }
662         me.decPeakRequests()
663         if me.isLowOnRequests() {
664                 me.updateRequests("Peer.cancel")
665         }
666 }
667
668 func (me *PeerConn) _cancel(r RequestIndex) bool {
669         me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
670         // Transmission does not send rejects for received cancels. See
671         // https://github.com/transmission/transmission/pull/2275.
672         return me.fastEnabled() && !me.remoteIsTransmission()
673 }
674
675 func (cn *PeerConn) fillWriteBuffer() {
676         if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
677                 // Fully committing to our max requests requires sufficient space (see
678                 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
679                 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
680                 // request reason will not be cleared, so we'll come right back here when there's space. We
681                 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
682                 // knowledge of write buffers.
683         }
684         cn.maybeUpdateActualRequestState()
685         if cn.pex.IsEnabled() {
686                 if flow := cn.pex.Share(cn.write); !flow {
687                         return
688                 }
689         }
690         cn.upload(cn.write)
691 }
692
693 func (cn *PeerConn) have(piece pieceIndex) {
694         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
695                 return
696         }
697         cn.write(pp.Message{
698                 Type:  pp.Have,
699                 Index: pp.Integer(piece),
700         })
701         cn.sentHaves.Add(bitmap.BitIndex(piece))
702 }
703
704 func (cn *PeerConn) postBitfield() {
705         if cn.sentHaves.Len() != 0 {
706                 panic("bitfield must be first have-related message sent")
707         }
708         if !cn.t.haveAnyPieces() {
709                 return
710         }
711         cn.write(pp.Message{
712                 Type:     pp.Bitfield,
713                 Bitfield: cn.t.bitfield(),
714         })
715         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
716 }
717
718 // Sets a reason to update requests, and if there wasn't already one, handle it.
719 func (cn *Peer) updateRequests(reason string) {
720         if cn.needRequestUpdate != "" {
721                 return
722         }
723         if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
724                 return
725         }
726         cn.needRequestUpdate = reason
727         cn.handleUpdateRequests()
728 }
729
730 func (cn *PeerConn) handleUpdateRequests() {
731         // The writer determines the request state as needed when it can write.
732         cn.tickleWriter()
733 }
734
735 // Emits the indices in the Bitmaps bms in order, never repeating any index.
736 // skip is mutated during execution, and its initial values will never be
737 // emitted.
738 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
739         return func(cb iter.Callback) {
740                 for _, bm := range bms {
741                         if !iter.All(
742                                 func(_i interface{}) bool {
743                                         i := _i.(int)
744                                         if skip.Contains(bitmap.BitIndex(i)) {
745                                                 return true
746                                         }
747                                         skip.Add(bitmap.BitIndex(i))
748                                         return cb(i)
749                                 },
750                                 bm.Iter,
751                         ) {
752                                 return
753                         }
754                 }
755         }
756 }
757
758 func (cn *Peer) peerPiecesChanged() {
759         cn.t.maybeDropMutuallyCompletePeer(cn)
760 }
761
762 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
763         if newMin > cn.peerMinPieces {
764                 cn.peerMinPieces = newMin
765         }
766 }
767
768 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
769         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
770                 return errors.New("invalid piece")
771         }
772         if cn.peerHasPiece(piece) {
773                 return nil
774         }
775         cn.raisePeerMinPieces(piece + 1)
776         if !cn.peerHasPiece(piece) {
777                 cn.t.incPieceAvailability(piece)
778         }
779         cn._peerPieces.Add(uint32(piece))
780         if cn.t.wantPieceIndex(piece) {
781                 cn.updateRequests("have")
782         }
783         cn.peerPiecesChanged()
784         return nil
785 }
786
787 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
788         if len(bf)%8 != 0 {
789                 panic("expected bitfield length divisible by 8")
790         }
791         // We know that the last byte means that at most the last 7 bits are wasted.
792         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
793         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
794                 // Ignore known excess pieces.
795                 bf = bf[:cn.t.numPieces()]
796         }
797         bm := boolSliceToBitmap(bf)
798         if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
799                 cn.onPeerHasAllPieces()
800                 return nil
801         }
802         if !bm.IsEmpty() {
803                 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
804         }
805         shouldUpdateRequests := false
806         if cn.peerSentHaveAll {
807                 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
808                         panic(cn)
809                 }
810                 cn.peerSentHaveAll = false
811                 if !cn._peerPieces.IsEmpty() {
812                         panic("if peer has all, we expect no individual peer pieces to be set")
813                 }
814         } else {
815                 bm.Xor(&cn._peerPieces)
816         }
817         cn.peerSentHaveAll = false
818         // bm is now 'on' for pieces that are changing
819         bm.Iterate(func(x uint32) bool {
820                 pi := pieceIndex(x)
821                 if cn._peerPieces.Contains(x) {
822                         // Then we must be losing this piece
823                         cn.t.decPieceAvailability(pi)
824                 } else {
825                         if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
826                                 shouldUpdateRequests = true
827                         }
828                         // We must be gaining this piece
829                         cn.t.incPieceAvailability(pieceIndex(x))
830                 }
831                 return true
832         })
833         // Apply the changes. If we had everything previously, this should be empty, so xor is the same
834         // as or.
835         cn._peerPieces.Xor(&bm)
836         if shouldUpdateRequests {
837                 cn.updateRequests("bitfield")
838         }
839         // We didn't guard this before, I see no reason to do it now.
840         cn.peerPiecesChanged()
841         return nil
842 }
843
844 func (cn *PeerConn) onPeerHasAllPieces() {
845         t := cn.t
846         if t.haveInfo() {
847                 cn._peerPieces.Iterate(func(x uint32) bool {
848                         t.decPieceAvailability(pieceIndex(x))
849                         return true
850                 })
851         }
852         t.addConnWithAllPieces(&cn.Peer)
853         cn.peerSentHaveAll = true
854         cn._peerPieces.Clear()
855         if !cn.t._pendingPieces.IsEmpty() {
856                 cn.updateRequests("Peer.onPeerHasAllPieces")
857         }
858         cn.peerPiecesChanged()
859 }
860
861 func (cn *PeerConn) onPeerSentHaveAll() error {
862         cn.onPeerHasAllPieces()
863         return nil
864 }
865
866 func (cn *PeerConn) peerSentHaveNone() error {
867         if cn.peerSentHaveAll {
868                 cn.t.decPeerPieceAvailability(&cn.Peer)
869         }
870         cn._peerPieces.Clear()
871         cn.peerSentHaveAll = false
872         cn.peerPiecesChanged()
873         return nil
874 }
875
876 func (c *PeerConn) requestPendingMetadata() {
877         if c.t.haveInfo() {
878                 return
879         }
880         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
881                 // Peer doesn't support this.
882                 return
883         }
884         // Request metadata pieces that we don't have in a random order.
885         var pending []int
886         for index := 0; index < c.t.metadataPieceCount(); index++ {
887                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
888                         pending = append(pending, index)
889                 }
890         }
891         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
892         for _, i := range pending {
893                 c.requestMetadataPiece(i)
894         }
895 }
896
897 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
898         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
899         if msg.Type == pp.Extended {
900                 for name, id := range cn.PeerExtensionIDs {
901                         if id != msg.ExtendedID {
902                                 continue
903                         }
904                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
905                 }
906         }
907         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
908 }
909
910 // After handshake, we know what Torrent and Client stats to include for a
911 // connection.
912 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
913         t := cn.t
914         f(&t.stats)
915         f(&t.cl.stats)
916 }
917
918 // All ConnStats that include this connection. Some objects are not known
919 // until the handshake is complete, after which it's expected to reconcile the
920 // differences.
921 func (cn *Peer) allStats(f func(*ConnStats)) {
922         f(&cn._stats)
923         if cn.reconciledHandshakeStats {
924                 cn.postHandshakeStats(f)
925         }
926 }
927
928 func (cn *PeerConn) wroteBytes(n int64) {
929         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
930 }
931
932 func (cn *Peer) readBytes(n int64) {
933         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
934 }
935
936 // Returns whether the connection could be useful to us. We're seeding and
937 // they want data, we don't have metainfo and they can provide it, etc.
938 func (c *Peer) useful() bool {
939         t := c.t
940         if c.closed.IsSet() {
941                 return false
942         }
943         if !t.haveInfo() {
944                 return c.supportsExtension("ut_metadata")
945         }
946         if t.seeding() && c.peerInterested {
947                 return true
948         }
949         if c.peerHasWantedPieces() {
950                 return true
951         }
952         return false
953 }
954
955 func (c *Peer) lastHelpful() (ret time.Time) {
956         ret = c.lastUsefulChunkReceived
957         if c.t.seeding() && c.lastChunkSent.After(ret) {
958                 ret = c.lastChunkSent
959         }
960         return
961 }
962
963 func (c *PeerConn) fastEnabled() bool {
964         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
965 }
966
967 func (c *PeerConn) reject(r Request) {
968         if !c.fastEnabled() {
969                 panic("fast not enabled")
970         }
971         c.write(r.ToMsg(pp.Reject))
972         delete(c.peerRequests, r)
973 }
974
975 func (c *PeerConn) onReadRequest(r Request) error {
976         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
977         if _, ok := c.peerRequests[r]; ok {
978                 torrent.Add("duplicate requests received", 1)
979                 return nil
980         }
981         if c.choking {
982                 torrent.Add("requests received while choking", 1)
983                 if c.fastEnabled() {
984                         torrent.Add("requests rejected while choking", 1)
985                         c.reject(r)
986                 }
987                 return nil
988         }
989         // TODO: What if they've already requested this?
990         if len(c.peerRequests) >= localClientReqq {
991                 torrent.Add("requests received while queue full", 1)
992                 if c.fastEnabled() {
993                         c.reject(r)
994                 }
995                 // BEP 6 says we may close here if we choose.
996                 return nil
997         }
998         if !c.t.havePiece(pieceIndex(r.Index)) {
999                 // This isn't necessarily them screwing up. We can drop pieces
1000                 // from our storage, and can't communicate this to peers
1001                 // except by reconnecting.
1002                 requestsReceivedForMissingPieces.Add(1)
1003                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
1004         }
1005         // Check this after we know we have the piece, so that the piece length will be known.
1006         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
1007                 torrent.Add("bad requests received", 1)
1008                 return errors.New("bad Request")
1009         }
1010         if c.peerRequests == nil {
1011                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
1012         }
1013         value := &peerRequestState{}
1014         c.peerRequests[r] = value
1015         go c.peerRequestDataReader(r, value)
1016         return nil
1017 }
1018
1019 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
1020         b, err := readPeerRequestData(r, c)
1021         c.locker().Lock()
1022         defer c.locker().Unlock()
1023         if err != nil {
1024                 c.peerRequestDataReadFailed(err, r)
1025         } else {
1026                 if b == nil {
1027                         panic("data must be non-nil to trigger send")
1028                 }
1029                 torrent.Add("peer request data read successes", 1)
1030                 prs.data = b
1031                 c.tickleWriter()
1032         }
1033 }
1034
1035 // If this is maintained correctly, we might be able to support optional synchronous reading for
1036 // chunk sending, the way it used to work.
1037 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1038         torrent.Add("peer request data read failures", 1)
1039         logLevel := log.Warning
1040         if c.t.hasStorageCap() {
1041                 // It's expected that pieces might drop. See
1042                 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
1043                 logLevel = log.Debug
1044         }
1045         c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
1046         if c.t.closed.IsSet() {
1047                 return
1048         }
1049         i := pieceIndex(r.Index)
1050         if c.t.pieceComplete(i) {
1051                 // There used to be more code here that just duplicated the following break. Piece
1052                 // completions are currently cached, so I'm not sure how helpful this update is, except to
1053                 // pull any completion changes pushed to the storage backend in failed reads that got us
1054                 // here.
1055                 c.t.updatePieceCompletion(i)
1056         }
1057         // We've probably dropped a piece from storage, but there's no way to communicate this to the
1058         // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
1059         // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
1060         // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
1061         // initially).
1062         if c.fastEnabled() {
1063                 c.reject(r)
1064         } else {
1065                 if c.choking {
1066                         // If fast isn't enabled, I think we would have wiped all peer requests when we last
1067                         // choked, and requests while we're choking would be ignored. It could be possible that
1068                         // a peer request data read completed concurrently to it being deleted elsewhere.
1069                         c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1070                 }
1071                 // Choking a non-fast peer should cause them to flush all their requests.
1072                 c.choke(c.write)
1073         }
1074 }
1075
1076 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1077         b := make([]byte, r.Length)
1078         p := c.t.info.Piece(int(r.Index))
1079         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1080         if n == len(b) {
1081                 if err == io.EOF {
1082                         err = nil
1083                 }
1084         } else {
1085                 if err == nil {
1086                         panic("expected error")
1087                 }
1088         }
1089         return b, err
1090 }
1091
1092 func runSafeExtraneous(f func()) {
1093         if true {
1094                 go f()
1095         } else {
1096                 f()
1097         }
1098 }
1099
1100 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1101         c.logger.WithLevel(level).WithContextText(fmt.Sprintf(
1102                 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1103         )).SkipCallers(1).Printf(format, arg...)
1104 }
1105
1106 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1107 // exit. Returning will end the connection.
1108 func (c *PeerConn) mainReadLoop() (err error) {
1109         defer func() {
1110                 if err != nil {
1111                         torrent.Add("connection.mainReadLoop returned with error", 1)
1112                 } else {
1113                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1114                 }
1115         }()
1116         t := c.t
1117         cl := t.cl
1118
1119         decoder := pp.Decoder{
1120                 R:         bufio.NewReaderSize(c.r, 1<<17),
1121                 MaxLength: 256 * 1024,
1122                 Pool:      &t.chunkPool,
1123         }
1124         for {
1125                 var msg pp.Message
1126                 func() {
1127                         cl.unlock()
1128                         defer cl.lock()
1129                         err = decoder.Decode(&msg)
1130                 }()
1131                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1132                         cb(c, &msg)
1133                 }
1134                 if t.closed.IsSet() || c.closed.IsSet() {
1135                         return nil
1136                 }
1137                 if err != nil {
1138                         return err
1139                 }
1140                 c.lastMessageReceived = time.Now()
1141                 if msg.Keepalive {
1142                         receivedKeepalives.Add(1)
1143                         continue
1144                 }
1145                 messageTypesReceived.Add(msg.Type.String(), 1)
1146                 if msg.Type.FastExtension() && !c.fastEnabled() {
1147                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1148                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1149                 }
1150                 switch msg.Type {
1151                 case pp.Choke:
1152                         if c.peerChoking {
1153                                 break
1154                         }
1155                         if !c.fastEnabled() {
1156                                 if !c.deleteAllRequests().IsEmpty() {
1157                                         c.t.iterPeers(func(p *Peer) {
1158                                                 if p.isLowOnRequests() {
1159                                                         p.updateRequests("choked by non-fast PeerConn")
1160                                                 }
1161                                         })
1162                                 }
1163                         } else {
1164                                 // We don't decrement pending requests here, let's wait for the peer to either
1165                                 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
1166                                 // us and resume where they left off, we don't want to have piled on to those chunks
1167                                 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
1168                                 // could let us request a lot of stuff, then choke us and never reject, but they're
1169                                 // only a single peer, our chunk balancing should smooth over this abuse.
1170                         }
1171                         c.peerChoking = true
1172                         c.updateExpectingChunks()
1173                 case pp.Unchoke:
1174                         if !c.peerChoking {
1175                                 // Some clients do this for some reason. Transmission doesn't error on this, so we
1176                                 // won't for consistency.
1177                                 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1178                                 break
1179                         }
1180                         c.peerChoking = false
1181                         preservedCount := 0
1182                         c.requestState.Requests.Iterate(func(x uint32) bool {
1183                                 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1184                                         preservedCount++
1185                                 }
1186                                 return true
1187                         })
1188                         if preservedCount != 0 {
1189                                 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1190                                 // right now.
1191                                 c.logger.WithLevel(log.Debug).Printf(
1192                                         "%v requests were preserved while being choked (fast=%v)",
1193                                         preservedCount,
1194                                         c.fastEnabled())
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).SetLevel(log.Debug).Log(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).SetLevel(log.Debug).Log(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 *Peer) netGoodPiecesDirtied() int64 {
1599         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1600 }
1601
1602 func (c *Peer) peerHasWantedPieces() bool {
1603         if all, _ := c.peerHasAllPieces(); all {
1604                 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1605         }
1606         if !c.t.haveInfo() {
1607                 return !c.peerPieces().IsEmpty()
1608         }
1609         return c.peerPieces().Intersects(&c.t._pendingPieces)
1610 }
1611
1612 // Returns true if an outstanding request is removed. Cancelled requests should be handled
1613 // separately.
1614 func (c *Peer) deleteRequest(r RequestIndex) bool {
1615         if !c.requestState.Requests.CheckedRemove(r) {
1616                 return false
1617         }
1618         for _, f := range c.callbacks.DeletedRequest {
1619                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1620         }
1621         c.updateExpectingChunks()
1622         if c.t.requestingPeer(r) != c {
1623                 panic("only one peer should have a given request at a time")
1624         }
1625         delete(c.t.pendingRequests, r)
1626         delete(c.t.lastRequested, r)
1627         // c.t.iterPeers(func(p *Peer) {
1628         //      if p.isLowOnRequests() {
1629         //              p.updateRequests("Peer.deleteRequest")
1630         //      }
1631         // })
1632         return true
1633 }
1634
1635 func (c *Peer) deleteAllRequests() (deleted *roaring.Bitmap) {
1636         deleted = c.requestState.Requests.Clone()
1637         deleted.Iterate(func(x uint32) bool {
1638                 if !c.deleteRequest(x) {
1639                         panic("request should exist")
1640                 }
1641                 return true
1642         })
1643         c.assertNoRequests()
1644         return
1645 }
1646
1647 func (c *Peer) assertNoRequests() {
1648         if !c.requestState.Requests.IsEmpty() {
1649                 panic(c.requestState.Requests.GetCardinality())
1650         }
1651 }
1652
1653 func (c *Peer) cancelAllRequests() (cancelled *roaring.Bitmap) {
1654         cancelled = c.requestState.Requests.Clone()
1655         cancelled.Iterate(func(x uint32) bool {
1656                 c.cancel(x)
1657                 return true
1658         })
1659         c.assertNoRequests()
1660         return
1661 }
1662
1663 // This is called when something has changed that should wake the writer, such as putting stuff into
1664 // the writeBuffer, or changing some state that the writer can act on.
1665 func (c *PeerConn) tickleWriter() {
1666         c.messageWriter.writeCond.Broadcast()
1667 }
1668
1669 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1670         c.lastChunkSent = time.Now()
1671         return msg(pp.Message{
1672                 Type:  pp.Piece,
1673                 Index: r.Index,
1674                 Begin: r.Begin,
1675                 Piece: state.data,
1676         })
1677 }
1678
1679 func (c *PeerConn) setTorrent(t *Torrent) {
1680         if c.t != nil {
1681                 panic("connection already associated with a torrent")
1682         }
1683         c.t = t
1684         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1685         t.reconcileHandshakeStats(c)
1686 }
1687
1688 func (c *Peer) peerPriority() (peerPriority, error) {
1689         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1690 }
1691
1692 func (c *Peer) remoteIp() net.IP {
1693         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1694         return net.ParseIP(host)
1695 }
1696
1697 func (c *Peer) remoteIpPort() IpPort {
1698         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1699         return IpPort{ipa.IP, uint16(ipa.Port)}
1700 }
1701
1702 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1703         f := pp.PexPeerFlags(0)
1704         if c.PeerPrefersEncryption {
1705                 f |= pp.PexPrefersEncryption
1706         }
1707         if c.outgoing {
1708                 f |= pp.PexOutgoingConn
1709         }
1710         if c.utp() {
1711                 f |= pp.PexSupportsUtp
1712         }
1713         return f
1714 }
1715
1716 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1717 // advertised listen port.
1718 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1719         if !c.outgoing && c.PeerListenPort != 0 {
1720                 switch addr := c.RemoteAddr.(type) {
1721                 case *net.TCPAddr:
1722                         dialAddr := *addr
1723                         dialAddr.Port = c.PeerListenPort
1724                         return &dialAddr
1725                 case *net.UDPAddr:
1726                         dialAddr := *addr
1727                         dialAddr.Port = c.PeerListenPort
1728                         return &dialAddr
1729                 }
1730         }
1731         return c.RemoteAddr
1732 }
1733
1734 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1735         f := c.pexPeerFlags()
1736         addr := c.dialAddr()
1737         return pexEvent{t, addr, f, nil}
1738 }
1739
1740 func (c *PeerConn) String() string {
1741         return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1742 }
1743
1744 func (c *Peer) trust() connectionTrust {
1745         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1746 }
1747
1748 type connectionTrust struct {
1749         Implicit            bool
1750         NetGoodPiecesDirted int64
1751 }
1752
1753 func (l connectionTrust) Less(r connectionTrust) bool {
1754         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1755 }
1756
1757 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1758 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1759 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1760         cn.locker().RLock()
1761         defer cn.locker().RUnlock()
1762         return cn.newPeerPieces()
1763 }
1764
1765 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1766 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1767         // TODO: Can we use copy on write?
1768         ret := cn.peerPieces().Clone()
1769         if all, _ := cn.peerHasAllPieces(); all {
1770                 if cn.t.haveInfo() {
1771                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1772                 } else {
1773                         ret.AddRange(0, bitmap.ToEnd)
1774                 }
1775         }
1776         return ret
1777 }
1778
1779 func (cn *Peer) stats() *ConnStats {
1780         return &cn._stats
1781 }
1782
1783 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1784         pc, ok := p.peerImpl.(*PeerConn)
1785         return pc, ok
1786 }
1787
1788 func (p *Peer) uncancelledRequests() uint64 {
1789         return p.requestState.Requests.GetCardinality()
1790 }
1791
1792 func (pc *PeerConn) remoteIsTransmission() bool {
1793         return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1794 }