]> Sergey Matveev's repositories - btrtrc.git/blob - peerconn.go
Misc debug status, pex conn tracking improvements
[btrtrc.git] / peerconn.go
1 package torrent
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "errors"
8         "fmt"
9         "io"
10         "math/rand"
11         "net"
12         "strconv"
13         "strings"
14         "time"
15
16         "github.com/RoaringBitmap/roaring"
17         . "github.com/anacrolix/generics"
18         "github.com/anacrolix/log"
19         "github.com/anacrolix/missinggo/v2/bitmap"
20         "github.com/anacrolix/multiless"
21         "golang.org/x/time/rate"
22
23         "github.com/anacrolix/torrent/bencode"
24         "github.com/anacrolix/torrent/internal/alloclim"
25         "github.com/anacrolix/torrent/metainfo"
26         "github.com/anacrolix/torrent/mse"
27         pp "github.com/anacrolix/torrent/peer_protocol"
28 )
29
30 // Maintains the state of a BitTorrent-protocol based connection with a peer.
31 type PeerConn struct {
32         Peer
33
34         // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
35         // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
36         connString string
37
38         // See BEP 3 etc.
39         PeerID             PeerID
40         PeerExtensionBytes pp.PeerExtensionBits
41
42         // The actual Conn, used for closing, and setting socket options. Do not use methods on this
43         // while holding any mutexes.
44         conn net.Conn
45         // The Reader and Writer for this Conn, with hooks installed for stats,
46         // limiting, deadlines etc.
47         w io.Writer
48         r io.Reader
49
50         messageWriter peerConnMsgWriter
51
52         uploadTimer *time.Timer
53         pex         pexConnState
54
55         // The pieces the peer has claimed to have.
56         _peerPieces roaring.Bitmap
57         // The peer has everything. This can occur due to a special message, when
58         // we may not even know the number of pieces in the torrent yet.
59         peerSentHaveAll bool
60
61         peerRequestDataAllocLimiter alloclim.Limiter
62 }
63
64 func (cn *PeerConn) peerImplStatusLines() []string {
65         lines := make([]string, 0, 2)
66         lines = append(
67                 lines,
68                 fmt.Sprintf("%+-55q %v %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString))
69         if cn.supportsExtension(pp.ExtensionNamePex) {
70                 lines = append(
71                         lines,
72                         fmt.Sprintf(
73                                 "pex: %v conns, %v unsent events",
74                                 cn.pex.remoteLiveConns,
75                                 cn.pex.numPending()))
76         }
77         return lines
78 }
79
80 // Returns true if the connection is over IPv6.
81 func (cn *PeerConn) ipv6() bool {
82         ip := cn.remoteIp()
83         if ip.To4() != nil {
84                 return false
85         }
86         return len(ip) == net.IPv6len
87 }
88
89 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
90 // specification for this.
91 func (cn *PeerConn) isPreferredDirection() bool {
92         return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
93 }
94
95 // Returns whether the left connection should be preferred over the right one,
96 // considering only their networking properties. If ok is false, we can't
97 // decide.
98 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) bool {
99         var ml multiless.Computation
100         ml = ml.Bool(r.isPreferredDirection(), l.isPreferredDirection())
101         ml = ml.Bool(l.utp(), r.utp())
102         ml = ml.Bool(r.ipv6(), l.ipv6())
103         return ml.Less()
104 }
105
106 func (cn *PeerConn) peerHasAllPieces() (all, known bool) {
107         if cn.peerSentHaveAll {
108                 return true, true
109         }
110         if !cn.t.haveInfo() {
111                 return false, false
112         }
113         return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
114 }
115
116 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
117         cn.setNumPieces(info.NumPieces())
118 }
119
120 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
121 // receiving badly sized BITFIELD, or invalid HAVE messages.
122 func (cn *PeerConn) setNumPieces(num pieceIndex) {
123         cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
124         cn.peerPiecesChanged()
125 }
126
127 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
128         return &cn._peerPieces
129 }
130
131 func (cn *PeerConn) connectionFlags() (ret string) {
132         c := func(b byte) {
133                 ret += string([]byte{b})
134         }
135         if cn.cryptoMethod == mse.CryptoMethodRC4 {
136                 c('E')
137         } else if cn.headerEncrypted {
138                 c('e')
139         }
140         ret += string(cn.Discovery)
141         if cn.utp() {
142                 c('U')
143         }
144         return
145 }
146
147 func (cn *PeerConn) utp() bool {
148         return parseNetworkString(cn.Network).Udp
149 }
150
151 func (cn *PeerConn) onClose() {
152         if cn.pex.IsEnabled() {
153                 cn.pex.Close()
154         }
155         cn.tickleWriter()
156         if cn.conn != nil {
157                 go cn.conn.Close()
158         }
159         if cb := cn.callbacks.PeerConnClosed; cb != nil {
160                 cb(cn)
161         }
162 }
163
164 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
165 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
166 func (cn *PeerConn) write(msg pp.Message) bool {
167         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
168         // We don't need to track bytes here because the connection's Writer has that behaviour injected
169         // (although there's some delay between us buffering the message, and the connection writer
170         // flushing it out.).
171         notFull := cn.messageWriter.write(msg)
172         // Last I checked only Piece messages affect stats, and we don't write those.
173         cn.wroteMsg(&msg)
174         cn.tickleWriter()
175         return notFull
176 }
177
178 func (cn *PeerConn) requestMetadataPiece(index int) {
179         eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
180         if eID == pp.ExtensionDeleteNumber {
181                 return
182         }
183         if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
184                 return
185         }
186         cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
187         cn.write(pp.MetadataExtensionRequestMsg(eID, index))
188         for index >= len(cn.metadataRequests) {
189                 cn.metadataRequests = append(cn.metadataRequests, false)
190         }
191         cn.metadataRequests[index] = true
192 }
193
194 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
195         return index < len(cn.metadataRequests) && cn.metadataRequests[index]
196 }
197
198 func (cn *PeerConn) onPeerSentCancel(r Request) {
199         if _, ok := cn.peerRequests[r]; !ok {
200                 torrent.Add("unexpected cancels received", 1)
201                 return
202         }
203         if cn.fastEnabled() {
204                 cn.reject(r)
205         } else {
206                 delete(cn.peerRequests, r)
207         }
208 }
209
210 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
211         if cn.choking {
212                 return true
213         }
214         cn.choking = true
215         more = msg(pp.Message{
216                 Type: pp.Choke,
217         })
218         if !cn.fastEnabled() {
219                 cn.deleteAllPeerRequests()
220         }
221         return
222 }
223
224 func (cn *PeerConn) deleteAllPeerRequests() {
225         for _, state := range cn.peerRequests {
226                 state.allocReservation.Drop()
227         }
228         cn.peerRequests = nil
229 }
230
231 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
232         if !cn.choking {
233                 return true
234         }
235         cn.choking = false
236         return msg(pp.Message{
237                 Type: pp.Unchoke,
238         })
239 }
240
241 func (pc *PeerConn) writeInterested(interested bool) bool {
242         return pc.write(pp.Message{
243                 Type: func() pp.MessageType {
244                         if interested {
245                                 return pp.Interested
246                         } else {
247                                 return pp.NotInterested
248                         }
249                 }(),
250         })
251 }
252
253 func (me *PeerConn) _request(r Request) bool {
254         return me.write(pp.Message{
255                 Type:   pp.Request,
256                 Index:  r.Index,
257                 Begin:  r.Begin,
258                 Length: r.Length,
259         })
260 }
261
262 func (me *PeerConn) _cancel(r RequestIndex) bool {
263         me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
264         // Transmission does not send rejects for received cancels. See
265         // https://github.com/transmission/transmission/pull/2275.
266         return me.fastEnabled() && !me.remoteIsTransmission()
267 }
268
269 func (cn *PeerConn) fillWriteBuffer() {
270         if cn.messageWriter.writeBuffer.Len() > writeBufferLowWaterLen {
271                 // Fully committing to our max requests requires sufficient space (see
272                 // maxLocalToRemoteRequests). Flush what we have instead. We also prefer always to make
273                 // requests than to do PEX or upload, so we short-circuit before handling those. Any update
274                 // request reason will not be cleared, so we'll come right back here when there's space. We
275                 // can't do this in maybeUpdateActualRequestState because it's a method on Peer and has no
276                 // knowledge of write buffers.
277         }
278         cn.maybeUpdateActualRequestState()
279         if cn.pex.IsEnabled() {
280                 if flow := cn.pex.Share(cn.write); !flow {
281                         return
282                 }
283         }
284         cn.upload(cn.write)
285 }
286
287 func (cn *PeerConn) have(piece pieceIndex) {
288         if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
289                 return
290         }
291         cn.write(pp.Message{
292                 Type:  pp.Have,
293                 Index: pp.Integer(piece),
294         })
295         cn.sentHaves.Add(bitmap.BitIndex(piece))
296 }
297
298 func (cn *PeerConn) postBitfield() {
299         if cn.sentHaves.Len() != 0 {
300                 panic("bitfield must be first have-related message sent")
301         }
302         if !cn.t.haveAnyPieces() {
303                 return
304         }
305         cn.write(pp.Message{
306                 Type:     pp.Bitfield,
307                 Bitfield: cn.t.bitfield(),
308         })
309         cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
310 }
311
312 func (cn *PeerConn) handleUpdateRequests() {
313         // The writer determines the request state as needed when it can write.
314         cn.tickleWriter()
315 }
316
317 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
318         if newMin > cn.peerMinPieces {
319                 cn.peerMinPieces = newMin
320         }
321 }
322
323 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
324         if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
325                 return errors.New("invalid piece")
326         }
327         if cn.peerHasPiece(piece) {
328                 return nil
329         }
330         cn.raisePeerMinPieces(piece + 1)
331         if !cn.peerHasPiece(piece) {
332                 cn.t.incPieceAvailability(piece)
333         }
334         cn._peerPieces.Add(uint32(piece))
335         if cn.t.wantPieceIndex(piece) {
336                 cn.updateRequests("have")
337         }
338         cn.peerPiecesChanged()
339         return nil
340 }
341
342 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
343         if len(bf)%8 != 0 {
344                 panic("expected bitfield length divisible by 8")
345         }
346         // We know that the last byte means that at most the last 7 bits are wasted.
347         cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
348         if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
349                 // Ignore known excess pieces.
350                 bf = bf[:cn.t.numPieces()]
351         }
352         bm := boolSliceToBitmap(bf)
353         if cn.t.haveInfo() && pieceIndex(bm.GetCardinality()) == cn.t.numPieces() {
354                 cn.onPeerHasAllPieces()
355                 return nil
356         }
357         if !bm.IsEmpty() {
358                 cn.raisePeerMinPieces(pieceIndex(bm.Maximum()) + 1)
359         }
360         shouldUpdateRequests := false
361         if cn.peerSentHaveAll {
362                 if !cn.t.deleteConnWithAllPieces(&cn.Peer) {
363                         panic(cn)
364                 }
365                 cn.peerSentHaveAll = false
366                 if !cn._peerPieces.IsEmpty() {
367                         panic("if peer has all, we expect no individual peer pieces to be set")
368                 }
369         } else {
370                 bm.Xor(&cn._peerPieces)
371         }
372         cn.peerSentHaveAll = false
373         // bm is now 'on' for pieces that are changing
374         bm.Iterate(func(x uint32) bool {
375                 pi := pieceIndex(x)
376                 if cn._peerPieces.Contains(x) {
377                         // Then we must be losing this piece
378                         cn.t.decPieceAvailability(pi)
379                 } else {
380                         if !shouldUpdateRequests && cn.t.wantPieceIndex(pieceIndex(x)) {
381                                 shouldUpdateRequests = true
382                         }
383                         // We must be gaining this piece
384                         cn.t.incPieceAvailability(pieceIndex(x))
385                 }
386                 return true
387         })
388         // Apply the changes. If we had everything previously, this should be empty, so xor is the same
389         // as or.
390         cn._peerPieces.Xor(&bm)
391         if shouldUpdateRequests {
392                 cn.updateRequests("bitfield")
393         }
394         // We didn't guard this before, I see no reason to do it now.
395         cn.peerPiecesChanged()
396         return nil
397 }
398
399 func (cn *PeerConn) onPeerHasAllPieces() {
400         t := cn.t
401         if t.haveInfo() {
402                 cn._peerPieces.Iterate(func(x uint32) bool {
403                         t.decPieceAvailability(pieceIndex(x))
404                         return true
405                 })
406         }
407         t.addConnWithAllPieces(&cn.Peer)
408         cn.peerSentHaveAll = true
409         cn._peerPieces.Clear()
410         if !cn.t._pendingPieces.IsEmpty() {
411                 cn.updateRequests("Peer.onPeerHasAllPieces")
412         }
413         cn.peerPiecesChanged()
414 }
415
416 func (cn *PeerConn) onPeerSentHaveAll() error {
417         cn.onPeerHasAllPieces()
418         return nil
419 }
420
421 func (cn *PeerConn) peerSentHaveNone() error {
422         if !cn.peerSentHaveAll {
423                 cn.t.decPeerPieceAvailability(&cn.Peer)
424         }
425         cn._peerPieces.Clear()
426         cn.peerSentHaveAll = false
427         cn.peerPiecesChanged()
428         return nil
429 }
430
431 func (c *PeerConn) requestPendingMetadata() {
432         if c.t.haveInfo() {
433                 return
434         }
435         if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
436                 // Peer doesn't support this.
437                 return
438         }
439         // Request metadata pieces that we don't have in a random order.
440         var pending []int
441         for index := 0; index < c.t.metadataPieceCount(); index++ {
442                 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
443                         pending = append(pending, index)
444                 }
445         }
446         rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
447         for _, i := range pending {
448                 c.requestMetadataPiece(i)
449         }
450 }
451
452 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
453         torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
454         if msg.Type == pp.Extended {
455                 for name, id := range cn.PeerExtensionIDs {
456                         if id != msg.ExtendedID {
457                                 continue
458                         }
459                         torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
460                 }
461         }
462         cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
463 }
464
465 func (cn *PeerConn) wroteBytes(n int64) {
466         cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
467 }
468
469 func (c *PeerConn) fastEnabled() bool {
470         return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
471 }
472
473 func (c *PeerConn) reject(r Request) {
474         if !c.fastEnabled() {
475                 panic("fast not enabled")
476         }
477         c.write(r.ToMsg(pp.Reject))
478         // It is possible to reject a request before it is added to peer requests due to being invalid.
479         if state, ok := c.peerRequests[r]; ok {
480                 state.allocReservation.Drop()
481                 delete(c.peerRequests, r)
482         }
483 }
484
485 func (c *PeerConn) maximumPeerRequestChunkLength() (_ Option[int]) {
486         uploadRateLimiter := c.t.cl.config.UploadRateLimiter
487         if uploadRateLimiter.Limit() == rate.Inf {
488                 return
489         }
490         return Some(uploadRateLimiter.Burst())
491 }
492
493 // startFetch is for testing purposes currently.
494 func (c *PeerConn) onReadRequest(r Request, startFetch bool) error {
495         requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
496         if _, ok := c.peerRequests[r]; ok {
497                 torrent.Add("duplicate requests received", 1)
498                 if c.fastEnabled() {
499                         return errors.New("received duplicate request with fast enabled")
500                 }
501                 return nil
502         }
503         if c.choking {
504                 torrent.Add("requests received while choking", 1)
505                 if c.fastEnabled() {
506                         torrent.Add("requests rejected while choking", 1)
507                         c.reject(r)
508                 }
509                 return nil
510         }
511         // TODO: What if they've already requested this?
512         if len(c.peerRequests) >= localClientReqq {
513                 torrent.Add("requests received while queue full", 1)
514                 if c.fastEnabled() {
515                         c.reject(r)
516                 }
517                 // BEP 6 says we may close here if we choose.
518                 return nil
519         }
520         if opt := c.maximumPeerRequestChunkLength(); opt.Ok && int(r.Length) > opt.Value {
521                 err := fmt.Errorf("peer requested chunk too long (%v)", r.Length)
522                 c.logger.Levelf(log.Warning, err.Error())
523                 if c.fastEnabled() {
524                         c.reject(r)
525                         return nil
526                 } else {
527                         return err
528                 }
529         }
530         if !c.t.havePiece(pieceIndex(r.Index)) {
531                 // TODO: Tell the peer we don't have the piece, and reject this request.
532                 requestsReceivedForMissingPieces.Add(1)
533                 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
534         }
535         pieceLength := c.t.pieceLength(pieceIndex(r.Index))
536         // Check this after we know we have the piece, so that the piece length will be known.
537         if chunkOverflowsPiece(r.ChunkSpec, pieceLength) {
538                 torrent.Add("bad requests received", 1)
539                 return errors.New("chunk overflows piece")
540         }
541         if c.peerRequests == nil {
542                 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
543         }
544         value := &peerRequestState{
545                 allocReservation: c.peerRequestDataAllocLimiter.Reserve(int64(r.Length)),
546         }
547         c.peerRequests[r] = value
548         if startFetch {
549                 // TODO: Limit peer request data read concurrency.
550                 go c.peerRequestDataReader(r, value)
551         }
552         return nil
553 }
554
555 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
556         b, err := c.readPeerRequestData(r, prs)
557         c.locker().Lock()
558         defer c.locker().Unlock()
559         if err != nil {
560                 c.peerRequestDataReadFailed(err, r)
561         } else {
562                 if b == nil {
563                         panic("data must be non-nil to trigger send")
564                 }
565                 torrent.Add("peer request data read successes", 1)
566                 prs.data = b
567                 // This might be required for the error case too (#752 and #753).
568                 c.tickleWriter()
569         }
570 }
571
572 // If this is maintained correctly, we might be able to support optional synchronous reading for
573 // chunk sending, the way it used to work.
574 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
575         torrent.Add("peer request data read failures", 1)
576         logLevel := log.Warning
577         if c.t.hasStorageCap() {
578                 // It's expected that pieces might drop. See
579                 // https://github.com/anacrolix/torrent/issues/702#issuecomment-1000953313.
580                 logLevel = log.Debug
581         }
582         c.logger.WithDefaultLevel(logLevel).Printf("error reading chunk for peer Request %v: %v", r, err)
583         if c.t.closed.IsSet() {
584                 return
585         }
586         i := pieceIndex(r.Index)
587         if c.t.pieceComplete(i) {
588                 // There used to be more code here that just duplicated the following break. Piece
589                 // completions are currently cached, so I'm not sure how helpful this update is, except to
590                 // pull any completion changes pushed to the storage backend in failed reads that got us
591                 // here.
592                 c.t.updatePieceCompletion(i)
593         }
594         // We've probably dropped a piece from storage, but there's no way to communicate this to the
595         // peer. If they ask for it again, we kick them allowing us to send them updated piece states if
596         // we reconnect. TODO: Instead, we could just try to update them with Bitfield or HaveNone and
597         // if they kick us for breaking protocol, on reconnect we will be compliant again (at least
598         // initially).
599         if c.fastEnabled() {
600                 c.reject(r)
601         } else {
602                 if c.choking {
603                         // If fast isn't enabled, I think we would have wiped all peer requests when we last
604                         // choked, and requests while we're choking would be ignored. It could be possible that
605                         // a peer request data read completed concurrently to it being deleted elsewhere.
606                         c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
607                 }
608                 // Choking a non-fast peer should cause them to flush all their requests.
609                 c.choke(c.write)
610         }
611 }
612
613 func (c *PeerConn) readPeerRequestData(r Request, prs *peerRequestState) ([]byte, error) {
614         // Should we depend on Torrent closure here? I think it's okay to get cancelled from elsewhere,
615         // or fail to read and then cleanup.
616         ctx := context.Background()
617         err := prs.allocReservation.Wait(ctx)
618         if err != nil {
619                 if ctx.Err() == nil {
620                         // The error is from the reservation itself. Something is very broken, or we're not
621                         // guarding against excessively large requests.
622                         err = log.WithLevel(log.Critical, err)
623                 }
624                 err = fmt.Errorf("waiting for alloc limit reservation: %w", err)
625                 return nil, err
626         }
627         b := make([]byte, r.Length)
628         p := c.t.info.Piece(int(r.Index))
629         n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
630         if n == len(b) {
631                 if err == io.EOF {
632                         err = nil
633                 }
634         } else {
635                 if err == nil {
636                         panic("expected error")
637                 }
638         }
639         return b, err
640 }
641
642 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
643         c.logger.WithContextText(fmt.Sprintf(
644                 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
645         )).SkipCallers(1).Levelf(level, format, arg...)
646 }
647
648 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
649 // exit. Returning will end the connection.
650 func (c *PeerConn) mainReadLoop() (err error) {
651         defer func() {
652                 if err != nil {
653                         torrent.Add("connection.mainReadLoop returned with error", 1)
654                 } else {
655                         torrent.Add("connection.mainReadLoop returned with no error", 1)
656                 }
657         }()
658         t := c.t
659         cl := t.cl
660
661         decoder := pp.Decoder{
662                 R:         bufio.NewReaderSize(c.r, 1<<17),
663                 MaxLength: 4 * pp.Integer(max(int64(t.chunkSize), defaultChunkSize)),
664                 Pool:      &t.chunkPool,
665         }
666         for {
667                 var msg pp.Message
668                 func() {
669                         cl.unlock()
670                         defer cl.lock()
671                         err = decoder.Decode(&msg)
672                 }()
673                 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
674                         cb(c, &msg)
675                 }
676                 if t.closed.IsSet() || c.closed.IsSet() {
677                         return nil
678                 }
679                 if err != nil {
680                         return err
681                 }
682                 c.lastMessageReceived = time.Now()
683                 if msg.Keepalive {
684                         receivedKeepalives.Add(1)
685                         continue
686                 }
687                 messageTypesReceived.Add(msg.Type.String(), 1)
688                 if msg.Type.FastExtension() && !c.fastEnabled() {
689                         runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
690                         return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
691                 }
692                 switch msg.Type {
693                 case pp.Choke:
694                         if c.peerChoking {
695                                 break
696                         }
697                         if !c.fastEnabled() {
698                                 c.deleteAllRequests("choked by non-fast PeerConn")
699                         } else {
700                                 // We don't decrement pending requests here, let's wait for the peer to either
701                                 // reject or satisfy the outstanding requests. Additionally, some peers may unchoke
702                                 // us and resume where they left off, we don't want to have piled on to those chunks
703                                 // in the meanwhile. I think a peer's ability to abuse this should be limited: they
704                                 // could let us request a lot of stuff, then choke us and never reject, but they're
705                                 // only a single peer, our chunk balancing should smooth over this abuse.
706                         }
707                         c.peerChoking = true
708                         c.updateExpectingChunks()
709                 case pp.Unchoke:
710                         if !c.peerChoking {
711                                 // Some clients do this for some reason. Transmission doesn't error on this, so we
712                                 // won't for consistency.
713                                 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
714                                 break
715                         }
716                         c.peerChoking = false
717                         preservedCount := 0
718                         c.requestState.Requests.Iterate(func(x RequestIndex) bool {
719                                 if !c.peerAllowedFast.Contains(c.t.pieceIndexOfRequestIndex(x)) {
720                                         preservedCount++
721                                 }
722                                 return true
723                         })
724                         if preservedCount != 0 {
725                                 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
726                                 // right now.
727                                 c.logger.Levelf(log.Debug,
728                                         "%v requests were preserved while being choked (fast=%v)",
729                                         preservedCount,
730                                         c.fastEnabled())
731
732                                 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
733                         }
734                         if !c.t._pendingPieces.IsEmpty() {
735                                 c.updateRequests("unchoked")
736                         }
737                         c.updateExpectingChunks()
738                 case pp.Interested:
739                         c.peerInterested = true
740                         c.tickleWriter()
741                 case pp.NotInterested:
742                         c.peerInterested = false
743                         // We don't clear their requests since it isn't clear in the spec.
744                         // We'll probably choke them for this, which will clear them if
745                         // appropriate, and is clearly specified.
746                 case pp.Have:
747                         err = c.peerSentHave(pieceIndex(msg.Index))
748                 case pp.Bitfield:
749                         err = c.peerSentBitfield(msg.Bitfield)
750                 case pp.Request:
751                         r := newRequestFromMessage(&msg)
752                         err = c.onReadRequest(r, true)
753                         if err != nil {
754                                 err = fmt.Errorf("on reading request %v: %w", r, err)
755                         }
756                 case pp.Piece:
757                         c.doChunkReadStats(int64(len(msg.Piece)))
758                         err = c.receiveChunk(&msg)
759                         if len(msg.Piece) == int(t.chunkSize) {
760                                 t.chunkPool.Put(&msg.Piece)
761                         }
762                         if err != nil {
763                                 err = fmt.Errorf("receiving chunk: %w", err)
764                         }
765                 case pp.Cancel:
766                         req := newRequestFromMessage(&msg)
767                         c.onPeerSentCancel(req)
768                 case pp.Port:
769                         ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
770                         if !ok {
771                                 break
772                         }
773                         pingAddr := net.UDPAddr{
774                                 IP:   ipa.IP,
775                                 Port: ipa.Port,
776                         }
777                         if msg.Port != 0 {
778                                 pingAddr.Port = int(msg.Port)
779                         }
780                         cl.eachDhtServer(func(s DhtServer) {
781                                 go s.Ping(&pingAddr)
782                         })
783                 case pp.Suggest:
784                         torrent.Add("suggests received", 1)
785                         log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).LogLevel(log.Debug, c.t.logger)
786                         c.updateRequests("suggested")
787                 case pp.HaveAll:
788                         err = c.onPeerSentHaveAll()
789                 case pp.HaveNone:
790                         err = c.peerSentHaveNone()
791                 case pp.Reject:
792                         req := newRequestFromMessage(&msg)
793                         if !c.remoteRejectedRequest(c.t.requestIndexFromRequest(req)) {
794                                 c.logger.Printf("received invalid reject [request=%v, peer=%v]", req, c)
795                                 err = fmt.Errorf("received invalid reject [request=%v]", req)
796                         }
797                 case pp.AllowedFast:
798                         torrent.Add("allowed fasts received", 1)
799                         log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).LogLevel(log.Debug, c.t.logger)
800                         c.updateRequests("PeerConn.mainReadLoop allowed fast")
801                 case pp.Extended:
802                         err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
803                 default:
804                         err = fmt.Errorf("received unknown message type: %#v", msg.Type)
805                 }
806                 if err != nil {
807                         return err
808                 }
809         }
810 }
811
812 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
813         defer func() {
814                 // TODO: Should we still do this?
815                 if err != nil {
816                         // These clients use their own extension IDs for outgoing message
817                         // types, which is incorrect.
818                         if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
819                                 err = nil
820                         }
821                 }
822         }()
823         t := c.t
824         cl := t.cl
825         switch id {
826         case pp.HandshakeExtendedID:
827                 var d pp.ExtendedHandshakeMessage
828                 if err := bencode.Unmarshal(payload, &d); err != nil {
829                         c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
830                         return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
831                 }
832                 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
833                         cb(c, &d)
834                 }
835                 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
836                 if d.Reqq != 0 {
837                         c.PeerMaxRequests = d.Reqq
838                 }
839                 c.PeerClientName.Store(d.V)
840                 if c.PeerExtensionIDs == nil {
841                         c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
842                 }
843                 c.PeerListenPort = d.Port
844                 c.PeerPrefersEncryption = d.Encryption
845                 for name, id := range d.M {
846                         if _, ok := c.PeerExtensionIDs[name]; !ok {
847                                 peersSupportingExtension.Add(
848                                         // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
849                                         // entered here which caused problems later when unmarshalling.
850                                         strconv.Quote(string(name)),
851                                         1)
852                         }
853                         c.PeerExtensionIDs[name] = id
854                 }
855                 if d.MetadataSize != 0 {
856                         if err = t.setMetadataSize(d.MetadataSize); err != nil {
857                                 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
858                         }
859                 }
860                 c.requestPendingMetadata()
861                 if !t.cl.config.DisablePEX {
862                         t.pex.Add(c) // we learnt enough now
863                         // This checks the extension is supported internally.
864                         c.pex.Init(c)
865                 }
866                 return nil
867         case metadataExtendedId:
868                 err := cl.gotMetadataExtensionMsg(payload, t, c)
869                 if err != nil {
870                         return fmt.Errorf("handling metadata extension message: %w", err)
871                 }
872                 return nil
873         case pexExtendedId:
874                 if !c.pex.IsEnabled() {
875                         return nil // or hang-up maybe?
876                 }
877                 return c.pex.Recv(payload)
878         default:
879                 return fmt.Errorf("unexpected extended message ID: %v", id)
880         }
881 }
882
883 // Set both the Reader and Writer for the connection from a single ReadWriter.
884 func (cn *PeerConn) setRW(rw io.ReadWriter) {
885         cn.r = rw
886         cn.w = rw
887 }
888
889 // Returns the Reader and Writer as a combined ReadWriter.
890 func (cn *PeerConn) rw() io.ReadWriter {
891         return struct {
892                 io.Reader
893                 io.Writer
894         }{cn.r, cn.w}
895 }
896
897 func (c *PeerConn) uploadAllowed() bool {
898         if c.t.cl.config.NoUpload {
899                 return false
900         }
901         if c.t.dataUploadDisallowed {
902                 return false
903         }
904         if c.t.seeding() {
905                 return true
906         }
907         if !c.peerHasWantedPieces() {
908                 return false
909         }
910         // Don't upload more than 100 KiB more than we download.
911         if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
912                 return false
913         }
914         return true
915 }
916
917 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
918         if c.uploadTimer == nil {
919                 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
920         } else {
921                 c.uploadTimer.Reset(delay)
922         }
923 }
924
925 // Also handles choking and unchoking of the remote peer.
926 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
927         // Breaking or completing this loop means we don't want to upload to the
928         // peer anymore, and we choke them.
929 another:
930         for c.uploadAllowed() {
931                 // We want to upload to the peer.
932                 if !c.unchoke(msg) {
933                         return false
934                 }
935                 for r, state := range c.peerRequests {
936                         if state.data == nil {
937                                 continue
938                         }
939                         res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
940                         if !res.OK() {
941                                 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
942                         }
943                         delay := res.Delay()
944                         if delay > 0 {
945                                 res.Cancel()
946                                 c.setRetryUploadTimer(delay)
947                                 // Hard to say what to return here.
948                                 return true
949                         }
950                         more := c.sendChunk(r, msg, state)
951                         delete(c.peerRequests, r)
952                         if !more {
953                                 return false
954                         }
955                         goto another
956                 }
957                 return true
958         }
959         return c.choke(msg)
960 }
961
962 func (cn *PeerConn) drop() {
963         cn.t.dropConnection(cn)
964 }
965
966 func (cn *PeerConn) ban() {
967         cn.t.cl.banPeerIP(cn.remoteIp())
968 }
969
970 // This is called when something has changed that should wake the writer, such as putting stuff into
971 // the writeBuffer, or changing some state that the writer can act on.
972 func (c *PeerConn) tickleWriter() {
973         c.messageWriter.writeCond.Broadcast()
974 }
975
976 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
977         c.lastChunkSent = time.Now()
978         state.allocReservation.Release()
979         return msg(pp.Message{
980                 Type:  pp.Piece,
981                 Index: r.Index,
982                 Begin: r.Begin,
983                 Piece: state.data,
984         })
985 }
986
987 func (c *PeerConn) setTorrent(t *Torrent) {
988         if c.t != nil {
989                 panic("connection already associated with a torrent")
990         }
991         c.t = t
992         c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
993         t.reconcileHandshakeStats(c)
994 }
995
996 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
997         f := pp.PexPeerFlags(0)
998         if c.PeerPrefersEncryption {
999                 f |= pp.PexPrefersEncryption
1000         }
1001         if c.outgoing {
1002                 f |= pp.PexOutgoingConn
1003         }
1004         if c.utp() {
1005                 f |= pp.PexSupportsUtp
1006         }
1007         return f
1008 }
1009
1010 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1011 // advertised listen port.
1012 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1013         if !c.outgoing && c.PeerListenPort != 0 {
1014                 switch addr := c.RemoteAddr.(type) {
1015                 case *net.TCPAddr:
1016                         dialAddr := *addr
1017                         dialAddr.Port = c.PeerListenPort
1018                         return &dialAddr
1019                 case *net.UDPAddr:
1020                         dialAddr := *addr
1021                         dialAddr.Port = c.PeerListenPort
1022                         return &dialAddr
1023                 }
1024         }
1025         return c.RemoteAddr
1026 }
1027
1028 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1029         f := c.pexPeerFlags()
1030         addr := c.dialAddr()
1031         return pexEvent{t, addr, f, nil}
1032 }
1033
1034 func (c *PeerConn) String() string {
1035         return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1036 }
1037
1038 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1039 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1040 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1041         cn.locker().RLock()
1042         defer cn.locker().RUnlock()
1043         return cn.newPeerPieces()
1044 }
1045
1046 func (pc *PeerConn) remoteIsTransmission() bool {
1047         return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'
1048 }