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