From 738a75bc1ca5cb7dd88d9c14ab3068418e6588d8 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Sat, 3 Feb 2018 13:35:09 +1100 Subject: [PATCH] Prepare to support sending reject messages --- connection.go | 24 +++++++++++++++++++++++- misc.go | 9 +++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/connection.go b/connection.go index 70afb2a8..3ad80b5b 100644 --- a/connection.go +++ b/connection.go @@ -824,13 +824,34 @@ func (c *connection) lastHelpful() (ret time.Time) { return } +func (c *connection) fastEnabled() bool { + return c.PeerExtensionBytes.SupportsFast() && c.t.cl.extensionBytes.SupportsFast() +} + +// Returns true if we were able to reject the request. +func (c *connection) reject(r request) bool { + if !c.fastEnabled() { + return false + } + c.deleteRequest(r) + c.Post(r.ToMsg(pp.Reject)) + return true +} + func (c *connection) onReadRequest(r request) error { requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1) + if r.Begin+r.Length > c.t.pieceLength(int(r.Index)) { + return errors.New("bad request") + } + if _, ok := c.PeerRequests[r]; ok { + return nil + } if c.Choked { + c.reject(r) return nil } if len(c.PeerRequests) >= maxRequests { - // TODO: Should we drop them or Choke them instead? + c.reject(r) return nil } if !c.t.havePiece(r.Index.Int()) { @@ -1254,6 +1275,7 @@ func (c *connection) deleteRequest(r request) bool { } delete(c.requests, r) c.t.pendingRequests[r]-- + c.updateRequests() return true } diff --git a/misc.go b/misc.go index 58221661..f3b38bf3 100644 --- a/misc.go +++ b/misc.go @@ -17,6 +17,15 @@ type request struct { chunkSpec } +func (r request) ToMsg(mt pp.MessageType) pp.Message { + return pp.Message{ + Type: mt, + Index: r.Index, + Begin: r.Begin, + Length: r.Length, + } +} + func newRequest(index, begin, length pp.Integer) request { return request{index, chunkSpec{begin, length}} } -- 2.44.0