X-Git-Url: https://git.octo.it/?a=blobdiff_plain;f=src%2Futils_subst.c;h=a49f6db56e8b75307e7790ae1601edb08c2f6b10;hb=9c98fa31ef50a6ff849d36cac4f5297faa6f7909;hp=05dc8441c8f965a088134132411c27bac4c180c5;hpb=97fe230249ff8bf6aa71acfa206443c4a7238ab7;p=collectd.git diff --git a/src/utils_subst.c b/src/utils_subst.c index 05dc8441..a49f6db5 100644 --- a/src/utils_subst.c +++ b/src/utils_subst.c @@ -37,7 +37,8 @@ char *subst (char *buf, size_t buflen, const char *string, int off1, int off2, || (NULL == replacement)) return NULL; - sstrncpy (buf_ptr, string, (off1 + 1 > buflen) ? buflen : off1 + 1); + sstrncpy (buf_ptr, string, + ((size_t)off1 + 1 > buflen) ? buflen : (size_t)off1 + 1); buf_ptr += off1; len -= off1; @@ -78,5 +79,66 @@ char *asubst (const char *string, int off1, int off2, const char *replacement) return ret; } /* asubst */ +char *subst_string (char *buf, size_t buflen, const char *string, + const char *needle, const char *replacement) +{ + char *temp; + size_t needle_len; + size_t i; + + if ((buf == NULL) || (string == NULL) + || (needle == NULL) || (replacement == NULL)) + return (NULL); + + temp = (char *) malloc (buflen); + if (temp == NULL) + { + ERROR ("subst_string: malloc failed."); + return (NULL); + } + + needle_len = strlen (needle); + strncpy (buf, string, buflen); + + /* Limit the loop to prevent endless loops. */ + for (i = 0; i < buflen; i++) + { + char *begin_ptr; + size_t begin; + + /* Find `needle' in `buf'. */ + begin_ptr = strstr (buf, needle); + if (begin_ptr == NULL) + break; + + /* Calculate the start offset. */ + begin = begin_ptr - buf; + + /* Substitute the region using `subst'. The result is stored in + * `temp'. */ + begin_ptr = subst (temp, buflen, buf, + begin, begin + needle_len, + replacement); + if (begin_ptr == NULL) + { + WARNING ("subst_string: subst failed."); + break; + } + + /* Copy the new string in `temp' to `buf' for the next round. */ + strncpy (buf, temp, buflen); + } + + if (i >= buflen) + { + WARNING ("subst_string: Loop exited after %zu iterations: " + "string = %s; needle = %s; replacement = %s;", + i, string, needle, replacement); + } + + sfree (temp); + return (buf); +} /* char *subst_string */ + /* vim: set sw=4 ts=4 tw=78 noexpandtab : */