Skip to content

Commit

Permalink
Avoid infinite loop on malformed message (#1208)
Browse files Browse the repository at this point in the history
* Avoid infinite loop on malformed message

If handling of such messages is deemed unimportant, `indexOf` is still faster (~40%) and cleaner than a manual loop.

Addresses #1048 to an extent.

* Use indexOf fallback for Node ≤0.12
  • Loading branch information
charmander authored and brianc committed Feb 21, 2017
1 parent 5b6d883 commit 4101781
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/connection.js
Expand Up @@ -13,6 +13,21 @@ var util = require('util');
var Writer = require('buffer-writer');
var Reader = require('packet-reader');

var indexOf =
'indexOf' in Buffer.prototype ?
function indexOf(buffer, value, start) {
return buffer.indexOf(value, start);
} :
function indexOf(buffer, value, start) {
for (var i = start, len = buffer.length; i < len; i++) {
if (buffer[i] === value) {
return i;
}
}

return -1;
};

var TEXT_MODE = 0;
var BINARY_MODE = 1;
var Connection = function(config) {
Expand Down Expand Up @@ -647,8 +662,9 @@ Connection.prototype.readBytes = function(buffer, length) {

Connection.prototype.parseCString = function(buffer) {
var start = this.offset;
while(buffer[this.offset++] !== 0) { }
return buffer.toString(this.encoding, start, this.offset - 1);
var end = indexOf(buffer, 0, start);
this.offset = end + 1;
return buffer.toString(this.encoding, start, end);
};
//end parsing methods
module.exports = Connection;

0 comments on commit 4101781

Please sign in to comment.