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