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