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