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