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