From 036fd126e8b880f52ca48ecaf4d29de70811d59a Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Wed, 16 Apr 2014 17:33:33 +1000 Subject: [PATCH] Implement receiving cancel messages --- client.go | 5 +++++ connection.go | 12 ++++++++++++ misc.go | 4 ++++ 3 files changed, 21 insertions(+) diff --git a/client.go b/client.go index 76425ccc..f8737600 100644 --- a/client.go +++ b/client.go @@ -425,6 +425,11 @@ func (me *Client) connectionLoop(torrent *torrent, conn *connection) error { Begin: msg.Begin, Piece: p, }) + case peer_protocol.Cancel: + req := newRequest(msg.Index, msg.Begin, msg.Length) + if !conn.PeerCancel(req) { + log.Printf("received unexpected cancel: %v", req) + } case peer_protocol.Bitfield: if len(msg.Bitfield) < len(torrent.Pieces) { err = errors.New("received invalid bitfield") diff --git a/connection.go b/connection.go index ee54f10c..aefe0ba0 100644 --- a/connection.go +++ b/connection.go @@ -88,6 +88,18 @@ func (c *connection) Request(chunk Request) bool { return true } +// Returns true if an unsatisfied request was canceled. +func (c *connection) PeerCancel(r Request) bool { + if c.PeerRequests == nil { + return false + } + if _, ok := c.PeerRequests[r]; !ok { + return false + } + delete(c.PeerRequests, r) + return true +} + func (c *connection) Unchoke() { if !c.Choked { return diff --git a/misc.go b/misc.go index ce0997f2..b0fb349e 100644 --- a/misc.go +++ b/misc.go @@ -65,6 +65,10 @@ type Request struct { chunkSpec } +func newRequest(index, begin, length peer_protocol.Integer) Request { + return Request{index, chunkSpec{begin, length}} +} + type pieceByBytesPendingSlice struct { Pending, Indices []peer_protocol.Integer } -- 2.44.0