Avoid infinite loop on malformed message (#1208)

* 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
This commit is contained in:
Charmander 2017-02-21 09:19:03 -08:00 committed by Brian C
parent 5b6d883723
commit 41017814d3

View File

@ -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) {
@ -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;