base64: fix off-by-one buffer size bug
authorPaul Eggert <eggert@cs.ucla.edu>
Wed, 10 Aug 2011 19:36:13 +0000 (12:36 -0700)
committerPaul Eggert <eggert@cs.ucla.edu>
Wed, 10 Aug 2011 19:36:31 +0000 (12:36 -0700)
Problem and (trivial) fix reported by Gijs van Tulder in
<http://lists.gnu.org/archive/html/bug-gnulib/2011-08/msg00083.html>.
* lib/base64.c (base64_decode_alloc_ctx): Allocate one more byte.
* tests/test-base64.c (main): Catch the bug.

ChangeLog
lib/base64.c
tests/test-base64.c

index 538c121ab83cecf08143ae814d17d9cd7a08ae24..2ed4429cbc9445de54e1dc9d45e2608dfa5f50f0 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,11 @@
+2011-08-10  Paul Eggert  <eggert@cs.ucla.edu>
+
+       base64: fix off-by-one buffer size bug
+       Problem and (trivial) fix reported by Gijs van Tulder in
+       <http://lists.gnu.org/archive/html/bug-gnulib/2011-08/msg00083.html>.
+       * lib/base64.c (base64_decode_alloc_ctx): Allocate one more byte.
+       * tests/test-base64.c (main): Catch the bug.
+
 2011-08-10  Eric Blake  <eblake@redhat.com>
 
        closein: correct comments
index 99fcc57c3cc220159cd4d5dc1ba54557e3c625b4..1f07c7c48dad54249d2d59bcfb77cd63f83acc17 100644 (file)
@@ -552,10 +552,10 @@ base64_decode_alloc_ctx (struct base64_decode_context *ctx,
 {
   /* This may allocate a few bytes too many, depending on input,
      but it's not worth the extra CPU time to compute the exact size.
-     The exact size is 3 * inlen / 4, minus 1 if the input ends
-     with "=" and minus another 1 if the input ends with "==".
+     The exact size is 3 * (inlen + (ctx ? ctx->i : 0)) / 4, minus 1 if the
+     input ends with "=" and minus another 1 if the input ends with "==".
      Dividing before multiplying avoids the possibility of overflow.  */
-  size_t needlen = 3 * (inlen / 4) + 2;
+  size_t needlen = 3 * (inlen / 4) + 3;
 
   *out = malloc (needlen);
   if (!*out)
index c7cad2f7a4b96caf0a7c3542883e1853681c80bb..b1979b4e7ea93cc17c27a223251cd775df39ca48 100644 (file)
@@ -184,9 +184,8 @@ main (void)
 
     ok = base64_decode_alloc_ctx (&ctx, "hp", 2, &p, &len);
     ASSERT (ok);
-    ASSERT (len == 2);
-    /* Actually this looks buggy.  Shouldn't output be 'ghi'? */
-    ASSERT (memcmp (p, "gh", len) == 0);
+    ASSERT (len == 3);
+    ASSERT (memcmp (p, "ghi", len) == 0);
     ok = base64_decode_alloc_ctx (&ctx, "", 0, &p, &len);
     ASSERT (ok);
   }