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