diff --git a/crypto/buf/buf.c b/crypto/buf/buf.c index fe55c0ce..94bbeafc 100644 --- a/crypto/buf/buf.c +++ b/crypto/buf/buf.c @@ -153,6 +153,18 @@ char *BUF_strdup(const char *buf) { return BUF_strndup(buf, strlen(buf)); } +size_t BUF_strnlen(const char *str, size_t max_len) { + size_t i; + + for (i = 0; i < max_len; i++) { + if (str[i] == 0) { + break; + } + } + + return i; +} + char *BUF_strndup(const char *buf, size_t size) { char *ret; size_t alloc_size; @@ -161,6 +173,8 @@ char *BUF_strndup(const char *buf, size_t size) { return NULL; } + size = BUF_strnlen(buf, size); + alloc_size = size + 1; if (alloc_size < size) { /* overflow */ diff --git a/crypto/buf/buf.h b/crypto/buf/buf.h index 4cfeee49..d1e63f2d 100644 --- a/crypto/buf/buf.h +++ b/crypto/buf/buf.h @@ -89,6 +89,11 @@ size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len); /* BUF_strdup returns an allocated, duplicate of |str|. */ char *BUF_strdup(const char *str); +/* BUF_strnlen returns the number of characters in |str|, excluding the NUL + * byte, but at most |max_len|. This function never reads more than |max_len| + * bytes from |str|. */ +size_t BUF_strnlen(const char *str, size_t max_len); + /* BUF_strndup returns an allocated, duplicate of |str|, which is, at most, * |size| bytes. The result is always NUL terminated. */ char *BUF_strndup(const char *str, size_t size);