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