[elinks-dev] parse_bencoding_integer does not detect all overflows

Kalle Olavi Niemitalo kon at iki.fi
Sat Jan 26 04:14:11 PST 2008

```In src/protocol/bittorrent/bencoding.c, parse_bencoding_integer does:

off_t integer = 0;
...
for (; pos < length && isdigit(string[pos]); pos++) {
if (integer > (off_t) integer * 10)
return 0;
integer = (off_t) integer * 10 + string[pos] - '0';
}

The check (integer > (off_t) integer * 10) does not detect all
overflows.  Examples with 32-bit off_t:

integer = 0x1C71C71D (0x100000000/9 rounded up)
integer * 10 = 0x11C71C722, wraps to 0x1C71C722 which is > integer

integer = 0x73333333
integer * 10 = 0x47FFFFFFE, wraps to 0x7FFFFFFE which is > integer

Examples with 64-bit off_t:

integer = 0x1C71C71C71C71C72 (0x10000000000000000/9 rounded up)
integer * 10 = 0x11C71C71C71C71C74, wraps to 0x1C71C71C71C71C74
which is > integer

integer = 0x7333333333333333
integer * 10 = 0x47FFFFFFFFFFFFFFE, wraps to 0x7FFFFFFFFFFFFFFE
which is > integer

So if the overflow check is necessary, it should be corrected.
If overflows can be assumed to wrap (C does not guarantee that),
then I think the following is correct and the simplest solution:

for (; pos < length && isdigit(string[pos]); pos++) {
off_t newint = integer * 10 + string[pos] - '0';

if (newint / 10 != integer)
return 0; /* overflow */
integer = newint;
}

OTOH, if overflows instead trap or saturate, then this won't work.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 188 bytes
Desc: not available
{"ft_lang_label":"__label__en","ft_lang_prob":0.5391062,"math_prob":0.96282476,"size":1730,"snap":"2019-26-2019-30","text_gpt3_token_len":547,"char_repetition_ratio":0.19930474,"word_repetition_ratio":0.11290322,"special_character_ratio":0.3630058,"punctuation_ratio":0.16197184,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96440804,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-06-18T13:35:02Z\",\"WARC-Record-ID\":\"<urn:uuid:f8f00d78-924c-4c03-aac7-5228759d2aad>\",\"Content-Length\":\"4804\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:8af1c73a-0c0a-44ef-b15d-54147675553c>\",\"WARC-Concurrent-To\":\"<urn:uuid:99b37c5d-7c73-4d30-b351-e9a821327fea>\",\"WARC-IP-Address\":\"192.155.86.174\",\"WARC-Target-URI\":\"http://archive.linuxfromscratch.org/mail-archives/elinks-dev/2008-January/001706.html\",\"WARC-Payload-Digest\":\"sha1:KOMJKY7IGBIBKUTEOFHCHVBIEBRUWV5Q\",\"WARC-Block-Digest\":\"sha1:LUN62SBA2XSWKW6MS5S4NGSPJUXYIP5Y\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-26/CC-MAIN-2019-26_segments_1560627998724.57_warc_CC-MAIN-20190618123355-20190618145355-00252.warc.gz\"}"}