2
0
mirror of https://github.com/sudo-project/sudo.git synced 2025-09-05 00:35:14 +00:00

Avoid using sprintf(), vsprintf(), strcat(), and strncat().

It is less error-prone to use functions with a return value that
indicates when truncation ocurred.
This commit is contained in:
Todd C. Miller
2020-03-11 19:46:07 -06:00
parent 1015b493b0
commit a23048bbb2
2 changed files with 11 additions and 21 deletions

View File

@@ -141,31 +141,23 @@ char *
str_replaced(const char *source, size_t dest_len, const char *old, const char *new)
{
char *result = calloc(1, dest_len);
char *dest = result;
char *pos = NULL;
size_t old_len = strlen(old);
size_t new_len = strlen(new);
size_t available_len = dest_len;
while ((pos = strstr(source, old)) != NULL) {
size_t skipped_len = (size_t)(pos - source);
if (available_len <= skipped_len + 1)
size_t len = snprintf(dest, dest_len,
"%.*s%s", (int)(pos - source), source, new);
if (len >= dest_len)
goto fail;
available_len -= skipped_len;
strncat(result, source, skipped_len);
if (available_len <= new_len + 1)
goto fail;
available_len -= new_len;
strcat(result, new);
dest_len -= len;
dest += len;
source = pos + old_len;
}
if (available_len <= strlen(source) + 1)
if (strlcpy(dest, source, dest_len) >= dest_len)
goto fail;
strcat(result, source);
return result;