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