From: Jo-Philipp Wich Date: Thu, 7 Dec 2017 10:40:21 +0000 (+0100) Subject: file_util: implement urlencode_path() helper X-Git-Url: http://git.cdn.openwrt.org/?a=commitdiff_plain;h=73e6c815a0813c143723b27c255f6a1190beb2a0;p=project%2Fopkg-lede.git file_util: implement urlencode_path() helper Introduce a helper function urlencode_path() which can be used to encode problematic characters in package file names. Signed-off-by: Jo-Philipp Wich Tested-by: Rafał Miłecki --- diff --git a/libopkg/file_util.c b/libopkg/file_util.c index 1f89541..14ca02e 100644 --- a/libopkg/file_util.c +++ b/libopkg/file_util.c @@ -346,3 +346,63 @@ int rm_r(const char *path) return ret; } + +static int urlencode_is_specialchar(char c) +{ + switch (c) { + case ':': + case '?': + case '#': + case '[': + case ']': + case '@': + case '!': + case '$': + case '&': + case '\'': + case '(': + case ')': + case '*': + case '+': + case ',': + case ';': + case '=': + case '%': + return 1; + + default: + return 0; + } +} + +char *urlencode_path(const char *filename) +{ + static const char bin2hex[16] = { + '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f' + }; + + size_t len = 0; + const char *in; + char *copy, *out; + + for (in = filename; *in != 0; in++) + len += urlencode_is_specialchar(*in) ? 3 : 1; + + copy = xcalloc(1, len + 1); + + for (in = filename, out = copy; *in != 0; in++) { + if (urlencode_is_specialchar(*in)) { + *out++ = '%'; + *out++ = bin2hex[*in / 16]; + *out++ = bin2hex[*in % 16]; + } + else { + *out++ = *in; + } + } + + return copy; +} diff --git a/libopkg/file_util.h b/libopkg/file_util.h index d8e6767..e078f41 100644 --- a/libopkg/file_util.h +++ b/libopkg/file_util.h @@ -31,4 +31,6 @@ int rm_r(const char *path); char *checksum_bin2hex(const char *src, size_t len); char *checksum_hex2bin(const char *src, size_t *len); +char *urlencode_path(const char *filename); + #endif