utils: strlcpy() and strlcat() don't clobber dst

As David Laight correctly pointed out, the first version of strlcpy()
modified dst buffer behind the string copied into it. Fix this by
writing NUL to the byte immediately following src string instead of to
the last byte in dst. Doing so also allows to reduce overhead by using
memcpy().

Improve strlcat() by avoiding the call to strlcpy() if dst string is
already full, not just as sanity check.

Signed-off-by: Phil Sutter <phil@nwl.cc>
This commit is contained in:
Phil Sutter 2017-09-06 18:51:42 +02:00 committed by Stephen Hemminger
parent 01e5409371
commit 50ea3c6438
1 changed files with 8 additions and 4 deletions

View File

@ -1233,18 +1233,22 @@ int get_real_family(int rtm_type, int rtm_family)
size_t strlcpy(char *dst, const char *src, size_t size)
{
size_t srclen = strlen(src);
if (size) {
strncpy(dst, src, size - 1);
dst[size - 1] = '\0';
size_t minlen = min(srclen, size - 1);
memcpy(dst, src, minlen);
dst[minlen] = '\0';
}
return strlen(src);
return srclen;
}
size_t strlcat(char *dst, const char *src, size_t size)
{
size_t dlen = strlen(dst);
if (dlen > size)
if (dlen >= size)
return dlen + strlen(src);
return dlen + strlcpy(dst + dlen, src, size - dlen);