From 41df65c455175e439ef74557ff704fd2dce176cf Mon Sep 17 00:00:00 2001 From: EyitopeIO Date: Thu, 18 Apr 2024 02:26:40 +0100 Subject: [PATCH] review: Make thread-safe by removing static allocation * Also removed potention buffer overflow --- src/link.c | 3 +++ src/util.c | 20 ++++++++++++-------- src/util.h | 2 +- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/link.c b/src/link.c index 71a2bb1..36f1727 100644 --- a/src/link.c +++ b/src/link.c @@ -77,12 +77,15 @@ static CURL *Link_to_curl(Link *link) if (ret) { lprintf(error, "%s", curl_easy_strerror(ret)); } + char *escaped_spaces = escape_char(link->f_url, ESCAPED_CHAR_SPACE); ret = curl_easy_setopt(curl, CURLOPT_URL, escaped_spaces ? escaped_spaces : link->f_url); if (ret) { lprintf(error, "%s", curl_easy_strerror(ret)); } + free(escaped_spaces); + ret = curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1); if (ret) { lprintf(error, "%s", curl_easy_strerror(ret)); diff --git a/src/util.c b/src/util.c index 1d81410..179be6a 100644 --- a/src/util.c +++ b/src/util.c @@ -51,7 +51,6 @@ char *path_append(const char *path, const char *filename) char *escape_char(const char *url, const ESCAPE_CHAR c) { - static char escaped[MAX_PATH_LEN]; char escape_me; /* A space, for example, becomes thrice bigger as '%20' after escaping */ @@ -73,29 +72,34 @@ char *escape_char(const char *url, const ESCAPE_CHAR c) int len = strnlen(url, MAX_PATH_LEN); /* Best case scenario of only one character to escape */ - if (strnlen(url,MAX_PATH_LEN) + 3 > MAX_PATH_LEN) { + if (len + 3 > MAX_PATH_LEN) { lprintf(fatal, "URL too long: %s\n", url); } - memset(escaped, 0, MAX_PATH_LEN); + char *escaped = CALLOC(MAX_PATH_LEN, sizeof(char)); - int j = 0; + int j = 0, k = 0; for (int i = 0; i < len; i++) { + /* Precaution against writing beyond the buffer, since we do not count + * all spaces beforehand to know the exact amount of memory to calloc + * for the escaped URL. + */ + if (k > MAX_PATH_LEN) { + lprintf(fatal, "URL too long: %s\n", url); + } if (url[i] == escape_me) { switch (c) { case ESCAPED_CHAR_SPACE: strncpy(escaped + j, "%20", how_bigger); break; } - - j += how_bigger; + k = j + how_bigger; + j = k; } else { escaped[j++] = url[i]; } } - - escaped[j] = '\0'; return escaped; } diff --git a/src/util.h b/src/util.h index c07065a..f66a925 100644 --- a/src/util.h +++ b/src/util.h @@ -30,7 +30,7 @@ char *path_append(const char *path, const char *filename); * the string with the escaped character. We don't use curl_easy_escape() on * the entire URL because it would break the URL. For example, 'http://a c' * becomes 'http:%2F%2Fa%20c', escaping more characters than we want. - * \note DO NOT free the char * after use. It is statically allocated. + * \note You need to free the char * after use. */ char *escape_char(const char *s, ESCAPE_CHAR c);