From 8e1cbd8f7bd5deb3310be4f4f65f7aa6ea9a9beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anton=20Luka=20=C5=A0ijanec?= Date: Mon, 21 Nov 2022 20:11:12 +0100 Subject: created utils/bencoding.c, fixed bencoding (for now decode only). TODO: fuzz --- utils/bencoding.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 utils/bencoding.c (limited to 'utils') diff --git a/utils/bencoding.c b/utils/bencoding.c new file mode 100644 index 0000000..a60e1b3 --- /dev/null +++ b/utils/bencoding.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include +#include +#include +#define S0(x) (x ? x : "") +int main (int argc, char ** argv) { + if (argc != 1+1) + error_at_line(1, 0, __FILE__, __LINE__, "%s encode < json || %s decode < bencoding", S0(argv[0]), S0(argv[0])); + int size = 2048; + int len = 0; + char * in = malloc(size); + while (!feof(stdin) && !ferror(stdin)) { + if (!in) + error_at_line(2, 0, __FILE__, __LINE__, "heap alloc failed"); + len += fread(in, 1, size-len-1, stdin); + if ((size - len) < 1024) + in = realloc(in, size *= 2); + } + if (argv[1][0] == 'e') + error_at_line(3, 0, __FILE__, __LINE__, "N/I"); + struct bencoding * bencoding = bdecode(in, size, terminate); + len = b2json_length(bencoding); + char out[len+1]; + char * end = b2json(out, bencoding); + *end = '\0'; + puts(out); + if (end - out != len) + error_at_line(4, 0, __FILE__, __LINE__, "b2json wrote %ld instead of %d bytes.", end-out, len); + fprintf(stderr, "len: %d\n", len); + free_bencoding(bencoding); + free(in); + return 0; +} -- cgit v1.2.3