]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
df395006c1061b0d26000084bb991f6432551ff0
[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]int
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                 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]int)
505         }
506         cn.validReceiveChunks[r]++
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                                 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update
605                                 // when https://github.com/pion/datachannel/issues/59 is fixed.
606                                 return cn.writeBuffer.Len() < 1<<15
607                         })
608                 }
609                 if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout {
610                         cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary())
611                         postedKeepalives.Add(1)
612                 }
613                 if cn.writeBuffer.Len() == 0 {
614                         // TODO: Minimize wakeups....
615                         cn.writerCond.Wait()
616                         continue
617                 }
618                 // Flip the buffers.
619                 frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf
620                 cn.locker().Unlock()
621                 n, err := cn.w.Write(frontBuf.Bytes())
622                 cn.locker().Lock()
623                 if n != 0 {
624                         lastWrite = time.Now()
625                         keepAliveTimer.Reset(keepAliveTimeout)
626                 }
627                 if err != nil {
628                         cn.logger.Printf("error writing: %v", err)
629                         return
630                 }
631                 if n != frontBuf.Len() {
632                         panic("short write")
633                 }
634                 frontBuf.Reset()
635         }
636 }
637
638 func (cn *PeerConn) have(piece pieceIndex) {
639         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
640                 return
641         }
642         cn.post(pp.Message{
643                 Type:  pp.Have,
644                 Index: pp.Integer(piece),
645         })
646         cn.sentHaves.Add(bitmap.BitIndex(piece))
647 }
648
649 func (cn *PeerConn) postBitfield() {
650         if cn.sentHaves.Len() != 0 {
651                 panic("bitfield must be first have-related message sent")
652         }
653         if !cn.t.haveAnyPieces() {
654                 return
655         }
656         cn.post(pp.Message{
657                 Type:     pp.Bitfield,
658                 Bitfield: cn.t.bitfield(),
659         })
660         cn.sentHaves = cn.t._completedPieces.Copy()
661 }
662
663 func (cn *PeerConn) updateRequests() {
664         // log.Print("update requests")
665         cn.tickleWriter()
666 }
667
668 // Emits the indices in the Bitmaps bms in order, never repeating any index.
669 // skip is mutated during execution, and its initial values will never be
670 // emitted.
671 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
672         return func(cb iter.Callback) {
673                 for _, bm := range bms {
674                         if !iter.All(
675                                 func(i interface{}) bool {
676                                         skip.Add(i.(int))
677                                         return cb(i)
678                                 },
679                                 bitmap.Sub(bm, *skip).Iter,
680                         ) {
681                                 return
682                         }
683                 }
684         }
685 }
686
687 func iterUnbiasedPieceRequestOrder(cn requestStrategyConnection, f func(piece pieceIndex) bool) bool {
688         now, readahead := cn.torrent().readerPiecePriorities()
689         skip := bitmap.Flip(cn.peerPieces(), 0, cn.torrent().numPieces())
690         skip.Union(cn.torrent().ignorePieces())
691         // Return an iterator over the different priority classes, minus the skip pieces.
692         return iter.All(
693                 func(_piece interface{}) bool {
694                         return f(pieceIndex(_piece.(bitmap.BitIndex)))
695                 },
696                 iterBitmapsDistinct(&skip, now, readahead),
697                 // We have to iterate _pendingPieces separately because it isn't a Bitmap.
698                 func(cb iter.Callback) {
699                         cn.torrent().pendingPieces().IterTyped(func(piece int) bool {
700                                 if skip.Contains(piece) {
701                                         return true
702                                 }
703                                 more := cb(piece)
704                                 skip.Add(piece)
705                                 return more
706                         })
707                 },
708         )
709 }
710
711 // The connection should download highest priority pieces first, without any inclination toward
712 // avoiding wastage. Generally we might do this if there's a single connection, or this is the
713 // fastest connection, and we have active readers that signal an ordering preference. It's
714 // conceivable that the best connection should do this, since it's least likely to waste our time if
715 // assigned to the highest priority pieces, and assigning more than one this role would cause
716 // significant wasted bandwidth.
717 func (cn *PeerConn) shouldRequestWithoutBias() bool {
718         return cn.t.requestStrategy.shouldRequestWithoutBias(cn.requestStrategyConnection())
719 }
720
721 func (cn *PeerConn) iterPendingPieces(f func(pieceIndex) bool) bool {
722         if !cn.t.haveInfo() {
723                 return false
724         }
725         return cn.t.requestStrategy.iterPendingPieces(cn, f)
726 }
727 func (cn *PeerConn) iterPendingPiecesUntyped(f iter.Callback) {
728         cn.iterPendingPieces(func(i pieceIndex) bool { return f(i) })
729 }
730
731 func (cn *PeerConn) iterPendingRequests(piece pieceIndex, f func(request) bool) bool {
732         return cn.t.requestStrategy.iterUndirtiedChunks(
733                 cn.t.piece(piece).requestStrategyPiece(),
734                 func(cs chunkSpec) bool {
735                         return f(request{pp.Integer(piece), cs})
736                 },
737         )
738 }
739
740 // check callers updaterequests
741 func (cn *PeerConn) stopRequestingPiece(piece pieceIndex) bool {
742         return cn._pieceRequestOrder.Remove(bitmap.BitIndex(piece))
743 }
744
745 // This is distinct from Torrent piece priority, which is the user's
746 // preference. Connection piece priority is specific to a connection and is
747 // used to pseudorandomly avoid connections always requesting the same pieces
748 // and thus wasting effort.
749 func (cn *PeerConn) updatePiecePriority(piece pieceIndex) bool {
750         tpp := cn.t.piecePriority(piece)
751         if !cn.peerHasPiece(piece) {
752                 tpp = PiecePriorityNone
753         }
754         if tpp == PiecePriorityNone {
755                 return cn.stopRequestingPiece(piece)
756         }
757         prio := cn.getPieceInclination()[piece]
758         prio = cn.t.requestStrategy.piecePriority(cn, piece, tpp, prio)
759         return cn._pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias()
760 }
761
762 func (cn *PeerConn) getPieceInclination() []int {
763         if cn.pieceInclination == nil {
764                 cn.pieceInclination = cn.t.getConnPieceInclination()
765         }
766         return cn.pieceInclination
767 }
768
769 func (cn *PeerConn) discardPieceInclination() {
770         if cn.pieceInclination == nil {
771                 return
772         }
773         cn.t.putPieceInclination(cn.pieceInclination)
774         cn.pieceInclination = nil
775 }
776
777 func (cn *PeerConn) peerPiecesChanged() {
778         if cn.t.haveInfo() {
779                 prioritiesChanged := false
780                 for i := pieceIndex(0); i < cn.t.numPieces(); i++ {
781                         if cn.updatePiecePriority(i) {
782                                 prioritiesChanged = true
783                         }
784                 }
785                 if prioritiesChanged {
786                         cn.updateRequests()
787                 }
788         }
789 }
790
791 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
792         if newMin > cn.peerMinPieces {
793                 cn.peerMinPieces = newMin
794         }
795 }
796
797 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
798         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
799                 return errors.New("invalid piece")
800         }
801         if cn.peerHasPiece(piece) {
802                 return nil
803         }
804         cn.raisePeerMinPieces(piece + 1)
805         cn._peerPieces.Set(bitmap.BitIndex(piece), true)
806         if cn.updatePiecePriority(piece) {
807                 cn.updateRequests()
808         }
809         return nil
810 }
811
812 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
813         cn.peerSentHaveAll = false
814         if len(bf)%8 != 0 {
815                 panic("expected bitfield length divisible by 8")
816         }
817         // We know that the last byte means that at most the last 7 bits are
818         // wasted.
819         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
820         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
821                 // Ignore known excess pieces.
822                 bf = bf[:cn.t.numPieces()]
823         }
824         for i, have := range bf {
825                 if have {
826                         cn.raisePeerMinPieces(pieceIndex(i) + 1)
827                 }
828                 cn._peerPieces.Set(i, have)
829         }
830         cn.peerPiecesChanged()
831         return nil
832 }
833
834 func (cn *PeerConn) onPeerSentHaveAll() error {
835         cn.peerSentHaveAll = true
836         cn._peerPieces.Clear()
837         cn.peerPiecesChanged()
838         return nil
839 }
840
841 func (cn *PeerConn) peerSentHaveNone() error {
842         cn._peerPieces.Clear()
843         cn.peerSentHaveAll = false
844         cn.peerPiecesChanged()
845         return nil
846 }
847
848 func (c *PeerConn) requestPendingMetadata() {
849         if c.t.haveInfo() {
850                 return
851         }
852         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
853                 // Peer doesn't support this.
854                 return
855         }
856         // Request metadata pieces that we don't have in a random order.
857         var pending []int
858         for index := 0; index < c.t.metadataPieceCount(); index++ {
859                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
860                         pending = append(pending, index)
861                 }
862         }
863         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
864         for _, i := range pending {
865                 c.requestMetadataPiece(i)
866         }
867 }
868
869 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
870         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
871         if msg.Type == pp.Extended {
872                 for name, id := range cn.PeerExtensionIDs {
873                         if id != msg.ExtendedID {
874                                 continue
875                         }
876                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
877                 }
878         }
879         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
880 }
881
882 func (cn *PeerConn) readMsg(msg *pp.Message) {
883         cn.allStats(func(cs *ConnStats) { cs.readMsg(msg) })
884 }
885
886 // After handshake, we know what Torrent and Client stats to include for a
887 // connection.
888 func (cn *PeerConn) postHandshakeStats(f func(*ConnStats)) {
889         t := cn.t
890         f(&t.stats)
891         f(&t.cl.stats)
892 }
893
894 // All ConnStats that include this connection. Some objects are not known
895 // until the handshake is complete, after which it's expected to reconcile the
896 // differences.
897 func (cn *PeerConn) allStats(f func(*ConnStats)) {
898         f(&cn._stats)
899         if cn.reconciledHandshakeStats {
900                 cn.postHandshakeStats(f)
901         }
902 }
903
904 func (cn *PeerConn) wroteBytes(n int64) {
905         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
906 }
907
908 func (cn *PeerConn) readBytes(n int64) {
909         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
910 }
911
912 // Returns whether the connection could be useful to us. We're seeding and
913 // they want data, we don't have metainfo and they can provide it, etc.
914 func (c *PeerConn) useful() bool {
915         t := c.t
916         if c.closed.IsSet() {
917                 return false
918         }
919         if !t.haveInfo() {
920                 return c.supportsExtension("ut_metadata")
921         }
922         if t.seeding() && c.peerInterested {
923                 return true
924         }
925         if c.peerHasWantedPieces() {
926                 return true
927         }
928         return false
929 }
930
931 func (c *PeerConn) lastHelpful() (ret time.Time) {
932         ret = c.lastUsefulChunkReceived
933         if c.t.seeding() && c.lastChunkSent.After(ret) {
934                 ret = c.lastChunkSent
935         }
936         return
937 }
938
939 func (c *PeerConn) fastEnabled() bool {
940         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
941 }
942
943 func (c *PeerConn) reject(r request) {
944         if !c.fastEnabled() {
945                 panic("fast not enabled")
946         }
947         c.post(r.ToMsg(pp.Reject))
948         delete(c.peerRequests, r)
949 }
950
951 func (c *PeerConn) onReadRequest(r request) error {
952         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
953         if _, ok := c.peerRequests[r]; ok {
954                 torrent.Add("duplicate requests received", 1)
955                 return nil
956         }
957         if c.choking {
958                 torrent.Add("requests received while choking", 1)
959                 if c.fastEnabled() {
960                         torrent.Add("requests rejected while choking", 1)
961                         c.reject(r)
962                 }
963                 return nil
964         }
965         if len(c.peerRequests) >= maxRequests {
966                 torrent.Add("requests received while queue full", 1)
967                 if c.fastEnabled() {
968                         c.reject(r)
969                 }
970                 // BEP 6 says we may close here if we choose.
971                 return nil
972         }
973         if !c.t.havePiece(pieceIndex(r.Index)) {
974                 // This isn't necessarily them screwing up. We can drop pieces
975                 // from our storage, and can't communicate this to peers
976                 // except by reconnecting.
977                 requestsReceivedForMissingPieces.Add(1)
978                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
979         }
980         // Check this after we know we have the piece, so that the piece length will be known.
981         if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
982                 torrent.Add("bad requests received", 1)
983                 return errors.New("bad request")
984         }
985         if c.peerRequests == nil {
986                 c.peerRequests = make(map[request]struct{}, maxRequests)
987         }
988         c.peerRequests[r] = struct{}{}
989         c.tickleWriter()
990         return nil
991 }
992
993 func runSafeExtraneous(f func()) {
994         if true {
995                 go f()
996         } else {
997                 f()
998         }
999 }
1000
1001 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1002 // exit. Returning will end the connection.
1003 func (c *PeerConn) mainReadLoop() (err error) {
1004         defer func() {
1005                 if err != nil {
1006                         torrent.Add("connection.mainReadLoop returned with error", 1)
1007                 } else {
1008                         torrent.Add("connection.mainReadLoop returned with no error", 1)
1009                 }
1010         }()
1011         t := c.t
1012         cl := t.cl
1013
1014         decoder := pp.Decoder{
1015                 R:         bufio.NewReaderSize(c.r, 1<<17),
1016                 MaxLength: 256 * 1024,
1017                 Pool:      t.chunkPool,
1018         }
1019         for {
1020                 var msg pp.Message
1021                 func() {
1022                         cl.unlock()
1023                         defer cl.lock()
1024                         err = decoder.Decode(&msg)
1025                 }()
1026                 if t.closed.IsSet() || c.closed.IsSet() {
1027                         return nil
1028                 }
1029                 if err != nil {
1030                         return err
1031                 }
1032                 c.readMsg(&msg)
1033                 c.lastMessageReceived = time.Now()
1034                 if msg.Keepalive {
1035                         receivedKeepalives.Add(1)
1036                         continue
1037                 }
1038                 messageTypesReceived.Add(msg.Type.String(), 1)
1039                 if msg.Type.FastExtension() && !c.fastEnabled() {
1040                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1041                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1042                 }
1043                 switch msg.Type {
1044                 case pp.Choke:
1045                         c.peerChoking = true
1046                         if !c.fastEnabled() {
1047                                 c.deleteAllRequests()
1048                         }
1049                         // We can then reset our interest.
1050                         c.updateRequests()
1051                         c.updateExpectingChunks()
1052                 case pp.Unchoke:
1053                         c.peerChoking = false
1054                         c.tickleWriter()
1055                         c.updateExpectingChunks()
1056                 case pp.Interested:
1057                         c.peerInterested = true
1058                         c.tickleWriter()
1059                 case pp.NotInterested:
1060                         c.peerInterested = false
1061                         // We don't clear their requests since it isn't clear in the spec.
1062                         // We'll probably choke them for this, which will clear them if
1063                         // appropriate, and is clearly specified.
1064                 case pp.Have:
1065                         err = c.peerSentHave(pieceIndex(msg.Index))
1066                 case pp.Bitfield:
1067                         err = c.peerSentBitfield(msg.Bitfield)
1068                 case pp.Request:
1069                         r := newRequestFromMessage(&msg)
1070                         err = c.onReadRequest(r)
1071                 case pp.Piece:
1072                         err = c.receiveChunk(&msg)
1073                         if len(msg.Piece) == int(t.chunkSize) {
1074                                 t.chunkPool.Put(&msg.Piece)
1075                         }
1076                         if err != nil {
1077                                 err = fmt.Errorf("receiving chunk: %s", err)
1078                         }
1079                 case pp.Cancel:
1080                         req := newRequestFromMessage(&msg)
1081                         c.onPeerSentCancel(req)
1082                 case pp.Port:
1083                         ipa, ok := tryIpPortFromNetAddr(c.remoteAddr)
1084                         if !ok {
1085                                 break
1086                         }
1087                         pingAddr := net.UDPAddr{
1088                                 IP:   ipa.IP,
1089                                 Port: ipa.Port,
1090                         }
1091                         if msg.Port != 0 {
1092                                 pingAddr.Port = int(msg.Port)
1093                         }
1094                         cl.eachDhtServer(func(s DhtServer) {
1095                                 go s.Ping(&pingAddr)
1096                         })
1097                 case pp.Suggest:
1098                         torrent.Add("suggests received", 1)
1099                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1100                         c.updateRequests()
1101                 case pp.HaveAll:
1102                         err = c.onPeerSentHaveAll()
1103                 case pp.HaveNone:
1104                         err = c.peerSentHaveNone()
1105                 case pp.Reject:
1106                         c.deleteRequest(newRequestFromMessage(&msg))
1107                         c.decExpectedChunkReceive(newRequestFromMessage(&msg))
1108                 case pp.AllowedFast:
1109                         torrent.Add("allowed fasts received", 1)
1110                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1111                         c.peerAllowedFast.Add(int(msg.Index))
1112                         c.updateRequests()
1113                 case pp.Extended:
1114                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1115                 default:
1116                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1117                 }
1118                 if err != nil {
1119                         return err
1120                 }
1121         }
1122 }
1123
1124 func (c *PeerConn) decExpectedChunkReceive(r request) {
1125         count := c.validReceiveChunks[r]
1126         if count == 1 {
1127                 delete(c.validReceiveChunks, r)
1128         } else if count > 1 {
1129                 c.validReceiveChunks[r] = count - 1
1130         } else {
1131                 panic(r)
1132         }
1133 }
1134
1135 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1136         defer func() {
1137                 // TODO: Should we still do this?
1138                 if err != nil {
1139                         // These clients use their own extension IDs for outgoing message
1140                         // types, which is incorrect.
1141                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1142                                 err = nil
1143                         }
1144                 }
1145         }()
1146         t := c.t
1147         cl := t.cl
1148         switch id {
1149         case pp.HandshakeExtendedID:
1150                 var d pp.ExtendedHandshakeMessage
1151                 if err := bencode.Unmarshal(payload, &d); err != nil {
1152                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1153                         return errors.Wrap(err, "unmarshalling extended handshake payload")
1154                 }
1155                 //c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1156                 if d.Reqq != 0 {
1157                         c.PeerMaxRequests = d.Reqq
1158                 }
1159                 c.PeerClientName = d.V
1160                 if c.PeerExtensionIDs == nil {
1161                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1162                 }
1163                 c.PeerListenPort = d.Port
1164                 c.PeerPrefersEncryption = d.Encryption
1165                 for name, id := range d.M {
1166                         if _, ok := c.PeerExtensionIDs[name]; !ok {
1167                                 torrent.Add(fmt.Sprintf("peers supporting extension %q", name), 1)
1168                         }
1169                         c.PeerExtensionIDs[name] = id
1170                 }
1171                 if d.MetadataSize != 0 {
1172                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
1173                                 return errors.Wrapf(err, "setting metadata size to %d", d.MetadataSize)
1174                         }
1175                 }
1176                 c.requestPendingMetadata()
1177                 if !t.cl.config.DisablePEX {
1178                         t.pex.Add(c) // we learnt enough now
1179                         c.pex.Init(c)
1180                 }
1181                 return nil
1182         case metadataExtendedId:
1183                 err := cl.gotMetadataExtensionMsg(payload, t, c)
1184                 if err != nil {
1185                         return fmt.Errorf("handling metadata extension message: %w", err)
1186                 }
1187                 return nil
1188         case pexExtendedId:
1189                 if !c.pex.IsEnabled() {
1190                         return nil // or hang-up maybe?
1191                 }
1192                 return c.pex.Recv(payload)
1193         default:
1194                 return fmt.Errorf("unexpected extended message ID: %v", id)
1195         }
1196 }
1197
1198 // Set both the Reader and Writer for the connection from a single ReadWriter.
1199 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1200         cn.r = rw
1201         cn.w = rw
1202 }
1203
1204 // Returns the Reader and Writer as a combined ReadWriter.
1205 func (cn *PeerConn) rw() io.ReadWriter {
1206         return struct {
1207                 io.Reader
1208                 io.Writer
1209         }{cn.r, cn.w}
1210 }
1211
1212 // Handle a received chunk from a peer.
1213 func (c *PeerConn) receiveChunk(msg *pp.Message) error {
1214         t := c.t
1215         cl := t.cl
1216         torrent.Add("chunks received", 1)
1217
1218         req := newRequestFromMessage(msg)
1219
1220         if c.peerChoking {
1221                 torrent.Add("chunks received while choking", 1)
1222         }
1223
1224         if c.validReceiveChunks[req] <= 0 {
1225                 torrent.Add("chunks received unexpected", 1)
1226                 return errors.New("received unexpected chunk")
1227         }
1228         c.decExpectedChunkReceive(req)
1229
1230         if c.peerChoking && c.peerAllowedFast.Get(int(req.Index)) {
1231                 torrent.Add("chunks received due to allowed fast", 1)
1232         }
1233
1234         // Request has been satisfied.
1235         if c.deleteRequest(req) {
1236                 if c.expectingChunks() {
1237                         c._chunksReceivedWhileExpecting++
1238                 }
1239         } else {
1240                 torrent.Add("chunks received unwanted", 1)
1241         }
1242
1243         // Do we actually want this chunk?
1244         if t.haveChunk(req) {
1245                 torrent.Add("chunks received wasted", 1)
1246                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1247                 return nil
1248         }
1249
1250         piece := &t.pieces[req.Index]
1251
1252         c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1253         c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1254         c.lastUsefulChunkReceived = time.Now()
1255         // if t.fastestConn != c {
1256         // log.Printf("setting fastest connection %p", c)
1257         // }
1258         t.fastestConn = c
1259
1260         // Need to record that it hasn't been written yet, before we attempt to do
1261         // anything with it.
1262         piece.incrementPendingWrites()
1263         // Record that we have the chunk, so we aren't trying to download it while
1264         // waiting for it to be written to storage.
1265         piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1266
1267         // Cancel pending requests for this chunk.
1268         for c := range t.conns {
1269                 c.postCancel(req)
1270         }
1271
1272         err := func() error {
1273                 cl.unlock()
1274                 defer cl.lock()
1275                 concurrentChunkWrites.Add(1)
1276                 defer concurrentChunkWrites.Add(-1)
1277                 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1278                 // number of connections. We write inline with receiving the chunk (with this lock dance),
1279                 // because we want to handle errors synchronously and I haven't thought of a nice way to
1280                 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1281                 // that instead.
1282                 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1283         }()
1284
1285         piece.decrementPendingWrites()
1286
1287         if err != nil {
1288                 c.logger.Printf("error writing received chunk %v: %v", req, err)
1289                 t.pendRequest(req)
1290                 //t.updatePieceCompletion(pieceIndex(msg.Index))
1291                 t.onWriteChunkErr(err)
1292                 return nil
1293         }
1294
1295         c.onDirtiedPiece(pieceIndex(req.Index))
1296
1297         if t.pieceAllDirty(pieceIndex(req.Index)) {
1298                 t.queuePieceCheck(pieceIndex(req.Index))
1299                 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1300                 // chunk status (such as the haveChunk call above) to have to check all the various other
1301                 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1302                 // that chunk pieces are pended at an appropriate time later however.
1303         }
1304
1305         cl.event.Broadcast()
1306         // We do this because we've written a chunk, and may change PieceState.Partial.
1307         t.publishPieceChange(pieceIndex(req.Index))
1308
1309         return nil
1310 }
1311
1312 func (c *PeerConn) onDirtiedPiece(piece pieceIndex) {
1313         if c.peerTouchedPieces == nil {
1314                 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1315         }
1316         c.peerTouchedPieces[piece] = struct{}{}
1317         ds := &c.t.pieces[piece].dirtiers
1318         if *ds == nil {
1319                 *ds = make(map[*PeerConn]struct{})
1320         }
1321         (*ds)[c] = struct{}{}
1322 }
1323
1324 func (c *PeerConn) uploadAllowed() bool {
1325         if c.t.cl.config.NoUpload {
1326                 return false
1327         }
1328         if c.t.seeding() {
1329                 return true
1330         }
1331         if !c.peerHasWantedPieces() {
1332                 return false
1333         }
1334         // Don't upload more than 100 KiB more than we download.
1335         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1336                 return false
1337         }
1338         return true
1339 }
1340
1341 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1342         if c.uploadTimer == nil {
1343                 c.uploadTimer = time.AfterFunc(delay, c.writerCond.Broadcast)
1344         } else {
1345                 c.uploadTimer.Reset(delay)
1346         }
1347 }
1348
1349 // Also handles choking and unchoking of the remote peer.
1350 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1351         // Breaking or completing this loop means we don't want to upload to the
1352         // peer anymore, and we choke them.
1353 another:
1354         for c.uploadAllowed() {
1355                 // We want to upload to the peer.
1356                 if !c.unchoke(msg) {
1357                         return false
1358                 }
1359                 for r := range c.peerRequests {
1360                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1361                         if !res.OK() {
1362                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1363                         }
1364                         delay := res.Delay()
1365                         if delay > 0 {
1366                                 res.Cancel()
1367                                 c.setRetryUploadTimer(delay)
1368                                 // Hard to say what to return here.
1369                                 return true
1370                         }
1371                         more, err := c.sendChunk(r, msg)
1372                         if err != nil {
1373                                 i := pieceIndex(r.Index)
1374                                 if c.t.pieceComplete(i) {
1375                                         c.t.updatePieceCompletion(i)
1376                                         if !c.t.pieceComplete(i) {
1377                                                 // We had the piece, but not anymore.
1378                                                 break another
1379                                         }
1380                                 }
1381                                 log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger)
1382                                 // If we failed to send a chunk, choke the peer to ensure they
1383                                 // flush all their requests. We've probably dropped a piece,
1384                                 // but there's no way to communicate this to the peer. If they
1385                                 // ask for it again, we'll kick them to allow us to send them
1386                                 // an updated bitfield.
1387                                 break another
1388                         }
1389                         delete(c.peerRequests, r)
1390                         if !more {
1391                                 return false
1392                         }
1393                         goto another
1394                 }
1395                 return true
1396         }
1397         return c.choke(msg)
1398 }
1399
1400 func (cn *PeerConn) drop() {
1401         cn.t.dropConnection(cn)
1402 }
1403
1404 func (cn *PeerConn) netGoodPiecesDirtied() int64 {
1405         return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1406 }
1407
1408 func (c *PeerConn) peerHasWantedPieces() bool {
1409         return !c._pieceRequestOrder.IsEmpty()
1410 }
1411
1412 func (c *PeerConn) numLocalRequests() int {
1413         return len(c.requests)
1414 }
1415
1416 func (c *PeerConn) deleteRequest(r request) bool {
1417         if _, ok := c.requests[r]; !ok {
1418                 return false
1419         }
1420         delete(c.requests, r)
1421         c.updateExpectingChunks()
1422         c.t.requestStrategy.hooks().deletedRequest(r)
1423         pr := c.t.pendingRequests
1424         pr[r]--
1425         n := pr[r]
1426         if n == 0 {
1427                 delete(pr, r)
1428         }
1429         if n < 0 {
1430                 panic(n)
1431         }
1432         c.updateRequests()
1433         for _c := range c.t.conns {
1434                 if !_c.interested && _c != c && c.peerHasPiece(pieceIndex(r.Index)) {
1435                         _c.updateRequests()
1436                 }
1437         }
1438         return true
1439 }
1440
1441 func (c *PeerConn) deleteAllRequests() {
1442         for r := range c.requests {
1443                 c.deleteRequest(r)
1444         }
1445         if len(c.requests) != 0 {
1446                 panic(len(c.requests))
1447         }
1448         // for c := range c.t.conns {
1449         //      c.tickleWriter()
1450         // }
1451 }
1452
1453 func (c *PeerConn) tickleWriter() {
1454         c.writerCond.Broadcast()
1455 }
1456
1457 func (c *PeerConn) postCancel(r request) bool {
1458         if !c.deleteRequest(r) {
1459                 return false
1460         }
1461         c.post(makeCancelMessage(r))
1462         return true
1463 }
1464
1465 func (c *PeerConn) sendChunk(r request, msg func(pp.Message) bool) (more bool, err error) {
1466         // Count the chunk being sent, even if it isn't.
1467         b := make([]byte, r.Length)
1468         p := c.t.info.Piece(int(r.Index))
1469         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1470         if n != len(b) {
1471                 if err == nil {
1472                         panic("expected error")
1473                 }
1474                 return
1475         } else if err == io.EOF {
1476                 err = nil
1477         }
1478         more = msg(pp.Message{
1479                 Type:  pp.Piece,
1480                 Index: r.Index,
1481                 Begin: r.Begin,
1482                 Piece: b,
1483         })
1484         c.lastChunkSent = time.Now()
1485         return
1486 }
1487
1488 func (c *PeerConn) setTorrent(t *Torrent) {
1489         if c.t != nil {
1490                 panic("connection already associated with a torrent")
1491         }
1492         c.t = t
1493         c.logger.Printf("torrent=%v", t)
1494         t.reconcileHandshakeStats(c)
1495 }
1496
1497 func (c *PeerConn) peerPriority() (peerPriority, error) {
1498         return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1499 }
1500
1501 func (c *PeerConn) remoteIp() net.IP {
1502         return addrIpOrNil(c.remoteAddr)
1503 }
1504
1505 func (c *PeerConn) remoteIpPort() IpPort {
1506         ipa, _ := tryIpPortFromNetAddr(c.remoteAddr)
1507         return IpPort{ipa.IP, uint16(ipa.Port)}
1508 }
1509
1510 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1511         f := pp.PexPeerFlags(0)
1512         if c.PeerPrefersEncryption {
1513                 f |= pp.PexPrefersEncryption
1514         }
1515         if c.outgoing {
1516                 f |= pp.PexOutgoingConn
1517         }
1518         if c.remoteAddr != nil && strings.Contains(c.remoteAddr.Network(), "udp") {
1519                 f |= pp.PexSupportsUtp
1520         }
1521         return f
1522 }
1523
1524 func (c *PeerConn) dialAddr() net.Addr {
1525         if !c.outgoing && c.PeerListenPort != 0 {
1526                 switch addr := c.remoteAddr.(type) {
1527                 case *net.TCPAddr:
1528                         dialAddr := *addr
1529                         dialAddr.Port = c.PeerListenPort
1530                         return &dialAddr
1531                 case *net.UDPAddr:
1532                         dialAddr := *addr
1533                         dialAddr.Port = c.PeerListenPort
1534                         return &dialAddr
1535                 }
1536         }
1537         return c.remoteAddr
1538 }
1539
1540 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1541         f := c.pexPeerFlags()
1542         addr := c.dialAddr()
1543         return pexEvent{t, addr, f}
1544 }
1545
1546 func (c *PeerConn) String() string {
1547         return fmt.Sprintf("connection %p", c)
1548 }
1549
1550 func (c *PeerConn) trust() connectionTrust {
1551         return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1552 }
1553
1554 type connectionTrust struct {
1555         Implicit            bool
1556         NetGoodPiecesDirted int64
1557 }
1558
1559 func (l connectionTrust) Less(r connectionTrust) bool {
1560         return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1561 }
1562
1563 func (cn *PeerConn) requestStrategyConnection() requestStrategyConnection {
1564         return cn
1565 }
1566
1567 func (cn *PeerConn) chunksReceivedWhileExpecting() int64 {
1568         return cn._chunksReceivedWhileExpecting
1569 }
1570
1571 func (cn *PeerConn) fastest() bool {
1572         return cn == cn.t.fastestConn
1573 }
1574
1575 func (cn *PeerConn) peerMaxRequests() int {
1576         return cn.PeerMaxRequests
1577 }
1578
1579 // Returns the pieces the peer has claimed to have.
1580 func (cn *PeerConn) PeerPieces() bitmap.Bitmap {
1581         cn.locker().RLock()
1582         defer cn.locker().RUnlock()
1583         return cn.peerPieces()
1584 }
1585
1586 func (cn *PeerConn) peerPieces() bitmap.Bitmap {
1587         ret := cn._peerPieces.Copy()
1588         if cn.peerSentHaveAll {
1589                 ret.AddRange(0, cn.t.numPieces())
1590         }
1591         return ret
1592 }
1593
1594 func (cn *PeerConn) pieceRequestOrder() *prioritybitmap.PriorityBitmap {
1595         return &cn._pieceRequestOrder
1596 }
1597
1598 func (cn *PeerConn) stats() *ConnStats {
1599         return &cn._stats
1600 }
1601
1602 func (cn *PeerConn) torrent() requestStrategyTorrent {
1603         return cn.t.requestStrategyTorrent()
1604 }