diff --git a/protocol/src/lib.rs b/protocol/src/lib.rs index f420042..d22a52a 100644 --- a/protocol/src/lib.rs +++ b/protocol/src/lib.rs @@ -768,7 +768,7 @@ impl<'a> Handshake<'a> { packet_buffer: &mut [u8], ) -> Result<(), Error> { // Find the end of the garbage. - let (garbage, message) = split_garbage_and_message( + let (garbage, message) = split_garbage( buffer, self.remote_garbage_terminator .ok_or(Error::HandshakeOutOfOrder)?, @@ -871,24 +871,23 @@ impl<'a> Handshake<'a> { } } -/// Split a message on the garbage terminator returning the garbage itself -/// and the remaing message. The message is expected to be the version packet, -/// but could be decoy packets. +/// Split off garbage in the buffer on the garbage terminator. +/// +/// # Returns +/// +/// A `Result` containing the garbage and the remaining ciphertext not including the terminator. /// /// # Error /// /// * `CiphertextTooSmall` - Buffer did not contain a garbage terminator. /// * `MaxGarbageLength` - Buffer did not contain the garbage terminator and contains too much garbage, should not be retried. -fn split_garbage_and_message( - message: &[u8], - garbage_term: [u8; 16], -) -> Result<(&[u8], &[u8]), Error> { - if let Some(index) = message +fn split_garbage(buffer: &[u8], garbage_term: [u8; 16]) -> Result<(&[u8], &[u8]), Error> { + if let Some(index) = buffer .windows(garbage_term.len()) .position(|window| window == garbage_term) { - Ok((&message[..index], &message[(index + garbage_term.len())..])) - } else if message.len() >= (MAX_NUM_GARBAGE_BYTES + NUM_GARBAGE_TERMINTOR_BYTES) { + Ok((&buffer[..index], &buffer[(index + garbage_term.len())..])) + } else if buffer.len() >= (MAX_NUM_GARBAGE_BYTES + NUM_GARBAGE_TERMINTOR_BYTES) { Err(Error::MaxGarbageLength) } else { // Terminator not found, the message needs more information. @@ -1013,7 +1012,7 @@ mod tests { fn test_max_garbage() { let too_much_garbage = vec![0; 4111]; let garbage_terminator = [1; 16]; - let result = split_garbage_and_message(&too_much_garbage, garbage_terminator); + let result = split_garbage(&too_much_garbage, garbage_terminator); assert!(matches!(result, Err(Error::MaxGarbageLength))); }