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