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