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