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