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