Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: attempt to fix panic on decoding startup message #112

Merged
merged 1 commit into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub enum PgWireError {
InvalidMessageType(u8),
#[error("Invalid target type, received {0}")]
InvalidTargetType(u8),
#[error("Invalid startup message")]
InvalidStartupMessage,
#[error(transparent)]
IoError(#[from] std::io::Error),
#[error("Portal not found for name: {0:?}")]
Expand Down
15 changes: 13 additions & 2 deletions src/messages/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ impl Default for Startup {
}

impl Startup {
const MINIMUM_STARTUP_MESSAGE_LEN: usize = 8;

fn is_protocol_version_supported(version: i32) -> bool {
version == 196608
}
Expand Down Expand Up @@ -64,7 +66,7 @@ impl Message for Startup {
fn decode(buf: &mut BytesMut) -> PgWireResult<Option<Self>> {
// packet len + protocol version
// check if packet is valid
if buf.remaining() >= 8 {
if buf.remaining() >= Self::MINIMUM_STARTUP_MESSAGE_LEN {
let packet_version = (&buf[4..8]).get_i32();
if !Self::is_protocol_version_supported(packet_version) {
return Err(PgWireError::InvalidProtocolVersion(packet_version));
Expand All @@ -74,8 +76,17 @@ impl Message for Startup {
codec::decode_packet(buf, 0, Self::decode_body)
}

fn decode_body(buf: &mut BytesMut, _: usize) -> PgWireResult<Self> {
fn decode_body(buf: &mut BytesMut, msg_len: usize) -> PgWireResult<Self> {
// double check to ensure that the packet has more than 8 bytes
// `codec::decode_packet` has its validation to ensure buf remaining is
// larger than `msg_len`. So with both checks, we should not have issue
// with reading protocol numbers.
if msg_len <= Self::MINIMUM_STARTUP_MESSAGE_LEN {
return Err(PgWireError::InvalidStartupMessage);
}

let mut msg = Startup::default();

// parse
msg.set_protocol_number_major(buf.get_u16());
msg.set_protocol_number_minor(buf.get_u16());
Expand Down
Loading