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