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