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