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