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