Permalink
Browse files

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
  • Loading branch information...
1 parent 5b6d883 commit 41017814d3c3195590bf23098aa9c63b3cb395de @charmander charmander committed with Feb 21, 2017
Showing with 18 additions and 2 deletions.
  1. +18 −2 lib/connection.js
View
@@ -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;

0 comments on commit 4101781

Please sign in to comment.