Skip to content

Commit

Permalink
Fix panic with invalid system time (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
5225225 authored Jan 9, 2022
1 parent a14ea97 commit 0bde6a8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,13 @@ pub enum DecodeError {
nanos: u32,
},

/// The decoder tried to decode a SystemTime and overflowed
InvalidSystemTime {
/// The duration which could not have been added to
/// [`UNIX_EPOCH`](std::time::SystemTime::UNIX_EPOCH)
duration: core::time::Duration,
},

/// The decoder tried to decode a `CStr` or `CString`, but the incoming data contained a 0 byte
#[cfg(feature = "std")]
CStrNulError {
Expand Down
5 changes: 4 additions & 1 deletion src/features/impl_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,10 @@ impl Encode for SystemTime {
impl Decode for SystemTime {
fn decode<D: Decoder>(decoder: D) -> Result<Self, DecodeError> {
let duration = Duration::decode(decoder)?;
Ok(SystemTime::UNIX_EPOCH + duration)
match SystemTime::UNIX_EPOCH.checked_add(duration) {
Some(t) => Ok(t),
None => Err(DecodeError::InvalidSystemTime { duration }),
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions tests/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,18 @@ fn test_std_commons() {
assert_eq!(path, decoded);
assert_eq!(len, 21);
}

#[test]
fn test_system_time_out_of_range() {
let mut input = [0xfd, 0x90, 0x0c, 0xfd, 0xfd, 0x90, 0x0c, 0xfd, 0x90, 0x90];

let result: Result<(std::time::SystemTime, usize), _> =
bincode::decode_from_slice(&mut input, Configuration::standard());

assert_eq!(
result.unwrap_err(),
bincode::error::DecodeError::InvalidSystemTime {
duration: std::time::Duration::new(10447520527445462160, 144),
}
);
}

0 comments on commit 0bde6a8

Please sign in to comment.