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