From: Matt Joiner Date: Tue, 22 Nov 2016 03:20:48 +0000 (+1100) Subject: Don't accept pieces with bad indexes X-Git-Tag: v1.0.0~533 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=90ca45dd2d73a2dbc0843f11f75fadfc08cc6eb4;p=btrtrc.git Don't accept pieces with bad indexes Fixes #132 --- diff --git a/connection.go b/connection.go index 5493714b..fbc888c3 100644 --- a/connection.go +++ b/connection.go @@ -942,9 +942,6 @@ func (c *connection) receiveChunk(msg *pp.Message) { unexpectedChunksReceived.Add(1) } - index := int(req.Index) - piece := &t.pieces[index] - // Do we actually want this chunk? if !t.wantPiece(req) { unwantedChunksReceived.Add(1) @@ -952,6 +949,9 @@ func (c *connection) receiveChunk(msg *pp.Message) { return } + index := int(req.Index) + piece := &t.pieces[index] + c.UsefulChunksReceived++ c.lastUsefulChunkReceived = time.Now() diff --git a/connection_test.go b/connection_test.go index 31ddbe14..48fb4f5f 100644 --- a/connection_test.go +++ b/connection_test.go @@ -16,7 +16,7 @@ import ( "github.com/stretchr/testify/require" "github.com/anacrolix/torrent/metainfo" - "github.com/anacrolix/torrent/peer_protocol" + pp "github.com/anacrolix/torrent/peer_protocol" "github.com/anacrolix/torrent/storage" ) @@ -157,8 +157,8 @@ func BenchmarkConnectionMainReadLoop(b *testing.B) { } close(mrlErr) }() - msg := peer_protocol.Message{ - Type: peer_protocol.Piece, + msg := pp.Message{ + Type: pp.Piece, Piece: make([]byte, defaultChunkSize), } wb, err := msg.MarshalBinary() @@ -178,3 +178,14 @@ func BenchmarkConnectionMainReadLoop(b *testing.B) { require.NoError(b, <-mrlErr) require.EqualValues(b, b.N, cn.UsefulChunksReceived) } + +func TestConnectionReceiveBadChunkIndex(t *testing.T) { + cn := connection{ + t: &Torrent{}, + } + require.False(t, cn.t.haveInfo()) + assert.NotPanics(t, func() { cn.receiveChunk(&pp.Message{}) }) + cn.t.info = &metainfo.Info{} + require.True(t, cn.t.haveInfo()) + assert.NotPanics(t, func() { cn.receiveChunk(&pp.Message{}) }) +} diff --git a/torrent.go b/torrent.go index d0f81fd7..2577960c 100644 --- a/torrent.go +++ b/torrent.go @@ -734,6 +734,9 @@ func (t *Torrent) wantPieceIndex(index int) bool { if !t.haveInfo() { return false } + if index < 0 || index >= t.numPieces() { + return false + } p := &t.pieces[index] if p.QueuedForHash { return false