From f291fbc8a7668639126f1cfcb55841c527f042fd Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Thu, 29 Jul 2010 14:48:07 -0700 Subject: [PATCH] Fix ending \0 in base64 decoding --- src/node_buffer.cc | 32 +++++++++++++++++++------------- test/simple/test-buffer.js | 2 +- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index ad5ee45f95..6e1ad00f18 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -557,51 +557,57 @@ Handle Buffer::Base64Write(const Arguments &args) { const char *pe = buffer->data() + buffer->length_; int i = 0; - char a,b,c,d; + char a,b,c,d, last; bool b_oob, c_oob; while (i < input_len && p < pe) { - if (input[i] == '=' || i >= input_len) break; - a = unbase64_table[input[i]]; + last = input[i]; + if (last == '=' || i >= input_len) break; + a = unbase64_table[last]; i++; - if (input[i] == '=' || i >= input_len) { + last = input[i]; + if (last == '=' || i >= input_len) { b = 0; b_oob = true; } else { - b = unbase64_table[input[i]]; + b = unbase64_table[last]; b_oob = false; } i++; - if (b_oob || input[i] == '=' || i >= input_len) { + last = input[i]; + if (b_oob || last == '=' || i >= input_len) { c = 0; c_oob = true; } else { - c = unbase64_table[input[i]]; + c = unbase64_table[last]; c_oob = false; } i++; - if (c_oob || input[i] == '=' || i >= input_len) { + last = input[i]; + if (c_oob || last == '=' || i >= input_len) { d = 0; } else { - d = unbase64_table[input[i]]; + d = unbase64_table[last]; } i++; - *p = (a << 2) | ((b & 0x30) >> 4); - if (++p >= pe) break; + if (last == '=' && *p == '\0') break; + if (++p == pe) break; if (b_oob) break; *p = ((b & 0x0F) << 4) | ((c & 0x3c) >> 2); - if (++p >= pe) break; + if (last == '=' && *p == '\0') break; + if (++p == pe) break; if (c_oob) break; *p = ((c & 0x03) << 6) | (d & 0x3f); - if (++p >= pe) break; + if (last == '=' && *p == '\0') break; + if (++p == pe) break; } return scope.Close(Integer::New(p - start)); diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 0b1a02caec..1e64beacb0 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -256,7 +256,7 @@ assert.equal(expected, (new Buffer(quote)).toString('base64')); b = new Buffer(1024); bytesWritten = b.write(expected, 0, 'base64'); assert.equal(quote, b.toString('ascii', 0, quote.length)); -assert.equal(quote.length+1, bytesWritten); // writes a \0 too +assert.equal(quote.length, bytesWritten); assert.equal(new Buffer('', 'base64').toString(), ''); assert.equal(new Buffer('K', 'base64').toString(), '');