From 4769a08bec788f647769794ef5305c0478a0c799 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Thu, 24 Aug 2017 13:35:30 +0200 Subject: [PATCH] actually throw on protocol violations That change makes the parser throw when a packet cannot be decoded properly. The exception is then caught by the server, which closes the connection. --- index.js | 22 ++++------------------ test/parser.js | 11 +++++++++-- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/index.js b/index.js index ea206ea..776a217 100644 --- a/index.js +++ b/index.js @@ -272,7 +272,9 @@ function decodeString(str) { type: Number(str.charAt(0)) }; - if (null == exports.types[p.type]) return error(); + if (exports.types[p.type] === null) { + throw new Error('unknown packet type'); + } // look up attachments if type binary if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) { @@ -318,22 +320,13 @@ function decodeString(str) { // look up json data if (str.charAt(++i)) { - p = tryParse(p, str.substr(i)); + p.data = JSON.parse(str.substr(i)); } debug('decoded %s as %j', str, p); return p; } -function tryParse(p, str) { - try { - p.data = JSON.parse(str); - } catch(e){ - return error(); - } - return p; -} - /** * Deallocates a parser's resources * @@ -391,10 +384,3 @@ BinaryReconstructor.prototype.finishedReconstruction = function() { this.reconPack = null; this.buffers = []; }; - -function error() { - return { - type: exports.ERROR, - data: 'parser error' - }; -} diff --git a/test/parser.js b/test/parser.js index 346ca3b..ef2a0c4 100644 --- a/test/parser.js +++ b/test/parser.js @@ -1,8 +1,6 @@ var parser = require('../index.js'); var expect = require('expect.js'); var helpers = require('./helpers.js'); -var encode = parser.encode; -var decode = parser.decode; describe('parser', function(){ @@ -59,4 +57,13 @@ describe('parser', function(){ expect(e.message).to.match(/Illegal/); } }); + + it('should throw when decoding an invalid packet', function(){ + try { + var decoder = new parser.Decoder(); + decoder.add('442["some","data","that","breaks","stuff"]'); + } catch (e) { + expect(e.message).to.match(/Illegal/); + } + }); });