From 7ab11e8295f8a802418437bae82dc64161360ed5 Mon Sep 17 00:00:00 2001 From: "Nicholas J. Kain" Date: Mon, 6 May 2013 07:06:33 -0400 Subject: [PATCH] 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. --- ncmlib/chroot.c | 2 +- ncmlib/strl.c | 21 +++++++++++++++++++++ ncmlib/strl.h | 5 +++++ ncmlib/strlist.c | 2 +- 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/ncmlib/chroot.c b/ncmlib/chroot.c index 4add5e3..6a5c38a 100644 --- a/ncmlib/chroot.c +++ b/ncmlib/chroot.c @@ -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; } diff --git a/ncmlib/strl.c b/ncmlib/strl.c index 3fd53c1..324bb17 100644 --- a/ncmlib/strl.c +++ b/ncmlib/strl.c @@ -30,6 +30,27 @@ #include #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) { diff --git a/ncmlib/strl.h b/ncmlib/strl.h index 8f114f1..b199433 100644 --- a/ncmlib/strl.h +++ b/ncmlib/strl.h @@ -30,6 +30,11 @@ #ifndef NCM_STRL_H_ #define NCM_STRL_H_ 1 +#include + +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 */ diff --git a/ncmlib/strlist.c b/ncmlib/strlist.c index e9d7ea4..a54499f 100644 --- a/ncmlib/strlist.c +++ b/ncmlib/strlist.c @@ -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;