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