Skip to content

Commit

Permalink
fix(utils): protect against errors in str_replace
Browse files Browse the repository at this point in the history
Protect against misuse of str_replace if the replace string is larger
than the find string by forcing an exit with error.
  • Loading branch information
stevenh committed Sep 28, 2021
1 parent 18bd4cc commit 0cc06b2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
15 changes: 13 additions & 2 deletions utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@

#include "utils.h"

#ifndef _WIN32
#include <err.h>
#include <sysexits.h>
#endif

#if !HAVE_STRNSTR

/*
Expand Down Expand Up @@ -138,9 +143,15 @@ str_replace(char *source, char *find, char *replace)
int rlen = strlen(replace);
int flen = strlen(find);

if (rlen > flen) {
err(EX_SOFTWARE, "str_replace: replace is larger than find");
}

while (NULL != s) {
strncpy(s, replace, rlen);
strcpy(s + rlen, s + flen);
strncpy(s, replace, rlen); // -Wstringop-truncation warning here is a false positive.
if (rlen < flen) {
strcpy(s + rlen, s + flen);
}
s += rlen;
s = strstr(s, find);
}
Expand Down
6 changes: 6 additions & 0 deletions utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#define QSTAT_UTILS_H

#ifndef _WIN32
#include <err.h>
#include <sysexits.h>
#ifdef HAVE_CONFIG_H
#include "gnuconfig.h"
#endif
Expand Down Expand Up @@ -43,6 +45,10 @@
#define EX_OSERR 71 /* system error (e.g., can't fork) */
#endif

#ifndef EX_SOFTWARE
#define EX_SOFTWARE 70 /* An internal software error has been detected */
#endif

#if !HAVE_ERR_H
void err(int eval, const char *fmt, ...);
void warn(const char *fmt, ...);
Expand Down

0 comments on commit 0cc06b2

Please sign in to comment.