Potential integer overflow in bandwidth throttling timing calculation #68

Closed
opened 2026-07-20 17:14:08 +02:00 by TapTap · 0 comments
Owner

Description

In src/shared/protocol.c lines 37-57, the bandwidth throttling uses long long for timing calculations:

long long elapsed_ns =
    (now.tv_sec - bw_last_refill.tv_sec) * 1000000000LL + (now.tv_nsec - bw_last_refill.tv_nsec);

If clock_gettime(CLOCK_MONOTONIC, ...) is called infrequently (minutes or hours apart), the tv_sec difference multiplied by 1 billion could overflow long long (max ~9.2e18). At ~300 years of difference, the multiply alone would overflow. While unlikely in practice, a long-running transfer paused for a very long time could trigger this.

Additionally, the token refill calculation on line 41:

long long tokens_to_add = (long long)((double)io_bwlimit * elapsed_ns / 1000000000.0);

Uses floating point in a timing-sensitive code path, and double may lose precision for very large values of io_bwlimit * elapsed_ns.

Location

src/shared/protocol.c:37-57

Suggested Fix

  1. Cap the elapsed time to a reasonable interval (e.g., 1 second)
  2. Avoid floating point by using integer arithmetic:
long long max_elapsed = 1000000000LL;  // cap to 1 second
if (elapsed_ns > max_elapsed)
    elapsed_ns = max_elapsed;

Severity

Low

Category

Quality

## Description In `src/shared/protocol.c` lines 37-57, the bandwidth throttling uses `long long` for timing calculations: ```c long long elapsed_ns = (now.tv_sec - bw_last_refill.tv_sec) * 1000000000LL + (now.tv_nsec - bw_last_refill.tv_nsec); ``` If `clock_gettime(CLOCK_MONOTONIC, ...)` is called infrequently (minutes or hours apart), the `tv_sec` difference multiplied by 1 billion could overflow `long long` (max ~9.2e18). At ~300 years of difference, the multiply alone would overflow. While unlikely in practice, a long-running transfer paused for a very long time could trigger this. Additionally, the token refill calculation on line 41: ```c long long tokens_to_add = (long long)((double)io_bwlimit * elapsed_ns / 1000000000.0); ``` Uses floating point in a timing-sensitive code path, and `double` may lose precision for very large values of `io_bwlimit * elapsed_ns`. ## Location `src/shared/protocol.c:37-57` ## Suggested Fix 1. Cap the elapsed time to a reasonable interval (e.g., 1 second) 2. Avoid floating point by using integer arithmetic: ```c long long max_elapsed = 1000000000LL; // cap to 1 second if (elapsed_ns > max_elapsed) elapsed_ns = max_elapsed; ``` ## Severity Low ## Category Quality
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: TapTap/FastSync#68