From: alex Date: Tue, 21 Dec 2021 19:59:43 +0000 (-0800) Subject: ... X-Git-Url: http://git.infiniteadaptability.org/?a=commitdiff_plain;h=83eb2c8ce221ada2fc82195932299ad655a71afa;p=seeder ... --- diff --git a/inc/bencode.h b/inc/bencode.h index 0d4ecff..e5b1008 100644 --- a/inc/bencode.h +++ b/inc/bencode.h @@ -1,6 +1,7 @@ #ifndef __BENCODE_H_ #define __BENCODE_H_ +#include #include #include #include @@ -23,7 +24,7 @@ ssize_t bencode_int(long long int,uint8_t*,size_t); ssize_t bencode_list_end(uint8_t*,size_t); ssize_t bencode_list_start(uint8_t*,size_t); ssize_t bencode_size(size_t,uint8_t*,size_t); -size_t bencode_size_int(int); +size_t bencode_size_int(intmax_t); ssize_t bencode_string(const uint8_t*,size_t,uint8_t*,size_t); #endif diff --git a/src/bencode/encode.c b/src/bencode/encode.c index c7dc994..6da2000 100644 --- a/src/bencode/encode.c +++ b/src/bencode/encode.c @@ -54,6 +54,8 @@ ssize_t bencode_list_start(uint8_t *output, size_t output_size) { ssize_t bencode_size(size_t len, uint8_t *output, size_t output_size) { size_t i; + if(len>INTMAX_MAX) { return -1; } + i = bencode_size_int(len); i++; // account for ':' if(i>output_size) { return -1; } @@ -64,10 +66,10 @@ ssize_t bencode_size(size_t len, uint8_t *output, size_t output_size) { return i; } -size_t bencode_size_int(int i) { +size_t bencode_size_int(intmax_t i) { size_t j = (i<0)?1:0; - i = abs(i); + i = imaxabs(i); if(0==i) { return 1; } while(i>0) { diff --git a/test/unit/bencode.tests.c b/test/unit/bencode.tests.c index 72adc76..d8723d0 100644 --- a/test/unit/bencode.tests.c +++ b/test/unit/bencode.tests.c @@ -8,6 +8,8 @@ static void bdecode_string_basic_test(); static void bdecode_type_basic_test(); static void bencode_dict_basic_test(); static void bencode_list_basic_test(); +static void bencode_size_basic_test(); +static void bencode_size_int_basic_test(); static void bencode_string_basic_test(); int main() { @@ -18,6 +20,8 @@ int main() { bdecode_type_basic_test(); bencode_dict_basic_test(); bencode_list_basic_test(); + bencode_size_basic_test(); + bencode_size_int_basic_test(); bencode_string_basic_test(); clean_env(); @@ -135,6 +139,28 @@ static void bencode_list_basic_test() { assert(memcmp(buf,"l4:spam4:eggse",14)==0); } +static void bencode_size_basic_test() { + uint8_t buf[1024]; + + assert(bencode_size(0,buf,1)==-1); + assert(bencode_size(0,buf,2)==2); + + assert(bencode_size(1234567890,buf,1024)==11); + + assert(bencode_size(SIZE_MAX,buf,1024)==-1); + assert(bencode_size(INTMAX_MAX,buf,1024)>0); +} + +static void bencode_size_int_basic_test() { + assert(bencode_size_int(0)==1); + assert(bencode_size_int(-1)==2); + assert(bencode_size_int(109)==3); + assert(bencode_size_int(23984723984)==11); + assert(bencode_size_int(922337203685477580)==18); + assert(bencode_size_int(INTMAX_MIN)>0); + assert(bencode_size_int(INTMAX_MAX)>0); +} + static void bencode_string_basic_test() { uint8_t buf[1024];