Skip to content

Commit d66b377

Browse files
authored
Check Slice bounds in read_message to avoid panics (#371)
When recv is called in the mirroring client, we noticed an occasional panic when reading the message. thread 'tokio-runtime-worker' panicked at 'slice index starts at 5 but ends at 0', src/messages.rs:522:18 We are still debugging the reason why this happens but adding a check for slice bounds seems like a good idea. Instead of panicking, this will return an Err to the caller which will close the connection.
1 parent ac21ce5 commit d66b377

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/messages.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -517,14 +517,18 @@ where
517517

518518
bytes.resize(bytes.len() + len as usize - mem::size_of::<i32>(), b'0');
519519

520-
match stream
521-
.read_exact(
522-
&mut bytes[mem::size_of::<u8>() + mem::size_of::<i32>()
523-
..mem::size_of::<u8>() + mem::size_of::<i32>() + len as usize
524-
- mem::size_of::<i32>()],
525-
)
526-
.await
527-
{
520+
let slice_start = mem::size_of::<u8>() + mem::size_of::<i32>();
521+
let slice_end = slice_start + len as usize - mem::size_of::<i32>();
522+
523+
// Avoids a panic
524+
if slice_end < slice_start {
525+
return Err(Error::SocketError(format!(
526+
"Error reading message from socket - Code: {:?} - Length {:?}, Error: {:?}",
527+
code, len, "Unexpected length value for message"
528+
)));
529+
}
530+
531+
match stream.read_exact(&mut bytes[slice_start..slice_end]).await {
528532
Ok(_) => (),
529533
Err(err) => {
530534
return Err(Error::SocketError(format!(

0 commit comments

Comments
 (0)