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