]> Sergey Matveev's repositories - btrtrc.git/blob - peer.go
Fix TestSeedAfterDownloading when cgo is disabled
[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         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                 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
99                 PeerClientName   atomic.Value
100
101                 logger log.Logger
102         }
103
104         PeerSource string
105
106         peerRequestState struct {
107                 data             []byte
108                 allocReservation *alloclim.Reservation
109         }
110
111         PeerRemoteAddr interface {
112                 String() string
113         }
114
115         peerRequests = orderedBitmap[RequestIndex]
116 )
117
118 const (
119         PeerSourceUtHolepunch     = "C"
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         for _, prs := range p.peerRequests {
328                 prs.allocReservation.Drop()
329         }
330         p.peerImpl.onClose()
331         if p.t != nil {
332                 p.t.decPeerPieceAvailability(p)
333         }
334         for _, f := range p.callbacks.PeerClosed {
335                 f(p)
336         }
337 }
338
339 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
340 // they do (known=true).
341 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
342         if all, known := cn.peerHasAllPieces(); all && known {
343                 return true
344         }
345         return cn.peerPieces().ContainsInt(piece)
346 }
347
348 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
349 // https://github.com/pion/datachannel/issues/59 is fixed.
350 const (
351         writeBufferHighWaterLen = 1 << 15
352         writeBufferLowWaterLen  = writeBufferHighWaterLen / 2
353 )
354
355 var (
356         interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
357         requestMsgLen    = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
358         // This is the maximum request count that could fit in the write buffer if it's at or below the
359         // low water mark when we run maybeUpdateActualRequestState.
360         maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
361 )
362
363 // The actual value to use as the maximum outbound requests.
364 func (cn *Peer) nominalMaxRequests() maxRequests {
365         return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
366 }
367
368 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
369         ret = cn.cumulativeExpectedToReceiveChunks
370         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
371                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
372         }
373         return
374 }
375
376 func (cn *Peer) setInterested(interested bool) bool {
377         if cn.requestState.Interested == interested {
378                 return true
379         }
380         cn.requestState.Interested = interested
381         if interested {
382                 cn.lastBecameInterested = time.Now()
383         } else if !cn.lastBecameInterested.IsZero() {
384                 cn.priorInterest += time.Since(cn.lastBecameInterested)
385         }
386         cn.updateExpectingChunks()
387         // log.Printf("%p: setting interest: %v", cn, interested)
388         return cn.writeInterested(interested)
389 }
390
391 // The function takes a message to be sent, and returns true if more messages
392 // are okay.
393 type messageWriter func(pp.Message) bool
394
395 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
396 // when we want to go fast.
397 func (cn *Peer) shouldRequest(r RequestIndex) error {
398         err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
399         if err != nil {
400                 return err
401         }
402         pi := cn.t.pieceIndexOfRequestIndex(r)
403         if cn.requestState.Cancelled.Contains(r) {
404                 return errors.New("request is cancelled and waiting acknowledgement")
405         }
406         if !cn.peerHasPiece(pi) {
407                 return errors.New("requesting piece peer doesn't have")
408         }
409         if !cn.t.peerIsActive(cn) {
410                 panic("requesting but not in active conns")
411         }
412         if cn.closed.IsSet() {
413                 panic("requesting when connection is closed")
414         }
415         if cn.t.hashingPiece(pi) {
416                 panic("piece is being hashed")
417         }
418         if cn.t.pieceQueuedForHash(pi) {
419                 panic("piece is queued for hash")
420         }
421         if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
422                 // This could occur if we made a request with the fast extension, and then got choked and
423                 // haven't had the request rejected yet.
424                 if !cn.requestState.Requests.Contains(r) {
425                         panic("peer choking and piece not allowed fast")
426                 }
427         }
428         return nil
429 }
430
431 func (cn *Peer) mustRequest(r RequestIndex) bool {
432         more, err := cn.request(r)
433         if err != nil {
434                 panic(err)
435         }
436         return more
437 }
438
439 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
440         if err := cn.shouldRequest(r); err != nil {
441                 panic(err)
442         }
443         if cn.requestState.Requests.Contains(r) {
444                 return true, nil
445         }
446         if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
447                 return true, errors.New("too many outstanding requests")
448         }
449         cn.requestState.Requests.Add(r)
450         if cn.validReceiveChunks == nil {
451                 cn.validReceiveChunks = make(map[RequestIndex]int)
452         }
453         cn.validReceiveChunks[r]++
454         cn.t.requestState[r] = requestState{
455                 peer: cn,
456                 when: time.Now(),
457         }
458         cn.updateExpectingChunks()
459         ppReq := cn.t.requestIndexToRequest(r)
460         for _, f := range cn.callbacks.SentRequest {
461                 f(PeerRequestEvent{cn, ppReq})
462         }
463         return cn.peerImpl._request(ppReq), nil
464 }
465
466 func (me *Peer) cancel(r RequestIndex) {
467         if !me.deleteRequest(r) {
468                 panic("request not existing should have been guarded")
469         }
470         if me._cancel(r) {
471                 if !me.requestState.Cancelled.CheckedAdd(r) {
472                         panic("request already cancelled")
473                 }
474         }
475         me.decPeakRequests()
476         if me.isLowOnRequests() {
477                 me.updateRequests("Peer.cancel")
478         }
479 }
480
481 // Sets a reason to update requests, and if there wasn't already one, handle it.
482 func (cn *Peer) updateRequests(reason string) {
483         if cn.needRequestUpdate != "" {
484                 return
485         }
486         if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
487                 return
488         }
489         cn.needRequestUpdate = reason
490         cn.handleUpdateRequests()
491 }
492
493 // Emits the indices in the Bitmaps bms in order, never repeating any index.
494 // skip is mutated during execution, and its initial values will never be
495 // emitted.
496 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
497         return func(cb iter.Callback) {
498                 for _, bm := range bms {
499                         if !iter.All(
500                                 func(_i interface{}) bool {
501                                         i := _i.(int)
502                                         if skip.Contains(bitmap.BitIndex(i)) {
503                                                 return true
504                                         }
505                                         skip.Add(bitmap.BitIndex(i))
506                                         return cb(i)
507                                 },
508                                 bm.Iter,
509                         ) {
510                                 return
511                         }
512                 }
513         }
514 }
515
516 func (cn *Peer) peerPiecesChanged() {
517         cn.t.maybeDropMutuallyCompletePeer(cn)
518 }
519
520 // After handshake, we know what Torrent and Client stats to include for a
521 // connection.
522 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
523         t := cn.t
524         f(&t.stats)
525         f(&t.cl.connStats)
526 }
527
528 // All ConnStats that include this connection. Some objects are not known
529 // until the handshake is complete, after which it's expected to reconcile the
530 // differences.
531 func (cn *Peer) allStats(f func(*ConnStats)) {
532         f(&cn._stats)
533         if cn.reconciledHandshakeStats {
534                 cn.postHandshakeStats(f)
535         }
536 }
537
538 func (cn *Peer) readBytes(n int64) {
539         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
540 }
541
542 // Returns whether the connection could be useful to us. We're seeding and
543 // they want data, we don't have metainfo and they can provide it, etc.
544 func (c *Peer) useful() bool {
545         t := c.t
546         if c.closed.IsSet() {
547                 return false
548         }
549         if !t.haveInfo() {
550                 return c.supportsExtension("ut_metadata")
551         }
552         if t.seeding() && c.peerInterested {
553                 return true
554         }
555         if c.peerHasWantedPieces() {
556                 return true
557         }
558         return false
559 }
560
561 func (c *Peer) lastHelpful() (ret time.Time) {
562         ret = c.lastUsefulChunkReceived
563         if c.t.seeding() && c.lastChunkSent.After(ret) {
564                 ret = c.lastChunkSent
565         }
566         return
567 }
568
569 // Returns whether any part of the chunk would lie outside a piece of the given length.
570 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
571         switch {
572         default:
573                 return false
574         case cs.Begin+cs.Length > pieceLength:
575         // Check for integer overflow
576         case cs.Begin > pp.IntegerMax-cs.Length:
577         }
578         return true
579 }
580
581 func runSafeExtraneous(f func()) {
582         if true {
583                 go f()
584         } else {
585                 f()
586         }
587 }
588
589 // Returns true if it was valid to reject the request.
590 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
591         if c.deleteRequest(r) {
592                 c.decPeakRequests()
593         } else if !c.requestState.Cancelled.CheckedRemove(r) {
594                 return false
595         }
596         if c.isLowOnRequests() {
597                 c.updateRequests("Peer.remoteRejectedRequest")
598         }
599         c.decExpectedChunkReceive(r)
600         return true
601 }
602
603 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
604         count := c.validReceiveChunks[r]
605         if count == 1 {
606                 delete(c.validReceiveChunks, r)
607         } else if count > 1 {
608                 c.validReceiveChunks[r] = count - 1
609         } else {
610                 panic(r)
611         }
612 }
613
614 func (c *Peer) doChunkReadStats(size int64) {
615         c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
616 }
617
618 // Handle a received chunk from a peer.
619 func (c *Peer) receiveChunk(msg *pp.Message) error {
620         chunksReceived.Add("total", 1)
621
622         ppReq := newRequestFromMessage(msg)
623         t := c.t
624         err := t.checkValidReceiveChunk(ppReq)
625         if err != nil {
626                 err = log.WithLevel(log.Warning, err)
627                 return err
628         }
629         req := c.t.requestIndexFromRequest(ppReq)
630
631         if c.bannableAddr.Ok {
632                 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
633         }
634
635         if c.peerChoking {
636                 chunksReceived.Add("while choked", 1)
637         }
638
639         if c.validReceiveChunks[req] <= 0 {
640                 chunksReceived.Add("unexpected", 1)
641                 return errors.New("received unexpected chunk")
642         }
643         c.decExpectedChunkReceive(req)
644
645         if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
646                 chunksReceived.Add("due to allowed fast", 1)
647         }
648
649         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
650         // have actually already received the piece, while we have the Client unlocked to write the data
651         // out.
652         intended := false
653         {
654                 if c.requestState.Requests.Contains(req) {
655                         for _, f := range c.callbacks.ReceivedRequested {
656                                 f(PeerMessageEvent{c, msg})
657                         }
658                 }
659                 // Request has been satisfied.
660                 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
661                         intended = true
662                         if !c.peerChoking {
663                                 c._chunksReceivedWhileExpecting++
664                         }
665                         if c.isLowOnRequests() {
666                                 c.updateRequests("Peer.receiveChunk deleted request")
667                         }
668                 } else {
669                         chunksReceived.Add("unintended", 1)
670                 }
671         }
672
673         cl := t.cl
674
675         // Do we actually want this chunk?
676         if t.haveChunk(ppReq) {
677                 // panic(fmt.Sprintf("%+v", ppReq))
678                 chunksReceived.Add("redundant", 1)
679                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
680                 return nil
681         }
682
683         piece := &t.pieces[ppReq.Index]
684
685         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
686         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
687         if intended {
688                 c.piecesReceivedSinceLastRequestUpdate++
689                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
690         }
691         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
692                 f(ReceivedUsefulDataEvent{c, msg})
693         }
694         c.lastUsefulChunkReceived = time.Now()
695
696         // Need to record that it hasn't been written yet, before we attempt to do
697         // anything with it.
698         piece.incrementPendingWrites()
699         // Record that we have the chunk, so we aren't trying to download it while
700         // waiting for it to be written to storage.
701         piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
702
703         // Cancel pending requests for this chunk from *other* peers.
704         if p := t.requestingPeer(req); p != nil {
705                 if p == c {
706                         panic("should not be pending request from conn that just received it")
707                 }
708                 p.cancel(req)
709         }
710
711         err = func() error {
712                 cl.unlock()
713                 defer cl.lock()
714                 concurrentChunkWrites.Add(1)
715                 defer concurrentChunkWrites.Add(-1)
716                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
717                 // number of connections. We write inline with receiving the chunk (with this lock dance),
718                 // because we want to handle errors synchronously and I haven't thought of a nice way to
719                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
720                 // that instead.
721                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
722         }()
723
724         piece.decrementPendingWrites()
725
726         if err != nil {
727                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
728                 t.pendRequest(req)
729                 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
730                 // request update runs while we're writing the chunk that just failed. Then we never do a
731                 // fresh update after pending the failed request.
732                 c.updateRequests("Peer.receiveChunk error writing chunk")
733                 t.onWriteChunkErr(err)
734                 return nil
735         }
736
737         c.onDirtiedPiece(pieceIndex(ppReq.Index))
738
739         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
740         if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
741                 t.queuePieceCheck(pieceIndex(ppReq.Index))
742                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
743                 // chunk status (such as the haveChunk call above) to have to check all the various other
744                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
745                 // that chunk pieces are pended at an appropriate time later however.
746         }
747
748         cl.event.Broadcast()
749         // We do this because we've written a chunk, and may change PieceState.Partial.
750         t.publishPieceChange(pieceIndex(ppReq.Index))
751
752         return nil
753 }
754
755 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
756         if c.peerTouchedPieces == nil {
757                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
758         }
759         c.peerTouchedPieces[piece] = struct{}{}
760         ds := &c.t.pieces[piece].dirtiers
761         if *ds == nil {
762                 *ds = make(map[*Peer]struct{})
763         }
764         (*ds)[c] = struct{}{}
765 }
766
767 func (cn *Peer) netGoodPiecesDirtied() int64 {
768         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
769 }
770
771 func (c *Peer) peerHasWantedPieces() bool {
772         if all, _ := c.peerHasAllPieces(); all {
773                 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
774         }
775         if !c.t.haveInfo() {
776                 return !c.peerPieces().IsEmpty()
777         }
778         return c.peerPieces().Intersects(&c.t._pendingPieces)
779 }
780
781 // Returns true if an outstanding request is removed. Cancelled requests should be handled
782 // separately.
783 func (c *Peer) deleteRequest(r RequestIndex) bool {
784         if !c.requestState.Requests.CheckedRemove(r) {
785                 return false
786         }
787         for _, f := range c.callbacks.DeletedRequest {
788                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
789         }
790         c.updateExpectingChunks()
791         if c.t.requestingPeer(r) != c {
792                 panic("only one peer should have a given request at a time")
793         }
794         delete(c.t.requestState, r)
795         // c.t.iterPeers(func(p *Peer) {
796         //      if p.isLowOnRequests() {
797         //              p.updateRequests("Peer.deleteRequest")
798         //      }
799         // })
800         return true
801 }
802
803 func (c *Peer) deleteAllRequests(reason string) {
804         if c.requestState.Requests.IsEmpty() {
805                 return
806         }
807         c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
808                 if !c.deleteRequest(x) {
809                         panic("request should exist")
810                 }
811                 return true
812         })
813         c.assertNoRequests()
814         c.t.iterPeers(func(p *Peer) {
815                 if p.isLowOnRequests() {
816                         p.updateRequests(reason)
817                 }
818         })
819         return
820 }
821
822 func (c *Peer) assertNoRequests() {
823         if !c.requestState.Requests.IsEmpty() {
824                 panic(c.requestState.Requests.GetCardinality())
825         }
826 }
827
828 func (c *Peer) cancelAllRequests() {
829         c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
830                 c.cancel(x)
831                 return true
832         })
833         c.assertNoRequests()
834         return
835 }
836
837 func (c *Peer) peerPriority() (peerPriority, error) {
838         return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
839 }
840
841 func (c *Peer) remoteIp() net.IP {
842         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
843         return net.ParseIP(host)
844 }
845
846 func (c *Peer) remoteIpPort() IpPort {
847         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
848         return IpPort{ipa.IP, uint16(ipa.Port)}
849 }
850
851 func (c *Peer) trust() connectionTrust {
852         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
853 }
854
855 type connectionTrust struct {
856         Implicit            bool
857         NetGoodPiecesDirted int64
858 }
859
860 func (l connectionTrust) Less(r connectionTrust) bool {
861         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
862 }
863
864 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
865 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
866         // TODO: Can we use copy on write?
867         ret := cn.peerPieces().Clone()
868         if all, _ := cn.peerHasAllPieces(); all {
869                 if cn.t.haveInfo() {
870                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
871                 } else {
872                         ret.AddRange(0, bitmap.ToEnd)
873                 }
874         }
875         return ret
876 }
877
878 func (cn *Peer) stats() *ConnStats {
879         return &cn._stats
880 }
881
882 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
883         pc, ok := p.peerImpl.(*PeerConn)
884         return pc, ok
885 }
886
887 func (p *Peer) uncancelledRequests() uint64 {
888         return p.requestState.Requests.GetCardinality()
889 }
890
891 type peerLocalPublicAddr = IpPort
892
893 func (p *Peer) isLowOnRequests() bool {
894         return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
895 }
896
897 func (p *Peer) decPeakRequests() {
898         // // This can occur when peak requests are altered by the update request timer to be lower than
899         // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
900         // // wonder what happens if maxRequests is not signed.
901         // if p.peakRequests < 1 {
902         //      panic(p.peakRequests)
903         // }
904         p.peakRequests--
905 }