Skip to content

Commit

Permalink
review: Make thread-safe by removing static allocation
Browse files Browse the repository at this point in the history
* Also removed potention buffer overflow
  • Loading branch information
EyitopeIO committed Apr 18, 2024
1 parent bf2ab8f commit 41df65c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
3 changes: 3 additions & 0 deletions src/link.c
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
20 changes: 12 additions & 8 deletions src/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -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;
}

Expand Down
2 changes: 1 addition & 1 deletion src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit 41df65c

Please sign in to comment.