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