]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Reduce the diff to master and add peerRequesting feature const
[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                 i := RequestIndex(_i)
186                 return cn.actualRequestState.Requests.Rank((i+1)*cn.t.chunksPerRegularPiece())-
187                         cn.actualRequestState.Requests.Rank(i*cn.t.chunksPerRegularPiece()) == 0
188         }) {
189                 return true
190         }
191         return !cn.peerChoking
192 }
193
194 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
195         return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
196 }
197
198 // Returns true if the connection is over IPv6.
199 func (cn *PeerConn) ipv6() bool {
200         ip := cn.remoteIp()
201         if ip.To4() != nil {
202                 return false
203         }
204         return len(ip) == net.IPv6len
205 }
206
207 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
208 // specification for this.
209 func (cn *PeerConn) isPreferredDirection() bool {
210         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
211 }
212
213 // Returns whether the left connection should be preferred over the right one,
214 // considering only their networking properties. If ok is false, we can't
215 // decide.
216 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
217         var ml multiLess
218         ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
219         ml.NextBool(!l.utp(), !r.utp())
220         ml.NextBool(l.ipv6(), r.ipv6())
221         return ml.FinalOk()
222 }
223
224 func (cn *Peer) cumInterest() time.Duration {
225         ret := cn.priorInterest
226         if cn.actualRequestState.Interested {
227                 ret += time.Since(cn.lastBecameInterested)
228         }
229         return ret
230 }
231
232 func (cn *Peer) peerHasAllPieces() (all bool, known bool) {
233         if cn.peerSentHaveAll {
234                 return true, true
235         }
236         if !cn.t.haveInfo() {
237                 return false, false
238         }
239         return bitmap.Flip(cn._peerPieces, 0, bitmap.BitRange(cn.t.numPieces())).IsEmpty(), true
240 }
241
242 func (cn *PeerConn) locker() *lockWithDeferreds {
243         return cn.t.cl.locker()
244 }
245
246 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
247         _, ok := cn.PeerExtensionIDs[ext]
248         return ok
249 }
250
251 // The best guess at number of pieces in the torrent for this peer.
252 func (cn *Peer) bestPeerNumPieces() pieceIndex {
253         if cn.t.haveInfo() {
254                 return cn.t.numPieces()
255         }
256         return cn.peerMinPieces
257 }
258
259 func (cn *Peer) completedString() string {
260         have := pieceIndex(cn._peerPieces.Len())
261         if cn.peerSentHaveAll {
262                 have = cn.bestPeerNumPieces()
263         }
264         return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
265 }
266
267 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
268         cn.setNumPieces(info.NumPieces())
269 }
270
271 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
272 // receiving badly sized BITFIELD, or invalid HAVE messages.
273 func (cn *PeerConn) setNumPieces(num pieceIndex) {
274         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
275         cn.peerPiecesChanged()
276 }
277
278 func eventAgeString(t time.Time) string {
279         if t.IsZero() {
280                 return "never"
281         }
282         return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
283 }
284
285 func (cn *PeerConn) connectionFlags() (ret string) {
286         c := func(b byte) {
287                 ret += string([]byte{b})
288         }
289         if cn.cryptoMethod == mse.CryptoMethodRC4 {
290                 c('E')
291         } else if cn.headerEncrypted {
292                 c('e')
293         }
294         ret += string(cn.Discovery)
295         if cn.utp() {
296                 c('U')
297         }
298         return
299 }
300
301 func (cn *PeerConn) utp() bool {
302         return parseNetworkString(cn.Network).Udp
303 }
304
305 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
306 func (cn *Peer) statusFlags() (ret string) {
307         c := func(b byte) {
308                 ret += string([]byte{b})
309         }
310         if cn.actualRequestState.Interested {
311                 c('i')
312         }
313         if cn.choking {
314                 c('c')
315         }
316         c('-')
317         ret += cn.connectionFlags()
318         c('-')
319         if cn.peerInterested {
320                 c('i')
321         }
322         if cn.peerChoking {
323                 c('c')
324         }
325         return
326 }
327
328 func (cn *Peer) downloadRate() float64 {
329         num := cn._stats.BytesReadUsefulData.Int64()
330         if num == 0 {
331                 return 0
332         }
333         return float64(num) / cn.totalExpectingTime().Seconds()
334 }
335
336 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
337         ret = make(map[pieceIndex]int)
338         cn.actualRequestState.Requests.Iterate(func(x uint32) bool {
339                 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
340                 return true
341         })
342         return
343 }
344
345 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
346         // \t isn't preserved in <pre> blocks?
347         if cn.closed.IsSet() {
348                 fmt.Fprint(w, "CLOSED: ")
349         }
350         fmt.Fprintln(w, cn.connStatusString())
351         prio, err := cn.peerPriority()
352         prioStr := fmt.Sprintf("%08x", prio)
353         if err != nil {
354                 prioStr += ": " + err.Error()
355         }
356         fmt.Fprintf(w, "    bep40-prio: %v\n", prioStr)
357         fmt.Fprintf(w, "    last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
358                 eventAgeString(cn.lastMessageReceived),
359                 eventAgeString(cn.completedHandshake),
360                 eventAgeString(cn.lastHelpful()),
361                 cn.cumInterest(),
362                 cn.totalExpectingTime(),
363         )
364         fmt.Fprintf(w,
365                 "    %s completed, %d pieces touched, good chunks: %v/%v-%v reqq: %d/(%d/%d)-%d/%d, flags: %s, dr: %.1f KiB/s\n",
366                 cn.completedString(),
367                 len(cn.peerTouchedPieces),
368                 &cn._stats.ChunksReadUseful,
369                 &cn._stats.ChunksRead,
370                 &cn._stats.ChunksWritten,
371                 cn.actualRequestState.Requests.GetCardinality(),
372                 cn.nominalMaxRequests(),
373                 cn.PeerMaxRequests,
374                 len(cn.peerRequests),
375                 localClientReqq,
376                 cn.statusFlags(),
377                 cn.downloadRate()/(1<<10),
378         )
379         fmt.Fprintf(w, "    requested pieces:")
380         type pieceNumRequestsType struct {
381                 piece       pieceIndex
382                 numRequests int
383         }
384         var pieceNumRequests []pieceNumRequestsType
385         for piece, count := range cn.numRequestsByPiece() {
386                 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
387         }
388         sort.Slice(pieceNumRequests, func(i, j int) bool {
389                 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
390         })
391         for _, elem := range pieceNumRequests {
392                 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
393         }
394         fmt.Fprintf(w, "\n")
395 }
396
397 func (p *Peer) close() {
398         if !p.closed.Set() {
399                 return
400         }
401         p.discardPieceInclination()
402         p._pieceRequestOrder.Clear()
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), 128))
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[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                 return me.peerImpl._cancel(me.t.requestIndexToRequest(r))
612         }
613         return true
614 }
615
616 func (me *PeerConn) _cancel(r Request) bool {
617         return me.write(makeCancelMessage(r))
618 }
619
620 func (cn *PeerConn) fillWriteBuffer() {
621         if !cn.applyNextRequestState() {
622                 return
623         }
624         if cn.pex.IsEnabled() {
625                 if flow := cn.pex.Share(cn.write); !flow {
626                         return
627                 }
628         }
629         cn.upload(cn.write)
630 }
631
632 func (cn *PeerConn) have(piece pieceIndex) {
633         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
634                 return
635         }
636         cn.write(pp.Message{
637                 Type:  pp.Have,
638                 Index: pp.Integer(piece),
639         })
640         cn.sentHaves.Add(bitmap.BitIndex(piece))
641 }
642
643 func (cn *PeerConn) postBitfield() {
644         if cn.sentHaves.Len() != 0 {
645                 panic("bitfield must be first have-related message sent")
646         }
647         if !cn.t.haveAnyPieces() {
648                 return
649         }
650         cn.write(pp.Message{
651                 Type:     pp.Bitfield,
652                 Bitfield: cn.t.bitfield(),
653         })
654         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
655 }
656
657 func (cn *PeerConn) updateRequests() {
658         if peerRequesting {
659                 if cn.actualRequestState.Requests.GetCardinality() != 0 {
660                         return
661                 }
662                 cn.tickleWriter()
663                 return
664         }
665         cn.t.cl.tickleRequester()
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 // check callers updaterequests
692 func (cn *Peer) stopRequestingPiece(piece pieceIndex) bool {
693         return cn._pieceRequestOrder.Remove(piece)
694 }
695
696 // This is distinct from Torrent piece priority, which is the user's
697 // preference. Connection piece priority is specific to a connection and is
698 // used to pseudorandomly avoid connections always requesting the same pieces
699 // and thus wasting effort.
700 func (cn *Peer) updatePiecePriority(piece pieceIndex) bool {
701         tpp := cn.t.piecePriority(piece)
702         if !cn.peerHasPiece(piece) {
703                 tpp = PiecePriorityNone
704         }
705         if tpp == PiecePriorityNone {
706                 return cn.stopRequestingPiece(piece)
707         }
708         prio := cn.getPieceInclination()[piece]
709         return cn._pieceRequestOrder.Set(piece, prio)
710 }
711
712 func (cn *Peer) getPieceInclination() []int {
713         if cn.pieceInclination == nil {
714                 cn.pieceInclination = cn.t.getConnPieceInclination()
715         }
716         return cn.pieceInclination
717 }
718
719 func (cn *Peer) discardPieceInclination() {
720         if cn.pieceInclination == nil {
721                 return
722         }
723         cn.t.putPieceInclination(cn.pieceInclination)
724         cn.pieceInclination = nil
725 }
726
727 func (cn *Peer) peerPiecesChanged() {
728         if cn.t.haveInfo() {
729                 prioritiesChanged := false
730                 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
731                         if cn.updatePiecePriority(i) {
732                                 prioritiesChanged = true
733                         }
734                 }
735                 if prioritiesChanged {
736                         cn.updateRequests()
737                 }
738         }
739         cn.t.maybeDropMutuallyCompletePeer(cn)
740 }
741
742 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
743         if newMin > cn.peerMinPieces {
744                 cn.peerMinPieces = newMin
745         }
746 }
747
748 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
749         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
750                 return errors.New("invalid piece")
751         }
752         if cn.peerHasPiece(piece) {
753                 return nil
754         }
755         cn.raisePeerMinPieces(piece + 1)
756         if !cn.peerHasPiece(piece) {
757                 cn.t.incPieceAvailability(piece)
758         }
759         cn._peerPieces.Set(bitmap.BitIndex(piece), true)
760         cn.t.maybeDropMutuallyCompletePeer(&cn.Peer)
761         if cn.updatePiecePriority(piece) {
762                 cn.updateRequests()
763         }
764         return nil
765 }
766
767 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
768         if len(bf)%8 != 0 {
769                 panic("expected bitfield length divisible by 8")
770         }
771         // We know that the last byte means that at most the last 7 bits are wasted.
772         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
773         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
774                 // Ignore known excess pieces.
775                 bf = bf[:cn.t.numPieces()]
776         }
777         pp := cn.newPeerPieces()
778         cn.peerSentHaveAll = false
779         for i, have := range bf {
780                 if have {
781                         cn.raisePeerMinPieces(pieceIndex(i) + 1)
782                         if !pp.Contains(bitmap.BitIndex(i)) {
783                                 cn.t.incPieceAvailability(i)
784                         }
785                 } else {
786                         if pp.Contains(bitmap.BitIndex(i)) {
787                                 cn.t.decPieceAvailability(i)
788                         }
789                 }
790                 cn._peerPieces.Set(bitmap.BitIndex(i), have)
791         }
792         cn.peerPiecesChanged()
793         return nil
794 }
795
796 func (cn *Peer) onPeerHasAllPieces() {
797         t := cn.t
798         if t.haveInfo() {
799                 npp, pc := cn.newPeerPieces(), t.numPieces()
800                 for i := 0; i < pc; i += 1 {
801                         if !npp.Contains(bitmap.BitIndex(i)) {
802                                 t.incPieceAvailability(i)
803                         }
804                 }
805         }
806         cn.peerSentHaveAll = true
807         cn._peerPieces.Clear()
808         cn.peerPiecesChanged()
809 }
810
811 func (cn *PeerConn) onPeerSentHaveAll() error {
812         cn.onPeerHasAllPieces()
813         return nil
814 }
815
816 func (cn *PeerConn) peerSentHaveNone() error {
817         cn.t.decPeerPieceAvailability(&cn.Peer)
818         cn._peerPieces.Clear()
819         cn.peerSentHaveAll = false
820         cn.peerPiecesChanged()
821         return nil
822 }
823
824 func (c *PeerConn) requestPendingMetadata() {
825         if c.t.haveInfo() {
826                 return
827         }
828         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
829                 // Peer doesn't support this.
830                 return
831         }
832         // Request metadata pieces that we don't have in a random order.
833         var pending []int
834         for index := 0; index < c.t.metadataPieceCount(); index++ {
835                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
836                         pending = append(pending, index)
837                 }
838         }
839         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
840         for _, i := range pending {
841                 c.requestMetadataPiece(i)
842         }
843 }
844
845 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
846         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
847         if msg.Type == pp.Extended {
848                 for name, id := range cn.PeerExtensionIDs {
849                         if id != msg.ExtendedID {
850                                 continue
851                         }
852                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
853                 }
854         }
855         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
856 }
857
858 // After handshake, we know what Torrent and Client stats to include for a
859 // connection.
860 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
861         t := cn.t
862         f(&t.stats)
863         f(&t.cl.stats)
864 }
865
866 // All ConnStats that include this connection. Some objects are not known
867 // until the handshake is complete, after which it's expected to reconcile the
868 // differences.
869 func (cn *Peer) allStats(f func(*ConnStats)) {
870         f(&cn._stats)
871         if cn.reconciledHandshakeStats {
872                 cn.postHandshakeStats(f)
873         }
874 }
875
876 func (cn *PeerConn) wroteBytes(n int64) {
877         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
878 }
879
880 func (cn *PeerConn) readBytes(n int64) {
881         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
882 }
883
884 // Returns whether the connection could be useful to us. We're seeding and
885 // they want data, we don't have metainfo and they can provide it, etc.
886 func (c *Peer) useful() bool {
887         t := c.t
888         if c.closed.IsSet() {
889                 return false
890         }
891         if !t.haveInfo() {
892                 return c.supportsExtension("ut_metadata")
893         }
894         if t.seeding() && c.peerInterested {
895                 return true
896         }
897         if c.peerHasWantedPieces() {
898                 return true
899         }
900         return false
901 }
902
903 func (c *Peer) lastHelpful() (ret time.Time) {
904         ret = c.lastUsefulChunkReceived
905         if c.t.seeding() && c.lastChunkSent.After(ret) {
906                 ret = c.lastChunkSent
907         }
908         return
909 }
910
911 func (c *PeerConn) fastEnabled() bool {
912         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
913 }
914
915 func (c *PeerConn) reject(r Request) {
916         if !c.fastEnabled() {
917                 panic("fast not enabled")
918         }
919         c.write(r.ToMsg(pp.Reject))
920         delete(c.peerRequests, r)
921 }
922
923 func (c *PeerConn) onReadRequest(r Request) error {
924         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
925         if _, ok := c.peerRequests[r]; ok {
926                 torrent.Add("duplicate requests received", 1)
927                 return nil
928         }
929         if c.choking {
930                 torrent.Add("requests received while choking", 1)
931                 if c.fastEnabled() {
932                         torrent.Add("requests rejected while choking", 1)
933                         c.reject(r)
934                 }
935                 return nil
936         }
937         // TODO: What if they've already requested this?
938         if len(c.peerRequests) >= localClientReqq {
939                 torrent.Add("requests received while queue full", 1)
940                 if c.fastEnabled() {
941                         c.reject(r)
942                 }
943                 // BEP 6 says we may close here if we choose.
944                 return nil
945         }
946         if !c.t.havePiece(pieceIndex(r.Index)) {
947                 // This isn't necessarily them screwing up. We can drop pieces
948                 // from our storage, and can't communicate this to peers
949                 // except by reconnecting.
950                 requestsReceivedForMissingPieces.Add(1)
951                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
952         }
953         // Check this after we know we have the piece, so that the piece length will be known.
954         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
955                 torrent.Add("bad requests received", 1)
956                 return errors.New("bad Request")
957         }
958         if c.peerRequests == nil {
959                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
960         }
961         value := &peerRequestState{}
962         c.peerRequests[r] = value
963         go c.peerRequestDataReader(r, value)
964         //c.tickleWriter()
965         return nil
966 }
967
968 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
969         b, err := readPeerRequestData(r, c)
970         c.locker().Lock()
971         defer c.locker().Unlock()
972         if err != nil {
973                 c.peerRequestDataReadFailed(err, r)
974         } else {
975                 if b == nil {
976                         panic("data must be non-nil to trigger send")
977                 }
978                 prs.data = b
979                 c.tickleWriter()
980         }
981 }
982
983 // If this is maintained correctly, we might be able to support optional synchronous reading for
984 // chunk sending, the way it used to work.
985 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
986         c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
987         i := pieceIndex(r.Index)
988         if c.t.pieceComplete(i) {
989                 // There used to be more code here that just duplicated the following break. Piece
990                 // completions are currently cached, so I'm not sure how helpful this update is, except to
991                 // pull any completion changes pushed to the storage backend in failed reads that got us
992                 // here.
993                 c.t.updatePieceCompletion(i)
994         }
995         // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
996         // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
997         // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
998         // next connect. TODO: Support rejecting here too.
999         if c.choking {
1000                 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1001         }
1002         c.choke(c.write)
1003 }
1004
1005 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1006         b := make([]byte, r.Length)
1007         p := c.t.info.Piece(int(r.Index))
1008         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1009         if n == len(b) {
1010                 if err == io.EOF {
1011                         err = nil
1012                 }
1013         } else {
1014                 if err == nil {
1015                         panic("expected error")
1016                 }
1017         }
1018         return b, err
1019 }
1020
1021 func runSafeExtraneous(f func()) {
1022         if true {
1023                 go f()
1024         } else {
1025                 f()
1026         }
1027 }
1028
1029 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1030 // exit. Returning will end the connection.
1031 func (c *PeerConn) mainReadLoop() (err error) {
1032         defer func() {
1033                 if err != nil {
1034                         torrent.Add("connection.mainReadLoop returned with error", 1)
1035                 } else {
1036                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1037                 }
1038         }()
1039         t := c.t
1040         cl := t.cl
1041
1042         decoder := pp.Decoder{
1043                 R:         bufio.NewReaderSize(c.r, 1<<17),
1044                 MaxLength: 256 * 1024,
1045                 Pool:      &t.chunkPool,
1046         }
1047         for {
1048                 var msg pp.Message
1049                 func() {
1050                         cl.unlock()
1051                         defer cl.lock()
1052                         err = decoder.Decode(&msg)
1053                 }()
1054                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1055                         cb(c, &msg)
1056                 }
1057                 if t.closed.IsSet() || c.closed.IsSet() {
1058                         return nil
1059                 }
1060                 if err != nil {
1061                         return err
1062                 }
1063                 c.lastMessageReceived = time.Now()
1064                 if msg.Keepalive {
1065                         receivedKeepalives.Add(1)
1066                         continue
1067                 }
1068                 messageTypesReceived.Add(msg.Type.String(), 1)
1069                 if msg.Type.FastExtension() && !c.fastEnabled() {
1070                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1071                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1072                 }
1073                 switch msg.Type {
1074                 case pp.Choke:
1075                         c.peerChoking = true
1076                         if !c.fastEnabled() {
1077                                 c.deleteAllRequests()
1078                         }
1079                         // We can then reset our interest.
1080                         c.updateRequests()
1081                         c.updateExpectingChunks()
1082                 case pp.Unchoke:
1083                         c.peerChoking = false
1084                         c.tickleWriter()
1085                         c.updateExpectingChunks()
1086                 case pp.Interested:
1087                         c.peerInterested = true
1088                         c.tickleWriter()
1089                 case pp.NotInterested:
1090                         c.peerInterested = false
1091                         // We don't clear their requests since it isn't clear in the spec.
1092                         // We'll probably choke them for this, which will clear them if
1093                         // appropriate, and is clearly specified.
1094                 case pp.Have:
1095                         err = c.peerSentHave(pieceIndex(msg.Index))
1096                 case pp.Bitfield:
1097                         err = c.peerSentBitfield(msg.Bitfield)
1098                 case pp.Request:
1099                         r := newRequestFromMessage(&msg)
1100                         err = c.onReadRequest(r)
1101                 case pp.Piece:
1102                         c.doChunkReadStats(int64(len(msg.Piece)))
1103                         err = c.receiveChunk(&msg)
1104                         if len(msg.Piece) == int(t.chunkSize) {
1105                                 t.chunkPool.Put(&msg.Piece)
1106                         }
1107                         if err != nil {
1108                                 err = fmt.Errorf("receiving chunk: %s", err)
1109                         }
1110                 case pp.Cancel:
1111                         req := newRequestFromMessage(&msg)
1112                         c.onPeerSentCancel(req)
1113                 case pp.Port:
1114                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1115                         if !ok {
1116                                 break
1117                         }
1118                         pingAddr := net.UDPAddr{
1119                                 IP:   ipa.IP,
1120                                 Port: ipa.Port,
1121                         }
1122                         if msg.Port != 0 {
1123                                 pingAddr.Port = int(msg.Port)
1124                         }
1125                         cl.eachDhtServer(func(s DhtServer) {
1126                                 go s.Ping(&pingAddr)
1127                         })
1128                 case pp.Suggest:
1129                         torrent.Add("suggests received", 1)
1130                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1131                         c.updateRequests()
1132                 case pp.HaveAll:
1133                         err = c.onPeerSentHaveAll()
1134                 case pp.HaveNone:
1135                         err = c.peerSentHaveNone()
1136                 case pp.Reject:
1137                         c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1138                 case pp.AllowedFast:
1139                         torrent.Add("allowed fasts received", 1)
1140                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1141                         c.peerAllowedFast.Add(bitmap.BitIndex(msg.Index))
1142                         c.updateRequests()
1143                 case pp.Extended:
1144                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1145                 default:
1146                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1147                 }
1148                 if err != nil {
1149                         return err
1150                 }
1151         }
1152 }
1153
1154 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1155         if c.deleteRequest(r) {
1156                 c.decExpectedChunkReceive(r)
1157         }
1158 }
1159
1160 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1161         count := c.validReceiveChunks[r]
1162         if count == 1 {
1163                 delete(c.validReceiveChunks, r)
1164         } else if count > 1 {
1165                 c.validReceiveChunks[r] = count - 1
1166         } else {
1167                 panic(r)
1168         }
1169 }
1170
1171 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1172         defer func() {
1173                 // TODO: Should we still do this?
1174                 if err != nil {
1175                         // These clients use their own extension IDs for outgoing message
1176                         // types, which is incorrect.
1177                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1178                                 err = nil
1179                         }
1180                 }
1181         }()
1182         t := c.t
1183         cl := t.cl
1184         switch id {
1185         case pp.HandshakeExtendedID:
1186                 var d pp.ExtendedHandshakeMessage
1187                 if err := bencode.Unmarshal(payload, &d); err != nil {
1188                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1189                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1190                 }
1191                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1192                         cb(c, &d)
1193                 }
1194                 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1195                 if d.Reqq != 0 {
1196                         c.PeerMaxRequests = d.Reqq
1197                 }
1198                 c.PeerClientName = d.V
1199                 if c.PeerExtensionIDs == nil {
1200                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1201                 }
1202                 c.PeerListenPort = d.Port
1203                 c.PeerPrefersEncryption = d.Encryption
1204                 for name, id := range d.M {
1205                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1206                                 peersSupportingExtension.Add(string(name), 1)
1207                         }
1208                         c.PeerExtensionIDs[name] = id
1209                 }
1210                 if d.MetadataSize != 0 {
1211                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1212                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1213                         }
1214                 }
1215                 c.requestPendingMetadata()
1216                 if !t.cl.config.DisablePEX {
1217                         t.pex.Add(c) // we learnt enough now
1218                         c.pex.Init(c)
1219                 }
1220                 return nil
1221         case metadataExtendedId:
1222                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1223                 if err != nil {
1224                         return fmt.Errorf("handling metadata extension message: %w", err)
1225                 }
1226                 return nil
1227         case pexExtendedId:
1228                 if !c.pex.IsEnabled() {
1229                         return nil // or hang-up maybe?
1230                 }
1231                 return c.pex.Recv(payload)
1232         default:
1233                 return fmt.Errorf("unexpected extended message ID: %v", id)
1234         }
1235 }
1236
1237 // Set both the Reader and Writer for the connection from a single ReadWriter.
1238 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1239         cn.r = rw
1240         cn.w = rw
1241 }
1242
1243 // Returns the Reader and Writer as a combined ReadWriter.
1244 func (cn *PeerConn) rw() io.ReadWriter {
1245         return struct {
1246                 io.Reader
1247                 io.Writer
1248         }{cn.r, cn.w}
1249 }
1250
1251 func (c *Peer) doChunkReadStats(size int64) {
1252         c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1253 }
1254
1255 // Handle a received chunk from a peer.
1256 func (c *Peer) receiveChunk(msg *pp.Message) error {
1257         chunksReceived.Add("total", 1)
1258
1259         ppReq := newRequestFromMessage(msg)
1260         req := c.t.requestIndexFromRequest(ppReq)
1261
1262         if c.peerChoking {
1263                 chunksReceived.Add("while choked", 1)
1264         }
1265
1266         if c.validReceiveChunks[req] <= 0 {
1267                 chunksReceived.Add("unexpected", 1)
1268                 return errors.New("received unexpected chunk")
1269         }
1270         c.decExpectedChunkReceive(req)
1271
1272         if c.peerChoking && c.peerAllowedFast.Get(bitmap.BitIndex(ppReq.Index)) {
1273                 chunksReceived.Add("due to allowed fast", 1)
1274         }
1275
1276         // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1277         // have actually already received the piece, while we have the Client unlocked to write the data
1278         // out.
1279         deletedRequest := false
1280         {
1281                 if c.actualRequestState.Requests.Contains(req) {
1282                         for _, f := range c.callbacks.ReceivedRequested {
1283                                 f(PeerMessageEvent{c, msg})
1284                         }
1285                 }
1286                 // Request has been satisfied.
1287                 if c.deleteRequest(req) {
1288                         deletedRequest = true
1289                         if !c.peerChoking {
1290                                 c._chunksReceivedWhileExpecting++
1291                         }
1292                 } else {
1293                         chunksReceived.Add("unwanted", 1)
1294                 }
1295         }
1296
1297         t := c.t
1298         cl := t.cl
1299
1300         // Do we actually want this chunk?
1301         if t.haveChunk(ppReq) {
1302                 chunksReceived.Add("wasted", 1)
1303                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1304                 return nil
1305         }
1306
1307         piece := &t.pieces[ppReq.Index]
1308
1309         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1310         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1311         if deletedRequest {
1312                 c.piecesReceivedSinceLastRequestUpdate++
1313                 c.updateRequests()
1314                 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1315         }
1316         for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1317                 f(ReceivedUsefulDataEvent{c, msg})
1318         }
1319         c.lastUsefulChunkReceived = time.Now()
1320
1321         // Need to record that it hasn't been written yet, before we attempt to do
1322         // anything with it.
1323         piece.incrementPendingWrites()
1324         // Record that we have the chunk, so we aren't trying to download it while
1325         // waiting for it to be written to storage.
1326         piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1327
1328         // Cancel pending requests for this chunk from *other* peers.
1329         t.iterPeers(func(p *Peer) {
1330                 if p == c {
1331                         return
1332                 }
1333                 p.cancel(req)
1334         })
1335
1336         err := func() error {
1337                 cl.unlock()
1338                 defer cl.lock()
1339                 concurrentChunkWrites.Add(1)
1340                 defer concurrentChunkWrites.Add(-1)
1341                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1342                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1343                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1344                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1345                 // that instead.
1346                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1347         }()
1348
1349         piece.decrementPendingWrites()
1350
1351         if err != nil {
1352                 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1353                 t.pendRequest(req)
1354                 //t.updatePieceCompletion(pieceIndex(msg.Index))
1355                 t.onWriteChunkErr(err)
1356                 return nil
1357         }
1358
1359         c.onDirtiedPiece(pieceIndex(ppReq.Index))
1360
1361         // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1362         if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1363                 t.queuePieceCheck(pieceIndex(ppReq.Index))
1364                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1365                 // chunk status (such as the haveChunk call above) to have to check all the various other
1366                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1367                 // that chunk pieces are pended at an appropriate time later however.
1368         }
1369
1370         cl.event.Broadcast()
1371         // We do this because we've written a chunk, and may change PieceState.Partial.
1372         t.publishPieceChange(pieceIndex(ppReq.Index))
1373
1374         return nil
1375 }
1376
1377 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1378         if c.peerTouchedPieces == nil {
1379                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1380         }
1381         c.peerTouchedPieces[piece] = struct{}{}
1382         ds := &c.t.pieces[piece].dirtiers
1383         if *ds == nil {
1384                 *ds = make(map[*Peer]struct{})
1385         }
1386         (*ds)[c] = struct{}{}
1387 }
1388
1389 func (c *PeerConn) uploadAllowed() bool {
1390         if c.t.cl.config.NoUpload {
1391                 return false
1392         }
1393         if c.t.dataUploadDisallowed {
1394                 return false
1395         }
1396         if c.t.seeding() {
1397                 return true
1398         }
1399         if !c.peerHasWantedPieces() {
1400                 return false
1401         }
1402         // Don't upload more than 100 KiB more than we download.
1403         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1404                 return false
1405         }
1406         return true
1407 }
1408
1409 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1410         if c.uploadTimer == nil {
1411                 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1412         } else {
1413                 c.uploadTimer.Reset(delay)
1414         }
1415 }
1416
1417 // Also handles choking and unchoking of the remote peer.
1418 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1419         // Breaking or completing this loop means we don't want to upload to the
1420         // peer anymore, and we choke them.
1421 another:
1422         for c.uploadAllowed() {
1423                 // We want to upload to the peer.
1424                 if !c.unchoke(msg) {
1425                         return false
1426                 }
1427                 for r, state := range c.peerRequests {
1428                         if state.data == nil {
1429                                 continue
1430                         }
1431                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1432                         if !res.OK() {
1433                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1434                         }
1435                         delay := res.Delay()
1436                         if delay > 0 {
1437                                 res.Cancel()
1438                                 c.setRetryUploadTimer(delay)
1439                                 // Hard to say what to return here.
1440                                 return true
1441                         }
1442                         more := c.sendChunk(r, msg, state)
1443                         delete(c.peerRequests, r)
1444                         if !more {
1445                                 return false
1446                         }
1447                         goto another
1448                 }
1449                 return true
1450         }
1451         return c.choke(msg)
1452 }
1453
1454 func (cn *PeerConn) drop() {
1455         cn.t.dropConnection(cn)
1456 }
1457
1458 func (cn *Peer) netGoodPiecesDirtied() int64 {
1459         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1460 }
1461
1462 func (c *Peer) peerHasWantedPieces() bool {
1463         return !c._pieceRequestOrder.IsEmpty()
1464 }
1465
1466 func (c *Peer) deleteRequest(r RequestIndex) bool {
1467         c.nextRequestState.Requests.Remove(r)
1468         if !c.actualRequestState.Requests.CheckedRemove(r) {
1469                 return false
1470         }
1471         for _, f := range c.callbacks.DeletedRequest {
1472                 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1473         }
1474         c.updateExpectingChunks()
1475         pr := c.t.pendingRequests
1476         pr[r]--
1477         n := pr[r]
1478         if n == 0 {
1479                 delete(pr, r)
1480         }
1481         if n < 0 {
1482                 panic(n)
1483         }
1484         return true
1485 }
1486
1487 func (c *Peer) deleteAllRequests() {
1488         c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1489                 c.deleteRequest(x)
1490                 return true
1491         })
1492         if !c.actualRequestState.Requests.IsEmpty() {
1493                 panic(c.actualRequestState.Requests.GetCardinality())
1494         }
1495         c.nextRequestState.Requests.Clear()
1496         // for c := range c.t.conns {
1497         //      c.tickleWriter()
1498         // }
1499 }
1500
1501 // This is called when something has changed that should wake the writer, such as putting stuff into
1502 // the writeBuffer, or changing some state that the writer can act on.
1503 func (c *PeerConn) tickleWriter() {
1504         c.messageWriter.writeCond.Broadcast()
1505 }
1506
1507 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1508         c.lastChunkSent = time.Now()
1509         return msg(pp.Message{
1510                 Type:  pp.Piece,
1511                 Index: r.Index,
1512                 Begin: r.Begin,
1513                 Piece: state.data,
1514         })
1515 }
1516
1517 func (c *PeerConn) setTorrent(t *Torrent) {
1518         if c.t != nil {
1519                 panic("connection already associated with a torrent")
1520         }
1521         c.t = t
1522         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1523         t.reconcileHandshakeStats(c)
1524 }
1525
1526 func (c *Peer) peerPriority() (peerPriority, error) {
1527         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1528 }
1529
1530 func (c *Peer) remoteIp() net.IP {
1531         host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1532         return net.ParseIP(host)
1533 }
1534
1535 func (c *Peer) remoteIpPort() IpPort {
1536         ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1537         return IpPort{ipa.IP, uint16(ipa.Port)}
1538 }
1539
1540 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1541         f := pp.PexPeerFlags(0)
1542         if c.PeerPrefersEncryption {
1543                 f |= pp.PexPrefersEncryption
1544         }
1545         if c.outgoing {
1546                 f |= pp.PexOutgoingConn
1547         }
1548         if c.utp() {
1549                 f |= pp.PexSupportsUtp
1550         }
1551         return f
1552 }
1553
1554 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1555 // advertised listen port.
1556 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1557         if !c.outgoing && c.PeerListenPort != 0 {
1558                 switch addr := c.RemoteAddr.(type) {
1559                 case *net.TCPAddr:
1560                         dialAddr := *addr
1561                         dialAddr.Port = c.PeerListenPort
1562                         return &dialAddr
1563                 case *net.UDPAddr:
1564                         dialAddr := *addr
1565                         dialAddr.Port = c.PeerListenPort
1566                         return &dialAddr
1567                 }
1568         }
1569         return c.RemoteAddr
1570 }
1571
1572 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1573         f := c.pexPeerFlags()
1574         addr := c.dialAddr()
1575         return pexEvent{t, addr, f}
1576 }
1577
1578 func (c *PeerConn) String() string {
1579         return fmt.Sprintf("connection %p", c)
1580 }
1581
1582 func (c *Peer) trust() connectionTrust {
1583         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1584 }
1585
1586 type connectionTrust struct {
1587         Implicit            bool
1588         NetGoodPiecesDirted int64
1589 }
1590
1591 func (l connectionTrust) Less(r connectionTrust) bool {
1592         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1593 }
1594
1595 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1596 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1597 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1598         cn.locker().RLock()
1599         defer cn.locker().RUnlock()
1600         return cn.newPeerPieces()
1601 }
1602
1603 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1604 func (cn *Peer) newPeerPieces() bitmap.Bitmap {
1605         ret := cn._peerPieces.Copy()
1606         if cn.peerSentHaveAll {
1607                 if cn.t.haveInfo() {
1608                         ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1609                 } else {
1610                         ret.AddRange(0, bitmap.ToEnd)
1611                 }
1612         }
1613         return ret
1614 }
1615
1616 func (cn *Peer) stats() *ConnStats {
1617         return &cn._stats
1618 }
1619
1620 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1621         pc, ok := p.peerImpl.(*PeerConn)
1622         return pc, ok
1623 }
1624
1625 func (p *PeerConn) onNextRequestStateChanged() {
1626         p.tickleWriter()
1627 }