23 Commits

Author SHA1 Message Date
James Coglan 0594d1b16b Bump version to 0.1.6. 2017-09-10 17:40:58 +01:00
James Coglan 3fc65a8277 Move the license into its own file. 2017-09-10 17:39:05 +01:00
James Coglan c0ef506072 Use package.json instead of .npmignore to set files in the package. 2017-09-10 17:38:46 +01:00
James Coglan 689e37cfb7 Use windowBits:9 for deflate and inflate streams if the session is configured to use 8. 2017-09-08 22:29:37 +01:00
James Coglan 7abe8c8a7f Update spec URLs from the draft spec to RFC 7692. 2017-08-18 09:46:01 +01:00
James Coglan cbae000ab3 Use Z_DEFAULT_COMPRESSION rather than Z_DEFAULT_LEVEL, it's more descriptive. 2017-08-18 09:32:57 +01:00
James Coglan 9e8a72316d Correct a typo in an error message. 2017-08-17 22:15:58 +01:00
James Coglan 2f277e23c8 Drop testing for io.js releases, which barely anybody is still using. 2017-08-01 23:47:55 +01:00
James Coglan 0215b35a21 In Node 8, the zlib API is read-only and so cannot be stubbed on the real module. Therefore we need to pass in an object to replace the zlib module in the code under test, on which we can mock/stub method calls. 2017-08-01 01:13:54 +01:00
James Coglan f98b56db0f Test on Node 7 and 8. 2017-08-01 00:54:02 +01:00
James Coglan cad0e4f121 Remove non-breaking spaces from README. 2016-10-08 03:10:52 +01:00
James Coglan 0e8539acf7 Test on Node 6.0. 2016-04-30 13:08:52 +01:00
James Coglan 48a078f8e7 Bump version to 0.1.5 and drop support for Node 0.6. 2016-02-24 08:29:42 +00:00
James Coglan 60764f5757 Bump the copyright year. 2016-02-06 19:15:25 +00:00
James Coglan 6b75657a94 Use https: URLs for github.com in package.json. 2016-02-06 19:15:03 +00:00
James Coglan d22edec996 Catch errors thrown by close() on zlib streams. If they throw, we were about to discard them anyway, so there's no need to do anything. 2016-02-06 14:22:53 +00:00
James Coglan 1d219334bf Create CODE_OF_CONDUCT.md. 2015-11-08 12:16:23 +00:00
James Coglan 913b174ea1 Bump version to 0.1.4. 2015-11-06 22:08:35 +00:00
James Coglan 0eb99773db Test on Node 5. 2015-11-05 21:22:05 +00:00
James Coglan 758ed46420 Run tests on major versions of iojs and node 4. 2015-10-17 12:56:52 +01:00
James Coglan 9cb62ecd49 Refactor ServerSession.generateResponse() to group all logic around setting each parameter -- both the internal setting and the response value -- together, and from here work around an issue in Firefox that means the client will fail if the server sends an unsolicited server_max_window_bits parameter. 2015-10-11 13:21:04 +01:00
James Coglan dca0a77b0d Bump version to 0.1.3. 2015-04-10 20:46:44 +01:00
James Coglan 6e314bde56 Stash the scripts we built for #4 in the examples directory. 2015-04-10 20:46:21 +01:00
24 changed files with 6401 additions and 463 deletions
-1
View File
@@ -1,2 +1 @@
lib
node_modules
-6
View File
@@ -1,6 +0,0 @@
.git
.gitignore
.npmignore
.travis.yml
node_modules
spec
+7 -4
View File
@@ -1,12 +1,15 @@
sudo: false
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "iojs"
- "4"
- "5"
- "6"
- "7"
- "8"
before_install:
- '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@~1.4.0'
script: make test
- '[ "${TRAVIS_NODE_VERSION}" = "0.8" ] && npm install -g npm@~1.4.0 || true'
+19
View File
@@ -1,3 +1,22 @@
### 0.1.6 / 2017-09-10
* Use `9` instead of `8` as the `windowBits` parameter to zlib, to deal with
restrictions introduced in zlib v1.2.9
### 0.1.5 / 2016-02-24
* Catch errors thrown by `close()` on zlib streams
### 0.1.4 / 2015-11-06
* The server does not send `server_max_window_bits` if the client does not ask
for it; this works around an issue in Firefox.
### 0.1.3 / 2015-04-10
* Fix a race condition causing some fragments of deflate output to be dropped
* Make sure to emit minimal output on all Node versions
### 0.1.2 / 2014-12-18
* Don't allow configure() to be called with unrecognized options
+4
View File
@@ -0,0 +1,4 @@
# Code of Conduct
All projects under the [Faye](https://github.com/faye) umbrella are covered by
the [Code of Conduct](https://github.com/faye/code-of-conduct).
+20
View File
@@ -0,0 +1,20 @@
# The MIT License
Copyright (c) 2014-2017 James Coglan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-19
View File
@@ -1,19 +0,0 @@
SHELL := /bin/bash
PATH := node_modules/.bin:$(PATH)
source_files := $(shell find src -name '*.js')
target_files := $(source_files:src/%.js=lib/%.js)
.PHONY: all clean test
all: $(target_files)
lib/%.js: src/%.js
mkdir -p $(dir $@)
babel $< --out-file $@ --source-maps true
clean:
rm -rf lib
test: all
jstest spec/runner.js
+1 -24
View File
@@ -11,7 +11,7 @@ WebSocket protocol extension as a plugin for
$ npm install permessage-deflate
```
## Usage
## Usage
Add the plugin to your extensions:
@@ -67,26 +67,3 @@ can be used to set the local session's behaviour and control that of the peer:
requested by the peer
* `requestMaxWindowBits`: an integer from `8` to `15` inclusive to ask the other
peer to use to set its maximum sliding window size, if supported
## License
(The MIT License)
Copyright (c) 2014-2015 James Coglan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+5809
View File
File diff suppressed because it is too large Load Diff
+52
View File
@@ -0,0 +1,52 @@
var fs = require('fs'),
deflate = require('..');
var records = fs.readFileSync(__dirname + '/bad.out.log', 'utf8')
.replace(/\s*$/g, '')
.split(/\n/)
.map(JSON.parse);
var client = deflate.createClientSession(),
offer = client.generateOffer(),
server = deflate.createServerSession([offer]),
response = server.generateResponse(),
compressed = [],
size = [0, 0];
client.activate(response);
function compress(index) {
var record = records[index];
if (!record) {
console.log(size, size[0] / size[1]);
return decompress(0);
}
var message = {data: new Buffer(record[3], 'base64')};
size[0] += message.data.length;
server.processOutgoingMessage(message, function(error, message) {
compressed[index] = message;
size[1] += message.data.length;
compress(index + 1);
});
}
function decompress(index) {
var record = records[index];
if (!record) return;
var payload = record[3],
message = compressed[index];
client.processIncomingMessage(message, function(error, message) {
var output = message.data.toString('base64');
if (output !== payload) {
console.error('Failed on', record, message);
process.exit(1);
}
decompress(index + 1);
});
}
compress(0);
+77
View File
@@ -0,0 +1,77 @@
'use strict';
var util = require('util'),
common = require('./common'),
Session = require('./session');
var ClientSession = function(options) {
Session.call(this, options);
};
util.inherits(ClientSession, Session);
ClientSession.validParams = function(params) {
if (!common.validParams(params)) return false;
if (params.hasOwnProperty('client_max_window_bits')) {
if (common.VALID_WINDOW_BITS.indexOf(params.client_max_window_bits) < 0)
return false;
}
return true;
};
ClientSession.prototype.generateOffer = function() {
var offer = {};
if (this._acceptNoContextTakeover)
offer.client_no_context_takeover = true;
if (this._acceptMaxWindowBits !== undefined) {
if (common.VALID_WINDOW_BITS.indexOf(this._acceptMaxWindowBits) < 0) {
throw new Error('Invalid value for maxWindowBits');
}
offer.client_max_window_bits = this._acceptMaxWindowBits;
} else {
offer.client_max_window_bits = true;
}
if (this._requestNoContextTakeover)
offer.server_no_context_takeover = true;
if (this._requestMaxWindowBits !== undefined) {
if (common.VALID_WINDOW_BITS.indexOf(this._requestMaxWindowBits) < 0) {
throw new Error('Invalid value for requestMaxWindowBits');
}
offer.server_max_window_bits = this._requestMaxWindowBits;
}
return offer;
};
ClientSession.prototype.activate = function(params) {
if (!ClientSession.validParams(params)) return false;
if (this._acceptMaxWindowBits && params.client_max_window_bits) {
if (params.client_max_window_bits > this._acceptMaxWindowBits) return false;
}
if (this._requestNoContextTakeover && !params.server_no_context_takeover)
return false;
if (this._requestMaxWindowBits) {
if (!params.server_max_window_bits) return false;
if (params.server_max_window_bits > this._requestMaxWindowBits) return false;
}
this._ownContextTakeover = !(this._acceptNoContextTakeover || params.client_no_context_takeover);
this._ownWindowBits = Math.min(
this._acceptMaxWindowBits || common.MAX_WINDOW_BITS,
params.client_max_window_bits || common.MAX_WINDOW_BITS
);
this._peerContextTakeover = !params.server_no_context_takeover;
this._peerWindowBits = params.server_max_window_bits || common.MAX_WINDOW_BITS;
return true;
};
module.exports = ClientSession;
+59
View File
@@ -0,0 +1,59 @@
'use strict';
var common = {
VALID_PARAMS: [
'server_no_context_takeover',
'client_no_context_takeover',
'server_max_window_bits',
'client_max_window_bits'
],
MIN_WINDOW_BITS: 9,
MAX_WINDOW_BITS: 15,
VALID_WINDOW_BITS: [8, 9, 10, 11, 12, 13, 14, 15],
concat: function(buffers, length) {
var buffer = new Buffer(length),
offset = 0;
for (var i = 0, n = buffers.length; i < n; i++) {
buffers[i].copy(buffer, offset);
offset += buffers[i].length;
}
return buffer;
},
fetch: function(options, key, _default) {
if (options.hasOwnProperty(key))
return options[key];
else
return _default;
},
validateOptions: function(options, validKeys) {
for (var key in options) {
if (validKeys.indexOf(key) < 0)
throw new Error('Unrecognized option: ' + key);
}
},
validParams: function(params) {
var keys = Object.keys(params), i = keys.length;
while (i--) {
if (this.VALID_PARAMS.indexOf(keys[i]) < 0) return false;
if (params[keys[i]] instanceof Array) return false;
}
if (params.hasOwnProperty('server_no_context_takeover')) {
if (params.server_no_context_takeover !== true) return false;
}
if (params.hasOwnProperty('client_no_context_takeover')) {
if (params.client_no_context_takeover !== true) return false;
}
if (params.hasOwnProperty('server_max_window_bits')) {
if (this.VALID_WINDOW_BITS.indexOf(params.server_max_window_bits) < 0) return false;
}
return true;
}
};
module.exports = common;
+45
View File
@@ -0,0 +1,45 @@
'use strict';
var ClientSession = require('./client_session'),
ServerSession = require('./server_session'),
common = require('./common');
var VALID_OPTIONS = [
'level',
'memLevel',
'strategy',
'noContextTakeover',
'maxWindowBits',
'requestNoContextTakeover',
'requestMaxWindowBits',
'zlib'
];
var PermessageDeflate = {
configure: function(options) {
common.validateOptions(options, VALID_OPTIONS);
var opts = this._options || {};
for (var key in opts) options[key] = opts[key];
return Object.create(this, {_options: {value: options}});
},
createClientSession: function() {
return new ClientSession(this._options || {});
},
createServerSession: function(offers) {
for (var i = 0, n = offers.length; i < n; i++) {
if (ServerSession.validParams(offers[i]))
return new ServerSession(this._options || {}, offers[i]);
}
return null;
},
name: 'permessage-deflate',
type: 'permessage',
rsv1: true,
rsv2: false,
rsv3: false
};
module.exports = PermessageDeflate;
+66
View File
@@ -0,0 +1,66 @@
'use strict';
var util = require('util'),
common = require('./common'),
Session = require('./session');
var ServerSession = function(options, params) {
Session.call(this, options);
this._params = params;
};
util.inherits(ServerSession, Session);
ServerSession.validParams = function(params) {
if (!common.validParams(params)) return false;
if (params.hasOwnProperty('client_max_window_bits')) {
if ([true].concat(common.VALID_WINDOW_BITS).indexOf(params.client_max_window_bits) < 0)
return false;
}
return true;
};
ServerSession.prototype.generateResponse = function() {
var response = {};
// https://tools.ietf.org/html/rfc7692#section-7.1.1.1
this._ownContextTakeover = !this._acceptNoContextTakeover &&
!this._params.server_no_context_takeover;
if (!this._ownContextTakeover) response.server_no_context_takeover = true;
// https://tools.ietf.org/html/rfc7692#section-7.1.1.2
this._peerContextTakeover = !this._requestNoContextTakeover &&
!this._params.client_no_context_takeover;
if (!this._peerContextTakeover) response.client_no_context_takeover = true;
// https://tools.ietf.org/html/rfc7692#section-7.1.2.1
this._ownWindowBits = Math.min(this._acceptMaxWindowBits || common.MAX_WINDOW_BITS,
this._params.server_max_window_bits || common.MAX_WINDOW_BITS);
// In violation of the spec, Firefox closes the connection if it does not
// send server_max_window_bits but the server includes this in its response
if (this._ownWindowBits < common.MAX_WINDOW_BITS && this._params.server_max_window_bits)
response.server_max_window_bits = this._ownWindowBits;
// https://tools.ietf.org/html/rfc7692#section-7.1.2.2
var clientMax = this._params.client_max_window_bits, requestMax;
if (clientMax) {
if (clientMax === true) clientMax = common.MAX_WINDOW_BITS;
this._peerWindowBits = Math.min(this._requestMaxWindowBits || common.MAX_WINDOW_BITS, clientMax);
} else {
this._peerWindowBits = common.MAX_WINDOW_BITS;
}
if (this._peerWindowBits < common.MAX_WINDOW_BITS)
response.client_max_window_bits = this._peerWindowBits;
return response;
};
module.exports = ServerSession;
+174
View File
@@ -0,0 +1,174 @@
'use strict';
var zlib = require('zlib'),
common = require('./common');
var Session = function(options) {
this._level = common.fetch(options, 'level', zlib.Z_DEFAULT_COMPRESSION);
this._memLevel = common.fetch(options, 'memLevel', zlib.Z_DEFAULT_MEMLEVEL);
this._strategy = common.fetch(options, 'strategy', zlib.Z_DEFAULT_STRATEGY);
this._acceptNoContextTakeover = common.fetch(options, 'noContextTakeover', false);
this._acceptMaxWindowBits = common.fetch(options, 'maxWindowBits', undefined);
this._requestNoContextTakeover = common.fetch(options, 'requestNoContextTakeover', false);
this._requestMaxWindowBits = common.fetch(options, 'requestMaxWindowBits', undefined);
this._queueIn = [];
this._queueOut = [];
this._zlib = common.fetch(options, 'zlib', zlib);
};
Session.prototype.processIncomingMessage = function(message, callback) {
if (!message.rsv1) return callback(null, message);
if (this._lockIn) return this._queueIn.push([message, callback]);
var inflate = this._getInflate(),
chunks = [],
length = 0,
self = this;
if (this._inflate) this._lockIn = true;
var return_ = function(error, message) {
return_ = function() {};
inflate.removeListener('data', onData);
inflate.removeListener('error', onError);
if (!self._inflate) self._close(inflate);
self._lockIn = false;
var next = self._queueIn.shift();
if (next) self.processIncomingMessage.apply(self, next);
callback(error, message);
};
var onData = function(data) {
chunks.push(data);
length += data.length;
};
var onError = function(error) {
return_(error, null);
};
inflate.on('data', onData);
inflate.on('error', onError);
inflate.write(message.data);
inflate.write(new Buffer([0x00, 0x00, 0xff, 0xff]));
inflate.flush(function() {
message.data = common.concat(chunks, length);
return_(null, message);
});
};
Session.prototype.processOutgoingMessage = function(message, callback) {
if (this._lockOut) return this._queueOut.push([message, callback]);
var deflate = this._getDeflate(),
chunks = [],
length = 0,
self = this;
if (this._deflate) this._lockOut = true;
var return_ = function(error, message) {
return_ = function() {};
deflate.removeListener('data', onData);
deflate.removeListener('error', onError);
if (!self._deflate) self._close(deflate);
self._lockOut = false;
var next = self._queueOut.shift();
if (next) self.processOutgoingMessage.apply(self, next);
callback(error, message);
};
var onData = function(data) {
chunks.push(data);
length += data.length;
};
var onError = function(error) {
return_(error, null);
};
deflate.on('data', onData);
deflate.on('error', onError);
deflate.write(message.data);
var onFlush = function() {
var data = common.concat(chunks, length);
message.data = data.slice(0, data.length - 4);
message.rsv1 = true;
return_(null, message);
};
if (deflate.params !== undefined)
deflate.flush(zlib.Z_SYNC_FLUSH, onFlush);
else
deflate.flush(onFlush);
};
Session.prototype.close = function() {
this._close(this._inflate);
this._inflate = null;
this._close(this._deflate);
this._deflate = null;
};
Session.prototype._getInflate = function() {
if (this._inflate) return this._inflate;
var windowBits = Math.max(this._peerWindowBits, common.MIN_WINDOW_BITS),
inflate = this._zlib.createInflateRaw({windowBits: windowBits});
if (this._peerContextTakeover) this._inflate = inflate;
return inflate;
};
Session.prototype._getDeflate = function() {
if (this._deflate) return this._deflate;
var windowBits = Math.max(this._ownWindowBits, common.MIN_WINDOW_BITS);
var deflate = this._zlib.createDeflateRaw({
windowBits: windowBits,
level: this._level,
memLevel: this._memLevel,
strategy: this._strategy
});
var flush = deflate.flush;
// This monkey-patch is needed to make Node 0.10 produce optimal output.
// Without this it uses Z_FULL_FLUSH and effectively drops all its context
// state on every flush.
if (deflate._flushFlag !== undefined && deflate.params === undefined)
deflate.flush = function(callback) {
var ws = this._writableState;
if (ws.ended || ws.ending || ws.needDrain) {
flush.call(this, callback);
} else {
this._flushFlag = zlib.Z_SYNC_FLUSH;
this.write(new Buffer(0), '', callback);
}
};
if (this._ownContextTakeover) this._deflate = deflate;
return deflate;
};
Session.prototype._close = function(codec) {
if (!codec || !codec.close) return;
try { codec.close() } catch (error) {}
};
module.exports = Session;
+9 -5
View File
@@ -1,18 +1,22 @@
{ "name" : "permessage-deflate"
, "description" : "Per-message DEFLATE compression extension for WebSocket connections"
, "homepage" : "http://github.com/faye/permessage-deflate-node"
, "homepage" : "https://github.com/faye/permessage-deflate-node"
, "author" : "James Coglan <jcoglan@gmail.com> (http://jcoglan.com/)"
, "keywords" : ["websocket", "compression", "deflate"]
, "license" : "MIT"
, "version" : "0.1.3"
, "engines" : {"node": ">=0.6.0"}
, "version" : "0.1.6"
, "engines" : { "node": ">=0.8.0" }
, "files" : ["lib"]
, "main" : "./lib/permessage_deflate"
, "devDependencies" : {"babel": "", "jstest": ""}
, "devDependencies" : { "jstest": "*" }
, "scripts" : { "test": "jstest spec/runner.js" }
, "repository" : { "type" : "git"
, "url" : "git://github.com/faye/permessage-deflate-node.git"
}
, "bugs" : "http://github.com/faye/permessage-deflate-node/issues"
, "bugs" : "https://github.com/faye/permessage-deflate-node/issues"
}
+31 -18
View File
@@ -1,17 +1,18 @@
var PermessageDeflate = require('../lib/permessage_deflate'),
zlib = require('zlib'),
_zlib = require('zlib'),
test = require('jstest').Test
test.describe("ClientSession", function() { with(this) {
before(function() { with(this) {
this.ext = PermessageDeflate.configure(options)
this.session = ext.createClientSession()
this.deflate = zlibMock()
this.inflate = zlibMock()
this.level = zlib.Z_DEFAULT_LEVEL
this.memLevel = zlib.Z_DEFAULT_MEMLEVEL
this.strategy = zlib.Z_DEFAULT_STRATEGY
this.level = _zlib.Z_DEFAULT_LEVEL
this.memLevel = _zlib.Z_DEFAULT_MEMLEVEL
this.strategy = _zlib.Z_DEFAULT_STRATEGY
this.ext = PermessageDeflate.configure(options)
this.zlib = {}
this.session = ext.configure({zlib: zlib}).createClientSession()
this.message = {data: "hello", rsv1: true}
}})
@@ -90,6 +91,12 @@ test.describe("ClientSession", function() { with(this) {
processIncomingMessage()
processIncomingMessage()
}})
it("catches errors thrown by zlib", function() { with(this) {
activate()
stub(zlib, "createInflateRaw").returning(inflate)
assertNothingThrown(function() { processIncomingMessage() })
}})
}})
describe("when the response includes client_no_context_takeover", function() { with(this) {
@@ -106,6 +113,12 @@ test.describe("ClientSession", function() { with(this) {
processOutgoingMessage()
processOutgoingMessage()
}})
it("catches errors thrown by zlib", function() { with(this) {
activate()
stub(zlib, "createDeflateRaw").returning(deflate)
assertNothingThrown(function() { processOutgoingMessage() })
}})
}})
describe("when the response includes server_max_window_bits", function() { with(this) {
@@ -115,9 +128,9 @@ test.describe("ClientSession", function() { with(this) {
assertEqual( true, activate() )
}})
it("uses context takeover and 8 window bits for inflating incoming messages", function() { with(this) {
it("uses context takeover and 9 window bits for inflating incoming messages", function() { with(this) {
activate()
expect(zlib, "createInflateRaw").given({windowBits: 8}).exactly(1).returning(inflate)
expect(zlib, "createInflateRaw").given({windowBits: 9}).exactly(1).returning(inflate)
processIncomingMessage()
processIncomingMessage()
}})
@@ -138,9 +151,9 @@ test.describe("ClientSession", function() { with(this) {
assertEqual( true, activate() )
}})
it("uses context takeover and 8 window bits for deflating outgoing messages", function() { with(this) {
it("uses context takeover and 9 window bits for deflating outgoing messages", function() { with(this) {
activate()
expect(zlib, "createDeflateRaw").given({windowBits: 8, level: level, memLevel: memLevel, strategy: strategy}).exactly(1).returning(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 9, level: level, memLevel: memLevel, strategy: strategy}).exactly(1).returning(deflate)
processOutgoingMessage()
processOutgoingMessage()
}})
@@ -212,9 +225,9 @@ test.describe("ClientSession", function() { with(this) {
assertEqual( true, activate() )
}})
it("uses context takeover and 8 window bits for deflating outgoing messages", function() { with(this) {
it("uses context takeover and 9 window bits for deflating outgoing messages", function() { with(this) {
activate()
expect(zlib, "createDeflateRaw").given({windowBits: 8, level: level, memLevel: memLevel, strategy: strategy}).exactly(1).returning(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 9, level: level, memLevel: memLevel, strategy: strategy}).exactly(1).returning(deflate)
processOutgoingMessage()
processOutgoingMessage()
}})
@@ -305,11 +318,11 @@ test.describe("ClientSession", function() { with(this) {
}})
describe("with level", function() { with(this) {
define("options", {level: zlib.Z_BEST_SPEED})
define("options", {level: _zlib.Z_BEST_SPEED})
it("sets the level of the deflate stream", function() { with(this) {
activate()
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: zlib.Z_BEST_SPEED, memLevel: memLevel, strategy: strategy}).returns(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: _zlib.Z_BEST_SPEED, memLevel: memLevel, strategy: strategy}).returns(deflate)
processOutgoingMessage()
}})
}})
@@ -319,17 +332,17 @@ test.describe("ClientSession", function() { with(this) {
it("sets the memLevel of the deflate stream", function() { with(this) {
activate()
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: zlib.Z_DEFAULT_LEVEL, memLevel: 5, strategy: strategy}).returns(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: _zlib.Z_DEFAULT_LEVEL, memLevel: 5, strategy: strategy}).returns(deflate)
processOutgoingMessage()
}})
}})
describe("with strategy", function() { with(this) {
define("options", {strategy: zlib.Z_FILTERED})
define("options", {strategy: _zlib.Z_FILTERED})
it("sets the strategy of the deflate stream", function() { with(this) {
activate()
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: zlib.Z_DEFAULT_LEVEL, memLevel: memLevel, strategy: zlib.Z_FILTERED}).returns(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: _zlib.Z_DEFAULT_LEVEL, memLevel: memLevel, strategy: _zlib.Z_FILTERED}).returns(deflate)
processOutgoingMessage()
}})
}})
-2
View File
@@ -1,4 +1,2 @@
require('babel/polyfill');
require('./client_session_spec')
require('./server_session_spec')
+28 -15
View File
@@ -1,17 +1,18 @@
var PermessageDeflate = require('../lib/permessage_deflate'),
zlib = require('zlib'),
_zlib = require('zlib'),
test = require('jstest').Test
test.describe("ClientSession", function() { with(this) {
test.describe("ServerSession", function() { with(this) {
before(function() { with(this) {
this.ext = PermessageDeflate.configure(options)
this.session = ext.createServerSession([offer])
this.deflate = zlibMock()
this.inflate = zlibMock()
this.level = zlib.Z_DEFAULT_LEVEL
this.memLevel = zlib.Z_DEFAULT_MEMLEVEL
this.strategy = zlib.Z_DEFAULT_STRATEGY
this.level = _zlib.Z_DEFAULT_LEVEL
this.memLevel = _zlib.Z_DEFAULT_MEMLEVEL
this.strategy = _zlib.Z_DEFAULT_STRATEGY
this.ext = PermessageDeflate.configure(options)
this.zlib = {}
this.session = ext.configure({zlib: zlib}).createServerSession([offer])
this.message = {data: "hello", rsv1: true}
}})
@@ -81,6 +82,12 @@ test.describe("ClientSession", function() { with(this) {
processOutgoingMessage()
processOutgoingMessage()
}})
it("catches errors thrown by zlib", function() { with(this) {
response()
stub(zlib, "createDeflateRaw").returning(deflate)
assertNothingThrown(function() { processOutgoingMessage() })
}})
}})
describe("when the offer includes client_no_context_takeover", function() { with(this) {
@@ -97,6 +104,12 @@ test.describe("ClientSession", function() { with(this) {
processIncomingMessage()
processIncomingMessage()
}})
it("catches errors thrown by zlib", function() { with(this) {
response()
stub(zlib, "createInflateRaw").returning(inflate)
assertNothingThrown(function() { processIncomingMessage() })
}})
}})
describe("when the offer includes server_max_window_bits", function() { with(this) {
@@ -183,8 +196,8 @@ test.describe("ClientSession", function() { with(this) {
define("options", {maxWindowBits: 12})
describe("with an empty offer", function() { with(this) {
it("includes server_max_window_bits in the response", function() { with(this) {
assertEqual( {server_max_window_bits: 12}, response() )
it("does not include server_max_window_bits in the response", function() { with(this) {
assertEqual( {}, response() )
}})
it("uses context takeover and 12 window bits for deflating outgoing messages", function() { with(this) {
@@ -307,11 +320,11 @@ test.describe("ClientSession", function() { with(this) {
}})
describe("with level", function() { with(this) {
define("options", {level: zlib.Z_BEST_SPEED})
define("options", {level: _zlib.Z_BEST_SPEED})
it("sets the level of the deflate stream", function() { with(this) {
response()
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: zlib.Z_BEST_SPEED, memLevel: memLevel, strategy: strategy}).returns(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: _zlib.Z_BEST_SPEED, memLevel: memLevel, strategy: strategy}).returns(deflate)
processOutgoingMessage()
}})
}})
@@ -321,17 +334,17 @@ test.describe("ClientSession", function() { with(this) {
it("sets the memLevel of the deflate stream", function() { with(this) {
response()
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: zlib.Z_DEFAULT_LEVEL, memLevel: 5, strategy: strategy}).returns(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: _zlib.Z_DEFAULT_LEVEL, memLevel: 5, strategy: strategy}).returns(deflate)
processOutgoingMessage()
}})
}})
describe("with strategy", function() { with(this) {
define("options", {strategy: zlib.Z_FILTERED})
define("options", {strategy: _zlib.Z_FILTERED})
it("sets the strategy of the deflate stream", function() { with(this) {
response()
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: zlib.Z_DEFAULT_LEVEL, memLevel: memLevel, strategy: zlib.Z_FILTERED}).returns(deflate)
expect(zlib, "createDeflateRaw").given({windowBits: 15, level: _zlib.Z_DEFAULT_LEVEL, memLevel: memLevel, strategy: _zlib.Z_FILTERED}).returns(deflate)
processOutgoingMessage()
}})
}})
-69
View File
@@ -1,69 +0,0 @@
import Session from './session';
import * as common from './common';
export default class ClientSession extends Session {
static validParams(params) {
if (!common.validParams(params)) return false;
if (params.hasOwnProperty('client_max_window_bits')) {
if (common.VALID_WINDOW_BITS.indexOf(params.client_max_window_bits) < 0)
return false;
}
return true;
}
generateOffer() {
let offer = {};
if (this._acceptNoContextTakeover)
offer.client_no_context_takeover = true;
if (this._acceptMaxWindowBits !== undefined) {
if (common.VALID_WINDOW_BITS.indexOf(this._acceptMaxWindowBits) < 0) {
throw new Error('Invalid value for maxWindowBits');
}
offer.client_max_window_bits = this._acceptMaxWindowBits;
} else {
offer.client_max_window_bits = true;
}
if (this._requestNoContextTakeover)
offer.server_no_context_takeover = true;
if (this._requestMaxWindowBits !== undefined) {
if (common.VALID_WINDOW_BITS.indexOf(this._requestMaxWindowBits) < 0) {
throw new Error('Invalid valud for requestMaxWindowBits');
}
offer.server_max_window_bits = this._requestMaxWindowBits;
}
return offer;
}
activate(params) {
if (!ClientSession.validParams(params)) return false;
if (this._acceptMaxWindowBits && params.client_max_window_bits) {
if (params.client_max_window_bits > this._acceptMaxWindowBits) return false;
}
if (this._requestNoContextTakeover && !params.server_no_context_takeover)
return false;
if (this._requestMaxWindowBits) {
if (!params.server_max_window_bits) return false;
if (params.server_max_window_bits > this._requestMaxWindowBits) return false;
}
this._ownContextTakeover = !(this._acceptNoContextTakeover || params.client_no_context_takeover);
this._ownWindowBits = Math.min(
this._acceptMaxWindowBits || common.DEFAULT_MAX_WINDOW_BITS,
params.client_max_window_bits || common.DEFAULT_MAX_WINDOW_BITS
);
this._peerContextTakeover = !params.server_no_context_takeover;
this._peerWindowBits = params.server_max_window_bits || common.DEFAULT_MAX_WINDOW_BITS;
return true;
}
}
-44
View File
@@ -1,44 +0,0 @@
const VALID_PARAMS = [
'server_no_context_takeover',
'client_no_context_takeover',
'server_max_window_bits',
'client_max_window_bits'
];
export const DEFAULT_MAX_WINDOW_BITS = 15;
export const VALID_WINDOW_BITS = [8, 9, 10, 11, 12, 13, 14, 15];
export function concat(buffers, length) {
let buffer = new Buffer(length),
offset = 0;
for (let buf of buffers) {
buf.copy(buffer, offset);
offset += buf.length;
}
return buffer;
}
export function validateOptions(options, validKeys) {
for (let key in options) {
if (validKeys.indexOf(key) < 0)
throw new Error(`Unrecognized option: ${key}`);
}
}
export function validParams(params) {
for (let key of Object.keys(params)) {
if (VALID_PARAMS.indexOf(key) < 0) return false;
if (params[key] instanceof Array) return false;
}
if (params.hasOwnProperty('server_no_context_takeover')) {
if (params.server_no_context_takeover !== true) return false;
}
if (params.hasOwnProperty('client_no_context_takeover')) {
if (params.client_no_context_takeover !== true) return false;
}
if (params.hasOwnProperty('server_max_window_bits')) {
if (this.VALID_WINDOW_BITS.indexOf(params.server_max_window_bits) < 0) return false;
}
return true;
}
-42
View File
@@ -1,42 +0,0 @@
import ClientSession from './client_session';
import ServerSession from './server_session';
import { validateOptions } from './common';
const VALID_OPTIONS = [
'level',
'memLevel',
'strategy',
'noContextTakeover',
'maxWindowBits',
'requestNoContextTakeover',
'requestMaxWindowBits'
];
const PermessageDeflate = {
configure(options) {
validateOptions(options, VALID_OPTIONS);
let opts = this._options || {};
for (let key in opts) options[key] = opts[key];
return Object.create(this, {_options: {value: options}});
},
createClientSession() {
return new ClientSession(this._options || {});
},
createServerSession(offers) {
for (let offer of offers) {
if (ServerSession.validParams(offer))
return new ServerSession(this._options || {}, offer);
}
return null;
},
name: 'permessage-deflate',
type: 'permessage',
rsv1: true,
rsv2: false,
rsv3: false
};
export default PermessageDeflate;
-58
View File
@@ -1,58 +0,0 @@
import Session from './session';
import * as common from './common';
export default class ServerSession extends Session {
constructor(options, params) {
super(options);
this._params = params;
}
static validParams(params) {
if (!common.validParams(params)) return false;
if (params.hasOwnProperty('client_max_window_bits')) {
if ([true].concat(common.VALID_WINDOW_BITS).indexOf(params.client_max_window_bits) < 0)
return false;
}
return true;
}
generateResponse() {
let params = {};
// https://tools.ietf.org/html/draft-ietf-hybi-permessage-compression#section-8.1.1.1
if (this._acceptNoContextTakeover || this._params.server_no_context_takeover)
params.server_no_context_takeover = true;
// https://tools.ietf.org/html/draft-ietf-hybi-permessage-compression#section-8.1.1.2
if (this._requestNoContextTakeover || this._params.client_no_context_takeover)
params.client_no_context_takeover = true;
// https://tools.ietf.org/html/draft-ietf-hybi-permessage-compression#section-8.1.2.1
let acceptMax, serverMax;
if (this._acceptMaxWindowBits || this._params.server_max_window_bits) {
acceptMax = this._acceptMaxWindowBits || common.DEFAULT_MAX_WINDOW_BITS;
serverMax = this._params.server_max_window_bits || common.DEFAULT_MAX_WINDOW_BITS;
params.server_max_window_bits = Math.min(acceptMax, serverMax);
}
// https://tools.ietf.org/html/draft-ietf-hybi-permessage-compression#section-8.1.2.2
let clientMax = this._params.client_max_window_bits, requestMax;
if (clientMax) {
if (clientMax === true) {
if (this._requestMaxWindowBits) params.client_max_window_bits = this._requestMaxWindowBits;
} else {
requestMax = this._requestMaxWindowBits || common.DEFAULT_MAX_WINDOW_BITS;
params.client_max_window_bits = Math.min(requestMax, clientMax);
}
}
this._ownContextTakeover = !params.server_no_context_takeover;
this._ownWindowBits = params.server_max_window_bits || common.DEFAULT_MAX_WINDOW_BITS;
this._peerContextTakeover = !params.client_no_context_takeover;
this._peerWindowBits = params.client_max_window_bits || common.DEFAULT_MAX_WINDOW_BITS;
return params;
}
}
-156
View File
@@ -1,156 +0,0 @@
import zlib from 'zlib';
import { concat } from './common';
export default class Session {
constructor({ level = zlib.Z_DEFAULT_LEVEL,
memLevel = zlib.Z_DEFAULT_MEMLEVEL,
strategy = zlib.Z_DEFAULT_STRATEGY,
noContextTakeover = false,
maxWindowBits,
requestNoContextTakeover = false,
requestMaxWindowBits }) {
this._level = level;
this._memLevel = memLevel;
this._strategy = strategy;
this._acceptNoContextTakeover = noContextTakeover;
this._acceptMaxWindowBits = maxWindowBits;
this._requestNoContextTakeover = requestNoContextTakeover;
this._requestMaxWindowBits = requestMaxWindowBits;
this._queueIn = [];
this._queueOut = [];
}
processIncomingMessage(message, callback) {
if (!message.rsv1) return callback(null, message);
if (this._lockIn) return this._queueIn.push([message, callback]);
let [inflate, chunks, length] = [this._getInflate(), [], 0];
if (this._inflate) this._lockIn = true;
let return_ = (error, message) => {
return_ = () => {};
inflate.removeListener('data', onData);
inflate.removeListener('error', onError);
if (!this._inflate && inflate.close) inflate.close();
this._lockIn = false;
let next = this._queueIn.shift();
if (next) this.processIncomingMessage.apply(this, next);
callback(error, message);
};
let onData = (data) => {
chunks.push(data);
length += data.length;
};
let onError = (error) => return_(error, null);
inflate.on('data', onData);
inflate.on('error', onError);
inflate.write(message.data);
inflate.write(new Buffer([0x00, 0x00, 0xff, 0xff]));
inflate.flush(() => {
message.data = concat(chunks, length);
return_(null, message);
});
}
processOutgoingMessage(message, callback) {
if (this._lockOut) return this._queueOut.push([message, callback]);
let [deflate, chunks, length] = [this._getDeflate(), [], 0];
if (this._deflate) this._lockOut = true;
let return_ = (error, message) => {
return_ = () => {};
deflate.removeListener('data', onData);
deflate.removeListener('error', onError);
if (!this._deflate && deflate.close) deflate.close();
this._lockOut = false;
let next = this._queueOut.shift();
if (next) this.processOutgoingMessage.apply(this, next);
callback(error, message);
};
let onData = (data) => {
chunks.push(data);
length += data.length;
};
let onError = (error) => return_(error, null);
deflate.on('data', onData);
deflate.on('error', onError);
deflate.write(message.data);
let onFlush = () => {
let data = concat(chunks, length);
message.data = data.slice(0, data.length - 4);
message.rsv1 = true;
return_(null, message);
};
if (deflate.params !== undefined)
deflate.flush(zlib.Z_SYNC_FLUSH, onFlush);
else
deflate.flush(onFlush);
}
close() {
if (this._inflate && this._inflate.close) this._inflate.close();
this._inflate = null;
if (this._deflate && this._deflate.close) this._deflate.close();
this._deflate = null;
}
_getInflate() {
if (this._inflate) return this._inflate;
let inflate = zlib.createInflateRaw({windowBits: this._peerWindowBits});
if (this._peerContextTakeover) this._inflate = inflate;
return inflate;
}
_getDeflate() {
if (this._deflate) return this._deflate;
let deflate = zlib.createDeflateRaw({
windowBits: this._ownWindowBits,
level: this._level,
memLevel: this._memLevel,
strategy: this._strategy
});
let flush = deflate.flush;
// This monkey-patch is needed to make Node 0.10 produce optimal output.
// Without this it uses Z_FULL_FLUSH and effectively drops all its context
// state on every flush.
if (deflate._flushFlag !== undefined && deflate.params === undefined)
deflate.flush = function(callback) {
let ws = this._writableState;
if (ws.ended || ws.ending || ws.needDrain) {
flush.call(this, callback);
} else {
this._flushFlag = zlib.Z_SYNC_FLUSH;
this.write(new Buffer(0), '', callback);
}
};
if (this._ownContextTakeover) this._deflate = deflate;
return deflate;
}
}