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