From 396700797b9ba3ccf799ac8bdc7b750bd86b5564 Mon Sep 17 00:00:00 2001 From: Sam Stenvall Date: Thu, 8 Jan 2015 14:22:12 +0200 Subject: [PATCH] [utils] add url_encode() function --- src/tvheadend.h | 4 ++++ src/utils.c | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/tvheadend.h b/src/tvheadend.h index 70eb5437..79240099 100644 --- a/src/tvheadend.h +++ b/src/tvheadend.h @@ -711,6 +711,10 @@ int rmtree ( const char *path ); char *regexp_escape ( const char *str ); +/* URL decoding */ +char to_hex(char code); +char *url_encode(char *str); + static inline int32_t deltaI32(int32_t a, int32_t b) { return (a > b) ? (a - b) : (b - a); } static inline uint32_t deltaU32(uint32_t a, uint32_t b) { return (a > b) ? (a - b) : (b - a); } diff --git a/src/utils.c b/src/utils.c index 67448c45..92d309fc 100644 --- a/src/utils.c +++ b/src/utils.c @@ -25,6 +25,7 @@ #include #include #include +#include #include "tvheadend.h" #if defined(PLATFORM_DARWIN) @@ -588,3 +589,29 @@ regexp_escape(const char* str) *b = 0; return tmp; } + +/* Converts an integer value to its hex character + http://www.geekhideout.com/urlcode.shtml */ +char to_hex(char code) { + static char hex[] = "0123456789abcdef"; + return hex[code & 15]; +} + +/* Returns a url-encoded version of str + IMPORTANT: be sure to free() the returned string after use + http://www.geekhideout.com/urlcode.shtml */ +char *url_encode(char *str) { + char *pstr = str, *buf = malloc(strlen(str) * 3 + 1), *pbuf = buf; + while (*pstr) { + if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') + *pbuf++ = *pstr; + /*else if (*pstr == ' ') + *pbuf++ = '+';*/ + else + *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15); + pstr++; + } + *pbuf = '\0'; + return buf; +} +