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