]> Sergey Matveev's repositories - btrtrc.git/blob - peer.go
Add envpprof to issue-930 test
[btrtrc.git] / peer.go
1 package torrent
2
3 import (
4         "errors"
5         "fmt"
6         "io"
7         "net"
8         "strings"
9         "sync"
10         "time"
11
12         "github.com/RoaringBitmap/roaring"
13         "github.com/anacrolix/chansync"
14         . "github.com/anacrolix/generics"
15         "github.com/anacrolix/log"
16         "github.com/anacrolix/missinggo/iter"
17         "github.com/anacrolix/missinggo/v2/bitmap"
18         "github.com/anacrolix/multiless"
19
20         "github.com/anacrolix/torrent/internal/alloclim"
21         "github.com/anacrolix/torrent/mse"
22         pp "github.com/anacrolix/torrent/peer_protocol"
23         request_strategy "github.com/anacrolix/torrent/request-strategy"
24         typedRoaring "github.com/anacrolix/torrent/typed-roaring"
25 )
26
27 type (
28         Peer struct {
29                 // First to ensure 64-bit alignment for atomics. See #262.
30                 _stats ConnStats
31
32                 t *Torrent
33
34                 peerImpl
35                 callbacks *Callbacks
36
37                 outgoing   bool
38                 Network    string
39                 RemoteAddr PeerRemoteAddr
40                 // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
41                 // config.
42                 localPublicAddr peerLocalPublicAddr
43                 bannableAddr    Option[bannableAddr]
44                 // True if the connection is operating over MSE obfuscation.
45                 headerEncrypted bool
46                 cryptoMethod    mse.CryptoMethod
47                 Discovery       PeerSource
48                 trusted         bool
49                 closed          chansync.SetOnce
50                 // Set true after we've added our ConnStats generated during handshake to
51                 // other ConnStat instances as determined when the *Torrent became known.
52                 reconciledHandshakeStats bool
53
54                 lastMessageReceived     time.Time
55                 completedHandshake      time.Time
56                 lastUsefulChunkReceived time.Time
57                 lastChunkSent           time.Time
58
59                 // Stuff controlled by the local peer.
60                 needRequestUpdate    string
61                 requestState         request_strategy.PeerRequestState
62                 updateRequestsTimer  *time.Timer
63                 lastRequestUpdate    time.Time
64                 peakRequests         maxRequests
65                 lastBecameInterested time.Time
66                 priorInterest        time.Duration
67
68                 lastStartedExpectingToReceiveChunks time.Time
69                 cumulativeExpectedToReceiveChunks   time.Duration
70                 _chunksReceivedWhileExpecting       int64
71
72                 choking                                bool
73                 piecesReceivedSinceLastRequestUpdate   maxRequests
74                 maxPiecesReceivedBetweenRequestUpdates maxRequests
75                 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
76                 // and implementation differences, we may receive chunks that are no longer in the set of
77                 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
78                 validReceiveChunks map[RequestIndex]int
79                 // Indexed by metadata piece, set to true if posted and pending a
80                 // response.
81                 metadataRequests []bool
82                 sentHaves        bitmap.Bitmap
83
84                 // Stuff controlled by the remote peer.
85                 peerInterested        bool
86                 peerChoking           bool
87                 peerRequests          map[Request]*peerRequestState
88                 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
89                 // The highest possible number of pieces the torrent could have based on
90                 // communication with the peer. Generally only useful until we have the
91                 // torrent info.
92                 peerMinPieces pieceIndex
93                 // Pieces we've accepted chunks for from the peer.
94                 peerTouchedPieces map[pieceIndex]struct{}
95                 peerAllowedFast   typedRoaring.Bitmap[pieceIndex]
96
97                 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
98
99                 logger log.Logger
100         }
101
102         PeerSource string
103
104         peerRequestState struct {
105                 data             []byte
106                 allocReservation *alloclim.Reservation
107         }
108
109         PeerRemoteAddr interface {
110                 String() string
111         }
112
113         peerRequests = orderedBitmap[RequestIndex]
114 )
115
116 const (
117         PeerSourceUtHolepunch     = "C"
118         PeerSourceTracker         = "Tr"
119         PeerSourceIncoming        = "I"
120         PeerSourceDhtGetPeers     = "Hg" // Peers we found by searching a DHT.
121         PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
122         PeerSourcePex             = "X"
123         // The peer was given directly, such as through a magnet link.
124         PeerSourceDirect = "M"
125 )
126
127 // Returns the Torrent a Peer belongs to. Shouldn't change for the lifetime of the Peer. May be nil
128 // if we are the receiving end of a connection and the handshake hasn't been received or accepted
129 // yet.
130 func (p *Peer) Torrent() *Torrent {
131         return p.t
132 }
133
134 func (p *Peer) initRequestState() {
135         p.requestState.Requests = &peerRequests{}
136 }
137
138 func (cn *Peer) updateExpectingChunks() {
139         if cn.expectingChunks() {
140                 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
141                         cn.lastStartedExpectingToReceiveChunks = time.Now()
142                 }
143         } else {
144                 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
145                         cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
146                         cn.lastStartedExpectingToReceiveChunks = time.Time{}
147                 }
148         }
149 }
150
151 func (cn *Peer) expectingChunks() bool {
152         if cn.requestState.Requests.IsEmpty() {
153                 return false
154         }
155         if !cn.requestState.Interested {
156                 return false
157         }
158         if !cn.peerChoking {
159                 return true
160         }
161         haveAllowedFastRequests := false
162         cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
163                 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
164                         cn.requestState.Requests,
165                         cn.t.pieceRequestIndexOffset(i),
166                         cn.t.pieceRequestIndexOffset(i+1),
167                 ) == 0
168                 return !haveAllowedFastRequests
169         })
170         return haveAllowedFastRequests
171 }
172
173 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
174         return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
175 }
176
177 func (cn *Peer) cumInterest() time.Duration {
178         ret := cn.priorInterest
179         if cn.requestState.Interested {
180                 ret += time.Since(cn.lastBecameInterested)
181         }
182         return ret
183 }
184
185 func (cn *Peer) locker() *lockWithDeferreds {
186         return cn.t.cl.locker()
187 }
188
189 func (cn *PeerConn) supportsExtension(ext pp.ExtensionName) bool {
190         _, ok := cn.PeerExtensionIDs[ext]
191         return ok
192 }
193
194 // The best guess at number of pieces in the torrent for this peer.
195 func (cn *Peer) bestPeerNumPieces() pieceIndex {
196         if cn.t.haveInfo() {
197                 return cn.t.numPieces()
198         }
199         return cn.peerMinPieces
200 }
201
202 func (cn *Peer) completedString() string {
203         have := pieceIndex(cn.peerPieces().GetCardinality())
204         if all, _ := cn.peerHasAllPieces(); all {
205                 have = cn.bestPeerNumPieces()
206         }
207         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
208 }
209
210 func eventAgeString(t time.Time) string {
211         if t.IsZero() {
212                 return "never"
213         }
214         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
215 }
216
217 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
218 func (cn *Peer) statusFlags() (ret string) {
219         c := func(b byte) {
220                 ret += string([]byte{b})
221         }
222         if cn.requestState.Interested {
223                 c('i')
224         }
225         if cn.choking {
226                 c('c')
227         }
228         c(':')
229         ret += cn.connectionFlags()
230         c(':')
231         if cn.peerInterested {
232                 c('i')
233         }
234         if cn.peerChoking {
235                 c('c')
236         }
237         return
238 }
239
240 func (cn *Peer) downloadRate() float64 {
241         num := cn._stats.BytesReadUsefulData.Int64()
242         if num == 0 {
243                 return 0
244         }
245         return float64(num) / cn.totalExpectingTime().Seconds()
246 }
247
248 func (p *Peer) DownloadRate() float64 {
249         p.locker().RLock()
250         defer p.locker().RUnlock()
251
252         return p.downloadRate()
253 }
254
255 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
256         var last Option[pieceIndex]
257         var count int
258         next := func(item Option[pieceIndex]) {
259                 if item == last {
260                         count++
261                 } else {
262                         if count != 0 {
263                                 f(last.Value, count)
264                         }
265                         last = item
266                         count = 1
267                 }
268         }
269         cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
270                 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
271                 return true
272         })
273         next(None[pieceIndex]())
274 }
275
276 func (cn *Peer) writeStatus(w io.Writer) {
277         // \t isn't preserved in <pre> blocks?
278         if cn.closed.IsSet() {
279                 fmt.Fprint(w, "CLOSED: ")
280         }
281         fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
282         prio, err := cn.peerPriority()
283         prioStr := fmt.Sprintf("%08x", prio)
284         if err != nil {
285                 prioStr += ": " + err.Error()
286         }
287         fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
288         fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
289                 eventAgeString(cn.lastMessageReceived),
290                 eventAgeString(cn.completedHandshake),
291                 eventAgeString(cn.lastHelpful()),
292                 cn.cumInterest(),
293                 cn.totalExpectingTime(),
294         )
295         fmt.Fprintf(w,
296                 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
297                 cn.completedString(),
298                 len(cn.peerTouchedPieces),
299                 &cn._stats.ChunksReadUseful,
300                 &cn._stats.ChunksRead,
301                 &cn._stats.ChunksWritten,
302                 cn.requestState.Requests.GetCardinality(),
303                 cn.requestState.Cancelled.GetCardinality(),
304                 cn.nominalMaxRequests(),
305                 cn.PeerMaxRequests,
306                 len(cn.peerRequests),
307                 localClientReqq,
308                 cn.statusFlags(),
309                 cn.downloadRate()/(1<<10),
310         )
311         fmt.Fprintf(w, "requested pieces:")
312         cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
313                 fmt.Fprintf(w, " %v(%v)", piece, count)
314         })
315         fmt.Fprintf(w, "\n")
316 }
317
318 func (p *Peer) close() {
319         if !p.closed.Set() {
320                 return
321         }
322         if p.updateRequestsTimer != nil {
323                 p.updateRequestsTimer.Stop()
324         }
325         for _, prs := range p.peerRequests {
326                 prs.allocReservation.Drop()
327         }
328         p.peerImpl.onClose()
329         if p.t != nil {
330                 p.t.decPeerPieceAvailability(p)
331         }
332         for _, f := range p.callbacks.PeerClosed {
333                 f(p)
334         }
335 }
336
337 func (p *Peer) Close() error {
338         p.locker().Lock()
339         defer p.locker().Unlock()
340         p.close()
341         return nil
342 }
343
344 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
345 // they do (known=true).
346 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
347         if all, known := cn.peerHasAllPieces(); all && known {
348                 return true
349         }
350         return cn.peerPieces().ContainsInt(piece)
351 }
352
353 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
354 // https://github.com/pion/datachannel/issues/59 is fixed.
355 const (
356         writeBufferHighWaterLen = 1 << 15
357         writeBufferLowWaterLen  = writeBufferHighWaterLen / 2
358 )
359
360 var (
361         interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
362         requestMsgLen    = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
363         // This is the maximum request count that could fit in the write buffer if it's at or below the
364         // low water mark when we run maybeUpdateActualRequestState.
365         maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
366 )
367
368 // The actual value to use as the maximum outbound requests.
369 func (cn *Peer) nominalMaxRequests() maxRequests {
370         return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
371 }
372
373 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
374         ret = cn.cumulativeExpectedToReceiveChunks
375         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
376                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
377         }
378         return
379 }
380
381 func (cn *Peer) setInterested(interested bool) bool {
382         if cn.requestState.Interested == interested {
383                 return true
384         }
385         cn.requestState.Interested = interested
386         if interested {
387                 cn.lastBecameInterested = time.Now()
388         } else if !cn.lastBecameInterested.IsZero() {
389                 cn.priorInterest += time.Since(cn.lastBecameInterested)
390         }
391         cn.updateExpectingChunks()
392         // log.Printf("%p: setting interest: %v", cn, interested)
393         return cn.writeInterested(interested)
394 }
395
396 // The function takes a message to be sent, and returns true if more messages
397 // are okay.
398 type messageWriter func(pp.Message) bool
399
400 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
401 // when we want to go fast.
402 func (cn *Peer) shouldRequest(r RequestIndex) error {
403         err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
404         if err != nil {
405                 return err
406         }
407         pi := cn.t.pieceIndexOfRequestIndex(r)
408         if cn.requestState.Cancelled.Contains(r) {
409                 return errors.New("request is cancelled and waiting acknowledgement")
410         }
411         if !cn.peerHasPiece(pi) {
412                 return errors.New("requesting piece peer doesn't have")
413         }
414         if !cn.t.peerIsActive(cn) {
415                 panic("requesting but not in active conns")
416         }
417         if cn.closed.IsSet() {
418                 panic("requesting when connection is closed")
419         }
420         if cn.t.hashingPiece(pi) {
421                 panic("piece is being hashed")
422         }
423         if cn.t.pieceQueuedForHash(pi) {
424                 panic("piece is queued for hash")
425         }
426         if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
427                 // This could occur if we made a request with the fast extension, and then got choked and
428                 // haven't had the request rejected yet.
429                 if !cn.requestState.Requests.Contains(r) {
430                         panic("peer choking and piece not allowed fast")
431                 }
432         }
433         return nil
434 }
435
436 func (cn *Peer) mustRequest(r RequestIndex) bool {
437         more, err := cn.request(r)
438         if err != nil {
439                 panic(err)
440         }
441         return more
442 }
443
444 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
445         if err := cn.shouldRequest(r); err != nil {
446                 panic(err)
447         }
448         if cn.requestState.Requests.Contains(r) {
449                 return true, nil
450         }
451         if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
452                 return true, errors.New("too many outstanding requests")
453         }
454         cn.requestState.Requests.Add(r)
455         if cn.validReceiveChunks == nil {
456                 cn.validReceiveChunks = make(map[RequestIndex]int)
457         }
458         cn.validReceiveChunks[r]++
459         cn.t.requestState[r] = requestState{
460                 peer: cn,
461                 when: time.Now(),
462         }
463         cn.updateExpectingChunks()
464         ppReq := cn.t.requestIndexToRequest(r)
465         for _, f := range cn.callbacks.SentRequest {
466                 f(PeerRequestEvent{cn, ppReq})
467         }
468         return cn.peerImpl._request(ppReq), nil
469 }
470
471 func (me *Peer) cancel(r RequestIndex) {
472         if !me.deleteRequest(r) {
473                 panic("request not existing should have been guarded")
474         }
475         if me._cancel(r) {
476                 // Record that we expect to get a cancel ack.
477                 if !me.requestState.Cancelled.CheckedAdd(r) {
478                         panic("request already cancelled")
479                 }
480         }
481         me.decPeakRequests()
482         if me.isLowOnRequests() {
483                 me.updateRequests("Peer.cancel")
484         }
485 }
486
487 // Sets a reason to update requests, and if there wasn't already one, handle it.
488 func (cn *Peer) updateRequests(reason string) {
489         if cn.needRequestUpdate != "" {
490                 return
491         }
492         cn.needRequestUpdate = reason
493         cn.handleUpdateRequests()
494 }
495
496 // Emits the indices in the Bitmaps bms in order, never repeating any index.
497 // skip is mutated during execution, and its initial values will never be
498 // emitted.
499 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
500         return func(cb iter.Callback) {
501                 for _, bm := range bms {
502                         if !iter.All(
503                                 func(_i interface{}) bool {
504                                         i := _i.(int)
505                                         if skip.Contains(bitmap.BitIndex(i)) {
506                                                 return true
507                                         }
508                                         skip.Add(bitmap.BitIndex(i))
509                                         return cb(i)
510                                 },
511                                 bm.Iter,
512                         ) {
513                                 return
514                         }
515                 }
516         }
517 }
518
519 // After handshake, we know what Torrent and Client stats to include for a
520 // connection.
521 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
522         t := cn.t
523         f(&t.stats)
524         f(&t.cl.connStats)
525 }
526
527 // All ConnStats that include this connection. Some objects are not known
528 // until the handshake is complete, after which it's expected to reconcile the
529 // differences.
530 func (cn *Peer) allStats(f func(*ConnStats)) {
531         f(&cn._stats)
532         if cn.reconciledHandshakeStats {
533                 cn.postHandshakeStats(f)
534         }
535 }
536
537 func (cn *Peer) readBytes(n int64) {
538         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
539 }
540
541 func (c *Peer) lastHelpful() (ret time.Time) {
542         ret = c.lastUsefulChunkReceived
543         if c.t.seeding() && c.lastChunkSent.After(ret) {
544                 ret = c.lastChunkSent
545         }
546         return
547 }
548
549 // Returns whether any part of the chunk would lie outside a piece of the given length.
550 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
551         switch {
552         default:
553                 return false
554         case cs.Begin+cs.Length > pieceLength:
555         // Check for integer overflow
556         case cs.Begin > pp.IntegerMax-cs.Length:
557         }
558         return true
559 }
560
561 func runSafeExtraneous(f func()) {
562         if true {
563                 go f()
564         } else {
565                 f()
566         }
567 }
568
569 // Returns true if it was valid to reject the request.
570 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
571         if c.deleteRequest(r) {
572                 c.decPeakRequests()
573         } else if !c.requestState.Cancelled.CheckedRemove(r) {
574                 return false
575         }
576         if c.isLowOnRequests() {
577                 c.updateRequests("Peer.remoteRejectedRequest")
578         }
579         c.decExpectedChunkReceive(r)
580         return true
581 }
582
583 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
584         count := c.validReceiveChunks[r]
585         if count == 1 {
586                 delete(c.validReceiveChunks, r)
587         } else if count > 1 {
588                 c.validReceiveChunks[r] = count - 1
589         } else {
590                 panic(r)
591         }
592 }
593
594 func (c *Peer) doChunkReadStats(size int64) {
595         c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
596 }
597
598 // Handle a received chunk from a peer.
599 func (c *Peer) receiveChunk(msg *pp.Message) error {
600         chunksReceived.Add("total", 1)
601
602         ppReq := newRequestFromMessage(msg)
603         t := c.t
604         err := t.checkValidReceiveChunk(ppReq)
605         if err != nil {
606                 err = log.WithLevel(log.Warning, err)
607                 return err
608         }
609         req := c.t.requestIndexFromRequest(ppReq)
610
611         recordBlockForSmartBan := sync.OnceFunc(func() {
612                 c.recordBlockForSmartBan(req, msg.Piece)
613         })
614         // This needs to occur before we return, but we try to do it when the client is unlocked. It
615         // can't be done before checking if chunks are valid because they won't be deallocated by piece
616         // hashing if they're out of bounds.
617         defer recordBlockForSmartBan()
618
619         if c.peerChoking {
620                 chunksReceived.Add("while choked", 1)
621         }
622
623         if c.validReceiveChunks[req] <= 0 {
624                 chunksReceived.Add("unexpected", 1)
625                 return errors.New("received unexpected chunk")
626         }
627         c.decExpectedChunkReceive(req)
628
629         if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
630                 chunksReceived.Add("due to allowed fast", 1)
631         }
632
633         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
634         // have actually already received the piece, while we have the Client unlocked to write the data
635         // out.
636         intended := false
637         {
638                 if c.requestState.Requests.Contains(req) {
639                         for _, f := range c.callbacks.ReceivedRequested {
640                                 f(PeerMessageEvent{c, msg})
641                         }
642                 }
643                 // Request has been satisfied.
644                 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
645                         intended = true
646                         if !c.peerChoking {
647                                 c._chunksReceivedWhileExpecting++
648                         }
649                         if c.isLowOnRequests() {
650                                 c.updateRequests("Peer.receiveChunk deleted request")
651                         }
652                 } else {
653                         chunksReceived.Add("unintended", 1)
654                 }
655         }
656
657         cl := t.cl
658
659         // Do we actually want this chunk?
660         if t.haveChunk(ppReq) {
661                 // panic(fmt.Sprintf("%+v", ppReq))
662                 chunksReceived.Add("redundant", 1)
663                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
664                 return nil
665         }
666
667         piece := &t.pieces[ppReq.Index]
668
669         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
670         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
671         if intended {
672                 c.piecesReceivedSinceLastRequestUpdate++
673                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
674         }
675         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
676                 f(ReceivedUsefulDataEvent{c, msg})
677         }
678         c.lastUsefulChunkReceived = time.Now()
679
680         // Need to record that it hasn't been written yet, before we attempt to do
681         // anything with it.
682         piece.incrementPendingWrites()
683         // Record that we have the chunk, so we aren't trying to download it while
684         // waiting for it to be written to storage.
685         piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
686
687         // Cancel pending requests for this chunk from *other* peers.
688         if p := t.requestingPeer(req); p != nil {
689                 if p == c {
690                         panic("should not be pending request from conn that just received it")
691                 }
692                 p.cancel(req)
693         }
694
695         err = func() error {
696                 cl.unlock()
697                 defer cl.lock()
698                 // Opportunistically do this here while we aren't holding the client lock.
699                 recordBlockForSmartBan()
700                 concurrentChunkWrites.Add(1)
701                 defer concurrentChunkWrites.Add(-1)
702                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
703                 // number of connections. We write inline with receiving the chunk (with this lock dance),
704                 // because we want to handle errors synchronously and I haven't thought of a nice way to
705                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
706                 // that instead.
707                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
708         }()
709
710         piece.decrementPendingWrites()
711
712         if err != nil {
713                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
714                 t.pendRequest(req)
715                 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
716                 // request update runs while we're writing the chunk that just failed. Then we never do a
717                 // fresh update after pending the failed request.
718                 c.updateRequests("Peer.receiveChunk error writing chunk")
719                 t.onWriteChunkErr(err)
720                 return nil
721         }
722
723         c.onDirtiedPiece(pieceIndex(ppReq.Index))
724
725         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
726         if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
727                 t.queuePieceCheck(pieceIndex(ppReq.Index))
728                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
729                 // chunk status (such as the haveChunk call above) to have to check all the various other
730                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
731                 // that chunk pieces are pended at an appropriate time later however.
732         }
733
734         cl.event.Broadcast()
735         // We do this because we've written a chunk, and may change PieceState.Partial.
736         t.publishPieceStateChange(pieceIndex(ppReq.Index))
737
738         return nil
739 }
740
741 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
742         if c.peerTouchedPieces == nil {
743                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
744         }
745         c.peerTouchedPieces[piece] = struct{}{}
746         ds := &c.t.pieces[piece].dirtiers
747         if *ds == nil {
748                 *ds = make(map[*Peer]struct{})
749         }
750         (*ds)[c] = struct{}{}
751 }
752
753 func (cn *Peer) netGoodPiecesDirtied() int64 {
754         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
755 }
756
757 func (c *Peer) peerHasWantedPieces() bool {
758         if all, _ := c.peerHasAllPieces(); all {
759                 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
760         }
761         if !c.t.haveInfo() {
762                 return !c.peerPieces().IsEmpty()
763         }
764         return c.peerPieces().Intersects(&c.t._pendingPieces)
765 }
766
767 // Returns true if an outstanding request is removed. Cancelled requests should be handled
768 // separately.
769 func (c *Peer) deleteRequest(r RequestIndex) bool {
770         if !c.requestState.Requests.CheckedRemove(r) {
771                 return false
772         }
773         for _, f := range c.callbacks.DeletedRequest {
774                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
775         }
776         c.updateExpectingChunks()
777         if c.t.requestingPeer(r) != c {
778                 panic("only one peer should have a given request at a time")
779         }
780         delete(c.t.requestState, r)
781         // c.t.iterPeers(func(p *Peer) {
782         //      if p.isLowOnRequests() {
783         //              p.updateRequests("Peer.deleteRequest")
784         //      }
785         // })
786         return true
787 }
788
789 func (c *Peer) deleteAllRequests(reason string) {
790         if c.requestState.Requests.IsEmpty() {
791                 return
792         }
793         c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
794                 if !c.deleteRequest(x) {
795                         panic("request should exist")
796                 }
797                 return true
798         })
799         c.assertNoRequests()
800         c.t.iterPeers(func(p *Peer) {
801                 if p.isLowOnRequests() {
802                         p.updateRequests(reason)
803                 }
804         })
805         return
806 }
807
808 func (c *Peer) assertNoRequests() {
809         if !c.requestState.Requests.IsEmpty() {
810                 panic(c.requestState.Requests.GetCardinality())
811         }
812 }
813
814 func (c *Peer) cancelAllRequests() {
815         c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
816                 c.cancel(x)
817                 return true
818         })
819         c.assertNoRequests()
820         return
821 }
822
823 func (c *Peer) peerPriority() (peerPriority, error) {
824         return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
825 }
826
827 func (c *Peer) remoteIp() net.IP {
828         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
829         return net.ParseIP(host)
830 }
831
832 func (c *Peer) remoteIpPort() IpPort {
833         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
834         return IpPort{ipa.IP, uint16(ipa.Port)}
835 }
836
837 func (c *Peer) trust() connectionTrust {
838         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
839 }
840
841 type connectionTrust struct {
842         Implicit            bool
843         NetGoodPiecesDirted int64
844 }
845
846 func (l connectionTrust) Less(r connectionTrust) bool {
847         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
848 }
849
850 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
851 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
852         // TODO: Can we use copy on write?
853         ret := cn.peerPieces().Clone()
854         if all, _ := cn.peerHasAllPieces(); all {
855                 if cn.t.haveInfo() {
856                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
857                 } else {
858                         ret.AddRange(0, bitmap.ToEnd)
859                 }
860         }
861         return ret
862 }
863
864 func (cn *Peer) stats() *ConnStats {
865         return &cn._stats
866 }
867
868 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
869         pc, ok := p.peerImpl.(*PeerConn)
870         return pc, ok
871 }
872
873 func (p *Peer) uncancelledRequests() uint64 {
874         return p.requestState.Requests.GetCardinality()
875 }
876
877 type peerLocalPublicAddr = IpPort
878
879 func (p *Peer) isLowOnRequests() bool {
880         return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
881 }
882
883 func (p *Peer) decPeakRequests() {
884         // // This can occur when peak requests are altered by the update request timer to be lower than
885         // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
886         // // wonder what happens if maxRequests is not signed.
887         // if p.peakRequests < 1 {
888         //      panic(p.peakRequests)
889         // }
890         p.peakRequests--
891 }
892
893 func (p *Peer) recordBlockForSmartBan(req RequestIndex, blockData []byte) {
894         if p.bannableAddr.Ok {
895                 p.t.smartBanCache.RecordBlock(p.bannableAddr.Value, req, blockData)
896         }
897 }