Skip to content

Commit 4101781

Browse files
charmanderbrianc
authored andcommitted
Avoid infinite loop on malformed message (brianc#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 brianc#1048 to an extent. * Use indexOf fallback for Node ≤0.12
1 parent 5b6d883 commit 4101781

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

lib/connection.js

+18-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,21 @@ var util = require('util');
1313
var Writer = require('buffer-writer');
1414
var Reader = require('packet-reader');
1515

16+
var indexOf =
17+
'indexOf' in Buffer.prototype ?
18+
function indexOf(buffer, value, start) {
19+
return buffer.indexOf(value, start);
20+
} :
21+
function indexOf(buffer, value, start) {
22+
for (var i = start, len = buffer.length; i < len; i++) {
23+
if (buffer[i] === value) {
24+
return i;
25+
}
26+
}
27+
28+
return -1;
29+
};
30+
1631
var TEXT_MODE = 0;
1732
var BINARY_MODE = 1;
1833
var Connection = function(config) {
@@ -647,8 +662,9 @@ Connection.prototype.readBytes = function(buffer, length) {
647662

648663
Connection.prototype.parseCString = function(buffer) {
649664
var start = this.offset;
650-
while(buffer[this.offset++] !== 0) { }
651-
return buffer.toString(this.encoding, start, this.offset - 1);
665+
var end = indexOf(buffer, 0, start);
666+
this.offset = end + 1;
667+
return buffer.toString(this.encoding, start, end);
652668
};
653669
//end parsing methods
654670
module.exports = Connection;

0 commit comments

Comments
 (0)