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