From 0a81fd6514fb10a9df9c63c6b63f42d6db1fdff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patrick=20Jos=C3=A9=20Pereira?= Date: Thu, 16 May 2024 11:13:48 -0300 Subject: [PATCH] build: binder: Improve try_from vec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Patrick José Pereira --- build/binder.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/build/binder.rs b/build/binder.rs index 1c5475b03..9c0db34b8 100644 --- a/build/binder.rs +++ b/build/binder.rs @@ -105,12 +105,26 @@ pub fn generate(modules: Vec, out: &mut W) { type Error = String; // TODO: define error types for each kind of failure fn try_from(buffer: &Vec) -> Result { + const MIN_MSG_SIZE: usize = 10; + // Parse start1 and start2 if !((buffer[0] == HEADER[0]) && (buffer[1] == HEADER[1])) { return Err(format!("Message should start with \"BR\" ASCII sequence, received: [{0}({:0x}), {1}({:0x})]", buffer[0], buffer[1])); } + let buffer_size = buffer.len(); + if buffer.len() < MIN_MSG_SIZE { + return Err(format!("Message is too short, should be at least {} bytes", MIN_MSG_SIZE).into()); + } + let payload_length = u16::from_le_bytes([buffer[2], buffer[3]]); + if payload_length as usize + MIN_MSG_SIZE != buffer.len() { + return Err(format!( + "Payload length does not match, expected: {payload_length}, received: {}", + buffer.len() - MIN_MSG_SIZE + )); + } + let protocol_message = ProtocolMessage { payload_length, message_id: u16::from_le_bytes([buffer[4], buffer[5]]),