Add strnkcpy() and strnkcat(). These are similar to strlcpy and strlcat,

but simply return a bool indicating whether the destination received
a truncated copy of the source (true if truncation occurs else false).

The change in return value semantics allows these functions to stop
scanning the source string early when truncation occurs, stopping the
program from scanning a possibly arbitrary-length source string.

I rarely use these return values in my own programs, so it won't be
very hard to bulk convert with no risk of regressions.

Further, the different namespace allows me to not depend on the presence
or absence of strlc(py|at) in the standard libraries.
This commit is contained in:
Nicholas J. Kain 2013-05-06 07:06:33 -04:00
parent f807e10e76
commit 7ab11e8295
4 changed files with 28 additions and 2 deletions

View File

@ -53,7 +53,7 @@ int chroot_enabled(void)
void update_chroot(const char *path)
{
strlcpy(chrootd, path, sizeof chrootd);
strnkcpy(chrootd, path, sizeof chrootd);
chroot_modified = 1;
}

View File

@ -30,6 +30,27 @@
#include <unistd.h>
#include "strl.h"
// true == truncated, false == no truncation
bool strnkcpy (char *dest, const char *src, size_t size)
{
if (size > 0) {
size_t i = 0;
size--;
for (; size > 0 && src[i] != '\0'; ++i, size--)
dest[i] = src[i];
dest[i] = '\0';
return size ? false : true;
} else
return true;
}
// true == truncated, false == no truncation
bool strnkcat (char *dest, const char *src, size_t size)
{
for (; size > 0 && *dest != '\0'; size--, dest++);
return strnkcpy(dest, src, size);
}
#ifndef HAVE_STRLCPY
size_t strlcpy (char *dest, const char *src, size_t size)
{

View File

@ -30,6 +30,11 @@
#ifndef NCM_STRL_H_
#define NCM_STRL_H_ 1
#include <stdbool.h>
bool strnkcpy (char *dest, const char *src, size_t size);
bool strnkcat (char *dest, const char *src, size_t size);
#ifndef HAVE_STRLCPY
size_t strlcpy (char *dest, const char *src, size_t size);
#endif /* HAVE_STRLCPY */

View File

@ -46,7 +46,7 @@ void add_to_strlist(strlist_t **list, char *name)
len = strlen(name) + 1;
if (len == 1) return;
s = xmalloc(len);
strlcpy(s, name, len);
strnkcpy(s, name, len);
item = xmalloc(sizeof (strlist_t));
item->str = s;