Don't allocate more than is needed in BUF_strndup()

(Imported from upstream's 4ceb430a468e8226175aa3f169c0e746877c17e1,
4f7236edc7d5c384bdb148faf7b23f887cf18f69 and
ed693e43329383c0d68455d83778cdc9748a074d)
diff --git a/crypto/buf/buf.c b/crypto/buf/buf.c
index fe55c0c..94bbeaf 100644
--- a/crypto/buf/buf.c
+++ b/crypto/buf/buf.c
@@ -153,6 +153,18 @@
   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 @@
     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 4cfeee4..d1e63f2 100644
--- a/crypto/buf/buf.h
+++ b/crypto/buf/buf.h
@@ -89,6 +89,11 @@
 /* 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);