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