]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Add Torrent-level request cancel for consistency
[btrtrc.git] / peerconn.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "errors"
7         "fmt"
8         "io"
9         "math/rand"
10         "net"
11         "sort"
12         "strconv"
13         "strings"
14         "sync/atomic"
15         "time"
16
17         "github.com/RoaringBitmap/roaring"
18         "github.com/anacrolix/log"
19         "github.com/anacrolix/missinggo/iter"
20         "github.com/anacrolix/missinggo/v2/bitmap"
21         "github.com/anacrolix/multiless"
22
23         "github.com/anacrolix/chansync"
24         "github.com/anacrolix/torrent/bencode"
25         "github.com/anacrolix/torrent/metainfo"
26         "github.com/anacrolix/torrent/mse"
27         pp "github.com/anacrolix/torrent/peer_protocol"
28         request_strategy "github.com/anacrolix/torrent/request-strategy"
29 )
30
31 type PeerSource string
32
33 const (
34         PeerSourceTracker         = "Tr"
35         PeerSourceIncoming        = "I"
36         PeerSourceDhtGetPeers     = "Hg" // Peers we found by searching a DHT.
37         PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
38         PeerSourcePex             = "X"
39         // The peer was given directly, such as through a magnet link.
40         PeerSourceDirect = "M"
41 )
42
43 type peerRequestState struct {
44         data []byte
45 }
46
47 type PeerRemoteAddr interface {
48         String() string
49 }
50
51 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
52 // indexable with the memory space available.
53 type (
54         maxRequests  = int
55         requestState = request_strategy.PeerNextRequestState
56 )
57
58 type Peer struct {
59         // First to ensure 64-bit alignment for atomics. See #262.
60         _stats ConnStats
61
62         t *Torrent
63
64         peerImpl
65         callbacks *Callbacks
66
67         outgoing   bool
68         Network    string
69         RemoteAddr PeerRemoteAddr
70         // True if the connection is operating over MSE obfuscation.
71         headerEncrypted bool
72         cryptoMethod    mse.CryptoMethod
73         Discovery       PeerSource
74         trusted         bool
75         closed          chansync.SetOnce
76         // Set true after we've added our ConnStats generated during handshake to
77         // other ConnStat instances as determined when the *Torrent became known.
78         reconciledHandshakeStats bool
79
80         lastMessageReceived     time.Time
81         completedHandshake      time.Time
82         lastUsefulChunkReceived time.Time
83         lastChunkSent           time.Time
84
85         // Stuff controlled by the local peer.
86         needRequestUpdate    string
87         actualRequestState   requestState
88         updateRequestsTimer  *time.Timer
89         cancelledRequests    roaring.Bitmap
90         lastBecameInterested time.Time
91         priorInterest        time.Duration
92
93         lastStartedExpectingToReceiveChunks time.Time
94         cumulativeExpectedToReceiveChunks   time.Duration
95         _chunksReceivedWhileExpecting       int64
96
97         choking                                bool
98         piecesReceivedSinceLastRequestUpdate   maxRequests
99         maxPiecesReceivedBetweenRequestUpdates maxRequests
100         // Chunks that we might reasonably expect to receive from the peer. Due to
101         // latency, buffering, and implementation differences, we may receive
102         // chunks that are no longer in the set of requests actually want.
103         validReceiveChunks map[RequestIndex]int
104         // Indexed by metadata piece, set to true if posted and pending a
105         // response.
106         metadataRequests []bool
107         sentHaves        bitmap.Bitmap
108
109         // Stuff controlled by the remote peer.
110         peerInterested        bool
111         peerChoking           bool
112         peerRequests          map[Request]*peerRequestState
113         PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
114         PeerListenPort        int
115         // The highest possible number of pieces the torrent could have based on
116         // communication with the peer. Generally only useful until we have the
117         // torrent info.
118         peerMinPieces pieceIndex
119         // Pieces we've accepted chunks for from the peer.
120         peerTouchedPieces map[pieceIndex]struct{}
121         peerAllowedFast   roaring.Bitmap
122
123         PeerMaxRequests  maxRequests // Maximum pending requests the peer allows.
124         PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
125         PeerClientName   atomic.Value
126
127         logger log.Logger
128 }
129
130 // Maintains the state of a BitTorrent-protocol based connection with a peer.
131 type PeerConn struct {
132         Peer
133
134         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
135         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
136         connString string
137
138         // See BEP 3 etc.
139         PeerID             PeerID
140         PeerExtensionBytes pp.PeerExtensionBits
141
142         // The actual Conn, used for closing, and setting socket options. Do not use methods on this
143         // while holding any mutexes.
144         conn net.Conn
145         // The Reader and Writer for this Conn, with hooks installed for stats,
146         // limiting, deadlines etc.
147         w io.Writer
148         r io.Reader
149
150         messageWriter peerConnMsgWriter
151
152         uploadTimer *time.Timer
153         pex         pexConnState
154
155         // The pieces the peer has claimed to have.
156         _peerPieces roaring.Bitmap
157         // The peer has everything. This can occur due to a special message, when
158         // we may not even know the number of pieces in the torrent yet.
159         peerSentHaveAll bool
160 }
161
162 func (cn *PeerConn) connStatusString() string {
163         return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
164 }
165
166 func (cn *Peer) updateExpectingChunks() {
167         if cn.expectingChunks() {
168                 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
169                         cn.lastStartedExpectingToReceiveChunks = time.Now()
170                 }
171         } else {
172                 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
173                         cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
174                         cn.lastStartedExpectingToReceiveChunks = time.Time{}
175                 }
176         }
177 }
178
179 func (cn *Peer) expectingChunks() bool {
180         if cn.actualRequestState.Requests.IsEmpty() {
181                 return false
182         }
183         if !cn.actualRequestState.Interested {
184                 return false
185         }
186         if !cn.peerChoking {
187                 return true
188         }
189         haveAllowedFastRequests := false
190         cn.peerAllowedFast.Iterate(func(i uint32) bool {
191                 haveAllowedFastRequests = roaringBitmapRangeCardinality(
192                         &cn.actualRequestState.Requests,
193                         cn.t.pieceRequestIndexOffset(pieceIndex(i)),
194                         cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
195                 ) == 0
196                 return !haveAllowedFastRequests
197         })
198         return haveAllowedFastRequests
199 }
200
201 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
202         return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
203 }
204
205 // Returns true if the connection is over IPv6.
206 func (cn *PeerConn) ipv6() bool {
207         ip := cn.remoteIp()
208         if ip.To4() != nil {
209                 return false
210         }
211         return len(ip) == net.IPv6len
212 }
213
214 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
215 // specification for this.
216 func (cn *PeerConn) isPreferredDirection() bool {
217         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
218 }
219
220 // Returns whether the left connection should be preferred over the right one,
221 // considering only their networking properties. If ok is false, we can't
222 // decide.
223 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
224         var ml multiLess
225         ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
226         ml.NextBool(!l.utp(), !r.utp())
227         ml.NextBool(l.ipv6(), r.ipv6())
228         return ml.FinalOk()
229 }
230
231 func (cn *Peer) cumInterest() time.Duration {
232         ret := cn.priorInterest
233         if cn.actualRequestState.Interested {
234                 ret += time.Since(cn.lastBecameInterested)
235         }
236         return ret
237 }
238
239 func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
240         if cn.peerSentHaveAll {
241                 return true, true
242         }
243         if !cn.t.haveInfo() {
244                 return false, false
245         }
246         return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
247 }
248
249 func (cn *Peer) locker() *lockWithDeferreds {
250         return cn.t.cl.locker()
251 }
252
253 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
254         _, ok := cn.PeerExtensionIDs[ext]
255         return ok
256 }
257
258 // The best guess at number of pieces in the torrent for this peer.
259 func (cn *Peer) bestPeerNumPieces() pieceIndex {
260         if cn.t.haveInfo() {
261                 return cn.t.numPieces()
262         }
263         return cn.peerMinPieces
264 }
265
266 func (cn *Peer) completedString() string {
267         have := pieceIndex(cn.peerPieces().GetCardinality())
268         if all, _ := cn.peerHasAllPieces(); all {
269                 have = cn.bestPeerNumPieces()
270         }
271         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
272 }
273
274 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
275         cn.setNumPieces(info.NumPieces())
276 }
277
278 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
279 // receiving badly sized BITFIELD, or invalid HAVE messages.
280 func (cn *PeerConn) setNumPieces(num pieceIndex) {
281         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
282         cn.peerPiecesChanged()
283 }
284
285 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
286         return &cn._peerPieces
287 }
288
289 func eventAgeString(t time.Time) string {
290         if t.IsZero() {
291                 return "never"
292         }
293         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
294 }
295
296 func (cn *PeerConn) connectionFlags() (ret string) {
297         c := func(b byte) {
298                 ret += string([]byte{b})
299         }
300         if cn.cryptoMethod == mse.CryptoMethodRC4 {
301                 c('E')
302         } else if cn.headerEncrypted {
303                 c('e')
304         }
305         ret += string(cn.Discovery)
306         if cn.utp() {
307                 c('U')
308         }
309         return
310 }
311
312 func (cn *PeerConn) utp() bool {
313         return parseNetworkString(cn.Network).Udp
314 }
315
316 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
317 func (cn *Peer) statusFlags() (ret string) {
318         c := func(b byte) {
319                 ret += string([]byte{b})
320         }
321         if cn.actualRequestState.Interested {
322                 c('i')
323         }
324         if cn.choking {
325                 c('c')
326         }
327         c('-')
328         ret += cn.connectionFlags()
329         c('-')
330         if cn.peerInterested {
331                 c('i')
332         }
333         if cn.peerChoking {
334                 c('c')
335         }
336         return
337 }
338
339 func (cn *Peer) downloadRate() float64 {
340         num := cn._stats.BytesReadUsefulData.Int64()
341         if num == 0 {
342                 return 0
343         }
344         return float64(num) / cn.totalExpectingTime().Seconds()
345 }
346
347 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
348         ret = make(map[pieceIndex]int)
349         cn.actualRequestState.Requests.Iterate(func(x uint32) bool {
350                 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
351                 return true
352         })
353         return
354 }
355
356 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
357         // \t isn't preserved in <pre> blocks?
358         if cn.closed.IsSet() {
359                 fmt.Fprint(w, "CLOSED: ")
360         }
361         fmt.Fprintln(w, cn.connStatusString())
362         prio, err := cn.peerPriority()
363         prioStr := fmt.Sprintf("%08x", prio)
364         if err != nil {
365                 prioStr += ": " + err.Error()
366         }
367         fmt.Fprintf(w, "    bep40-prio: %v\n", prioStr)
368         fmt.Fprintf(w, "    last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
369                 eventAgeString(cn.lastMessageReceived),
370                 eventAgeString(cn.completedHandshake),
371                 eventAgeString(cn.lastHelpful()),
372                 cn.cumInterest(),
373                 cn.totalExpectingTime(),
374         )
375         fmt.Fprintf(w,
376                 "    %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d-%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
377                 cn.completedString(),
378                 len(cn.peerTouchedPieces),
379                 &cn._stats.ChunksReadUseful,
380                 &cn._stats.ChunksRead,
381                 &cn._stats.ChunksWritten,
382                 cn.actualRequestState.Requests.GetCardinality(),
383                 cn.cancelledRequests.GetCardinality(),
384                 cn.nominalMaxRequests(),
385                 cn.PeerMaxRequests,
386                 len(cn.peerRequests),
387                 localClientReqq,
388                 cn.statusFlags(),
389                 cn.downloadRate()/(1<<10),
390         )
391         fmt.Fprintf(w, "    requested pieces:")
392         type pieceNumRequestsType struct {
393                 piece       pieceIndex
394                 numRequests int
395         }
396         var pieceNumRequests []pieceNumRequestsType
397         for piece, count := range cn.numRequestsByPiece() {
398                 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
399         }
400         sort.Slice(pieceNumRequests, func(i, j int) bool {
401                 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
402         })
403         for _, elem := range pieceNumRequests {
404                 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
405         }
406         fmt.Fprintf(w, "\n")
407 }
408
409 func (p *Peer) close() {
410         if !p.closed.Set() {
411                 return
412         }
413         if p.updateRequestsTimer != nil {
414                 p.updateRequestsTimer.Stop()
415         }
416         p.peerImpl.onClose()
417         if p.t != nil {
418                 p.t.decPeerPieceAvailability(p)
419         }
420         for _, f := range p.callbacks.PeerClosed {
421                 f(p)
422         }
423 }
424
425 func (cn *PeerConn) onClose() {
426         if cn.pex.IsEnabled() {
427                 cn.pex.Close()
428         }
429         cn.tickleWriter()
430         if cn.conn != nil {
431                 go cn.conn.Close()
432         }
433         if cb := cn.callbacks.PeerConnClosed; cb != nil {
434                 cb(cn)
435         }
436 }
437
438 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
439 // they do (known=true).
440 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
441         if all, known := cn.peerHasAllPieces(); all && known {
442                 return true
443         }
444         return cn.peerPieces().ContainsInt(piece)
445 }
446
447 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
448 // https://github.com/pion/datachannel/issues/59 is fixed.
449 const writeBufferHighWaterLen = 1 << 15
450
451 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
452 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
453 func (cn *PeerConn) write(msg pp.Message) bool {
454         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
455         // We don't need to track bytes here because the connection's Writer has that behaviour injected
456         // (although there's some delay between us buffering the message, and the connection writer
457         // flushing it out.).
458         notFull := cn.messageWriter.write(msg)
459         // Last I checked only Piece messages affect stats, and we don't write those.
460         cn.wroteMsg(&msg)
461         cn.tickleWriter()
462         return notFull
463 }
464
465 func (cn *PeerConn) requestMetadataPiece(index int) {
466         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
467         if eID == pp.ExtensionDeleteNumber {
468                 return
469         }
470         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
471                 return
472         }
473         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
474         cn.write(pp.MetadataExtensionRequestMsg(eID, index))
475         for index >= len(cn.metadataRequests) {
476                 cn.metadataRequests = append(cn.metadataRequests, false)
477         }
478         cn.metadataRequests[index] = true
479 }
480
481 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
482         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
483 }
484
485 // The actual value to use as the maximum outbound requests.
486 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
487         return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 2048))
488 }
489
490 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
491         ret = cn.cumulativeExpectedToReceiveChunks
492         if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
493                 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
494         }
495         return
496 }
497
498 func (cn *PeerConn) onPeerSentCancel(r Request) {
499         if _, ok := cn.peerRequests[r]; !ok {
500                 torrent.Add("unexpected cancels received", 1)
501                 return
502         }
503         if cn.fastEnabled() {
504                 cn.reject(r)
505         } else {
506                 delete(cn.peerRequests, r)
507         }
508 }
509
510 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
511         if cn.choking {
512                 return true
513         }
514         cn.choking = true
515         more = msg(pp.Message{
516                 Type: pp.Choke,
517         })
518         if cn.fastEnabled() {
519                 for r := range cn.peerRequests {
520                         // TODO: Don't reject pieces in allowed fast set.
521                         cn.reject(r)
522                 }
523         } else {
524                 cn.peerRequests = nil
525         }
526         return
527 }
528
529 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
530         if !cn.choking {
531                 return true
532         }
533         cn.choking = false
534         return msg(pp.Message{
535                 Type: pp.Unchoke,
536         })
537 }
538
539 func (cn *Peer) setInterested(interested bool) bool {
540         if cn.actualRequestState.Interested == interested {
541                 return true
542         }
543         cn.actualRequestState.Interested = interested
544         if interested {
545                 cn.lastBecameInterested = time.Now()
546         } else if !cn.lastBecameInterested.IsZero() {
547                 cn.priorInterest += time.Since(cn.lastBecameInterested)
548         }
549         cn.updateExpectingChunks()
550         // log.Printf("%p: setting interest: %v", cn, interested)
551         return cn.writeInterested(interested)
552 }
553
554 func (pc *PeerConn) writeInterested(interested bool) bool {
555         return pc.write(pp.Message{
556                 Type: func() pp.MessageType {
557                         if interested {
558                                 return pp.Interested
559                         } else {
560                                 return pp.NotInterested
561                         }
562                 }(),
563         })
564 }
565
566 // The function takes a message to be sent, and returns true if more messages
567 // are okay.
568 type messageWriter func(pp.Message) bool
569
570 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
571 // when we want to go fast.
572 func (cn *Peer) shouldRequest(r RequestIndex) error {
573         pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
574         if !cn.peerHasPiece(pi) {
575                 return errors.New("requesting piece peer doesn't have")
576         }
577         if !cn.t.peerIsActive(cn) {
578                 panic("requesting but not in active conns")
579         }
580         if cn.closed.IsSet() {
581                 panic("requesting when connection is closed")
582         }
583         if cn.t.hashingPiece(pi) {
584                 panic("piece is being hashed")
585         }
586         if cn.t.pieceQueuedForHash(pi) {
587                 panic("piece is queued for hash")
588         }
589         if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
590                 // This could occur if we made a request with the fast extension, and then got choked and
591                 // haven't had the request rejected yet.
592                 if !cn.actualRequestState.Requests.Contains(r) {
593                         panic("peer choking and piece not allowed fast")
594                 }
595         }
596         return nil
597 }
598
599 func (cn *Peer) mustRequest(r RequestIndex) bool {
600         more, err := cn.request(r)
601         if err != nil {
602                 panic(err)
603         }
604         return more
605 }
606
607 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
608         if err := cn.shouldRequest(r); err != nil {
609                 panic(err)
610         }
611         if cn.actualRequestState.Requests.Contains(r) {
612                 return true, nil
613         }
614         if maxRequests(cn.actualRequestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
615                 return true, errors.New("too many outstanding requests")
616         }
617         cn.actualRequestState.Requests.Add(r)
618         if cn.validReceiveChunks == nil {
619                 cn.validReceiveChunks = make(map[RequestIndex]int)
620         }
621         cn.validReceiveChunks[r]++
622         cn.t.pendingRequests[r] = cn
623         cn.t.lastRequested[r] = time.Now()
624         cn.updateExpectingChunks()
625         ppReq := cn.t.requestIndexToRequest(r)
626         for _, f := range cn.callbacks.SentRequest {
627                 f(PeerRequestEvent{cn, ppReq})
628         }
629         return cn.peerImpl._request(ppReq), nil
630 }
631
632 func (me *PeerConn) _request(r Request) bool {
633         return me.write(pp.Message{
634                 Type:   pp.Request,
635                 Index:  r.Index,
636                 Begin:  r.Begin,
637                 Length: r.Length,
638         })
639 }
640
641 func (me *Peer) cancel(r RequestIndex) {
642         if !me.actualRequestState.Requests.Contains(r) {
643                 panic(r)
644         }
645         me._cancel(r)
646 }
647
648 func (me *PeerConn) _cancel(r RequestIndex) {
649         if me.cancelledRequests.Contains(r) {
650                 // Already cancelled and waiting for a response.
651                 panic(r)
652         }
653         // Transmission does not send rejects for received cancels. See
654         // https://github.com/transmission/transmission/pull/2275.
655         if me.fastEnabled() && !me.remoteIsTransmission() {
656                 me.cancelledRequests.Add(r)
657         } else {
658                 if !me.deleteRequest(r) {
659                         panic("request not existing should have been guarded")
660                 }
661                 if me.isLowOnRequests() {
662                         me.updateRequests("Peer.cancel")
663                 }
664         }
665         me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
666 }
667
668 func (cn *PeerConn) fillWriteBuffer() {
669         if !cn.maybeUpdateActualRequestState() {
670                 return
671         }
672         if cn.pex.IsEnabled() {
673                 if flow := cn.pex.Share(cn.write); !flow {
674                         return
675                 }
676         }
677         cn.upload(cn.write)
678 }
679
680 func (cn *PeerConn) have(piece pieceIndex) {
681         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
682                 return
683         }
684         cn.write(pp.Message{
685                 Type:  pp.Have,
686                 Index: pp.Integer(piece),
687         })
688         cn.sentHaves.Add(bitmap.BitIndex(piece))
689 }
690
691 func (cn *PeerConn) postBitfield() {
692         if cn.sentHaves.Len() != 0 {
693                 panic("bitfield must be first have-related message sent")
694         }
695         if !cn.t.haveAnyPieces() {
696                 return
697         }
698         cn.write(pp.Message{
699                 Type:     pp.Bitfield,
700                 Bitfield: cn.t.bitfield(),
701         })
702         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
703 }
704
705 // Sets a reason to update requests, and if there wasn't already one, handle it.
706 func (cn *Peer) updateRequests(reason string) {
707         if cn.needRequestUpdate != "" {
708                 return
709         }
710         cn.needRequestUpdate = reason
711         cn.handleUpdateRequests()
712 }
713
714 func (cn *PeerConn) handleUpdateRequests() {
715         // The writer determines the request state as needed when it can write.
716         cn.tickleWriter()
717 }
718
719 // Emits the indices in the Bitmaps bms in order, never repeating any index.
720 // skip is mutated during execution, and its initial values will never be
721 // emitted.
722 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
723         return func(cb iter.Callback) {
724                 for _, bm := range bms {
725                         if !iter.All(
726                                 func(_i interface{}) bool {
727                                         i := _i.(int)
728                                         if skip.Contains(bitmap.BitIndex(i)) {
729                                                 return true
730                                         }
731                                         skip.Add(bitmap.BitIndex(i))
732                                         return cb(i)
733                                 },
734                                 bm.Iter,
735                         ) {
736                                 return
737                         }
738                 }
739         }
740 }
741
742 func (cn *Peer) peerPiecesChanged() {
743         cn.t.maybeDropMutuallyCompletePeer(cn)
744 }
745
746 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
747         if newMin > cn.peerMinPieces {
748                 cn.peerMinPieces = newMin
749         }
750 }
751
752 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
753         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
754                 return errors.New("invalid piece")
755         }
756         if cn.peerHasPiece(piece) {
757                 return nil
758         }
759         cn.raisePeerMinPieces(piece + 1)
760         if !cn.peerHasPiece(piece) {
761                 cn.t.incPieceAvailability(piece)
762         }
763         cn._peerPieces.Add(uint32(piece))
764         if cn.t.wantPieceIndex(piece) {
765                 cn.updateRequests("have")
766         }
767         cn.peerPiecesChanged()
768         return nil
769 }
770
771 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
772         if len(bf)%8 != 0 {
773                 panic("expected bitfield length divisible by 8")
774         }
775         // We know that the last byte means that at most the last 7 bits are wasted.
776         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
777         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
778                 // Ignore known excess pieces.
779                 bf = bf[:cn.t.numPieces()]
780         }
781         pp := cn.newPeerPieces()
782         cn.peerSentHaveAll = false
783         for i, have := range bf {
784                 if have {
785                         cn.raisePeerMinPieces(pieceIndex(i) + 1)
786                         if !pp.Contains(bitmap.BitIndex(i)) {
787                                 cn.t.incPieceAvailability(i)
788                         }
789                 } else {
790                         if pp.Contains(bitmap.BitIndex(i)) {
791                                 cn.t.decPieceAvailability(i)
792                         }
793                 }
794                 if have {
795                         cn._peerPieces.Add(uint32(i))
796                         if cn.t.wantPieceIndex(i) {
797                                 cn.updateRequests("bitfield")
798                         }
799                 } else {
800                         cn._peerPieces.Remove(uint32(i))
801                 }
802         }
803         cn.peerPiecesChanged()
804         return nil
805 }
806
807 func (cn *PeerConn) onPeerHasAllPieces() {
808         t := cn.t
809         if t.haveInfo() {
810                 npp, pc := cn.newPeerPieces(), t.numPieces()
811                 for i := 0; i < pc; i += 1 {
812                         if !npp.Contains(bitmap.BitIndex(i)) {
813                                 t.incPieceAvailability(i)
814                         }
815                 }
816         }
817         cn.peerSentHaveAll = true
818         cn._peerPieces.Clear()
819         if !cn.t._pendingPieces.IsEmpty() {
820                 cn.updateRequests("Peer.onPeerHasAllPieces")
821         }
822         cn.peerPiecesChanged()
823 }
824
825 func (cn *PeerConn) onPeerSentHaveAll() error {
826         cn.onPeerHasAllPieces()
827         return nil
828 }
829
830 func (cn *PeerConn) peerSentHaveNone() error {
831         cn.t.decPeerPieceAvailability(&cn.Peer)
832         cn._peerPieces.Clear()
833         cn.peerSentHaveAll = false
834         cn.peerPiecesChanged()
835         return nil
836 }
837
838 func (c *PeerConn) requestPendingMetadata() {
839         if c.t.haveInfo() {
840                 return
841         }
842         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
843                 // Peer doesn't support this.
844                 return
845         }
846         // Request metadata pieces that we don't have in a random order.
847         var pending []int
848         for index := 0; index < c.t.metadataPieceCount(); index++ {
849                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
850                         pending = append(pending, index)
851                 }
852         }
853         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
854         for _, i := range pending {
855                 c.requestMetadataPiece(i)
856         }
857 }
858
859 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
860         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
861         if msg.Type == pp.Extended {
862                 for name, id := range cn.PeerExtensionIDs {
863                         if id != msg.ExtendedID {
864                                 continue
865                         }
866                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
867                 }
868         }
869         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
870 }
871
872 // After handshake, we know what Torrent and Client stats to include for a
873 // connection.
874 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
875         t := cn.t
876         f(&t.stats)
877         f(&t.cl.stats)
878 }
879
880 // All ConnStats that include this connection. Some objects are not known
881 // until the handshake is complete, after which it's expected to reconcile the
882 // differences.
883 func (cn *Peer) allStats(f func(*ConnStats)) {
884         f(&cn._stats)
885         if cn.reconciledHandshakeStats {
886                 cn.postHandshakeStats(f)
887         }
888 }
889
890 func (cn *PeerConn) wroteBytes(n int64) {
891         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
892 }
893
894 func (cn *Peer) readBytes(n int64) {
895         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
896 }
897
898 // Returns whether the connection could be useful to us. We're seeding and
899 // they want data, we don't have metainfo and they can provide it, etc.
900 func (c *Peer) useful() bool {
901         t := c.t
902         if c.closed.IsSet() {
903                 return false
904         }
905         if !t.haveInfo() {
906                 return c.supportsExtension("ut_metadata")
907         }
908         if t.seeding() && c.peerInterested {
909                 return true
910         }
911         if c.peerHasWantedPieces() {
912                 return true
913         }
914         return false
915 }
916
917 func (c *Peer) lastHelpful() (ret time.Time) {
918         ret = c.lastUsefulChunkReceived
919         if c.t.seeding() && c.lastChunkSent.After(ret) {
920                 ret = c.lastChunkSent
921         }
922         return
923 }
924
925 func (c *PeerConn) fastEnabled() bool {
926         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
927 }
928
929 func (c *PeerConn) reject(r Request) {
930         if !c.fastEnabled() {
931                 panic("fast not enabled")
932         }
933         c.write(r.ToMsg(pp.Reject))
934         delete(c.peerRequests, r)
935 }
936
937 func (c *PeerConn) onReadRequest(r Request) error {
938         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
939         if _, ok := c.peerRequests[r]; ok {
940                 torrent.Add("duplicate requests received", 1)
941                 return nil
942         }
943         if c.choking {
944                 torrent.Add("requests received while choking", 1)
945                 if c.fastEnabled() {
946                         torrent.Add("requests rejected while choking", 1)
947                         c.reject(r)
948                 }
949                 return nil
950         }
951         // TODO: What if they've already requested this?
952         if len(c.peerRequests) >= localClientReqq {
953                 torrent.Add("requests received while queue full", 1)
954                 if c.fastEnabled() {
955                         c.reject(r)
956                 }
957                 // BEP 6 says we may close here if we choose.
958                 return nil
959         }
960         if !c.t.havePiece(pieceIndex(r.Index)) {
961                 // This isn't necessarily them screwing up. We can drop pieces
962                 // from our storage, and can't communicate this to peers
963                 // except by reconnecting.
964                 requestsReceivedForMissingPieces.Add(1)
965                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
966         }
967         // Check this after we know we have the piece, so that the piece length will be known.
968         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
969                 torrent.Add("bad requests received", 1)
970                 return errors.New("bad Request")
971         }
972         if c.peerRequests == nil {
973                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
974         }
975         value := &peerRequestState{}
976         c.peerRequests[r] = value
977         go c.peerRequestDataReader(r, value)
978         // c.tickleWriter()
979         return nil
980 }
981
982 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
983         b, err := readPeerRequestData(r, c)
984         c.locker().Lock()
985         defer c.locker().Unlock()
986         if err != nil {
987                 c.peerRequestDataReadFailed(err, r)
988         } else {
989                 if b == nil {
990                         panic("data must be non-nil to trigger send")
991                 }
992                 prs.data = b
993                 c.tickleWriter()
994         }
995 }
996
997 // If this is maintained correctly, we might be able to support optional synchronous reading for
998 // chunk sending, the way it used to work.
999 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1000         c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1001         if c.t.closed.IsSet() {
1002                 return
1003         }
1004         i := pieceIndex(r.Index)
1005         if c.t.pieceComplete(i) {
1006                 // There used to be more code here that just duplicated the following break. Piece
1007                 // completions are currently cached, so I'm not sure how helpful this update is, except to
1008                 // pull any completion changes pushed to the storage backend in failed reads that got us
1009                 // here.
1010                 c.t.updatePieceCompletion(i)
1011         }
1012         // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1013         // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1014         // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1015         // next connect. TODO: Support rejecting here too.
1016         if c.choking {
1017                 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1018         }
1019         c.choke(c.write)
1020 }
1021
1022 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1023         b := make([]byte, r.Length)
1024         p := c.t.info.Piece(int(r.Index))
1025         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1026         if n == len(b) {
1027                 if err == io.EOF {
1028                         err = nil
1029                 }
1030         } else {
1031                 if err == nil {
1032                         panic("expected error")
1033                 }
1034         }
1035         return b, err
1036 }
1037
1038 func runSafeExtraneous(f func()) {
1039         if true {
1040                 go f()
1041         } else {
1042                 f()
1043         }
1044 }
1045
1046 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1047         c.logger.WithLevel(level).WithContextText(fmt.Sprintf(
1048                 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1049         )).SkipCallers(1).Printf(format, arg...)
1050 }
1051
1052 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1053 // exit. Returning will end the connection.
1054 func (c *PeerConn) mainReadLoop() (err error) {
1055         defer func() {
1056                 if err != nil {
1057                         torrent.Add("connection.mainReadLoop returned with error", 1)
1058                 } else {
1059                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1060                 }
1061         }()
1062         t := c.t
1063         cl := t.cl
1064
1065         decoder := pp.Decoder{
1066                 R:         bufio.NewReaderSize(c.r, 1<<17),
1067                 MaxLength: 256 * 1024,
1068                 Pool:      &t.chunkPool,
1069         }
1070         for {
1071                 var msg pp.Message
1072                 func() {
1073                         cl.unlock()
1074                         defer cl.lock()
1075                         err = decoder.Decode(&msg)
1076                 }()
1077                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1078                         cb(c, &msg)
1079                 }
1080                 if t.closed.IsSet() || c.closed.IsSet() {
1081                         return nil
1082                 }
1083                 if err != nil {
1084                         return err
1085                 }
1086                 c.lastMessageReceived = time.Now()
1087                 if msg.Keepalive {
1088                         receivedKeepalives.Add(1)
1089                         continue
1090                 }
1091                 messageTypesReceived.Add(msg.Type.String(), 1)
1092                 if msg.Type.FastExtension() && !c.fastEnabled() {
1093                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1094                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1095                 }
1096                 switch msg.Type {
1097                 case pp.Choke:
1098                         if c.peerChoking {
1099                                 break
1100                         }
1101                         if !c.fastEnabled() {
1102                                 c.deleteAllRequests()
1103                         } else {
1104                                 // We don't decrement pending requests here, let's wait for the peer to either
1105                                 // reject or satisfy the outstanding requests. Additionally some peers may unchoke
1106                                 // us and resume where they left off, we don't want to have piled on to those chunks
1107                                 // in the meanwhile. I think a peers ability to abuse this should be limited: they
1108                                 // could let us request a lot of stuff, then choke us and never reject, but they're
1109                                 // only a single peer, our chunk balancing should smooth over this abuse.
1110                         }
1111                         c.peerChoking = true
1112                         // We can now reset our interest. I think we do this after setting the flag in case the
1113                         // peerImpl updates synchronously (webseeds?).
1114                         if !c.actualRequestState.Requests.IsEmpty() {
1115                                 c.updateRequests("choked")
1116                         }
1117                         c.updateExpectingChunks()
1118                 case pp.Unchoke:
1119                         if !c.peerChoking {
1120                                 // Some clients do this for some reason. Transmission doesn't error on this, so we
1121                                 // won't for consistency.
1122                                 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1123                                 break
1124                         }
1125                         c.peerChoking = false
1126                         preservedCount := 0
1127                         c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1128                                 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1129                                         preservedCount++
1130                                 }
1131                                 return true
1132                         })
1133                         if preservedCount != 0 {
1134                                 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1135                                 // right now.
1136                                 c.logger.WithLevel(log.Debug).Printf(
1137                                         "%v requests were preserved while being choked (fast=%v)",
1138                                         preservedCount,
1139                                         c.fastEnabled())
1140                                 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1141                         }
1142                         if !c.t._pendingPieces.IsEmpty() {
1143                                 c.updateRequests("unchoked")
1144                         }
1145                         c.updateExpectingChunks()
1146                 case pp.Interested:
1147                         c.peerInterested = true
1148                         c.tickleWriter()
1149                 case pp.NotInterested:
1150                         c.peerInterested = false
1151                         // We don't clear their requests since it isn't clear in the spec.
1152                         // We'll probably choke them for this, which will clear them if
1153                         // appropriate, and is clearly specified.
1154                 case pp.Have:
1155                         err = c.peerSentHave(pieceIndex(msg.Index))
1156                 case pp.Bitfield:
1157                         err = c.peerSentBitfield(msg.Bitfield)
1158                 case pp.Request:
1159                         r := newRequestFromMessage(&msg)
1160                         err = c.onReadRequest(r)
1161                 case pp.Piece:
1162                         c.doChunkReadStats(int64(len(msg.Piece)))
1163                         err = c.receiveChunk(&msg)
1164                         if len(msg.Piece) == int(t.chunkSize) {
1165                                 t.chunkPool.Put(&msg.Piece)
1166                         }
1167                         if err != nil {
1168                                 err = fmt.Errorf("receiving chunk: %w", err)
1169                         }
1170                 case pp.Cancel:
1171                         req := newRequestFromMessage(&msg)
1172                         c.onPeerSentCancel(req)
1173                 case pp.Port:
1174                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1175                         if !ok {
1176                                 break
1177                         }
1178                         pingAddr := net.UDPAddr{
1179                                 IP:   ipa.IP,
1180                                 Port: ipa.Port,
1181                         }
1182                         if msg.Port != 0 {
1183                                 pingAddr.Port = int(msg.Port)
1184                         }
1185                         cl.eachDhtServer(func(s DhtServer) {
1186                                 go s.Ping(&pingAddr)
1187                         })
1188                 case pp.Suggest:
1189                         torrent.Add("suggests received", 1)
1190                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1191                         c.updateRequests("suggested")
1192                 case pp.HaveAll:
1193                         err = c.onPeerSentHaveAll()
1194                 case pp.HaveNone:
1195                         err = c.peerSentHaveNone()
1196                 case pp.Reject:
1197                         c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1198                 case pp.AllowedFast:
1199                         torrent.Add("allowed fasts received", 1)
1200                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1201                         c.updateRequests("PeerConn.mainReadLoop allowed fast")
1202                 case pp.Extended:
1203                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1204                 default:
1205                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1206                 }
1207                 if err != nil {
1208                         return err
1209                 }
1210         }
1211 }
1212
1213 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1214         if c.deleteRequest(r) {
1215                 if c.isLowOnRequests() {
1216                         c.updateRequests("Peer.remoteRejectedRequest")
1217                 }
1218                 c.decExpectedChunkReceive(r)
1219         }
1220 }
1221
1222 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1223         count := c.validReceiveChunks[r]
1224         if count == 1 {
1225                 delete(c.validReceiveChunks, r)
1226         } else if count > 1 {
1227                 c.validReceiveChunks[r] = count - 1
1228         } else {
1229                 panic(r)
1230         }
1231 }
1232
1233 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1234         defer func() {
1235                 // TODO: Should we still do this?
1236                 if err != nil {
1237                         // These clients use their own extension IDs for outgoing message
1238                         // types, which is incorrect.
1239                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1240                                 err = nil
1241                         }
1242                 }
1243         }()
1244         t := c.t
1245         cl := t.cl
1246         switch id {
1247         case pp.HandshakeExtendedID:
1248                 var d pp.ExtendedHandshakeMessage
1249                 if err := bencode.Unmarshal(payload, &d); err != nil {
1250                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1251                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1252                 }
1253                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1254                         cb(c, &d)
1255                 }
1256                 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1257                 if d.Reqq != 0 {
1258                         c.PeerMaxRequests = d.Reqq
1259                 }
1260                 c.PeerClientName.Store(d.V)
1261                 if c.PeerExtensionIDs == nil {
1262                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1263                 }
1264                 c.PeerListenPort = d.Port
1265                 c.PeerPrefersEncryption = d.Encryption
1266                 for name, id := range d.M {
1267                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1268                                 peersSupportingExtension.Add(
1269                                         // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1270                                         // entered here which caused problems later when unmarshalling.
1271                                         strconv.Quote(string(name)),
1272                                         1)
1273                         }
1274                         c.PeerExtensionIDs[name] = id
1275                 }
1276                 if d.MetadataSize != 0 {
1277                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1278                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1279                         }
1280                 }
1281                 c.requestPendingMetadata()
1282                 if !t.cl.config.DisablePEX {
1283                         t.pex.Add(c) // we learnt enough now
1284                         c.pex.Init(c)
1285                 }
1286                 return nil
1287         case metadataExtendedId:
1288                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1289                 if err != nil {
1290                         return fmt.Errorf("handling metadata extension message: %w", err)
1291                 }
1292                 return nil
1293         case pexExtendedId:
1294                 if !c.pex.IsEnabled() {
1295                         return nil // or hang-up maybe?
1296                 }
1297                 return c.pex.Recv(payload)
1298         default:
1299                 return fmt.Errorf("unexpected extended message ID: %v", id)
1300         }
1301 }
1302
1303 // Set both the Reader and Writer for the connection from a single ReadWriter.
1304 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1305         cn.r = rw
1306         cn.w = rw
1307 }
1308
1309 // Returns the Reader and Writer as a combined ReadWriter.
1310 func (cn *PeerConn) rw() io.ReadWriter {
1311         return struct {
1312                 io.Reader
1313                 io.Writer
1314         }{cn.r, cn.w}
1315 }
1316
1317 func (c *Peer) doChunkReadStats(size int64) {
1318         c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1319 }
1320
1321 // Handle a received chunk from a peer.
1322 func (c *Peer) receiveChunk(msg *pp.Message) error {
1323         chunksReceived.Add("total", 1)
1324
1325         ppReq := newRequestFromMessage(msg)
1326         req := c.t.requestIndexFromRequest(ppReq)
1327
1328         if c.peerChoking {
1329                 chunksReceived.Add("while choked", 1)
1330         }
1331
1332         if c.validReceiveChunks[req] <= 0 {
1333                 chunksReceived.Add("unexpected", 1)
1334                 return errors.New("received unexpected chunk")
1335         }
1336         c.decExpectedChunkReceive(req)
1337
1338         if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1339                 chunksReceived.Add("due to allowed fast", 1)
1340         }
1341
1342         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1343         // have actually already received the piece, while we have the Client unlocked to write the data
1344         // out.
1345         deletedRequest := false
1346         {
1347                 if c.actualRequestState.Requests.Contains(req) {
1348                         for _, f := range c.callbacks.ReceivedRequested {
1349                                 f(PeerMessageEvent{c, msg})
1350                         }
1351                 }
1352                 // Request has been satisfied.
1353                 if c.deleteRequest(req) {
1354                         deletedRequest = true
1355                         if !c.peerChoking {
1356                                 c._chunksReceivedWhileExpecting++
1357                         }
1358                         if c.isLowOnRequests() {
1359                                 c.updateRequests("Peer.receiveChunk deleted request")
1360                         }
1361                 } else {
1362                         chunksReceived.Add("unwanted", 1)
1363                 }
1364         }
1365
1366         t := c.t
1367         cl := t.cl
1368
1369         // Do we actually want this chunk?
1370         if t.haveChunk(ppReq) {
1371                 // panic(fmt.Sprintf("%+v", ppReq))
1372                 chunksReceived.Add("wasted", 1)
1373                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1374                 return nil
1375         }
1376
1377         piece := &t.pieces[ppReq.Index]
1378
1379         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1380         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1381         if deletedRequest {
1382                 c.piecesReceivedSinceLastRequestUpdate++
1383                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1384         }
1385         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1386                 f(ReceivedUsefulDataEvent{c, msg})
1387         }
1388         c.lastUsefulChunkReceived = time.Now()
1389
1390         // Need to record that it hasn't been written yet, before we attempt to do
1391         // anything with it.
1392         piece.incrementPendingWrites()
1393         // Record that we have the chunk, so we aren't trying to download it while
1394         // waiting for it to be written to storage.
1395         piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1396
1397         // Cancel pending requests for this chunk from *other* peers.
1398         if p := t.pendingRequests[req]; p != nil {
1399                 if p == c {
1400                         panic("should not be pending request from conn that just received it")
1401                 }
1402                 p.cancel(req)
1403         }
1404
1405         err := func() error {
1406                 cl.unlock()
1407                 defer cl.lock()
1408                 concurrentChunkWrites.Add(1)
1409                 defer concurrentChunkWrites.Add(-1)
1410                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1411                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1412                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1413                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1414                 // that instead.
1415                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1416         }()
1417
1418         piece.decrementPendingWrites()
1419
1420         if err != nil {
1421                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1422                 t.pendRequest(req)
1423                 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1424                 // request update runs while we're writing the chunk that just failed. Then we never do a
1425                 // fresh update after pending the failed request.
1426                 c.updateRequests("Peer.receiveChunk error writing chunk")
1427                 t.onWriteChunkErr(err)
1428                 return nil
1429         }
1430
1431         c.onDirtiedPiece(pieceIndex(ppReq.Index))
1432
1433         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1434         if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1435                 t.queuePieceCheck(pieceIndex(ppReq.Index))
1436                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1437                 // chunk status (such as the haveChunk call above) to have to check all the various other
1438                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1439                 // that chunk pieces are pended at an appropriate time later however.
1440         }
1441
1442         cl.event.Broadcast()
1443         // We do this because we've written a chunk, and may change PieceState.Partial.
1444         t.publishPieceChange(pieceIndex(ppReq.Index))
1445
1446         return nil
1447 }
1448
1449 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1450         if c.peerTouchedPieces == nil {
1451                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1452         }
1453         c.peerTouchedPieces[piece] = struct{}{}
1454         ds := &c.t.pieces[piece].dirtiers
1455         if *ds == nil {
1456                 *ds = make(map[*Peer]struct{})
1457         }
1458         (*ds)[c] = struct{}{}
1459 }
1460
1461 func (c *PeerConn) uploadAllowed() bool {
1462         if c.t.cl.config.NoUpload {
1463                 return false
1464         }
1465         if c.t.dataUploadDisallowed {
1466                 return false
1467         }
1468         if c.t.seeding() {
1469                 return true
1470         }
1471         if !c.peerHasWantedPieces() {
1472                 return false
1473         }
1474         // Don't upload more than 100 KiB more than we download.
1475         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1476                 return false
1477         }
1478         return true
1479 }
1480
1481 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1482         if c.uploadTimer == nil {
1483                 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1484         } else {
1485                 c.uploadTimer.Reset(delay)
1486         }
1487 }
1488
1489 // Also handles choking and unchoking of the remote peer.
1490 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1491         // Breaking or completing this loop means we don't want to upload to the
1492         // peer anymore, and we choke them.
1493 another:
1494         for c.uploadAllowed() {
1495                 // We want to upload to the peer.
1496                 if !c.unchoke(msg) {
1497                         return false
1498                 }
1499                 for r, state := range c.peerRequests {
1500                         if state.data == nil {
1501                                 continue
1502                         }
1503                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1504                         if !res.OK() {
1505                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1506                         }
1507                         delay := res.Delay()
1508                         if delay > 0 {
1509                                 res.Cancel()
1510                                 c.setRetryUploadTimer(delay)
1511                                 // Hard to say what to return here.
1512                                 return true
1513                         }
1514                         more := c.sendChunk(r, msg, state)
1515                         delete(c.peerRequests, r)
1516                         if !more {
1517                                 return false
1518                         }
1519                         goto another
1520                 }
1521                 return true
1522         }
1523         return c.choke(msg)
1524 }
1525
1526 func (cn *PeerConn) drop() {
1527         cn.t.dropConnection(cn)
1528 }
1529
1530 func (cn *Peer) netGoodPiecesDirtied() int64 {
1531         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1532 }
1533
1534 func (c *Peer) peerHasWantedPieces() bool {
1535         if all, _ := c.peerHasAllPieces(); all {
1536                 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1537         }
1538         if !c.t.haveInfo() {
1539                 return !c.peerPieces().IsEmpty()
1540         }
1541         return c.peerPieces().Intersects(&c.t._pendingPieces)
1542 }
1543
1544 func (c *Peer) deleteRequest(r RequestIndex) bool {
1545         if !c.actualRequestState.Requests.CheckedRemove(r) {
1546                 return false
1547         }
1548         c.cancelledRequests.Remove(r)
1549         for _, f := range c.callbacks.DeletedRequest {
1550                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1551         }
1552         c.updateExpectingChunks()
1553         if c.t.requestingPeer(r) == c {
1554                 delete(c.t.pendingRequests, r)
1555                 delete(c.t.lastRequested, r)
1556         }
1557         return true
1558 }
1559
1560 func (c *Peer) deleteAllRequests() {
1561         c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1562                 c.deleteRequest(x)
1563                 return true
1564         })
1565         if !c.actualRequestState.Requests.IsEmpty() {
1566                 panic(c.actualRequestState.Requests.GetCardinality())
1567         }
1568 }
1569
1570 // This is called when something has changed that should wake the writer, such as putting stuff into
1571 // the writeBuffer, or changing some state that the writer can act on.
1572 func (c *PeerConn) tickleWriter() {
1573         c.messageWriter.writeCond.Broadcast()
1574 }
1575
1576 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1577         c.lastChunkSent = time.Now()
1578         return msg(pp.Message{
1579                 Type:  pp.Piece,
1580                 Index: r.Index,
1581                 Begin: r.Begin,
1582                 Piece: state.data,
1583         })
1584 }
1585
1586 func (c *PeerConn) setTorrent(t *Torrent) {
1587         if c.t != nil {
1588                 panic("connection already associated with a torrent")
1589         }
1590         c.t = t
1591         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1592         t.reconcileHandshakeStats(c)
1593 }
1594
1595 func (c *Peer) peerPriority() (peerPriority, error) {
1596         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1597 }
1598
1599 func (c *Peer) remoteIp() net.IP {
1600         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1601         return net.ParseIP(host)
1602 }
1603
1604 func (c *Peer) remoteIpPort() IpPort {
1605         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1606         return IpPort{ipa.IP, uint16(ipa.Port)}
1607 }
1608
1609 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1610         f := pp.PexPeerFlags(0)
1611         if c.PeerPrefersEncryption {
1612                 f |= pp.PexPrefersEncryption
1613         }
1614         if c.outgoing {
1615                 f |= pp.PexOutgoingConn
1616         }
1617         if c.utp() {
1618                 f |= pp.PexSupportsUtp
1619         }
1620         return f
1621 }
1622
1623 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1624 // advertised listen port.
1625 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1626         if !c.outgoing && c.PeerListenPort != 0 {
1627                 switch addr := c.RemoteAddr.(type) {
1628                 case *net.TCPAddr:
1629                         dialAddr := *addr
1630                         dialAddr.Port = c.PeerListenPort
1631                         return &dialAddr
1632                 case *net.UDPAddr:
1633                         dialAddr := *addr
1634                         dialAddr.Port = c.PeerListenPort
1635                         return &dialAddr
1636                 }
1637         }
1638         return c.RemoteAddr
1639 }
1640
1641 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1642         f := c.pexPeerFlags()
1643         addr := c.dialAddr()
1644         return pexEvent{t, addr, f, nil}
1645 }
1646
1647 func (c *PeerConn) String() string {
1648         return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1649 }
1650
1651 func (c *Peer) trust() connectionTrust {
1652         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1653 }
1654
1655 type connectionTrust struct {
1656         Implicit            bool
1657         NetGoodPiecesDirted int64
1658 }
1659
1660 func (l connectionTrust) Less(r connectionTrust) bool {
1661         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1662 }
1663
1664 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1665 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1666 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1667         cn.locker().RLock()
1668         defer cn.locker().RUnlock()
1669         return cn.newPeerPieces()
1670 }
1671
1672 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1673 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1674         // TODO: Can we use copy on write?
1675         ret := cn.peerPieces().Clone()
1676         if all, _ := cn.peerHasAllPieces(); all {
1677                 if cn.t.haveInfo() {
1678                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1679                 } else {
1680                         ret.AddRange(0, bitmap.ToEnd)
1681                 }
1682         }
1683         return ret
1684 }
1685
1686 func (cn *Peer) stats() *ConnStats {
1687         return &cn._stats
1688 }
1689
1690 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1691         pc, ok := p.peerImpl.(*PeerConn)
1692         return pc, ok
1693 }
1694
1695 func (pc *PeerConn) isLowOnRequests() bool {
1696         return pc.actualRequestState.Requests.IsEmpty()
1697 }
1698
1699 func (p *Peer) uncancelledRequests() uint64 {
1700         return p.actualRequestState.Requests.GetCardinality() - p.cancelledRequests.GetCardinality()
1701 }
1702
1703 func (pc *PeerConn) remoteIsTransmission() bool {
1704         return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1705 }