From 3e449b1b0560b2214cf5a6cd553fd6171cada7aa Mon Sep 17 00:00:00 2001 From: Adam Langley Date: Fri, 20 Jun 2014 12:00:00 -0700 Subject: [PATCH] Don't allocate more than is needed in BUF_strndup() (Imported from upstream's 4ceb430a468e8226175aa3f169c0e746877c17e1, 4f7236edc7d5c384bdb148faf7b23f887cf18f69 and ed693e43329383c0d68455d83778cdc9748a074d) --- crypto/buf/buf.c | 14 ++++++++++++++ crypto/buf/buf.h | 5 +++++ 2 files changed, 19 insertions(+) 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);