Skip to content

Commit a85f4c0

Browse files
authored
Remove some panics in deadline checking. (fortanix#87)
time_until_deadline had a time of check to time of use problem - the deadline could pass between a call to checked_duration_since and the evaluation of `deadline - now` (which panics if the result would be negative). Resolve that by flipping the order of checked_duration_since's arguments and using the result rather than ignoring it. Also there were three places that called deadline - now(), which could panic. Replace those with time_until_deadline().
1 parent 2d67477 commit a85f4c0

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/stream.rs

+8-6
Original file line numberDiff line numberDiff line change
@@ -81,12 +81,12 @@ impl Read for DeadlineStream {
8181
// then. Otherwise return a TimedOut error.
8282
fn time_until_deadline(deadline: Instant) -> IoResult<Duration> {
8383
let now = Instant::now();
84-
match now.checked_duration_since(deadline) {
85-
Some(_) => Err(IoError::new(
84+
match deadline.checked_duration_since(now) {
85+
None => Err(IoError::new(
8686
ErrorKind::TimedOut,
8787
"timed out reading response",
8888
)),
89-
None => Ok(deadline - now),
89+
Some(duration) => Ok(duration),
9090
}
9191
}
9292

@@ -394,7 +394,7 @@ pub(crate) fn connect_host(unit: &Unit, hostname: &str, port: u16) -> Result<Tcp
394394
// Setting it to None will disable the native system timeout
395395
if let Some(deadline) = deadline {
396396
stream
397-
.set_read_timeout(Some(deadline - Instant::now()))
397+
.set_read_timeout(Some(time_until_deadline(deadline)?))
398398
.ok();
399399
} else if unit.timeout_read > 0 {
400400
stream
@@ -406,7 +406,7 @@ pub(crate) fn connect_host(unit: &Unit, hostname: &str, port: u16) -> Result<Tcp
406406

407407
if let Some(deadline) = deadline {
408408
stream
409-
.set_write_timeout(Some(deadline - Instant::now()))
409+
.set_write_timeout(Some(time_until_deadline(deadline)?))
410410
.ok();
411411
} else if unit.timeout_write > 0 {
412412
stream
@@ -523,7 +523,9 @@ fn connect_socks5(
523523
let (lock, cvar) = &*master_signal;
524524
let done = lock.lock().unwrap();
525525

526-
let done_result = cvar.wait_timeout(done, deadline - Instant::now()).unwrap();
526+
let done_result = cvar
527+
.wait_timeout(done, time_until_deadline(deadline)?)
528+
.unwrap();
527529
let done = done_result.0;
528530
if *done {
529531
rx.recv().unwrap()?

0 commit comments

Comments
 (0)