From 2318162badbe5901320ed510504d7029be7c584f Mon Sep 17 00:00:00 2001 From: Jose Marcial Vieira Bisneto Date: Mon, 25 Sep 2017 10:27:13 -0300 Subject: [PATCH] Added a simple implementation of urlencode. --- include/libp2p/utils/urlencode.h | 4 +++ utils/urlencode.c | 51 ++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 include/libp2p/utils/urlencode.h create mode 100644 utils/urlencode.c diff --git a/include/libp2p/utils/urlencode.h b/include/libp2p/utils/urlencode.h new file mode 100644 index 0000000..69a8ed9 --- /dev/null +++ b/include/libp2p/utils/urlencode.h @@ -0,0 +1,4 @@ +#pragma once + +char *libp2p_utils_url_encode(char *src); +char *libp2p_utils_url_decode(char *src); diff --git a/utils/urlencode.c b/utils/urlencode.c new file mode 100644 index 0000000..e6bbbd2 --- /dev/null +++ b/utils/urlencode.c @@ -0,0 +1,51 @@ +#include +#include +#include + +char *libp2p_utils_url_encode(char *src) +{ + const char *hex = "0123456789abcdef"; + char *p, *dst = malloc (strlen(src) * 3); + + if (!dst) return NULL; + + for(p = dst ; *src ; src++ ) { + if( isalnum(*src)){ + *p++ = *src; + } else { + *p++ = '%'; + *p++ = hex[*src >> 4]; + *p++ = hex[*src & 15]; + } + } + *p++ = '\0'; + return realloc(dst, (size_t) (p - dst)); +} + +int h2b(int c) +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } else if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } else if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return 0; // ? +} + +char *libp2p_utils_url_decode(char *src) +{ + char *p, *dst = malloc (strlen(src)); + + for(p = dst ; *src ; src++ ) { + if(*src != '%'){ + *p++ = *src; + } else { + *p = h2b(*(++src)) << 4; + *p++ |= h2b(*(++src)) & 15; + } + } + *p++ = '\0'; + return realloc(dst, (size_t) (p - dst)); +}