From e4b716efaa00f34fe4d9f1c141c93e2aa994328c Mon Sep 17 00:00:00 2001 From: isaacs Date: Mon, 8 Apr 2013 08:46:51 -0700 Subject: [PATCH] http: Support write(data, 'hex') We were assuming that any string can be concatenated safely to CRLF. However, for hex, base64, or binary encoded writes, this is not the case, and results in sending the incorrect response. An unusual edge case, but certainly a bug. --- lib/http.js | 9 ++++++--- test/simple/test-http-byteswritten.js | 6 ++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/http.js b/lib/http.js index b4fc2add11..ac6b1c6bf7 100644 --- a/lib/http.js +++ b/lib/http.js @@ -772,15 +772,18 @@ OutgoingMessage.prototype.write = function(chunk, encoding) { var len, ret; if (this.chunkedEncoding) { - if (typeof(chunk) === 'string') { + if (typeof(chunk) === 'string' && + encoding !== 'hex' && + encoding !== 'base64' && + encoding !== 'binary') { len = Buffer.byteLength(chunk, encoding); chunk = len.toString(16) + CRLF + chunk + CRLF; ret = this._send(chunk, encoding); } else { - // buffer + // buffer, or a non-toString-friendly encoding len = chunk.length; this._send(len.toString(16) + CRLF); - this._send(chunk); + this._send(chunk, encoding); ret = this._send(CRLF); } } else { diff --git a/test/simple/test-http-byteswritten.js b/test/simple/test-http-byteswritten.js index fc090b17dc..160ea4d76e 100644 --- a/test/simple/test-http-byteswritten.js +++ b/test/simple/test-http-byteswritten.js @@ -35,10 +35,12 @@ var httpServer = http.createServer(function(req, res) { }); res.writeHead(200, { 'Content-Type': 'text/plain' }); - // Write 1mb to cause some requests to buffer - var chunk = new Array(1024).join('A'); + // Write 1.5mb to cause some requests to buffer + // Also, mix up the encodings a bit. + var chunk = new Array(1024 + 1).join('7'); for (var i = 0; i < 1024; i++) { res.write(chunk); + res.write(chunk, 'hex'); } // Get .bytesWritten while buffer is not empty assert(res.connection.bytesWritten > 0);