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