Skip to content

Commit 96baffe

Browse files
committed
cache: harden integer types and negative-len guard in Cache_read
- Change expected_segbc in Meta_write from long to off_t to prevent silent truncation on 32-bit/Windows before the INT_MAX cap check. - Use a size_t intermediate variable (calculated_segbc) in Cache_create before assigning to cf->segbc to avoid 32-bit long overflow during the division of content_length / blksz. - Add a len < 0 guard in Cache_read before the (size_t)len cast to prevent negative values wrapping to a large unsigned number and bypassing the remaining-bytes clamp.
1 parent f911f7c commit 96baffe

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

src/cache.c

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ static int Meta_write(Cache *cf)
358358
* cf->segbc must be strictly positive.
359359
*/
360360
off_t write_content_length = (off_t)cf->link->content_length;
361-
long expected_segbc = 0;
361+
off_t expected_segbc = 0;
362362
if (cf->blksz > 0 && write_content_length > 0) {
363363
expected_segbc = write_content_length / cf->blksz;
364364
if (expected_segbc >= INT_MAX) {
@@ -866,11 +866,14 @@ int Cache_create(const char *path)
866866
cf->path = STRNDUP(fn, PATH_MAX);
867867
cf->link = this_link;
868868
cf->blksz = CONFIG.data_blksz;
869-
cf->segbc = this_link->content_length / cf->blksz;
870-
if (cf->segbc >= INT_MAX) {
869+
size_t calculated_segbc = this_link->content_length / cf->blksz;
870+
if (calculated_segbc >= INT_MAX) {
871871
cf->segbc = INT_MAX;
872-
} else if (this_link->content_length % cf->blksz != 0) {
873-
cf->segbc += 1;
872+
} else {
873+
cf->segbc = (long)calculated_segbc;
874+
if (this_link->content_length % cf->blksz != 0) {
875+
cf->segbc += 1;
876+
}
874877
}
875878
cf->seg = CALLOC(cf->segbc, sizeof(Seg));
876879

@@ -1467,6 +1470,12 @@ long Cache_read(Cache *cf, char *const output_buf, off_t len,
14671470
return -EINVAL;
14681471
}
14691472

1473+
if (len < 0) {
1474+
lprintf(error, "requested to read negative bytes: %jd\n",
1475+
(intmax_t)len);
1476+
return -EINVAL;
1477+
}
1478+
14701479
if (offset_start < 0 || (size_t)offset_start >= cf->link->content_length) {
14711480
return 0;
14721481
}

0 commit comments

Comments
 (0)