]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Don't accept pieces with bad indexes
authorMatt Joiner <anacrolix@gmail.com>
Tue, 22 Nov 2016 03:20:48 +0000 (14:20 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Tue, 22 Nov 2016 03:20:48 +0000 (14:20 +1100)
Fixes #132

connection.go
connection_test.go
torrent.go

index 5493714bdabee9b177b031e1f22ab56088db05ca..fbc888c3fbedf766783d3ee50f61c5d40743a151 100644 (file)
@@ -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()
 
index 31ddbe141822f8bb7407e83530e6f43e1c72ead9..48fb4f5f9a447c3cae090e596e7d02c8b29cba53 100644 (file)
@@ -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{}) })
+}
index d0f81fd7f1bc3a2628ca5abd3616b0d486b74e1e..2577960ca3eea6bf6cd5c78778c4c2e7b35a12b7 100644 (file)
@@ -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