From 8faf6f7b72747dc147f2a5a6c92a5a375f449809 Mon Sep 17 00:00:00 2001
From: "nullable.type" <nullable.type@gmail.com>
Date: Sun, 16 Dec 2012 22:20:21 +0100
Subject: [PATCH] Made behavior of mg_get_cookie(..) on errors the same as
 mg_get_var(..). Separated the two cases a.) problems with destination buffer
 and b.) cookie header or cookie parameter not existing.

---
 mongoose.c | 51 ++++++++++++++++++++++++++++-----------------------
 mongoose.h |  6 +++---
 2 files changed, 31 insertions(+), 26 deletions(-)

diff --git a/mongoose.c b/mongoose.c
index d341c76bc..7b8ac8ef2 100644
--- a/mongoose.c
+++ b/mongoose.c
@@ -1698,32 +1698,37 @@ int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,
   const char *s, *p, *end;
   int name_len, len = -1;
 
-  dst[0] = '\0';
-  if ((s = mg_get_header(conn, "Cookie")) == NULL) {
-    return -1;
-  }
-
-  name_len = (int) strlen(cookie_name);
-  end = s + strlen(s);
+  if (dst == NULL || dst_size == 0) {
+      len = -2;
+  } else if (cookie_name == NULL || (s = mg_get_header(conn, "Cookie")) == NULL) {
+      len = -1;
+      dst[0] = '\0';
+  } else {
+    name_len = (int) strlen(cookie_name);
+    end = s + strlen(s);
+    dst[0] = '\0';
 
-  for (; (s = strstr(s, cookie_name)) != NULL; s += name_len)
-    if (s[name_len] == '=') {
-      s += name_len + 1;
-      if ((p = strchr(s, ' ')) == NULL)
-        p = end;
-      if (p[-1] == ';')
-        p--;
-      if (*s == '"' && p[-1] == '"' && p > s + 1) {
-        s++;
-        p--;
-      }
-      if ((size_t) (p - s) < dst_size) {
-        len = p - s;
-        mg_strlcpy(dst, s, (size_t) len + 1);
+    for (; (s = strstr(s, cookie_name)) != NULL; s += name_len) {
+      if (s[name_len] == '=') {
+        s += name_len + 1;
+        if ((p = strchr(s, ' ')) == NULL)
+          p = end;
+        if (p[-1] == ';')
+          p--;
+        if (*s == '"' && p[-1] == '"' && p > s + 1) {
+          s++;
+          p--;
+        }
+        if ((size_t) (p - s) < dst_size) {
+          len = p - s;
+          mg_strlcpy(dst, s, (size_t) len + 1);
+        } else {
+          len = -2;
+        }
+        break;
       }
-      break;
     }
-
+  }
   return len;
 }
 
diff --git a/mongoose.h b/mongoose.h
index a9f98c34c..18f343950 100644
--- a/mongoose.h
+++ b/mongoose.h
@@ -308,9 +308,9 @@ int mg_get_var(const char *data, size_t data_len,
 //
 // Return:
 //   On success, value length.
-//   On error, -1 (either "Cookie:" header is not present at all, or the
-//   requested parameter is not found, or destination buffer is too small
-//   to hold the value).
+//   On error:
+//      -1 (either "Cookie:" header is not present at all or the requested parameter is not found).
+//      -2 (destination buffer is NULL, zero length or too small to hold the value).
 int mg_get_cookie(const struct mg_connection *,
                   const char *cookie_name, char *buf, size_t buf_len);
 
-- 
GitLab