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