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