1
0
mirror of https://github.com/veggiedefender/torrent-client.git synced 2025-11-06 17:39:54 +02:00

Add bounds checking to bitfield

This way, we don't panic when we get an invalid HAVE message
This commit is contained in:
Jesse
2019-12-30 10:34:41 -05:00
parent 402e4e1665
commit 487337a08a
2 changed files with 14 additions and 1 deletions

View File

@@ -7,6 +7,9 @@ type Bitfield []byte
func (bf Bitfield) HasPiece(index int) bool {
byteIndex := index / 8
offset := index % 8
if byteIndex < 0 || byteIndex >= len(bf) {
return false
}
return bf[byteIndex]>>(7-offset)&1 != 0
}
@@ -14,5 +17,10 @@ func (bf Bitfield) HasPiece(index int) bool {
func (bf Bitfield) SetPiece(index int) {
byteIndex := index / 8
offset := index % 8
// silently discard invalid bounded index
if byteIndex < 0 || byteIndex >= len(bf) {
return
}
bf[byteIndex] |= 1 << (7 - offset)
}