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