Skip to content

Commit

Permalink
Handle overflow in Deadline calculation to ensure correct behavior fo…
Browse files Browse the repository at this point in the history
…r large time values.
  • Loading branch information
arturobernalg committed Jan 10, 2025
1 parent b435a0b commit bdb1c9b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,11 @@ public class Deadline {
*/
public static Deadline calculate(final long timeMillis, final TimeValue timeValue) {
if (TimeValue.isPositive(timeValue)) {
// TODO handle unlikely overflow
final long deadline = timeMillis + timeValue.toMilliseconds();
final long timeToAdd = timeValue.toMilliseconds();
if (timeToAdd > 0 && timeMillis > Long.MAX_VALUE - timeToAdd) {
return Deadline.MAX_VALUE; // Overflow detected
}
final long deadline = timeMillis + timeToAdd;
return deadline < 0 ? Deadline.MAX_VALUE : Deadline.fromUnixMilliseconds(deadline);
}
return Deadline.MAX_VALUE;
Expand Down
10 changes: 10 additions & 0 deletions httpcore5/src/test/java/org/apache/hc/core5/util/TestDeadline.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,14 @@ void testValue() {
final Deadline deadline = Deadline.fromUnixMilliseconds(nowPlusOneMin);
Assertions.assertEquals(nowPlusOneMin, deadline.getValue());
}

@Test
void testOverflowHandling() {
final long currentTime = Long.MAX_VALUE - 5000; // Simulate close to overflow
final TimeValue tenSeconds = TimeValue.ofMilliseconds(10000); // 10 seconds
final Deadline deadline = Deadline.calculate(currentTime, tenSeconds);

Assertions.assertEquals(Deadline.MAX_VALUE, deadline,
"Overflow should result in the maximum deadline value.");
}
}

0 comments on commit bdb1c9b

Please sign in to comment.